import * as Ed25519 from '@noble/ed25519';
import { Encoder } from '../../../utils/encoder.js';
import { DwnError, DwnErrorCode } from '../../../core/dwn-error.js';
function validateKey(jwk) {
    if (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519') {
        throw new DwnError(DwnErrorCode.Ed25519InvalidJwk, 'invalid jwk. kty MUST be OKP. crv MUST be Ed25519');
    }
}
function publicKeyToJwk(publicKeyBytes) {
    const x = Encoder.bytesToBase64Url(publicKeyBytes);
    const publicJwk = {
        alg: 'EdDSA',
        kty: 'OKP',
        crv: 'Ed25519',
        x
    };
    return publicJwk;
}
export const ed25519 = {
    sign: async (content, privateJwk) => {
        validateKey(privateJwk);
        const privateKeyBytes = Encoder.base64UrlToBytes(privateJwk.d);
        return Ed25519.signAsync(content, privateKeyBytes);
    },
    verify: async (content, signature, publicJwk) => {
        validateKey(publicJwk);
        const publicKeyBytes = Encoder.base64UrlToBytes(publicJwk.x);
        return Ed25519.verifyAsync(signature, content, publicKeyBytes);
    },
    generateKeyPair: async () => {
        const privateKeyBytes = Ed25519.utils.randomPrivateKey();
        const publicKeyBytes = await Ed25519.getPublicKeyAsync(privateKeyBytes);
        const d = Encoder.bytesToBase64Url(privateKeyBytes);
        const publicJwk = publicKeyToJwk(publicKeyBytes);
        const privateJwk = { ...publicJwk, d };
        return { publicJwk, privateJwk };
    },
    publicKeyToJwk: async (publicKeyBytes) => {
        return publicKeyToJwk(publicKeyBytes);
    }
};
//# sourceMappingURL=ed25519.js.map