"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InvalidSerializedSizeError = exports.InvalidUncompressedPrefixError = exports.InvalidCompressedPrefixError = exports.InvalidPrefixError = exports.InvalidError = void 0;
exports.assert = assert;
exports.compress = compress;
exports.from = from;
exports.fromBytes = fromBytes;
exports.fromHex = fromHex;
exports.toBytes = toBytes;
exports.toHex = toHex;
exports.validate = validate;
const Bytes = require("./Bytes.js");
const Errors = require("./Errors.js");
const Hex = require("./Hex.js");
const Json = require("./Json.js");
function assert(publicKey, options = {}) {
    const { compressed } = options;
    const { prefix, x, y } = publicKey;
    if (compressed === false ||
        (typeof x === 'bigint' && typeof y === 'bigint')) {
        if (prefix !== 4)
            throw new InvalidPrefixError({
                prefix,
                cause: new InvalidUncompressedPrefixError(),
            });
        return;
    }
    if (compressed === true ||
        (typeof x === 'bigint' && typeof y === 'undefined')) {
        if (prefix !== 3 && prefix !== 2)
            throw new InvalidPrefixError({
                prefix,
                cause: new InvalidCompressedPrefixError(),
            });
        return;
    }
    throw new InvalidError({ publicKey });
}
function compress(publicKey) {
    const { x, y } = publicKey;
    return {
        prefix: y % 2n === 0n ? 2 : 3,
        x,
    };
}
function from(value) {
    const publicKey = (() => {
        if (Hex.validate(value))
            return fromHex(value);
        if (Bytes.validate(value))
            return fromBytes(value);
        const { prefix, x, y } = value;
        if (typeof x === 'bigint' && typeof y === 'bigint')
            return { prefix: prefix ?? 0x04, x, y };
        return { prefix, x };
    })();
    assert(publicKey);
    return publicKey;
}
function fromBytes(publicKey) {
    return fromHex(Hex.fromBytes(publicKey));
}
function fromHex(publicKey) {
    if (publicKey.length !== 132 &&
        publicKey.length !== 130 &&
        publicKey.length !== 68)
        throw new InvalidSerializedSizeError({ publicKey });
    if (publicKey.length === 130) {
        const x = BigInt(Hex.slice(publicKey, 0, 32));
        const y = BigInt(Hex.slice(publicKey, 32, 64));
        return {
            prefix: 4,
            x,
            y,
        };
    }
    if (publicKey.length === 132) {
        const prefix = Number(Hex.slice(publicKey, 0, 1));
        const x = BigInt(Hex.slice(publicKey, 1, 33));
        const y = BigInt(Hex.slice(publicKey, 33, 65));
        return {
            prefix,
            x,
            y,
        };
    }
    const prefix = Number(Hex.slice(publicKey, 0, 1));
    const x = BigInt(Hex.slice(publicKey, 1, 33));
    return {
        prefix,
        x,
    };
}
function toBytes(publicKey, options = {}) {
    return Bytes.fromHex(toHex(publicKey, options));
}
function toHex(publicKey, options = {}) {
    assert(publicKey);
    const { prefix, x, y } = publicKey;
    const { includePrefix = true } = options;
    const publicKey_ = Hex.concat(includePrefix ? Hex.fromNumber(prefix, { size: 1 }) : '0x', Hex.fromNumber(x, { size: 32 }), typeof y === 'bigint' ? Hex.fromNumber(y, { size: 32 }) : '0x');
    return publicKey_;
}
function validate(publicKey, options = {}) {
    try {
        assert(publicKey, options);
        return true;
    }
    catch (_error) {
        return false;
    }
}
class InvalidError extends Errors.BaseError {
    constructor({ publicKey }) {
        super(`Value \`${Json.stringify(publicKey)}\` is not a valid public key.`, {
            metaMessages: [
                'Public key must contain:',
                '- an `x` and `prefix` value (compressed)',
                '- an `x`, `y`, and `prefix` value (uncompressed)',
            ],
        });
        Object.defineProperty(this, "name", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 'PublicKey.InvalidError'
        });
    }
}
exports.InvalidError = InvalidError;
class InvalidPrefixError extends Errors.BaseError {
    constructor({ prefix, cause }) {
        super(`Prefix "${prefix}" is invalid.`, {
            cause,
        });
        Object.defineProperty(this, "name", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 'PublicKey.InvalidPrefixError'
        });
    }
}
exports.InvalidPrefixError = InvalidPrefixError;
class InvalidCompressedPrefixError extends Errors.BaseError {
    constructor() {
        super('Prefix must be 2 or 3 for compressed public keys.');
        Object.defineProperty(this, "name", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 'PublicKey.InvalidCompressedPrefixError'
        });
    }
}
exports.InvalidCompressedPrefixError = InvalidCompressedPrefixError;
class InvalidUncompressedPrefixError extends Errors.BaseError {
    constructor() {
        super('Prefix must be 4 for uncompressed public keys.');
        Object.defineProperty(this, "name", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 'PublicKey.InvalidUncompressedPrefixError'
        });
    }
}
exports.InvalidUncompressedPrefixError = InvalidUncompressedPrefixError;
class InvalidSerializedSizeError extends Errors.BaseError {
    constructor({ publicKey }) {
        super(`Value \`${publicKey}\` is an invalid public key size.`, {
            metaMessages: [
                'Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).',
                `Received ${Hex.size(Hex.from(publicKey))} bytes.`,
            ],
        });
        Object.defineProperty(this, "name", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 'PublicKey.InvalidSerializedSizeError'
        });
    }
}
exports.InvalidSerializedSizeError = InvalidSerializedSizeError;
//# sourceMappingURL=PublicKey.js.map