shamir-secret-sharing-bn254
Version:

3,731 lines • 142 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// node_modules/@noble/hashes/crypto.js
var require_crypto = __commonJS({
"node_modules/@noble/hashes/crypto.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.crypto = void 0;
exports.crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
}
});
// node_modules/@noble/hashes/_assert.js
var require_assert = __commonJS({
"node_modules/@noble/hashes/_assert.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isBytes = isBytes;
exports.number = number;
exports.bool = bool;
exports.bytes = bytes;
exports.hash = hash;
exports.exists = exists;
exports.output = output;
function number(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`positive integer expected, not ${n}`);
}
function bool(b) {
if (typeof b !== "boolean")
throw new Error(`boolean expected, not ${b}`);
}
function isBytes(a) {
return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array";
}
function bytes(b, ...lengths) {
if (!isBytes(b))
throw new Error("Uint8Array expected");
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
}
function hash(h) {
if (typeof h !== "function" || typeof h.create !== "function")
throw new Error("Hash should be wrapped by utils.wrapConstructor");
number(h.outputLen);
number(h.blockLen);
}
function exists(instance, checkFinished = true) {
if (instance.destroyed)
throw new Error("Hash instance has been destroyed");
if (checkFinished && instance.finished)
throw new Error("Hash#digest() has already been called");
}
function output(out, instance) {
bytes(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error(`digestInto() expects output buffer of length at least ${min}`);
}
}
var assert = { number, bool, bytes, hash, exists, output };
exports.default = assert;
}
});
// node_modules/@noble/hashes/utils.js
var require_utils = __commonJS({
"node_modules/@noble/hashes/utils.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Hash = exports.nextTick = exports.byteSwapIfBE = exports.byteSwap = exports.isLE = exports.rotl = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0;
exports.isBytes = isBytes;
exports.byteSwap32 = byteSwap32;
exports.bytesToHex = bytesToHex;
exports.hexToBytes = hexToBytes;
exports.asyncLoop = asyncLoop;
exports.utf8ToBytes = utf8ToBytes;
exports.toBytes = toBytes;
exports.concatBytes = concatBytes;
exports.checkOpts = checkOpts;
exports.wrapConstructor = wrapConstructor;
exports.wrapConstructorWithOpts = wrapConstructorWithOpts;
exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts;
exports.randomBytes = randomBytes2;
var crypto_1 = require_crypto();
var _assert_js_1 = require_assert();
function isBytes(a) {
return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array";
}
var u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
exports.u8 = u8;
var u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
exports.u32 = u32;
var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
exports.createView = createView;
var rotr = (word, shift) => word << 32 - shift | word >>> shift;
exports.rotr = rotr;
var rotl = (word, shift) => word << shift | word >>> 32 - shift >>> 0;
exports.rotl = rotl;
exports.isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
var byteSwap = (word) => word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
exports.byteSwap = byteSwap;
exports.byteSwapIfBE = exports.isLE ? (n) => n : (n) => (0, exports.byteSwap)(n);
function byteSwap32(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] = (0, exports.byteSwap)(arr[i]);
}
}
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
function bytesToHex(bytes) {
(0, _assert_js_1.bytes)(bytes);
let hex = "";
for (let i = 0; i < bytes.length; i++) {
hex += hexes[bytes[i]];
}
return hex;
}
var asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
function asciiToBase16(char) {
if (char >= asciis._0 && char <= asciis._9)
return char - asciis._0;
if (char >= asciis._A && char <= asciis._F)
return char - (asciis._A - 10);
if (char >= asciis._a && char <= asciis._f)
return char - (asciis._a - 10);
return;
}
function hexToBytes(hex) {
if (typeof hex !== "string")
throw new Error("hex string expected, got " + typeof hex);
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
throw new Error("padded hex string expected, got unpadded hex of length " + hl);
const array = new Uint8Array(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
const n1 = asciiToBase16(hex.charCodeAt(hi));
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
if (n1 === void 0 || n2 === void 0) {
const char = hex[hi] + hex[hi + 1];
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
}
array[ai] = n1 * 16 + n2;
}
return array;
}
var nextTick = async () => {
};
exports.nextTick = nextTick;
async function asyncLoop(iters, tick, cb) {
let ts = Date.now();
for (let i = 0; i < iters; i++) {
cb(i);
const diff = Date.now() - ts;
if (diff >= 0 && diff < tick)
continue;
await (0, exports.nextTick)();
ts += diff;
}
}
function utf8ToBytes(str) {
if (typeof str !== "string")
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str));
}
function toBytes(data) {
if (typeof data === "string")
data = utf8ToBytes(data);
(0, _assert_js_1.bytes)(data);
return data;
}
function concatBytes(...arrays) {
let sum = 0;
for (let i = 0; i < arrays.length; i++) {
const a = arrays[i];
(0, _assert_js_1.bytes)(a);
sum += a.length;
}
const res = new Uint8Array(sum);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const a = arrays[i];
res.set(a, pad);
pad += a.length;
}
return res;
}
var Hash = class {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
};
exports.Hash = Hash;
var toStr2 = {}.toString;
function checkOpts(defaults, opts) {
if (opts !== void 0 && toStr2.call(opts) !== "[object Object]")
throw new Error("Options should be object or undefined");
const merged = Object.assign(defaults, opts);
return merged;
}
function wrapConstructor(hashCons) {
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
const tmp = hashCons();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = () => hashCons();
return hashC;
}
function wrapConstructorWithOpts(hashCons) {
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
const tmp = hashCons({});
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (opts) => hashCons(opts);
return hashC;
}
function wrapXOFConstructorWithOpts(hashCons) {
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
const tmp = hashCons({});
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (opts) => hashCons(opts);
return hashC;
}
function randomBytes2(bytesLength = 32) {
if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") {
return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
}
if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === "function") {
return crypto_1.crypto.randomBytes(bytesLength);
}
throw new Error("crypto.getRandomValues must be defined");
}
}
});
// node_modules/@noble/curves/abstract/utils.js
var require_utils2 = __commonJS({
"node_modules/@noble/curves/abstract/utils.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.notImplemented = exports.bitMask = void 0;
exports.isBytes = isBytes;
exports.abytes = abytes;
exports.abool = abool;
exports.bytesToHex = bytesToHex;
exports.numberToHexUnpadded = numberToHexUnpadded;
exports.hexToNumber = hexToNumber;
exports.hexToBytes = hexToBytes;
exports.bytesToNumberBE = bytesToNumberBE;
exports.bytesToNumberLE = bytesToNumberLE;
exports.numberToBytesBE = numberToBytesBE;
exports.numberToBytesLE = numberToBytesLE;
exports.numberToVarBytesBE = numberToVarBytesBE;
exports.ensureBytes = ensureBytes;
exports.concatBytes = concatBytes;
exports.equalBytes = equalBytes;
exports.utf8ToBytes = utf8ToBytes;
exports.inRange = inRange;
exports.aInRange = aInRange;
exports.bitLen = bitLen;
exports.bitGet = bitGet;
exports.bitSet = bitSet;
exports.createHmacDrbg = createHmacDrbg;
exports.validateObject = validateObject;
exports.memoized = memoized;
var _0n = /* @__PURE__ */ BigInt(0);
var _1n = /* @__PURE__ */ BigInt(1);
var _2n = /* @__PURE__ */ BigInt(2);
function isBytes(a) {
return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array";
}
function abytes(item) {
if (!isBytes(item))
throw new Error("Uint8Array expected");
}
function abool(title, value) {
if (typeof value !== "boolean")
throw new Error(`${title} must be valid boolean, got "${value}".`);
}
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
function bytesToHex(bytes) {
abytes(bytes);
let hex = "";
for (let i = 0; i < bytes.length; i++) {
hex += hexes[bytes[i]];
}
return hex;
}
function numberToHexUnpadded(num) {
const hex = num.toString(16);
return hex.length & 1 ? `0${hex}` : hex;
}
function hexToNumber(hex) {
if (typeof hex !== "string")
throw new Error("hex string expected, got " + typeof hex);
return BigInt(hex === "" ? "0" : `0x${hex}`);
}
var asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
function asciiToBase16(char) {
if (char >= asciis._0 && char <= asciis._9)
return char - asciis._0;
if (char >= asciis._A && char <= asciis._F)
return char - (asciis._A - 10);
if (char >= asciis._a && char <= asciis._f)
return char - (asciis._a - 10);
return;
}
function hexToBytes(hex) {
if (typeof hex !== "string")
throw new Error("hex string expected, got " + typeof hex);
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
throw new Error("padded hex string expected, got unpadded hex of length " + hl);
const array = new Uint8Array(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
const n1 = asciiToBase16(hex.charCodeAt(hi));
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
if (n1 === void 0 || n2 === void 0) {
const char = hex[hi] + hex[hi + 1];
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
}
array[ai] = n1 * 16 + n2;
}
return array;
}
function bytesToNumberBE(bytes) {
return hexToNumber(bytesToHex(bytes));
}
function bytesToNumberLE(bytes) {
abytes(bytes);
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
}
function numberToBytesBE(n, len) {
return hexToBytes(n.toString(16).padStart(len * 2, "0"));
}
function numberToBytesLE(n, len) {
return numberToBytesBE(n, len).reverse();
}
function numberToVarBytesBE(n) {
return hexToBytes(numberToHexUnpadded(n));
}
function ensureBytes(title, hex, expectedLength) {
let res;
if (typeof hex === "string") {
try {
res = hexToBytes(hex);
} catch (e) {
throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
}
} else if (isBytes(hex)) {
res = Uint8Array.from(hex);
} else {
throw new Error(`${title} must be hex string or Uint8Array`);
}
const len = res.length;
if (typeof expectedLength === "number" && len !== expectedLength)
throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
return res;
}
function concatBytes(...arrays) {
let sum = 0;
for (let i = 0; i < arrays.length; i++) {
const a = arrays[i];
abytes(a);
sum += a.length;
}
const res = new Uint8Array(sum);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const a = arrays[i];
res.set(a, pad);
pad += a.length;
}
return res;
}
function equalBytes(a, b) {
if (a.length !== b.length)
return false;
let diff = 0;
for (let i = 0; i < a.length; i++)
diff |= a[i] ^ b[i];
return diff === 0;
}
function utf8ToBytes(str) {
if (typeof str !== "string")
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str));
}
var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
function inRange(n, min, max) {
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
function aInRange(title, n, min, max) {
if (!inRange(n, min, max))
throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);
}
function bitLen(n) {
let len;
for (len = 0; n > _0n; n >>= _1n, len += 1)
;
return len;
}
function bitGet(n, pos) {
return n >> BigInt(pos) & _1n;
}
function bitSet(n, pos, value) {
return n | (value ? _1n : _0n) << BigInt(pos);
}
var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;
exports.bitMask = bitMask;
var u8n = (data) => new Uint8Array(data);
var u8fr = (arr) => Uint8Array.from(arr);
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
if (typeof hashLen !== "number" || hashLen < 2)
throw new Error("hashLen must be a number");
if (typeof qByteLen !== "number" || qByteLen < 2)
throw new Error("qByteLen must be a number");
if (typeof hmacFn !== "function")
throw new Error("hmacFn must be a function");
let v = u8n(hashLen);
let k = u8n(hashLen);
let i = 0;
const reset = () => {
v.fill(1);
k.fill(0);
i = 0;
};
const h = (...b) => hmacFn(k, v, ...b);
const reseed = (seed = u8n()) => {
k = h(u8fr([0]), seed);
v = h();
if (seed.length === 0)
return;
k = h(u8fr([1]), seed);
v = h();
};
const gen = () => {
if (i++ >= 1e3)
throw new Error("drbg: tried 1000 values");
let len = 0;
const out = [];
while (len < qByteLen) {
v = h();
const sl = v.slice();
out.push(sl);
len += v.length;
}
return concatBytes(...out);
};
const genUntil = (seed, pred) => {
reset();
reseed(seed);
let res = void 0;
while (!(res = pred(gen())))
reseed();
reset();
return res;
};
return genUntil;
}
var validatorFns = {
bigint: (val) => typeof val === "bigint",
function: (val) => typeof val === "function",
boolean: (val) => typeof val === "boolean",
string: (val) => typeof val === "string",
stringOrUint8Array: (val) => typeof val === "string" || isBytes(val),
isSafeInteger: (val) => Number.isSafeInteger(val),
array: (val) => Array.isArray(val),
field: (val, object) => object.Fp.isValid(val),
hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
};
function validateObject(object, validators, optValidators = {}) {
const checkField = (fieldName, type, isOptional) => {
const checkVal = validatorFns[type];
if (typeof checkVal !== "function")
throw new Error(`Invalid validator "${type}", expected function`);
const val = object[fieldName];
if (isOptional && val === void 0)
return;
if (!checkVal(val, object)) {
throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
}
};
for (const [fieldName, type] of Object.entries(validators))
checkField(fieldName, type, false);
for (const [fieldName, type] of Object.entries(optValidators))
checkField(fieldName, type, true);
return object;
}
var notImplemented = () => {
throw new Error("not implemented");
};
exports.notImplemented = notImplemented;
function memoized(fn) {
const map = /* @__PURE__ */ new WeakMap();
return (arg, ...args) => {
const val = map.get(arg);
if (val !== void 0)
return val;
const computed = fn(arg, ...args);
map.set(arg, computed);
return computed;
};
}
}
});
// node_modules/@noble/curves/abstract/modular.js
var require_modular = __commonJS({
"node_modules/@noble/curves/abstract/modular.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isNegativeLE = void 0;
exports.mod = mod;
exports.pow = pow;
exports.pow2 = pow2;
exports.invert = invert;
exports.tonelliShanks = tonelliShanks;
exports.FpSqrt = FpSqrt;
exports.validateField = validateField;
exports.FpPow = FpPow;
exports.FpInvertBatch = FpInvertBatch;
exports.FpDiv = FpDiv;
exports.FpLegendre = FpLegendre;
exports.FpIsSquare = FpIsSquare;
exports.nLength = nLength;
exports.Field = Field;
exports.FpSqrtOdd = FpSqrtOdd;
exports.FpSqrtEven = FpSqrtEven;
exports.hashToPrivateScalar = hashToPrivateScalar;
exports.getFieldBytesLength = getFieldBytesLength;
exports.getMinHashLength = getMinHashLength;
exports.mapHashToField = mapHashToField;
var utils_js_1 = require_utils2();
var _0n = BigInt(0);
var _1n = BigInt(1);
var _2n = BigInt(2);
var _3n = BigInt(3);
var _4n = BigInt(4);
var _5n = BigInt(5);
var _8n = BigInt(8);
var _9n = BigInt(9);
var _16n = BigInt(16);
function mod(a, b) {
const result = a % b;
return result >= _0n ? result : b + result;
}
function pow(num, power, modulo) {
if (modulo <= _0n || power < _0n)
throw new Error("Expected power/modulo > 0");
if (modulo === _1n)
return _0n;
let res = _1n;
while (power > _0n) {
if (power & _1n)
res = res * num % modulo;
num = num * num % modulo;
power >>= _1n;
}
return res;
}
function pow2(x, power, modulo) {
let res = x;
while (power-- > _0n) {
res *= res;
res %= modulo;
}
return res;
}
function invert(number, modulo) {
if (number === _0n || modulo <= _0n) {
throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
}
let a = mod(number, modulo);
let b = modulo;
let x = _0n, y = _1n, u = _1n, v = _0n;
while (a !== _0n) {
const q = b / a;
const r = b % a;
const m = x - u * q;
const n = y - v * q;
b = a, a = r, x = u, y = v, u = m, v = n;
}
const gcd = b;
if (gcd !== _1n)
throw new Error("invert: does not exist");
return mod(x, modulo);
}
function tonelliShanks(P) {
const legendreC = (P - _1n) / _2n;
let Q, S, Z;
for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)
;
for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)
;
if (S === 1) {
const p1div4 = (P + _1n) / _4n;
return function tonelliFast(Fp, n) {
const root = Fp.pow(n, p1div4);
if (!Fp.eql(Fp.sqr(root), n))
throw new Error("Cannot find square root");
return root;
};
}
const Q1div2 = (Q + _1n) / _2n;
return function tonelliSlow(Fp, n) {
if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
throw new Error("Cannot find square root");
let r = S;
let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q);
let x = Fp.pow(n, Q1div2);
let b = Fp.pow(n, Q);
while (!Fp.eql(b, Fp.ONE)) {
if (Fp.eql(b, Fp.ZERO))
return Fp.ZERO;
let m = 1;
for (let t2 = Fp.sqr(b); m < r; m++) {
if (Fp.eql(t2, Fp.ONE))
break;
t2 = Fp.sqr(t2);
}
const ge = Fp.pow(g, _1n << BigInt(r - m - 1));
g = Fp.sqr(ge);
x = Fp.mul(x, ge);
b = Fp.mul(b, g);
r = m;
}
return x;
};
}
function FpSqrt(P) {
if (P % _4n === _3n) {
const p1div4 = (P + _1n) / _4n;
return function sqrt3mod4(Fp, n) {
const root = Fp.pow(n, p1div4);
if (!Fp.eql(Fp.sqr(root), n))
throw new Error("Cannot find square root");
return root;
};
}
if (P % _8n === _5n) {
const c1 = (P - _5n) / _8n;
return function sqrt5mod8(Fp, n) {
const n2 = Fp.mul(n, _2n);
const v = Fp.pow(n2, c1);
const nv = Fp.mul(n, v);
const i = Fp.mul(Fp.mul(nv, _2n), v);
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
if (!Fp.eql(Fp.sqr(root), n))
throw new Error("Cannot find square root");
return root;
};
}
if (P % _16n === _9n) {
}
return tonelliShanks(P);
}
var isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
exports.isNegativeLE = isNegativeLE;
var FIELD_FIELDS = [
"create",
"isValid",
"is0",
"neg",
"inv",
"sqrt",
"sqr",
"eql",
"add",
"sub",
"mul",
"pow",
"div",
"addN",
"subN",
"mulN",
"sqrN"
];
function validateField(field) {
const initial = {
ORDER: "bigint",
MASK: "bigint",
BYTES: "isSafeInteger",
BITS: "isSafeInteger"
};
const opts = FIELD_FIELDS.reduce((map, val) => {
map[val] = "function";
return map;
}, initial);
return (0, utils_js_1.validateObject)(field, opts);
}
function FpPow(f, num, power) {
if (power < _0n)
throw new Error("Expected power > 0");
if (power === _0n)
return f.ONE;
if (power === _1n)
return num;
let p = f.ONE;
let d = num;
while (power > _0n) {
if (power & _1n)
p = f.mul(p, d);
d = f.sqr(d);
power >>= _1n;
}
return p;
}
function FpInvertBatch(f, nums) {
const tmp = new Array(nums.length);
const lastMultiplied = nums.reduce((acc, num, i) => {
if (f.is0(num))
return acc;
tmp[i] = acc;
return f.mul(acc, num);
}, f.ONE);
const inverted = f.inv(lastMultiplied);
nums.reduceRight((acc, num, i) => {
if (f.is0(num))
return acc;
tmp[i] = f.mul(acc, tmp[i]);
return f.mul(acc, num);
}, inverted);
return tmp;
}
function FpDiv(f, lhs, rhs) {
return f.mul(lhs, typeof rhs === "bigint" ? invert(rhs, f.ORDER) : f.inv(rhs));
}
function FpLegendre(order) {
const legendreConst = (order - _1n) / _2n;
return (f, x) => f.pow(x, legendreConst);
}
function FpIsSquare(f) {
const legendre = FpLegendre(f.ORDER);
return (x) => {
const p = legendre(f, x);
return f.eql(p, f.ZERO) || f.eql(p, f.ONE);
};
}
function nLength(n, nBitLength) {
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
const nByteLength = Math.ceil(_nBitLength / 8);
return { nBitLength: _nBitLength, nByteLength };
}
function Field(ORDER, bitLen, isLE2 = false, redef = {}) {
if (ORDER <= _0n)
throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
if (BYTES > 2048)
throw new Error("Field lengths over 2048 bytes are not supported");
const sqrtP = FpSqrt(ORDER);
const f = Object.freeze({
ORDER,
BITS,
BYTES,
MASK: (0, utils_js_1.bitMask)(BITS),
ZERO: _0n,
ONE: _1n,
create: (num) => mod(num, ORDER),
isValid: (num) => {
if (typeof num !== "bigint")
throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
return _0n <= num && num < ORDER;
},
is0: (num) => num === _0n,
isOdd: (num) => (num & _1n) === _1n,
neg: (num) => mod(-num, ORDER),
eql: (lhs, rhs) => lhs === rhs,
sqr: (num) => mod(num * num, ORDER),
add: (lhs, rhs) => mod(lhs + rhs, ORDER),
sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
pow: (num, power) => FpPow(f, num, power),
div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
// Same as above, but doesn't normalize
sqrN: (num) => num * num,
addN: (lhs, rhs) => lhs + rhs,
subN: (lhs, rhs) => lhs - rhs,
mulN: (lhs, rhs) => lhs * rhs,
inv: (num) => invert(num, ORDER),
sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
invertBatch: (lst) => FpInvertBatch(f, lst),
// TODO: do we really need constant cmov?
// We don't have const-time bigints anyway, so probably will be not very useful
cmov: (a, b, c) => c ? b : a,
toBytes: (num) => isLE2 ? (0, utils_js_1.numberToBytesLE)(num, BYTES) : (0, utils_js_1.numberToBytesBE)(num, BYTES),
fromBytes: (bytes) => {
if (bytes.length !== BYTES)
throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
return isLE2 ? (0, utils_js_1.bytesToNumberLE)(bytes) : (0, utils_js_1.bytesToNumberBE)(bytes);
}
});
return Object.freeze(f);
}
function FpSqrtOdd(Fp, elm) {
if (!Fp.isOdd)
throw new Error(`Field doesn't have isOdd`);
const root = Fp.sqrt(elm);
return Fp.isOdd(root) ? root : Fp.neg(root);
}
function FpSqrtEven(Fp, elm) {
if (!Fp.isOdd)
throw new Error(`Field doesn't have isOdd`);
const root = Fp.sqrt(elm);
return Fp.isOdd(root) ? Fp.neg(root) : root;
}
function hashToPrivateScalar(hash, groupOrder, isLE2 = false) {
hash = (0, utils_js_1.ensureBytes)("privateHash", hash);
const hashLen = hash.length;
const minLen = nLength(groupOrder).nByteLength + 8;
if (minLen < 24 || hashLen < minLen || hashLen > 1024)
throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);
const num = isLE2 ? (0, utils_js_1.bytesToNumberLE)(hash) : (0, utils_js_1.bytesToNumberBE)(hash);
return mod(num, groupOrder - _1n) + _1n;
}
function getFieldBytesLength(fieldOrder) {
if (typeof fieldOrder !== "bigint")
throw new Error("field order must be bigint");
const bitLength = fieldOrder.toString(2).length;
return Math.ceil(bitLength / 8);
}
function getMinHashLength(fieldOrder) {
const length = getFieldBytesLength(fieldOrder);
return length + Math.ceil(length / 2);
}
function mapHashToField(key, fieldOrder, isLE2 = false) {
const len = key.length;
const fieldLen = getFieldBytesLength(fieldOrder);
const minLen = getMinHashLength(fieldOrder);
if (len < 16 || len < minLen || len > 1024)
throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
const num = isLE2 ? (0, utils_js_1.bytesToNumberBE)(key) : (0, utils_js_1.bytesToNumberLE)(key);
const reduced = mod(num, fieldOrder - _1n) + _1n;
return isLE2 ? (0, utils_js_1.numberToBytesLE)(reduced, fieldLen) : (0, utils_js_1.numberToBytesBE)(reduced, fieldLen);
}
}
});
// node_modules/@noble/curves/abstract/hash-to-curve.js
var require_hash_to_curve = __commonJS({
"node_modules/@noble/curves/abstract/hash-to-curve.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.expand_message_xmd = expand_message_xmd;
exports.expand_message_xof = expand_message_xof;
exports.hash_to_field = hash_to_field;
exports.isogenyMap = isogenyMap;
exports.createHasher = createHasher;
var modular_js_1 = require_modular();
var utils_js_1 = require_utils2();
var os2ip = utils_js_1.bytesToNumberBE;
function i2osp(value, length) {
anum(value);
anum(length);
if (value < 0 || value >= 1 << 8 * length) {
throw new Error(`bad I2OSP call: value=${value} length=${length}`);
}
const res = Array.from({ length }).fill(0);
for (let i = length - 1; i >= 0; i--) {
res[i] = value & 255;
value >>>= 8;
}
return new Uint8Array(res);
}
function strxor(a, b) {
const arr = new Uint8Array(a.length);
for (let i = 0; i < a.length; i++) {
arr[i] = a[i] ^ b[i];
}
return arr;
}
function anum(item) {
if (!Number.isSafeInteger(item))
throw new Error("number expected");
}
function expand_message_xmd(msg, DST, lenInBytes, H) {
(0, utils_js_1.abytes)(msg);
(0, utils_js_1.abytes)(DST);
anum(lenInBytes);
if (DST.length > 255)
DST = H((0, utils_js_1.concatBytes)((0, utils_js_1.utf8ToBytes)("H2C-OVERSIZE-DST-"), DST));
const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
const ell = Math.ceil(lenInBytes / b_in_bytes);
if (lenInBytes > 65535 || ell > 255)
throw new Error("expand_message_xmd: invalid lenInBytes");
const DST_prime = (0, utils_js_1.concatBytes)(DST, i2osp(DST.length, 1));
const Z_pad = i2osp(0, r_in_bytes);
const l_i_b_str = i2osp(lenInBytes, 2);
const b = new Array(ell);
const b_0 = H((0, utils_js_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
b[0] = H((0, utils_js_1.concatBytes)(b_0, i2osp(1, 1), DST_prime));
for (let i = 1; i <= ell; i++) {
const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
b[i] = H((0, utils_js_1.concatBytes)(...args));
}
const pseudo_random_bytes = (0, utils_js_1.concatBytes)(...b);
return pseudo_random_bytes.slice(0, lenInBytes);
}
function expand_message_xof(msg, DST, lenInBytes, k, H) {
(0, utils_js_1.abytes)(msg);
(0, utils_js_1.abytes)(DST);
anum(lenInBytes);
if (DST.length > 255) {
const dkLen = Math.ceil(2 * k / 8);
DST = H.create({ dkLen }).update((0, utils_js_1.utf8ToBytes)("H2C-OVERSIZE-DST-")).update(DST).digest();
}
if (lenInBytes > 65535 || DST.length > 255)
throw new Error("expand_message_xof: invalid lenInBytes");
return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest();
}
function hash_to_field(msg, count, options) {
(0, utils_js_1.validateObject)(options, {
DST: "stringOrUint8Array",
p: "bigint",
m: "isSafeInteger",
k: "isSafeInteger",
hash: "hash"
});
const { p, k, m, hash, expand, DST: _DST } = options;
(0, utils_js_1.abytes)(msg);
anum(count);
const DST = typeof _DST === "string" ? (0, utils_js_1.utf8ToBytes)(_DST) : _DST;
const log2p = p.toString(2).length;
const L = Math.ceil((log2p + k) / 8);
const len_in_bytes = count * m * L;
let prb;
if (expand === "xmd") {
prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
} else if (expand === "xof") {
prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
} else if (expand === "_internal_pass") {
prb = msg;
} else {
throw new Error('expand must be "xmd" or "xof"');
}
const u = new Array(count);
for (let i = 0; i < count; i++) {
const e = new Array(m);
for (let j = 0; j < m; j++) {
const elm_offset = L * (j + i * m);
const tv = prb.subarray(elm_offset, elm_offset + L);
e[j] = (0, modular_js_1.mod)(os2ip(tv), p);
}
u[i] = e;
}
return u;
}
function isogenyMap(field, map) {
const COEFF = map.map((i) => Array.from(i).reverse());
return (x, y) => {
const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
x = field.div(xNum, xDen);
y = field.mul(y, field.div(yNum, yDen));
return { x, y };
};
}
function createHasher(Point, mapToCurve, def) {
if (typeof mapToCurve !== "function")
throw new Error("mapToCurve() must be defined");
return {
// Encodes byte string to elliptic curve.
// hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
hashToCurve(msg, options) {
const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options });
const u0 = Point.fromAffine(mapToCurve(u[0]));
const u1 = Point.fromAffine(mapToCurve(u[1]));
const P = u0.add(u1).clearCofactor();
P.assertValidity();
return P;
},
// Encodes byte string to elliptic curve.
// encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
encodeToCurve(msg, options) {
const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options });
const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor();
P.assertValidity();
return P;
},
// Same as encodeToCurve, but without hash
mapToCurve(scalars) {
if (!Array.isArray(scalars))
throw new Error("mapToCurve: expected array of bigints");
for (const i of scalars)
if (typeof i !== "bigint")
throw new Error(`mapToCurve: expected array of bigints, got ${i} in array`);
const P = Point.fromAffine(mapToCurve(scalars)).clearCofactor();
P.assertValidity();
return P;
}
};
}
}
});
// node_modules/@noble/curves/abstract/curve.js
var require_curve = __commonJS({
"node_modules/@noble/curves/abstract/curve.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.wNAF = wNAF;
exports.pippenger = pippenger;
exports.validateBasic = validateBasic;
var modular_js_1 = require_modular();
var utils_js_1 = require_utils2();
var _0n = BigInt(0);
var _1n = BigInt(1);
var pointPrecomputes = /* @__PURE__ */ new WeakMap();
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
function wNAF(c, bits) {
const constTimeNegate = (condition, item) => {
const neg = item.negate();
return condition ? neg : item;
};
const validateW = (W) => {
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);
};
const opts = (W) => {
validateW(W);
const windows = Math.ceil(bits / W) + 1;
const windowSize = 2 ** (W - 1);
return { windows, windowSize };
};
return {
constTimeNegate,
// non-const time multiplication ladder
unsafeLadder(elm, n) {
let p = c.ZERO;
let d = elm;
while (n > _0n) {
if (n & _1n)
p = p.add(d);
d = d.double();
n >>= _1n;
}
return p;
},
/**
* Creates a wNAF precomputation window. Used for caching.
* Default window size is set by `utils.precompute()` and is equal to 8.
* Number of precomputed points depends on the curve size:
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
* - 𝑊 is the window size
* - 𝑛 is the bitlength of the curve order.
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
* @returns precomputed point tables flattened to a single array
*/
precomputeWindow(elm, W) {
const { windows, windowSize } = opts(W);
const points = [];
let p = elm;
let base = p;
for (let window = 0; window < windows; window++) {
base = p;
points.push(base);
for (let i = 1; i < windowSize; i++) {
base = base.add(p);
points.push(base);
}
p = base.double();
}
return points;
},
/**
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
* @param W window size
* @param precomputes precomputed tables
* @param n scalar (we don't check here, but should be less than curve order)
* @returns real and fake (for const-time) points
*/
wNAF(W, precomputes, n) {
const { windows, windowSize } = opts(W);
let p = c.ZERO;
let f = c.BASE;
const mask = BigInt(2 ** W - 1);
const maxNumber = 2 ** W;
const shiftBy = BigInt(W);
for (let window = 0; window < windows; window++) {
const offset = window * windowSize;
let wbits = Number(n & mask);
n >>= shiftBy;
if (wbits > windowSize) {
wbits -= maxNumber;
n += _1n;
}
const offset1 = offset;
const offset2 = offset + Math.abs(wbits) - 1;
const cond1 = window % 2 !== 0;
const cond2 = wbits < 0;
if (wbits === 0) {
f = f.add(constTimeNegate(cond1, precomputes[offset1]));
} else {
p = p.add(constTimeNegate(cond2, precomputes[offset2]));
}
}
return { p, f };
},
wNAFCached(P, n, transform) {
const W = pointWindowSizes.get(P) || 1;
let comp = pointPrecomputes.get(P);
if (!comp) {
comp = this.precomputeWindow(P, W);
if (W !== 1)
pointPrecomputes.set(P, transform(comp));
}
return this.wNAF(W, comp, n);
},
// We calculate precomputes for elliptic curve point multiplication
// using windowed method. This specifies window size and
// stores precomputed values. Usually only base point would be precomputed.
setWindowSize(P, W) {
validateW(W);
pointWindowSizes.set(P, W);
pointPrecomputes.delete(P);
}
};
}
function pippenger(c, field, points, scalars) {
if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)
throw new Error("arrays of points and scalars must have equal length");
scalars.forEach((s, i) => {
if (!field.isValid(s))
throw new Error(`wrong scalar at index ${i}`);
});
points.forEach((p, i) => {
if (!(p instanceof c))
throw new Error(`wrong point at index ${i}`);
});
const wbits = (0, utils_js_1.bitLen)(BigInt(points.length));
const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1;
const MASK = (1 << windowSize) - 1;
const buckets = new Array(MASK + 1).fill(c.ZERO);
const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;
let sum = c.ZERO;
for (let i = lastBits; i >= 0; i -= windowSize) {
buckets.fill(c.ZERO);
for (let j = 0; j < scalars.length; j++) {
const scalar = scalars[j];
const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK));
buckets[wbits2] = buckets[wbits2].add(points[j]);
}
let resI = c.ZERO;
for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {
sumI = sumI.add(buckets[j]);
resI = resI.add(sumI);
}
sum = sum.add(resI);
if (i !== 0)
for (let j = 0; j < windowSize; j++)
sum = sum.double();
}
return sum;
}
function validateBasic(curve) {
(0, modular_js_1.validateField)(curve.Fp);
(0, utils_js_1.validateObject)(curve, {
n: "bigint",
h: "bigint",
Gx: "field",
Gy: "field"
}, {
nBitLength: "isSafeInteger",
nByteLength: "isSafeInteger"
});
return Object.freeze({
...(0, modular_js_1.nLength)(curve.n, curve.nBitLength),
...curve,
...{ p: curve.Fp.ORDER }
});
}
}
});
// node_modules/@noble/curves/abstract/weierstrass.js
var require_weierstrass = __commonJS({
"node_modules/@noble/curves/abstract/weierstrass.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DER = void 0;
exports.weierstrassPoints = weierstrassPoints;
exports.weierstrass = weierstrass;
exports.SWUFpSqrtRatio = SWUFpSqrtRatio;
exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU;
var curve_js_1 = require_curve();
var mod = require_modular();
var ut = require_utils2();
var utils_js_1 = require_utils2();
function validateSigVerOpts(opts) {
if (opts.lowS !== void 0)
(0, utils_js_1.abool)("lowS", opts.lowS);
if (opts.prehash !== void 0)
(0, utils_js_1.abool)("prehash", opts.prehash);
}
function validatePointOpts(curve) {
const opts = (0, curve_js_1.validateBasic)(curve);
ut.validateObject(opts, {
a: "field",
b: "field"
}, {
allowedPrivateKeyLengths: "array",
wrapPrivateKey: "boolean",
isTorsionFree: "function",
clearCofactor: "function",
allowInfinityPoint: "boolean",
fromBytes: "function",
toBytes: "function"
});
const { endo, Fp, a } = opts;
if (endo) {
if (!Fp.eql(a, Fp.ZERO)) {
throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");
}
if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
throw new Error("Expected endomorphism with beta: bigint and splitScalar: function");
}
}
return Object.freeze({ ...opts });
}
var { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
exports.DER = {
// asn.1 DER encoding utils
Err: class DERErr extends Error {
constructor(m = "") {
super(m);
}
},
// Basic building block is TLV (Tag-Length-Value)
_tlv: {
encode: (tag, data) => {
const { Err: E } = exports.DER;
if (tag < 0 || tag > 256)
throw new E("tlv.encode: wrong tag");
if (data.length & 1)
throw new E("tlv.encode: unpadded data");
const dataLen = data.length / 2;
const len = ut.numberToHexUnpadded(dataLen);
if (len.length / 2 & 128)
throw new E("tlv.encode: long form length too big");
const lenLen = dataLen > 127 ? ut.numberToHexUnpadded(len.length / 2 | 128) : "";
return `${ut.numberToHexUnpadded(tag)}${lenLen}${len}${data}`;
},
// v - value, l - left bytes (unparsed)
decode(tag, data) {
const { Err: E } = exports.DER;
let pos = 0;
if (tag < 0 || tag > 256)
throw new E("tlv.encode: wrong tag");
if (data.length < 2 || data[pos++] !== tag)
throw new E("tlv.decode: wrong tlv");
const first = data[pos++];
const isLong = !!(first & 128);
let length = 0;
if (!isLong)
length = first;
else {
const lenLen = first & 127;
if (!lenLen)
throw new E("tlv.decode(long): indefinite length not supported");
if (lenLen > 4)
throw new E("tlv.decode(long): byte length is too big");
const lengthBytes = data.subarray(pos, pos + lenLen);
if (lengthBytes.length !== lenLen)
throw new E("tlv.decode: length bytes not complete");
if (lengthBytes[0] === 0)
throw new E("tlv.decode(long): zero leftmost byte");
for (const b of lengthBytes)
length = length << 8 | b;
pos += lenLen;
if (length < 128)
throw new E("tlv.decode(long): not minimal encoding");
}
const v = data.subarray(pos, pos + length);
if (v.length !== length)
throw new E("tlv.decode: wrong value length");
return { v, l: data.subarray(pos + length) };
}
},
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
// since we always use positive integers here. It must always be empty:
// - add zero byte if exists
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
_int: {
encode(num) {
const { Err: E } = exports.DER;
if (num < _0n)
throw new E("integer: negative integers are not allowed");
let hex = ut.numberToHexUnpadded(num);
if (Number.parseInt(hex[0], 16) & 8)
hex = "00" + hex;
if (hex.length & 1)
throw new E("unexpected assertion");
return hex;
},
decode(data) {
const { Err: E } = exports.DER;
if (data[0] & 128)
throw new E("Invalid signature integer: negative");
if (data[0] === 0 && !(data[1] & 128))
throw new E("Invalid signature integer: unnecessary leading zero");
return b2n(data);
}
},
toSig(hex) {
const { Err: E, _int: int, _tlv: tlv } = exports.DER;
const data = typeof hex === "string" ? h2b(hex) : hex;
ut.abytes(data);
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
if (seqLeftBytes.length)
throw new E("Invalid signature: left bytes after parsing");
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
if (sLeftBytes.length)
throw new E("Invalid signature: left bytes after parsing");
return { r: int.decode(rBytes), s: int.decode(sBytes) };
},
hexFromSig(sig) {
const { _tlv: tlv, _int: int } = exports.DER;
const seq = `${tlv.encode(2, int.encode(sig.r))}${tlv.encode(2, int.encode(sig.s))}`;
return tlv.encode(48, seq);
}
};
var _0n = BigInt(0);
var _1n = BigInt(1);
var _2n = BigInt(2);
var _3n = BigInt(3);
var _4n = BigInt(4);
function weierstrassPoints(opts) {
const CURVE = validatePointOpts(opts);
const { Fp } = CURVE;
const Fn = mod.Field(CURVE.n, CURVE.nBitLength);
const toBytes = CURVE.toBytes || ((_c, point, _isCompressed) => {
const a = point.toAffine();
return ut.concatBytes(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
});
const fromBytes = CURVE.fromBytes || ((bytes) => {
const tail = bytes.subarray(1);
const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
return { x, y };
});
function weierstrassEquation(x) {
const { a, b } = CURVE;
const x2 = Fp.sqr(x);
const x3 = Fp.mul(x2, x);
return Fp.add(Fp.add(x3, Fp.mul(x, a)), b);
}
if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
throw new Error("bad generator point: equation left != right");
function isWithinCurveOrder(num) {
return ut.inRange(num, _1n, CURVE.n);
}
function normPrivateKeyToScalar(key) {
const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
if (lengths && typeof key !== "bigint") {
if (ut.isBytes(key))
key = ut.bytesToHex(key);
if (typeof key !== "string" || !lengths.includes(key.length))
throw new Error("Invalid key");
key = key.padStart(nByteLength * 2, "0");
}
let num;
try {
num = typeof key === "bigint" ? key : ut.bytesToNumberBE((0, utils_js_1.ensureBytes)("private key", key, nByteLength));
} catch (error) {
throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
}
if (wrapPrivateKey)
num = mod.mod(num, N);
ut.aInRange("private key", num, _1n, N);
return num;
}
function assertPrjPoint(other) {
if (!(other instanceof Point))
throw new Error("ProjectivePoint expected");
}
const toAffineMemo = (0, utils_js_1.memoized)((p, iz) => {
const { px: x, py: y, pz: z } = p;
if (Fp.eql(z, Fp.ONE))
return { x, y };
const is0 = p.is0();
if (iz == null)
iz = is0 ? Fp.ONE : Fp.inv(z);
const ax = Fp.mul(x, iz);
const ay = Fp.mul(y, iz);
const zz = Fp.mul(z, iz);
if (is0)
return { x: Fp.ZERO, y: Fp.ZERO };
if (!Fp.eql(zz, Fp.ONE))
throw new Error("invZ was invalid");
return { x: ax, y: ay };
});
const assertValidMemo = (0, utils_js_1.memoized)((p) => {
if (p.is0()) {
if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
return;
throw new Error("bad point: ZERO");
}
const { x, y } = p.toAffine();
if (!Fp.isValid(x) || !Fp.isValid(y))
throw new Error("bad point: x or y not FE");
const left = Fp.sqr(y);
const right = weierstrassEquation(x);
if (!Fp.eql(left, right))
throw new Error("bad point: equation left != right");
if (!p.isTorsionFree())
throw new Error("bad point: not in prime-order subgroup");
return true;
});
class Point {
constructor(px, py, pz) {
this.px = px;
this.py = py;
this.pz = pz;
if (px == null || !Fp.isValid(px))
throw new Error("x required");
if (py == null || !Fp.isValid(py))
throw new Error("y required");
if (pz == null || !Fp.isValid(pz))
throw new Error("z required");
Object.freeze(this);
}
// Does not validate if the point is on-curve.
// Use fromHex instead, or call assertValidity() later.
static fromAffine(p) {
const { x, y } = p || {};
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
throw new Error("invalid affine point");
if (p instanceof Point)
throw new Error("projective point not allowed");
const is0 = (i) => Fp.eql(i, Fp.ZERO);
if (is0(x) && is0(y))
return Point.ZERO;
return new Point(x, y, Fp.ONE);
}
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
/**
* Takes a bunch of Projective Points but executes only one
* inversion on all of them. Inversion is very slow operation,
* so this improves performance massively.
* Optimization: converts a list of projective points to a list of identical points with Z=1.
*/
static normalizeZ(points) {
const toInv = Fp.invertBatch(points.map((p) => p.pz));
return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
}
/**
* Converts hash string or Uint8Array to Point.
* @param hex short/long ECDSA hex
*/
static fromHex(hex) {
const P = Point.fromAffine(fromBytes((0, utils_js_1.ensureBytes)("pointHex", hex)));
P.assertValidity();
return P;
}
// Multiplies generator point by privateKey.
static fromPrivateKey(privateKey) {
return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
}
// Multiscalar Multiplication
static msm(points, scalars) {
return (0, curve_js_1.pippenger)(Point, Fn, points, scalars);
}
// "Private method", don't use it directly
_setWindowSize(windowSize) {
wnaf.setWindowSize(this, windowSize);
}
// A point on curve is valid if it conforms to equation.
assertValidity() {
assertValidMemo(this);
}
hasEvenY() {
const { y } = this.toAffine();
if (Fp.isOdd)
return !Fp.isOdd(y);
throw new Error("Field doesn't support isOdd");
}
/**
* Compare one point to another.
*/
equals(other) {
assertPrjPoint(other);
const { px: X1, py: Y1, pz: Z1 } = this;
const { px: X2, py: Y2, pz: Z2 } = other;
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
return U1 && U2;
}
/**
* Flips point to one corresponding to (x, -y) in Affine coordinates.
*/
negate() {
return new Point(this.px, Fp.neg(this.py), this.pz);
}
// Renes-Costello-Batina exception-free doubling formula.
// There is 30% faster Jacobian formula, but it is not complete.
// https://eprint.iacr.org/2015/1060, algorithm 3
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
double() {
const { a, b } = CURVE;
const b3 = Fp.mul(b, _3n);
const { px: X1, py: Y1, pz: Z1 } = this;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
let t0 = Fp.mul(X1, X1);
let t1 = Fp.mul(Y1, Y1);
let t2 = Fp.mul(Z1, Z1);
let t3 = Fp.mul(X1, Y1);
t3 = Fp.add(t3, t3);
Z3 = Fp.mul(X1, Z1);
Z3 = Fp.add(Z3, Z3);
X3 = Fp.mul(a, Z3);
Y3 = Fp.mul(b3, t2);
Y3 = Fp.add(X3, Y3);
X3 = Fp.sub(t1, Y3);
Y3 = Fp.add(t1, Y3);
Y3 = Fp.mul(X3, Y3);
X3 = Fp.mul(t3, X3);
Z3 = Fp.mul(b3, Z3);
t2 = Fp.mul(a, t2);
t3 = Fp.sub(t0, t2);
t3 = Fp.mul(a, t3);
t3 = Fp.add(t3, Z3);
Z3 = Fp.add(t0, t0);
t0 = Fp.add(Z3, t0);
t0 = Fp.add(t0, t2);
t0 = Fp.mul(t0, t3);
Y3 = Fp.add(Y3, t0);
t2 = Fp.mul(Y1, Z1);
t2 = Fp.add(t2, t2);
t0 = Fp.mul(t2, t3);
X3 = Fp.sub(X3, t0);
Z3 = Fp.mul(t2, t1);
Z3 = Fp.add(Z3, Z3);
Z3 = Fp.add(Z3, Z3);
return new Point(X3, Y3, Z3);
}
// Renes-Costello-Batina exception-free addition formula.
// There is 30% faster Jacobian formula, but it is not complete.
// https://eprint.iacr.org/2015/1060, algorithm 1
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
add(other) {
assertPrjPoint(other);
const { px: X1, py: Y1, pz: Z1 } = this;
const { px: X2, py: Y2, pz: Z2 } = other;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
const a = CURVE.a;
const b3 = Fp.mul(CURVE.b, _3n);
let t0 = Fp.mul(X1, X2);
let t1 = Fp.mul(Y1, Y2);
let t2 = Fp.mul(Z1, Z2);
let t3 = Fp.add(X1, Y1);
let t4 = Fp.add(X2, Y2);
t3 = Fp.mul(t3, t4);
t4 = Fp.add(t0, t1);
t3 = Fp.sub(t3, t4);
t4 = Fp.add(X1, Z1);
let t5 = Fp.add(X2, Z2);
t4 = Fp.mul(t4, t5);
t5 = Fp.add(t0, t2);
t4 = Fp.sub(t4, t5);
t5 = Fp.add(Y1, Z1);
X3 = Fp.add(Y2, Z2);
t5 = Fp.mul(t5, X3);
X3 = Fp.add(t1, t2);
t5 = Fp.sub(t5, X3);
Z3 = Fp.mul(a, t4);
X3 = Fp.mul(b3, t2);
Z3 = Fp.add(X3, Z3);
X3 = Fp.sub(t1, Z3);
Z3 = Fp.add(t1, Z3);
Y3 = Fp.mul(X3, Z3);
t1 = Fp.add(t0, t0);
t1 = Fp.add(t1, t0);
t2 = Fp.mul(a, t2);
t4 = Fp.mul(b3, t4);
t1 = Fp.add(t1, t2);
t2 = Fp.sub(t0, t2);
t2 = Fp.mul(a, t2);
t4 = Fp.add(t4, t2);
t0 = Fp.mul(t1, t4);
Y3 = Fp.add(Y3, t0);
t0 = Fp.mul(t5, t4);
X3 = Fp.mul(t3, X3);
X3 = Fp.sub(X3, t0);
t0 = Fp.mul(t3, t1);
Z3 = Fp.mul(t5, Z3);
Z3 = Fp.add(Z3, t0);
return new Point(X3, Y3, Z3);
}
subtract(other) {
return this.add(other.negate());
}
is0() {
return this.equals(Point.ZERO);
}
wNAF(n) {
return wnaf.wNAFCached(this, n, Point.normalizeZ);
}
/**
* Non-constant-time multiplication. Uses double-and-add algorithm.
* It's faster, but should only be used when you don't care about
* an exposed private key e.g. sig verification, which works over *public* keys.
*/
multiplyUnsafe(sc) {
ut.aInRange("scalar", sc, _0n, CURVE.n);
const I = Point.ZERO;
if (sc === _0n)
return I;
if (sc === _1n)
return this;
const { endo } = CURVE;
if (!endo)
return wnaf.unsafeLadder(this, sc);
let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
let k1p = I;
let k2p = I;
let d = this;
while (k1 > _0n || k2 > _0n) {
if (k1 & _1n)
k1p = k1p.add(d);
if (k2 & _1n)
k2p = k2p.add(d);
d = d.double();
k1 >>= _1n;
k2 >>= _1n;
}
if (k1neg)
k1p = k1p.negate();
if (k2neg)
k2p = k2p.negate();
k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
return k1p.add(k2p);
}
/**
* Constant time multiplication.
* Uses wNAF method. Windowed method may be 10% faster,
* but takes 2x longer to generate and consumes 2x memory.
* Uses precomputes when available.
* Uses endomorphism for Koblitz curves.
* @param scalar by which the point would be multiplied
* @returns New point
*/
multiply(scalar) {
const { endo, n: N } = CURVE;
ut.aInRange("scalar", scalar, _1n, N);
let point, fake;
if (endo) {
const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);
let { p: k1p, f: f1p } = this.wNAF(k1);
let { p: k2p, f: f2p } = this.wNAF(k2);
k1p = wnaf.constTimeNegate(k1neg, k1p);
k2p = wnaf.constTimeNegate(k2neg, k2p);
k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
point = k1p.add(k2p);
fake = f1p.add(f2p);
} else {
const { p, f } = this.wNAF(scalar);
point = p;
fake = f;
}
return Point.normalizeZ([point, fake])[0];
}
/**
* Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
* Not using Strauss-Shamir trick: precomputation tables are faster.
* The trick could be useful if both P and Q are not G (not in our case).
* @returns non-zero affine point
*/
multiplyAndAddUnsafe(Q, a, b) {
const G = Point.BASE;
const mul = (P, a2) => a2 === _0n || a2 === _1n || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2);
const sum = mul(this, a).add(mul(Q, b));
return sum.is0() ? void 0 : sum;
}
// Converts Projective point to affine (x, y) coordinates.
// Can accept precomputed Z^-1 - for example, from invertBatch.
// (x, y, z) ∋ (x=x/z, y=y/z)
toAffine(iz) {
return toAffineMemo(this, iz);
}
isTorsionFree() {
const { h: cofactor, isTorsionFree } = CURVE;
if (cofactor === _1n)
return true;
if (isTorsionFree)
return isTorsionFree(Point, this);
throw new Error("isTorsionFree() has not been declared for the elliptic curve");
}
clearCofactor() {
const { h: cofactor, clearCofactor } = CURVE;
if (cofactor === _1n)
return this;
if (clearCofactor)
return clearCofactor(Point, this);
return this.multiplyUnsafe(CURVE.h);
}
toRawBytes(isCompressed = true) {
(0, utils_js_1.abool)("isCompressed", isCompressed);
this.assertValidity();
return toBytes(Point, this, isCompressed);
}
toHex(isCompressed = true) {
(0, utils_js_1.abool)("isCompressed", isCompressed);
return ut.bytesToHex(this.toRawBytes(isCompressed));
}
}
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
const _bits = CURVE.nBitLength;
const wnaf = (0, curve_js_1.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
return {
CURVE,
ProjectivePoint: Point,
normPrivateKeyToScalar,
weierstrassEquation,
isWithinCurveOrder
};
}
function validateOpts(curve) {
const opts = (0, curve_js_1.validateBasic)(curve);
ut.validateObject(opts, {
hash: "hash",
hmac: "function",
randomBytes: "function"
}, {
bits2int: "function",
bits2int_modN: "function",
lowS: "boolean"
});
return Object.freeze({ lowS: true, ...opts });
}
function weierstrass(curveDef) {
const CURVE = validateOpts(curveDef);
const { Fp, n: CURVE_ORDER } = CURVE;
const compressedLen = Fp.BYTES + 1;
const uncompressedLen = 2 * Fp.BYTES + 1;
function modN(a) {
return mod.mod(a, CURVE_ORDER);
}
function invN(a) {
return mod.invert(a, CURVE_ORDER);
}
const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
...CURVE,
toBytes(_c, point, isCompressed) {
const a = point.toAffine();
const x = Fp.toBytes(a.x);
const cat = ut.concatBytes;
(0, utils_js_1.abool)("isCompressed", isCompressed);
if (isCompressed) {
return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
} else {
return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y));
}
},
fromBytes(bytes) {
const len = bytes.length;
const head = bytes[0];
const tail = bytes.subarray(1);
if (len === compressedLen && (head === 2 || head === 3)) {
const x = ut.bytesToNumberBE(tail);
if (!ut.inRange(x, _1n, Fp.ORDER))
throw new Error("Point is not on curve");
const y2 = weierstrassEquation(x);
let y;
try {
y = Fp.sqrt(y2);
} catch (sqrtError) {
const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : "";
throw new Error("Point is not on curve" + suffix);
}
const isYOdd = (y & _1n) === _1n;
const isHeadOdd = (head & 1) === 1;
if (isHeadOdd !== isYOdd)
y = Fp.neg(y);
return { x, y };
} else if (len === uncompressedLen && head === 4) {
const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
return { x, y };
} else {
throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
}
}
});
const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));
function isBiggerThanHalfOrder(number) {
const HALF = CURVE_ORDER >> _1n;
return number > HALF;
}
function normalizeS(s) {
return isBiggerThanHalfOrder(s) ? modN(-s) : s;
}
const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));
class Signature {
constructor(r, s, recovery) {
this.r = r;
this.s = s;
this.recovery = recovery;
this.assertValidity();
}
// pair (bytes of r, bytes of s)
static fromCompact(hex) {
const l = CURVE.nByteLength;
hex = (0, utils_js_1.ensureBytes)("compactSignature", hex, l * 2);
return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
}
// DER encoded ECDSA signature
// https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
static fromDER(hex) {
const { r, s } = exports.DER.toSig((0, utils_js_1.ensureBytes)("DER", hex));
return new Signature(r, s);
}
assertValidity() {
ut.aInRange("r", this.r, _1n, CURVE_ORDER);
ut.aInRange("s", this.s, _1n, CURVE_ORDER);
}
addRecoveryBit(recovery) {
return new Signature(this.r, this.s, recovery);
}
recoverPublicKey(msgHash) {
const { r, s, recovery: rec } = this;
const h = bits2int_modN((0, utils_js_1.ensureBytes)("msgHash", msgHash));
if (rec == null || ![0, 1, 2, 3].includes(rec))
throw new Error("recovery id invalid");
const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
if (radj >= Fp.ORDER)
throw new Error("recovery id 2 or 3 invalid");
const prefix = (rec & 1) === 0 ? "02" : "03";
const R = Point.fromHex(prefix + numToNByteStr(radj));
const ir = invN(radj);
const u1 = modN(-h * ir);
const u2 = modN(s * ir);
const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
if (!Q)
throw new Error("point at infinify");
Q.assertValidity();
return Q;
}
// Signatures should be low-s, to prevent malleability.
hasHighS() {
return isBiggerThanHalfOrder(this.s);
}
normalizeS() {
return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
}
// DER-encoded
toDERRawBytes() {
return ut.hexToBytes(this.toDERHex());
}
toDERHex() {
return exports.DER.hexFromSig({ r: this.r, s: this.s });
}
// padded bytes of r, then padded bytes of s
toCompactRawBytes() {
return ut.hexToBytes(this.toCompactHex());
}
toCompactHex() {
return numToNByteStr(this.r) + numToNByteStr(this.s);
}
}
const utils = {
isValidPrivateKey(privateKey) {
try {
normPrivateKeyToScalar(privateKey);
return true;
} catch (error) {
return false;
}
},
normPrivateKeyToScalar,
/**
* Produces cryptographically secure private key from random of size
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
*/
randomPrivateKey: () => {
const length = mod.getMinHashLength(CURVE.n);
return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);
},
/**
* Creates precompute table for an arbitrary EC point. Makes point "cached".
* Allows to massively speed-up `point.multiply(scalar)`.
* @returns cached point
* @example
* const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
* fast.multiply(privKey); // much faster ECDH now
*/
precompute(windowSize = 8, point = Point.BASE) {
point._setWindowSize(windowSize);
point.multiply(BigInt(3));
return point;
}
};
function getPublicKey(privateKey, isCompressed = true) {
return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
}
function isProbPub(item) {
const arr = ut.isBytes(item);
const str = typeof item === "string";
const len = (arr || str) && item.length;
if (arr)
return len === compressedLen || len === uncompressedLen;
if (str)
return len === 2 * compressedLen || len === 2 * uncompressedLen;
if (item instanceof Point)
return true;
return false;
}
function getSharedSecret(privateA, publicB, isCompressed = true) {
if (isProbPub(privateA))
throw new Error("first arg must be private key");
if (!isProbPub(publicB))
throw new Error("second arg must be public key");
const b = Point.fromHex(publicB);
return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
}
const bits2int = CURVE.bits2int || function(bytes) {
const num = ut.bytesToNumberBE(bytes);
const delta = bytes.length * 8 - CURVE.nBitLength;
return delta > 0 ? num >> BigInt(delta) : num;
};
const bits2int_modN = CURVE.bits2int_modN || function(bytes) {
return modN(bits2int(bytes));
};
const ORDER_MASK = ut.bitMask(CURVE.nBitLength);
function int2octets(num) {
ut.aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK);
return ut.numberToBytesBE(num, CURVE.nByteLength);
}
function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
if (["recovered", "canonical"].some((k) => k in opts))
throw new Error("sign() legacy options not supported");
const { hash, randomBytes: randomBytes2 } = CURVE;
let { lowS, prehash, extraEntropy: ent } = opts;
if (lowS == null)
lowS = true;
msgHash = (0, utils_js_1.ensureBytes)("msgHash", msgHash);
validateSigVerOpts(opts);
if (prehash)
msgHash = (0, utils_js_1.ensureBytes)("prehashed msgHash", hash(msgHash));
const h1int = bits2int_modN(msgHash);
const d = normPrivateKeyToScalar(privateKey);
const seedArgs = [int2octets(d), int2octets(h1int)];
if (ent != null && ent !== false) {
const e = ent === true ? randomBytes2(Fp.BYTES) : ent;
seedArgs.push((0, utils_js_1.ensureBytes)("extraEntropy", e));
}
const seed = ut.concatBytes(...seedArgs);
const m = h1int;
function k2sig(kBytes) {
const k = bits2int(kBytes);
if (!isWithinCurveOrder(k))
return;
const ik = invN(k);
const q = Point.BASE.multiply(k).toAffine();
const r = modN(q.x);
if (r === _0n)
return;
const s = modN(ik * modN(m + r * d));
if (s === _0n)
return;
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n);
let normS = s;
if (lowS && isBiggerThanHalfOrder(s)) {
normS = normalizeS(s);
recovery ^= 1;
}
return new Signature(r, normS, recovery);
}
return { seed, k2sig };
}
const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
function sign2(msgHash, privKey, opts = defaultSigOpts) {
const { seed, k2sig } = prepSig(msgHash, privKey, opts);
const C = CURVE;
const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
return drbg(seed, k2sig);
}
Point.BASE._setWindowSize(8);
function verify2(signature, msgHash, publicKey, opts = defaultVerOpts) {
const sg = signature;
msgHash = (0, utils_js_1.ensureBytes)("msgHash", msgHash);
publicKey = (0, utils_js_1.ensureBytes)("publicKey", publicKey);
if ("strict" in opts)
throw new Error("options.strict was renamed to lowS");
validateSigVerOpts(opts);
const { lowS, prehash } = opts;
let _sig = void 0;
let P;
try {
if (typeof sg === "string" || ut.isBytes(sg)) {
try {
_sig = Signature.fromDER(sg);
} catch (derError) {
if (!(derError instanceof exports.DER.Err))
throw derError;
_sig = Signature.fromCompact(sg);
}
} else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") {
const { r: r2, s: s2 } = sg;
_sig = new Signature(r2, s2);
} else {
throw new Error("PARSE");
}
P = Point.fromHex(publicKey);
} catch (error) {
if (error.message === "PARSE")
throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
return false;
}
if (lowS && _sig.hasHighS())
return false;
if (prehash)
msgHash = CURVE.hash(msgHash);
const { r, s } = _sig;
const h = bits2int_modN(msgHash);
const is = invN(s);
const u1 = modN(h * is);
const u2 = modN(r * is);
const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine();
if (!R)
return false;
const v = modN(R.x);
return v === r;
}
return {
CURVE,
getPublicKey,
getSharedSecret,
sign: sign2,
verify: verify2,
ProjectivePoint: Point,
Signature,
utils
};
}
function SWUFpSqrtRatio(Fp, Z) {
const q = Fp.ORDER;
let l = _0n;
for (let o = q - _1n; o % _2n === _0n; o /= _2n)
l += _1n;
const c1 = l;
const _2n_pow_c1_1 = _2n << c1 - _1n - _1n;
const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
const c2 = (q - _1n) / _2n_pow_c1;
const c3 = (c2 - _1n) / _2n;
const c4 = _2n_pow_c1 - _1n;
const c5 = _2n_pow_c1_1;
const c6 = Fp.pow(Z, c2);
const c7 = Fp.pow(Z, (c2 + _1n) / _2n);
let sqrtRatio = (u, v) => {
let tv1 = c6;
let tv2 = Fp.pow(v, c4);
let tv3 = Fp.sqr(tv2);
tv3 = Fp.mul(tv3, v);
let tv5 = Fp.mul(u, tv3);
tv5 = Fp.pow(tv5, c3);
tv5 = Fp.mul(tv5, tv2);
tv2 = Fp.mul(tv5, v);
tv3 = Fp.mul(tv5, u);
let tv4 = Fp.mul(tv3, tv2);
tv5 = Fp.pow(tv4, c5);
let isQR = Fp.eql(tv5, Fp.ONE);
tv2 = Fp.mul(tv3, c7);
tv5 = Fp.mul(tv4, tv1);
tv3 = Fp.cmov(tv2, tv3, isQR);
tv4 = Fp.cmov(tv5, tv4, isQR);
for (let i = c1; i > _1n; i--) {
let tv52 = i - _2n;
tv52 = _2n << tv52 - _1n;
let tvv5 = Fp.pow(tv4, tv52);
const e1 = Fp.eql(tvv5, Fp.ONE);
tv2 = Fp.mul(tv3, tv1);
tv1 = Fp.mul(tv1, tv1);
tvv5 = Fp.mul(tv4, tv1);
tv3 = Fp.cmov(tv2, tv3, e1);
tv4 = Fp.cmov(tvv5, tv4, e1);
}
return { isValid: isQR, value: tv3 };
};
if (Fp.ORDER % _4n === _3n) {
const c12 = (Fp.ORDER - _3n) / _4n;
const c22 = Fp.sqrt(Fp.neg(Z));
sqrtRatio = (u, v) => {
let tv1 = Fp.sqr(v);
const tv2 = Fp.mul(u, v);
tv1 = Fp.mul(tv1, tv2);
let y1 = Fp.pow(tv1, c12);
y1 = Fp.mul(y1, tv2);
const y2 = Fp.mul(y1, c22);
const tv3 = Fp.mul(Fp.sqr(y1), v);
const isQR = Fp.eql(tv3, u);
let y = Fp.cmov(y2, y1, isQR);
return { isValid: isQR, value: y };
};
}
return sqrtRatio;
}
function mapToCurveSimpleSWU(Fp, opts) {
mod.validateField(Fp);
if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))
throw new Error("mapToCurveSimpleSWU: invalid opts");
const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);
if (!Fp.isOdd)
throw new Error("Fp.isOdd is not implemented!");
return (u) => {
let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
tv1 = Fp.sqr(u);
tv1 = Fp.mul(tv1, opts.Z);
tv2 = Fp.sqr(tv1);
tv2 = Fp.add(tv2, tv1);
tv3 = Fp.add(tv2, Fp.ONE);
tv3 = Fp.mul(tv3, opts.B);
tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO));
tv4 = Fp.mul(tv4, opts.A);
tv2 = Fp.sqr(tv3);
tv6 = Fp.sqr(tv4);
tv5 = Fp.mul(tv6, opts.A);
tv2 = Fp.add(tv2, tv5);
tv2 = Fp.mul(tv2, tv3);
tv6 = Fp.mul(tv6, tv4);
tv5 = Fp.mul(tv6, opts.B);
tv2 = Fp.add(tv2, tv5);
x = Fp.mul(tv1, tv3);
const { isValid, value } = sqrtRatio(tv2, tv6);
y = Fp.mul(tv1, u);
y = Fp.mul(y, value);
x = Fp.cmov(x, tv3, isValid);
y = Fp.cmov(y, value, isValid);
const e1 = Fp.isOdd(u) === Fp.isOdd(y);
y = Fp.cmov(Fp.neg(y), y, e1);
x = Fp.div(x, tv4);
return { x, y };
};
}
}
});
// node_modules/@noble/curves/abstract/bls.js
var require_bls = __commonJS({
"node_modules/@noble/curves/abstract/bls.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bls = bls;
var modular_js_1 = require_modular();
var utils_js_1 = require_utils2();
var hash_to_curve_js_1 = require_hash_to_curve();
var weierstrass_js_1 = require_weierstrass();
var _0n = BigInt(0);
var _1n = BigInt(1);
var _2n = BigInt(2);
var _3n = BigInt(3);
function NAfDecomposition(a) {
const res = [];
for (; a > _1n; a >>= _1n) {
if ((a & _1n) === _0n)
res.unshift(0);
else if ((a & _3n) === _3n) {
res.unshift(-1);
a += _1n;
} else
res.unshift(1);
}
return res;
}
function bls(CURVE) {
const { Fp, Fr: Fr2, Fp2, Fp6, Fp12 } = CURVE.fields;
const BLS_X_IS_NEGATIVE = CURVE.params.xNegative;
const TWIST = CURVE.params.twistType;
const G1_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr2.ORDER, ...CURVE.G1 });
const G1 = Object.assign(G1_, (0, hash_to_curve_js_1.createHasher)(G1_.ProjectivePoint, CURVE.G1.mapToCurve, {
...CURVE.htfDefaults,
...CURVE.G1.htfDefaults
}));
const G2_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr2.ORDER, ...CURVE.G2 });
const G2 = Object.assign(G2_, (0, hash_to_curve_js_1.createHasher)(G2_.ProjectivePoint, CURVE.G2.mapToCurve, {
...CURVE.htfDefaults,
...CURVE.G2.htfDefaults
}));
let lineFunction;
if (TWIST === "multiplicative") {
lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py));
} else if (TWIST === "divisive") {
lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0);
} else
throw new Error("bls: unknown twist type");
const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n));
function pointDouble(ell, Rx, Ry, Rz) {
const t0 = Fp2.sqr(Ry);
const t1 = Fp2.sqr(Rz);
const t2 = Fp2.mulByB(Fp2.mul(t1, _3n));
const t3 = Fp2.mul(t2, _3n);
const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0);
const c0 = Fp2.sub(t2, t0);
const c1 = Fp2.mul(Fp2.sqr(Rx), _3n);
const c2 = Fp2.neg(t4);
ell.push([c0, c1, c2]);
Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2);
Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n));
Rz = Fp2.mul(t0, t4);
return { Rx, Ry, Rz };
}
function pointAdd(ell, Rx, Ry, Rz, Qx, Qy) {
const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz));
const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz));
const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy));
const c1 = Fp2.neg(t0);
const c2 = t1;
ell.push([c0, c1, c2]);
const t2 = Fp2.sqr(t1);
const t3 = Fp2.mul(t2, t1);
const t4 = Fp2.mul(t2, Rx);
const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz));
Rx = Fp2.mul(t1, t5);
Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry));
Rz = Fp2.mul(Rz, t3);
return { Rx, Ry, Rz };
}
const ATE_NAF = NAfDecomposition(CURVE.params.ateLoopSize);
const calcPairingPrecomputes = (0, utils_js_1.memoized)((point) => {
const p = point;
const { x, y } = p.toAffine();
const Qx = x, Qy = y, negQy = Fp2.neg(y);
let Rx = Qx, Ry = Qy, Rz = Fp2.ONE;
const ell = [];
for (const bit of ATE_NAF) {
const cur = [];
({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz));
if (bit)
({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy));
ell.push(cur);
}
if (CURVE.postPrecompute) {
const last = ell[ell.length - 1];
CURVE.postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last));
}
return ell;
});
function millerLoopBatch(pairs, withFinalExponent = false) {
let f12 = Fp12.ONE;
if (pairs.length) {
const ellLen = pairs[0][0].length;
for (let i = 0; i < ellLen; i++) {
f12 = Fp12.sqr(f12);
for (const [ell, Px, Py] of pairs) {
for (const [c0, c1, c2] of ell[i])
f12 = lineFunction(c0, c1, c2, f12, Px, Py);
}
}
}
if (BLS_X_IS_NEGATIVE)
f12 = Fp12.conjugate(f12);
return withFinalExponent ? Fp12.finalExponentiate(f12) : f12;
}
function pairingBatch(pairs, withFinalExponent = true) {
const res = [];
G1.ProjectivePoint.normalizeZ(pairs.map(({ g1 }) => g1));
G2.ProjectivePoint.normalizeZ(pairs.map(({ g2 }) => g2));
for (const { g1, g2 } of pairs) {
if (g1.equals(G1.ProjectivePoint.ZERO) || g2.equals(G2.ProjectivePoint.ZERO))
throw new Error("pairing is not available for ZERO point");
g1.assertValidity();
g2.assertValidity();
const Qa = g1.toAffine();
res.push([calcPairingPrecomputes(g2), Qa.x, Qa.y]);
}
return millerLoopBatch(res, withFinalExponent);
}
function pairing(Q, P, withFinalExponent = true) {
return pairingBatch([{ g1: Q, g2: P }], withFinalExponent);
}
const utils = {
randomPrivateKey: () => {
const length = (0, modular_js_1.getMinHashLength)(Fr2.ORDER);
return (0, modular_js_1.mapHashToField)(CURVE.randomBytes(length), Fr2.ORDER);
},
calcPairingPrecomputes
};
const { ShortSignature } = CURVE.G1;
const { Signature } = CURVE.G2;
function normP1(point) {
return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point);
}
function normP1Hash(point, htfOpts) {
return point instanceof G1.ProjectivePoint ? point : G1.hashToCurve((0, utils_js_1.ensureBytes)("point", point), htfOpts);
}
function normP2(point) {
return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point);
}
function normP2Hash(point, htfOpts) {
return point instanceof G2.ProjectivePoint ? point : G2.hashToCurve((0, utils_js_1.ensureBytes)("point", point), htfOpts);
}
function getPublicKey(privateKey) {
return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true);
}
function getPublicKeyForShortSignatures(privateKey) {
return G2.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true);
}
function sign2(message, privateKey, htfOpts) {
const msgPoint = normP2Hash(message, htfOpts);
msgPoint.assertValidity();
const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
if (message instanceof G2.ProjectivePoint)
return sigPoint;
return Signature.toRawBytes(sigPoint);
}
function signShortSignature(message, privateKey, htfOpts) {
const msgPoint = normP1Hash(message, htfOpts);
msgPoint.assertValidity();
const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
if (message instanceof G1.ProjectivePoint)
return sigPoint;
return ShortSignature.toRawBytes(sigPoint);
}
function verify2(signature, message, publicKey, htfOpts) {
const P = normP1(publicKey);
const Hm = normP2Hash(message, htfOpts);
const G = G1.ProjectivePoint.BASE;
const S = normP2(signature);
const exp = pairingBatch([
{ g1: P.negate(), g2: Hm },
// ePHM = pairing(P.negate(), Hm, false);
{ g1: G, g2: S }
// eGS = pairing(G, S, false);
]);
return Fp12.eql(exp, Fp12.ONE);
}
function verifyShortSignature(signature, message, publicKey, htfOpts) {
const P = normP2(publicKey);
const Hm = normP1Hash(message, htfOpts);
const G = G2.ProjectivePoint.BASE;
const S = normP1(signature);
const exp = pairingBatch([
{ g1: Hm, g2: P },
// eHmP = pairing(Hm, P, false);
{ g1: S, g2: G.negate() }
// eSG = pairing(S, G.negate(), false);
]);
return Fp12.eql(exp, Fp12.ONE);
}
function aggregatePublicKeys(publicKeys) {
if (!publicKeys.length)
throw new Error("Expected non-empty array");
const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO);
const aggAffine = agg;
if (publicKeys[0] instanceof G1.ProjectivePoint) {
aggAffine.assertValidity();
return aggAffine;
}
return aggAffine.toRawBytes(true);
}
function aggregateSignatures(signatures) {
if (!signatures.length)
throw new Error("Expected non-empty array");
const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO);
const aggAffine = agg;
if (signatures[0] instanceof G2.ProjectivePoint) {
aggAffine.assertValidity();
return aggAffine;
}
return Signature.toRawBytes(aggAffine);
}
function aggregateShortSignatures(signatures) {
if (!signatures.length)
throw new Error("Expected non-empty array");
const agg = signatures.map(normP1).reduce((sum, s) => sum.add(s), G1.ProjectivePoint.ZERO);
const aggAffine = agg;
if (signatures[0] instanceof G1.ProjectivePoint) {
aggAffine.assertValidity();
return aggAffine;
}
return ShortSignature.toRawBytes(aggAffine);
}
function verifyBatch(signature, messages, publicKeys, htfOpts) {
if (!messages.length)
throw new Error("Expected non-empty messages array");
if (publicKeys.length !== messages.length)
throw new Error("Pubkey count should equal msg count");
const sig = normP2(signature);
const nMessages = messages.map((i) => normP2Hash(i, htfOpts));
const nPublicKeys = publicKeys.map(normP1);
const messagePubKeyMap = /* @__PURE__ */ new Map();
for (let i = 0; i < nPublicKeys.length; i++) {
const pub = nPublicKeys[i];
const msg = nMessages[i];
let keys = messagePubKeyMap.get(msg);
if (keys === void 0) {
keys = [];
messagePubKeyMap.set(msg, keys);
}
keys.push(pub);
}
const paired = [];
try {
for (const [msg, keys] of messagePubKeyMap) {
const groupPublicKey = keys.reduce((acc, msg2) => acc.add(msg2));
paired.push({ g1: groupPublicKey, g2: msg });
}
paired.push({ g1: G1.ProjectivePoint.BASE.negate(), g2: sig });
return Fp12.eql(pairingBatch(paired), Fp12.ONE);
} catch {
return false;
}
}
G1.ProjectivePoint.BASE._setWindowSize(4);
return {
getPublicKey,
getPublicKeyForShortSignatures,
sign: sign2,
signShortSignature,
verify: verify2,
verifyBatch,
verifyShortSignature,
aggregatePublicKeys,
aggregateSignatures,
aggregateShortSignatures,
millerLoopBatch,
pairing,
pairingBatch,
G1,
G2,
Signature,
ShortSignature,
fields: {
Fr: Fr2,
Fp,
Fp2,
Fp6,
Fp12
},
params: {
ateLoopSize: CURVE.params.ateLoopSize,
r: CURVE.params.r,
G1b: CURVE.G1.b,
G2b: CURVE.G2.b
},
utils
};
}
}
});
// node_modules/@noble/curves/abstract/tower.js
var require_tower = __commonJS({
"node_modules/@noble/curves/abstract/tower.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.psiFrobenius = psiFrobenius;
exports.tower12 = tower12;
var mod = require_modular();
var utils_js_1 = require_utils2();
var _0n = BigInt(0);
var _1n = BigInt(1);
var _2n = BigInt(2);
var _3n = BigInt(3);
function calcFrobeniusCoefficients(Fp, nonResidue, modulus, degree, num = 1, divisor) {
const _divisor = BigInt(divisor === void 0 ? degree : divisor);
const towerModulus = modulus ** BigInt(degree);
const res = [];
for (let i = 0; i < num; i++) {
const a = BigInt(i + 1);
const powers = [];
for (let j = 0, qPower = _1n; j < degree; j++) {
const power = (a * qPower - a) / _divisor % towerModulus;
powers.push(Fp.pow(nonResidue, power));
qPower *= modulus;
}
res.push(powers);
}
return res;
}
function psiFrobenius(Fp, Fp2, base) {
const PSI_X = Fp2.pow(base, (Fp.ORDER - _1n) / _3n);
const PSI_Y = Fp2.pow(base, (Fp.ORDER - _1n) / _2n);
function psi(x, y) {
const x2 = Fp2.mul(Fp2.frobeniusMap(x, 1), PSI_X);
const y2 = Fp2.mul(Fp2.frobeniusMap(y, 1), PSI_Y);
return [x2, y2];
}
const PSI2_X = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _3n);
const PSI2_Y = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _2n);
if (!Fp2.eql(PSI2_Y, Fp2.neg(Fp2.ONE)))
throw new Error("psiFrobenius: PSI2_Y!==-1");
function psi2(x, y) {
return [Fp2.mul(x, PSI2_X), Fp2.neg(y)];
}
const mapAffine = (fn) => (c, P) => {
const affine = P.toAffine();
const p = fn(affine.x, affine.y);
return c.fromAffine({ x: p[0], y: p[1] });
};
const G2psi = mapAffine(psi);
const G2psi2 = mapAffine(psi2);
return { psi, psi2, G2psi, G2psi2, PSI_X, PSI_Y, PSI2_X, PSI2_Y };
}
function tower12(opts) {
const { ORDER } = opts;
const Fp = mod.Field(ORDER);
const FpNONRESIDUE = Fp.create(opts.NONRESIDUE || BigInt(-1));
const FpLegendre = mod.FpLegendre(ORDER);
const Fpdiv2 = Fp.div(Fp.ONE, _2n);
const FP2_FROBENIUS_COEFFICIENTS = calcFrobeniusCoefficients(Fp, FpNONRESIDUE, Fp.ORDER, 2)[0];
const Fp2Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({
c0: Fp.add(c0, r0),
c1: Fp.add(c1, r1)
});
const Fp2Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({
c0: Fp.sub(c0, r0),
c1: Fp.sub(c1, r1)
});
const Fp2Multiply = ({ c0, c1 }, rhs) => {
if (typeof rhs === "bigint")
return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) };
const { c0: r0, c1: r1 } = rhs;
let t1 = Fp.mul(c0, r0);
let t2 = Fp.mul(c1, r1);
const o0 = Fp.sub(t1, t2);
const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2));
return { c0: o0, c1: o1 };
};
const Fp2Square = ({ c0, c1 }) => {
const a = Fp.add(c0, c1);
const b = Fp.sub(c0, c1);
const c = Fp.add(c0, c0);
return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) };
};
const Fp2fromBigTuple = (tuple) => {
if (tuple.length !== 2)
throw new Error("Invalid tuple");
const fps = tuple.map((n) => Fp.create(n));
return { c0: fps[0], c1: fps[1] };
};
const FP2_ORDER = ORDER * ORDER;
const Fp2Nonresidue = Fp2fromBigTuple(opts.FP2_NONRESIDUE);
const Fp2 = {
ORDER: FP2_ORDER,
NONRESIDUE: Fp2Nonresidue,
BITS: (0, utils_js_1.bitLen)(FP2_ORDER),
BYTES: Math.ceil((0, utils_js_1.bitLen)(FP2_ORDER) / 8),
MASK: (0, utils_js_1.bitMask)((0, utils_js_1.bitLen)(FP2_ORDER)),
ZERO: { c0: Fp.ZERO, c1: Fp.ZERO },
ONE: { c0: Fp.ONE, c1: Fp.ZERO },
create: (num) => num,
isValid: ({ c0, c1 }) => typeof c0 === "bigint" && typeof c1 === "bigint",
is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1),
eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp.eql(c0, r0) && Fp.eql(c1, r1),
neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }),
pow: (num, power) => mod.FpPow(Fp2, num, power),
invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums),
// Normalized
add: Fp2Add,
sub: Fp2Subtract,
mul: Fp2Multiply,
sqr: Fp2Square,
// NonNormalized stuff
addN: Fp2Add,
subN: Fp2Subtract,
mulN: Fp2Multiply,
sqrN: Fp2Square,
// Why inversion for bigint inside Fp instead of Fp2? it is even used in that context?
div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === "bigint" ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)),
inv: ({ c0: a, c1: b }) => {
const factor = Fp.inv(Fp.create(a * a + b * b));
return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) };
},
sqrt: (num) => {
if (opts.Fp2sqrt)
return opts.Fp2sqrt(num);
const { c0, c1 } = num;
if (Fp.is0(c1)) {
if (Fp.eql(FpLegendre(Fp, c0), Fp.ONE))
return Fp2.create({ c0: Fp.sqrt(c0), c1: Fp.ZERO });
else
return Fp2.create({ c0: Fp.ZERO, c1: Fp.sqrt(Fp.div(c0, FpNONRESIDUE)) });
}
const a = Fp.sqrt(Fp.sub(Fp.sqr(c0), Fp.mul(Fp.sqr(c1), FpNONRESIDUE)));
let d = Fp.mul(Fp.add(a, c0), Fpdiv2);
const legendre = FpLegendre(Fp, d);
if (!Fp.is0(legendre) && !Fp.eql(legendre, Fp.ONE))
d = Fp.sub(d, a);
const a0 = Fp.sqrt(d);
const candidateSqrt = Fp2.create({ c0: a0, c1: Fp.div(Fp.mul(c1, Fpdiv2), a0) });
if (!Fp2.eql(Fp2.sqr(candidateSqrt), num))
throw new Error("Cannot find square root");
const x1 = candidateSqrt;
const x2 = Fp2.neg(x1);
const { re: re1, im: im1 } = Fp2.reim(x1);
const { re: re2, im: im2 } = Fp2.reim(x2);
if (im1 > im2 || im1 === im2 && re1 > re2)
return x1;
return x2;
},
// Same as sgn0_m_eq_2 in RFC 9380
isOdd: (x) => {
const { re: x0, im: x1 } = Fp2.reim(x);
const sign_0 = x0 % _2n;
const zero_0 = x0 === _0n;
const sign_1 = x1 % _2n;
return BigInt(sign_0 || zero_0 && sign_1) == _1n;
},
// Bytes util
fromBytes(b) {
if (b.length !== Fp2.BYTES)
throw new Error(`fromBytes wrong length=${b.length}`);
return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) };
},
toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp.toBytes(c0), Fp.toBytes(c1)),
cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({
c0: Fp.cmov(c0, r0, c),
c1: Fp.cmov(c1, r1, c)
}),
reim: ({ c0, c1 }) => ({ re: c0, im: c1 }),
// multiply by u + 1
mulByNonresidue: ({ c0, c1 }) => Fp2.mul({ c0, c1 }, Fp2Nonresidue),
mulByB: opts.Fp2mulByB,
fromBigTuple: Fp2fromBigTuple,
frobeniusMap: ({ c0, c1 }, power) => ({
c0,
c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2])
})
};
const Fp6Add = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({
c0: Fp2.add(c0, r0),
c1: Fp2.add(c1, r1),
c2: Fp2.add(c2, r2)
});
const Fp6Subtract = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({
c0: Fp2.sub(c0, r0),
c1: Fp2.sub(c1, r1),
c2: Fp2.sub(c2, r2)
});
const Fp6Multiply = ({ c0, c1, c2 }, rhs) => {
if (typeof rhs === "bigint") {
return {
c0: Fp2.mul(c0, rhs),
c1: Fp2.mul(c1, rhs),
c2: Fp2.mul(c2, rhs)
};
}
const { c0: r0, c1: r1, c2: r2 } = rhs;
const t0 = Fp2.mul(c0, r0);
const t1 = Fp2.mul(c1, r1);
const t2 = Fp2.mul(c2, r2);
return {
// t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1)
c0: Fp2.add(t0, Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))),
// (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1)
c1: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), Fp2.mulByNonresidue(t2)),
// T1 + (c0 + c2) * (r0 + r2) - T0 + T2
c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2))
};
};
const Fp6Square = ({ c0, c1, c2 }) => {
let t0 = Fp2.sqr(c0);
let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n);
let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n);
let t4 = Fp2.sqr(c2);
return {
c0: Fp2.add(Fp2.mulByNonresidue(t3), t0),
// T3 * (u + 1) + T0
c1: Fp2.add(Fp2.mulByNonresidue(t4), t1),
// T4 * (u + 1) + T1
// T1 + (c0 - c1 + c2)² + T3 - T0 - T4
c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4)
};
};
const [FP6_FROBENIUS_COEFFICIENTS_1, FP6_FROBENIUS_COEFFICIENTS_2] = calcFrobeniusCoefficients(Fp2, Fp2Nonresidue, Fp.ORDER, 6, 2, 3);
const Fp6 = {
ORDER: Fp2.ORDER,
// TODO: unused, but need to verify
BITS: 3 * Fp2.BITS,
BYTES: 3 * Fp2.BYTES,
MASK: (0, utils_js_1.bitMask)(3 * Fp2.BITS),
ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO },
ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO },
create: (num) => num,
isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2),
is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2),
neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }),
eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2),
sqrt: utils_js_1.notImplemented,
// Do we need division by bigint at all? Should be done via order:
div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === "bigint" ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)),
pow: (num, power) => mod.FpPow(Fp6, num, power),
invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums),
// Normalized
add: Fp6Add,
sub: Fp6Subtract,
mul: Fp6Multiply,
sqr: Fp6Square,
// NonNormalized stuff
addN: Fp6Add,
subN: Fp6Subtract,
mulN: Fp6Multiply,
sqrN: Fp6Square,
inv: ({ c0, c1, c2 }) => {
let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1)));
let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1));
let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2));
let t4 = Fp2.inv(Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0)));
return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) };
},
// Bytes utils
fromBytes: (b) => {
if (b.length !== Fp6.BYTES)
throw new Error(`fromBytes wrong length=${b.length}`);
return {
c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)),
c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)),
c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES))
};
},
toBytes: ({ c0, c1, c2 }) => (0, utils_js_1.concatBytes)(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)),
cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({
c0: Fp2.cmov(c0, r0, c),
c1: Fp2.cmov(c1, r1, c),
c2: Fp2.cmov(c2, r2, c)
}),
fromBigSix: (t) => {
if (!Array.isArray(t) || t.length !== 6)
throw new Error("Invalid Fp6 usage");
return {
c0: Fp2.fromBigTuple(t.slice(0, 2)),
c1: Fp2.fromBigTuple(t.slice(2, 4)),
c2: Fp2.fromBigTuple(t.slice(4, 6))
};
},
frobeniusMap: ({ c0, c1, c2 }, power) => ({
c0: Fp2.frobeniusMap(c0, power),
c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]),
c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6])
}),
mulByFp2: ({ c0, c1, c2 }, rhs) => ({
c0: Fp2.mul(c0, rhs),
c1: Fp2.mul(c1, rhs),
c2: Fp2.mul(c2, rhs)
}),
mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }),
// Sparse multiplication
mul1: ({ c0, c1, c2 }, b1) => ({
c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)),
c1: Fp2.mul(c0, b1),
c2: Fp2.mul(c1, b1)
}),
// Sparse multiplication
mul01({ c0, c1, c2 }, b0, b1) {
let t0 = Fp2.mul(c0, b0);
let t1 = Fp2.mul(c1, b1);
return {
// ((c1 + c2) * b1 - T1) * (u + 1) + T0
c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0),
// (b0 + b1) * (c0 + c1) - T0 - T1
c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1),
// (c0 + c2) * b0 - T0 + T1
c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1)
};
}
};
const FP12_FROBENIUS_COEFFICIENTS = calcFrobeniusCoefficients(Fp2, Fp2Nonresidue, Fp.ORDER, 12, 1, 6)[0];
const Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({
c0: Fp6.add(c0, r0),
c1: Fp6.add(c1, r1)
});
const Fp12Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({
c0: Fp6.sub(c0, r0),
c1: Fp6.sub(c1, r1)
});
const Fp12Multiply = ({ c0, c1 }, rhs) => {
if (typeof rhs === "bigint")
return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) };
let { c0: r0, c1: r1 } = rhs;
let t1 = Fp6.mul(c0, r0);
let t2 = Fp6.mul(c1, r1);
return {
c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)),
// T1 + T2 * v
// (c0 + c1) * (r0 + r1) - (T1 + T2)
c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2))
};
};
const Fp12Square = ({ c0, c1 }) => {
let ab = Fp6.mul(c0, c1);
return {
// (c1 * v + c0) * (c0 + c1) - AB - AB * v
c0: Fp6.sub(Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), Fp6.mulByNonresidue(ab)),
c1: Fp6.add(ab, ab)
};
};
function Fp4Square(a, b) {
const a2 = Fp2.sqr(a);
const b2 = Fp2.sqr(b);
return {
first: Fp2.add(Fp2.mulByNonresidue(b2), a2),
// b² * Nonresidue + a²
second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2)
// (a + b)² - a² - b²
};
}
const Fp12 = {
ORDER: Fp2.ORDER,
// TODO: unused, but need to verify
BITS: 2 * Fp2.BITS,
BYTES: 2 * Fp2.BYTES,
MASK: (0, utils_js_1.bitMask)(2 * Fp2.BITS),
ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO },
ONE: { c0: Fp6.ONE, c1: Fp6.ZERO },
create: (num) => num,
isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1),
is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1),
neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }),
eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1),
sqrt: utils_js_1.notImplemented,
inv: ({ c0, c1 }) => {
let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1))));
return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) };
},
div: (lhs, rhs) => Fp12.mul(lhs, typeof rhs === "bigint" ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)),
pow: (num, power) => mod.FpPow(Fp12, num, power),
invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums),
// Normalized
add: Fp12Add,
sub: Fp12Subtract,
mul: Fp12Multiply,
sqr: Fp12Square,
// NonNormalized stuff
addN: Fp12Add,
subN: Fp12Subtract,
mulN: Fp12Multiply,
sqrN: Fp12Square,
// Bytes utils
fromBytes: (b) => {
if (b.length !== Fp12.BYTES)
throw new Error(`fromBytes wrong length=${b.length}`);
return {
c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)),
c1: Fp6.fromBytes(b.subarray(Fp6.BYTES))
};
},
toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp6.toBytes(c0), Fp6.toBytes(c1)),
cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({
c0: Fp6.cmov(c0, r0, c),
c1: Fp6.cmov(c1, r1, c)
}),
// Utils
// toString() {
// return `Fp12(${this.c0} + ${this.c1} * w)`;
// },
// fromTuple(c: [Fp6, Fp6]) {
// return new Fp12(...c);
// }
fromBigTwelve: (t) => ({
c0: Fp6.fromBigSix(t.slice(0, 6)),
c1: Fp6.fromBigSix(t.slice(6, 12))
}),
// Raises to q**i -th power
frobeniusMap(lhs, power) {
const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power);
const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12];
return {
c0: Fp6.frobeniusMap(lhs.c0, power),
c1: Fp6.create({
c0: Fp2.mul(c0, coeff),
c1: Fp2.mul(c1, coeff),
c2: Fp2.mul(c2, coeff)
})
};
},
mulByFp2: ({ c0, c1 }, rhs) => ({
c0: Fp6.mulByFp2(c0, rhs),
c1: Fp6.mulByFp2(c1, rhs)
}),
conjugate: ({ c0, c1 }) => ({ c0, c1: Fp6.neg(c1) }),
// Sparse multiplication
mul014: ({ c0, c1 }, o0, o1, o4) => {
let t0 = Fp6.mul01(c0, o0, o1);
let t1 = Fp6.mul1(c1, o4);
return {
c0: Fp6.add(Fp6.mulByNonresidue(t1), t0),
// T1 * v + T0
// (c1 + c0) * [o0, o1+o4] - T0 - T1
c1: Fp6.sub(Fp6.sub(Fp6.mul01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1)
};
},
mul034: ({ c0, c1 }, o0, o3, o4) => {
const a = Fp6.create({
c0: Fp2.mul(c0.c0, o0),
c1: Fp2.mul(c0.c1, o0),
c2: Fp2.mul(c0.c2, o0)
});
const b = Fp6.mul01(c1, o3, o4);
const e = Fp6.mul01(Fp6.add(c0, c1), Fp2.add(o0, o3), o4);
return {
c0: Fp6.add(Fp6.mulByNonresidue(b), a),
c1: Fp6.sub(e, Fp6.add(a, b))
};
},
// A cyclotomic group is a subgroup of Fp^n defined by
// GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1}
// The result of any pairing is in a cyclotomic subgroup
// https://eprint.iacr.org/2009/565.pdf
_cyclotomicSquare: opts.Fp12cyclotomicSquare,
_cyclotomicExp: opts.Fp12cyclotomicExp,
// https://eprint.iacr.org/2010/354.pdf
// https://eprint.iacr.org/2009/565.pdf
finalExponentiate: opts.Fp12finalExponentiate
};
return { Fp, Fp2, Fp6, Fp4Square, Fp12 };
}
}
});
// node_modules/@noble/hashes/_u64.js
var require_u64 = __commonJS({
"node_modules/@noble/hashes/_u64.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.add5L = exports.add5H = exports.add4H = exports.add4L = exports.add3H = exports.add3L = exports.rotlBL = exports.rotlBH = exports.rotlSL = exports.rotlSH = exports.rotr32L = exports.rotr32H = exports.rotrBL = exports.rotrBH = exports.rotrSL = exports.rotrSH = exports.shrSL = exports.shrSH = exports.toBig = void 0;
exports.fromBig = fromBig;
exports.split = split2;
exports.add = add;
var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
var _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
if (le)
return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split2(lst, le = false) {
let Ah = new Uint32Array(lst.length);
let Al = new Uint32Array(lst.length);
for (let i = 0; i < lst.length; i++) {
const { h, l } = fromBig(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
var toBig = (h, l) => BigInt(h >>> 0) << _32n | BigInt(l >>> 0);
exports.toBig = toBig;
var shrSH = (h, _l, s) => h >>> s;
exports.shrSH = shrSH;
var shrSL = (h, l, s) => h << 32 - s | l >>> s;
exports.shrSL = shrSL;
var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
exports.rotrSH = rotrSH;
var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
exports.rotrSL = rotrSL;
var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
exports.rotrBH = rotrBH;
var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
exports.rotrBL = rotrBL;
var rotr32H = (_h, l) => l;
exports.rotr32H = rotr32H;
var rotr32L = (h, _l) => h;
exports.rotr32L = rotr32L;
var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
exports.rotlSH = rotlSH;
var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
exports.rotlSL = rotlSL;
var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
exports.rotlBH = rotlBH;
var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
exports.rotlBL = rotlBL;
function add(Ah, Al, Bh, Bl) {
const l = (Al >>> 0) + (Bl >>> 0);
return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
}
var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
exports.add3L = add3L;
var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
exports.add3H = add3H;
var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
exports.add4L = add4L;
var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
exports.add4H = add4H;
var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
exports.add5L = add5L;
var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
exports.add5H = add5H;
var u64 = {
fromBig,
split: split2,
toBig,
shrSH,
shrSL,
rotrSH,
rotrSL,
rotrBH,
rotrBL,
rotr32H,
rotr32L,
rotlSH,
rotlSL,
rotlBH,
rotlBL,
add,
add3L,
add3H,
add4L,
add4H,
add5H,
add5L
};
exports.default = u64;
}
});
// node_modules/@noble/hashes/sha3.js
var require_sha3 = __commonJS({
"node_modules/@noble/hashes/sha3.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.shake256 = exports.shake128 = exports.keccak_512 = exports.keccak_384 = exports.keccak_256 = exports.keccak_224 = exports.sha3_512 = exports.sha3_384 = exports.sha3_256 = exports.sha3_224 = exports.Keccak = void 0;
exports.keccakP = keccakP;
var _assert_js_1 = require_assert();
var _u64_js_1 = require_u64();
var utils_js_1 = require_utils();
var SHA3_PI = [];
var SHA3_ROTL = [];
var _SHA3_IOTA = [];
var _0n = /* @__PURE__ */ BigInt(0);
var _1n = /* @__PURE__ */ BigInt(1);
var _2n = /* @__PURE__ */ BigInt(2);
var _7n = /* @__PURE__ */ BigInt(7);
var _256n = /* @__PURE__ */ BigInt(256);
var _0x71n = /* @__PURE__ */ BigInt(113);
for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
[x, y] = [y, (2 * x + 3 * y) % 5];
SHA3_PI.push(2 * (5 * y + x));
SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
let t = _0n;
for (let j = 0; j < 7; j++) {
R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
if (R & _2n)
t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j)) - _1n;
}
_SHA3_IOTA.push(t);
}
var [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ (0, _u64_js_1.split)(_SHA3_IOTA, true);
var rotlH = (h, l, s) => s > 32 ? (0, _u64_js_1.rotlBH)(h, l, s) : (0, _u64_js_1.rotlSH)(h, l, s);
var rotlL = (h, l, s) => s > 32 ? (0, _u64_js_1.rotlBL)(h, l, s) : (0, _u64_js_1.rotlSL)(h, l, s);
function keccakP(s, rounds = 24) {
const B = new Uint32Array(5 * 2);
for (let round = 24 - rounds; round < 24; round++) {
for (let x = 0; x < 10; x++)
B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
for (let x = 0; x < 10; x += 2) {
const idx1 = (x + 8) % 10;
const idx0 = (x + 2) % 10;
const B0 = B[idx0];
const B1 = B[idx0 + 1];
const Th = rotlH(B0, B1, 1) ^ B[idx1];
const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
for (let y = 0; y < 50; y += 10) {
s[x + y] ^= Th;
s[x + y + 1] ^= Tl;
}
}
let curH = s[2];
let curL = s[3];
for (let t = 0; t < 24; t++) {
const shift = SHA3_ROTL[t];
const Th = rotlH(curH, curL, shift);
const Tl = rotlL(curH, curL, shift);
const PI = SHA3_PI[t];
curH = s[PI];
curL = s[PI + 1];
s[PI] = Th;
s[PI + 1] = Tl;
}
for (let y = 0; y < 50; y += 10) {
for (let x = 0; x < 10; x++)
B[x] = s[y + x];
for (let x = 0; x < 10; x++)
s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
}
s[0] ^= SHA3_IOTA_H[round];
s[1] ^= SHA3_IOTA_L[round];
}
B.fill(0);
}
var Keccak = class _Keccak extends utils_js_1.Hash {
// NOTE: we accept arguments in bytes instead of bits here.
constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
super();
this.blockLen = blockLen;
this.suffix = suffix;
this.outputLen = outputLen;
this.enableXOF = enableXOF;
this.rounds = rounds;
this.pos = 0;
this.posOut = 0;
this.finished = false;
this.destroyed = false;
(0, _assert_js_1.number)(outputLen);
if (0 >= this.blockLen || this.blockLen >= 200)
throw new Error("Sha3 supports only keccak-f1600 function");
this.state = new Uint8Array(200);
this.state32 = (0, utils_js_1.u32)(this.state);
}
keccak() {
if (!utils_js_1.isLE)
(0, utils_js_1.byteSwap32)(this.state32);
keccakP(this.state32, this.rounds);
if (!utils_js_1.isLE)
(0, utils_js_1.byteSwap32)(this.state32);
this.posOut = 0;
this.pos = 0;
}
update(data) {
(0, _assert_js_1.exists)(this);
const { blockLen, state } = this;
data = (0, utils_js_1.toBytes)(data);
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
for (let i = 0; i < take; i++)
state[this.pos++] ^= data[pos++];
if (this.pos === blockLen)
this.keccak();
}
return this;
}
finish() {
if (this.finished)
return;
this.finished = true;
const { state, suffix, pos, blockLen } = this;
state[pos] ^= suffix;
if ((suffix & 128) !== 0 && pos === blockLen - 1)
this.keccak();
state[blockLen - 1] ^= 128;
this.keccak();
}
writeInto(out) {
(0, _assert_js_1.exists)(this, false);
(0, _assert_js_1.bytes)(out);
this.finish();
const bufferOut = this.state;
const { blockLen } = this;
for (let pos = 0, len = out.length; pos < len; ) {
if (this.posOut >= blockLen)
this.keccak();
const take = Math.min(blockLen - this.posOut, len - pos);
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
this.posOut += take;
pos += take;
}
return out;
}
xofInto(out) {
if (!this.enableXOF)
throw new Error("XOF is not possible for this instance");
return this.writeInto(out);
}
xof(bytes) {
(0, _assert_js_1.number)(bytes);
return this.xofInto(new Uint8Array(bytes));
}
digestInto(out) {
(0, _assert_js_1.output)(out, this);
if (this.finished)
throw new Error("digest() was already called");
this.writeInto(out);
this.destroy();
return out;
}
digest() {
return this.digestInto(new Uint8Array(this.outputLen));
}
destroy() {
this.destroyed = true;
this.state.fill(0);
}
_cloneInto(to) {
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
to.state32.set(this.state32);
to.pos = this.pos;
to.posOut = this.posOut;
to.finished = this.finished;
to.rounds = rounds;
to.suffix = suffix;
to.outputLen = outputLen;
to.enableXOF = enableXOF;
to.destroyed = this.destroyed;
return to;
}
};
exports.Keccak = Keccak;
var gen = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapConstructor)(() => new Keccak(blockLen, suffix, outputLen));
exports.sha3_224 = gen(6, 144, 224 / 8);
exports.sha3_256 = gen(6, 136, 256 / 8);
exports.sha3_384 = gen(6, 104, 384 / 8);
exports.sha3_512 = gen(6, 72, 512 / 8);
exports.keccak_224 = gen(1, 144, 224 / 8);
exports.keccak_256 = gen(1, 136, 256 / 8);
exports.keccak_384 = gen(1, 104, 384 / 8);
exports.keccak_512 = gen(1, 72, 512 / 8);
var genShake = (suffix, blockLen, outputLen) => (0, utils_js_1.wrapXOFConstructorWithOpts)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true));
exports.shake128 = genShake(31, 168, 128 / 8);
exports.shake256 = genShake(31, 136, 256 / 8);
}
});
// node_modules/@kevincharm/noble-bn254-drand/dist/src/bn254.js
var require_bn254 = __commonJS({
"node_modules/@kevincharm/noble-bn254-drand/dist/src/bn254.js"(exports) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m[k];
} };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__importStar || function(mod2) {
if (mod2 && mod2.__esModule) return mod2;
var result = {};
if (mod2 != null) {
for (var k in mod2) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod2, k)) __createBinding(result, mod2, k);
}
__setModuleDefault(result, mod2);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.bn254 = void 0;
exports.mapToCurveSVDW = mapToCurveSVDW;
var utils_1 = require_utils();
var bls_1 = require_bls();
var modular_1 = require_modular();
var utils_2 = require_utils2();
var tower_1 = require_tower();
var mod = __importStar(require_modular());
var sha3_1 = require_sha3();
var utils_3 = require_utils2();
var _1n = BigInt(1);
var _2n = BigInt(2);
var _3n = BigInt(3);
var _6n = BigInt(6);
var BN_X = BigInt("4965661367192848881");
var BN_X_LEN = (0, utils_2.bitLen)(BN_X);
var SIX_X_SQUARED = _6n * BN_X ** _2n;
var Fr2 = (0, modular_1.Field)(BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"));
var Fp2B = {
c0: BigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373"),
c1: BigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")
};
var { Fp, Fp2, Fp6, Fp4Square, Fp12 } = (0, tower_1.tower12)({
ORDER: BigInt("21888242871839275222246405745257275088696311157297823662689037894645226208583"),
FP2_NONRESIDUE: [BigInt(9), _1n],
Fp2mulByB: (num) => Fp2.mul(num, Fp2B),
// The result of any pairing is in a cyclotomic subgroup
// https://eprint.iacr.org/2009/565.pdf
Fp12cyclotomicSquare: ({ c0, c1 }) => {
const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0;
const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1;
const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1);
const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2);
const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2);
let t9 = Fp2.mulByNonresidue(t8);
return {
c0: Fp6.create({
c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3),
// 2 * (T3 - c0c0) + T3
c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5),
// 2 * (T5 - c0c1) + T5
c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7)
}),
// 2 * (T7 - c0c2) + T7
c1: Fp6.create({
c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9),
// 2 * (T9 + c1c0) + T9
c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4),
// 2 * (T4 + c1c1) + T4
c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6)
})
};
},
Fp12cyclotomicExp(num, n) {
let z = Fp12.ONE;
for (let i = BN_X_LEN - 1; i >= 0; i--) {
z = Fp12._cyclotomicSquare(z);
if ((0, utils_2.bitGet)(n, i))
z = Fp12.mul(z, num);
}
return z;
},
// https://eprint.iacr.org/2010/354.pdf
// https://eprint.iacr.org/2009/565.pdf
Fp12finalExponentiate: (num) => {
const powMinusX = (num2) => Fp12.conjugate(Fp12._cyclotomicExp(num2, BN_X));
const r0 = Fp12.mul(Fp12.conjugate(num), Fp12.inv(num));
const r = Fp12.mul(Fp12.frobeniusMap(r0, 2), r0);
const y1 = Fp12._cyclotomicSquare(powMinusX(r));
const y2 = Fp12.mul(Fp12._cyclotomicSquare(y1), y1);
const y4 = powMinusX(y2);
const y6 = powMinusX(Fp12._cyclotomicSquare(y4));
const y8 = Fp12.mul(Fp12.mul(Fp12.conjugate(y6), y4), Fp12.conjugate(y2));
const y9 = Fp12.mul(y8, y1);
return Fp12.mul(Fp12.frobeniusMap(Fp12.mul(Fp12.conjugate(r), y9), 3), Fp12.mul(Fp12.frobeniusMap(y8, 2), Fp12.mul(Fp12.frobeniusMap(y9, 1), Fp12.mul(Fp12.mul(y8, y4), r))));
}
});
var { G2psi, psi } = (0, tower_1.psiFrobenius)(Fp, Fp2, Fp2.NONRESIDUE);
function SVDWFpIsSquare(Fp3) {
return (u) => {
const x = Fp3.pow(u, (Fp3.ORDER - 1n) / 2n);
let legendre;
if (Fp3.eql(x, Fp3.neg(Fp3.ONE))) {
legendre = -1n;
} else if (Fp3.eql(x, Fp3.ZERO)) {
legendre = 0n;
} else if (Fp3.eql(x, Fp3.ONE)) {
legendre = 1n;
} else {
throw new Error("Legendre failed");
}
return legendre === 1n;
};
}
function mapToCurveSVDW(Fp3, opts) {
mod.validateField(Fp3);
if (!Fp3.isValid(opts.A) || !Fp3.isValid(opts.B) || !Fp3.isValid(opts.Z))
throw new Error("mapToCurveSimpleSVDW: invalid opts");
const isSquare = SVDWFpIsSquare(Fp3);
if (!Fp3.isOdd)
throw new Error("Fp.isOdd is not implemented!");
const g = (x) => Fp3.add(Fp3.add(Fp3.mul(Fp3.mul(x, x), x), Fp3.mul(opts.A, x)), opts.B);
const two = Fp3.add(Fp3.ONE, Fp3.ONE);
const three = Fp3.add(two, Fp3.ONE);
const four = Fp3.add(three, Fp3.ONE);
const c1 = g(opts.Z);
const c2 = Fp3.mul(Fp3.neg(opts.Z), Fp3.inv(Fp3.add(Fp3.ONE, Fp3.ONE)));
const c3 = Fp3.sqrt(Fp3.mul(Fp3.neg(c1), Fp3.add(Fp3.mul(three, Fp3.mul(opts.Z, opts.Z)), Fp3.mul(four, opts.A))));
const c4 = Fp3.mul(Fp3.mul(four, Fp3.neg(c1)), Fp3.inv(Fp3.add(Fp3.mul(three, Fp3.mul(opts.Z, opts.Z)), Fp3.mul(four, opts.A))));
return (u) => {
let tv1, tv2, tv3, tv4, x1, gx1, e1, x2, gx2, e2, x3, x, gx, y, e3;
tv1 = Fp3.mul(u, u);
tv1 = Fp3.mul(tv1, c1);
tv2 = Fp3.add(Fp3.ONE, tv1);
tv1 = Fp3.sub(Fp3.ONE, tv1);
tv3 = Fp3.mul(tv1, tv2);
tv3 = Fp3.inv(tv3);
tv4 = Fp3.mul(u, tv1);
tv4 = Fp3.mul(tv4, tv3);
tv4 = Fp3.mul(tv4, c3);
x1 = Fp3.sub(c2, tv4);
gx1 = Fp3.mul(x1, x1);
gx1 = Fp3.add(gx1, opts.A);
gx1 = Fp3.mul(gx1, x1);
gx1 = Fp3.add(gx1, opts.B);
e1 = isSquare(gx1);
x2 = Fp3.add(c2, tv4);
gx2 = Fp3.mul(x2, x2);
gx2 = Fp3.add(gx2, opts.A);
gx2 = Fp3.mul(gx2, x2);
gx2 = Fp3.add(gx2, opts.B);
e2 = isSquare(gx2) && !e1;
x3 = Fp3.mul(tv2, tv2);
x3 = Fp3.mul(x3, tv3);
x3 = Fp3.mul(x3, x3);
x3 = Fp3.mul(x3, c4);
x3 = Fp3.add(x3, opts.Z);
x = Fp3.cmov(x3, x1, !!e1);
x = Fp3.cmov(x, x2, !!e2);
gx = Fp3.mul(x, x);
gx = Fp3.add(gx, opts.A);
gx = Fp3.mul(gx, x);
gx = Fp3.add(gx, opts.B);
y = Fp3.sqrt(gx);
e3 = Fp3.isOdd(u) === Fp3.isOdd(y);
y = Fp3.cmov(Fp3.neg(y), y, e3);
return { x, y };
};
}
var G1_SVDW = mapToCurveSVDW(Fp, {
A: Fp.ZERO,
B: _3n,
Z: Fp.ONE
});
var mapToCurveG1 = (scalars) => G1_SVDW(scalars[0]);
var drandHtf = Object.freeze({
// DST: a domain separation tag
// defined in section 2.2.5
// Use utils.getDSTLabel(), utils.setDSTLabel(value)
DST: "BLS_SIG_BN254G1_XMD:KECCAK-256_SVDW_RO_NUL_",
encodeDST: "BLS_SIG_BN254G1_XMD:KECCAK-256_SVDW_RO_NUL_",
// p: the characteristic of F
// where F is a finite field of characteristic p and order q = p^m
p: Fp.ORDER,
// m: the extension degree of F, m >= 1
// where F is a finite field of characteristic p and order q = p^m
m: 1,
// k: the target security level for the suite in bits
// defined in section 5.1
k: 128,
// option to use a message that has already been processed by
// expand_message_xmd
expand: "xmd",
// NB: We use keccak_256 to hash-to-curve for bn254 drand, as it is the
// cheapest hash function in the EVM.
hash: sha3_1.keccak_256
});
exports.bn254 = (0, bls_1.bls)({
// Fields
fields: { Fp, Fp2, Fp6, Fp12, Fr: Fr2 },
G1: {
Fp,
h: BigInt(1),
Gx: BigInt(1),
Gy: BigInt(2),
a: Fp.ZERO,
b: _3n,
htfDefaults: { ...drandHtf, m: 1 },
wrapPrivateKey: true,
allowInfinityPoint: true,
mapToCurve: mapToCurveG1,
fromBytes: (bytes) => {
const p = [bytes.slice(0, 32), bytes.slice(32, 64)].map((buf) => (0, utils_3.bytesToNumberBE)(buf));
const point = { x: Fp.create(p[0]), y: Fp.create(p[1]) };
exports.bn254.G1.ProjectivePoint.fromAffine(point).assertValidity();
return point;
},
toBytes: (c, point, _isCompressed) => {
const isZero = point.equals(c.ZERO);
const { x, y } = point.toAffine();
const { BYTES: len } = Fp;
if (isZero) {
return new Uint8Array(len);
}
return (0, utils_2.concatBytes)((0, utils_3.numberToBytesBE)(x, len), (0, utils_3.numberToBytesBE)(y, len));
},
ShortSignature: {
fromHex(hex) {
return exports.bn254.G1.ProjectivePoint.fromHex(hex);
},
toRawBytes(point) {
return point.toRawBytes();
},
toHex(point) {
return point.toHex();
}
}
},
G2: {
Fp: Fp2,
// cofactor: (36 * X^4) + (36 * X^3) + (30 * X^2) + 6*X + 1
h: BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),
Gx: Fp2.fromBigTuple([
BigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"),
BigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634")
]),
Gy: Fp2.fromBigTuple([
BigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"),
BigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531")
]),
a: Fp2.ZERO,
b: Fp2B,
hEff: BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),
htfDefaults: { ...drandHtf, m: 2 },
wrapPrivateKey: true,
allowInfinityPoint: true,
isTorsionFree: (c, P) => P.multiplyUnsafe(SIX_X_SQUARED).equals(G2psi(c, P)),
// [p]P = [6X^2]P
mapToCurve: utils_2.notImplemented,
fromBytes: (bytes) => {
const p = [
bytes.slice(32, 64),
bytes.slice(0, 32),
bytes.slice(96, 128),
bytes.slice(64, 96)
].map((buf) => (0, utils_3.bytesToNumberBE)(buf));
const x = Fp2.create({ c0: p[0], c1: p[1] });
const y = Fp2.create({ c0: p[2], c1: p[3] });
exports.bn254.G2.ProjectivePoint.fromAffine({ x, y }).assertValidity();
return { x, y };
},
toBytes: (c, point, _isCompressed) => {
const { BYTES: len } = Fp;
const isZero = point.equals(c.ZERO);
const { x, y } = point.toAffine();
const marshalSize = 4 * len;
if (isZero) {
return new Uint8Array(marshalSize);
}
const { re: x0, im: x1 } = Fp2.reim(x);
const { re: y0, im: y1 } = Fp2.reim(y);
return (0, utils_2.concatBytes)((0, utils_3.numberToBytesBE)(x1, len), (0, utils_3.numberToBytesBE)(x0, len), (0, utils_3.numberToBytesBE)(y1, len), (0, utils_3.numberToBytesBE)(y0, len));
},
Signature: {
fromHex(hex) {
return exports.bn254.G2.ProjectivePoint.fromHex(hex);
},
toRawBytes(point) {
return point.toRawBytes();
},
toHex(point) {
return point.toHex();
}
}
},
params: {
ateLoopSize: BN_X * _6n + _2n,
r: Fr2.ORDER,
xNegative: false,
twistType: "divisive"
},
htfDefaults: drandHtf,
hash: sha3_1.keccak_256,
randomBytes: utils_1.randomBytes,
postPrecompute: (Rx, Ry, Rz, Qx, Qy, pointAdd) => {
const q = psi(Qx, Qy);
({ Rx, Ry, Rz } = pointAdd(Rx, Ry, Rz, q[0], q[1]));
const q2 = psi(q[0], q[1]);
pointAdd(Rx, Ry, Rz, q2[0], Fp2.neg(q2[1]));
}
});
}
});
// node_modules/@kevincharm/noble-bn254-drand/dist/src/index.js
var require_src = __commonJS({
"node_modules/@kevincharm/noble-bn254-drand/dist/src/index.js"(exports) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m[k];
} };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __exportStar = exports && exports.__exportStar || function(m, exports2) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require_bn254(), exports);
}
});
// src/index.ts
var import_noble_bn254_drand = __toESM(require_src(), 1);
// node_modules/@noble/hashes/esm/crypto.js
var crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
// node_modules/@noble/hashes/esm/utils.js
var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
var toStr = {}.toString;
function randomBytes(bytesLength = 32) {
if (crypto && typeof crypto.getRandomValues === "function") {
return crypto.getRandomValues(new Uint8Array(bytesLength));
}
if (crypto && typeof crypto.randomBytes === "function") {
return crypto.randomBytes(bytesLength);
}
throw new Error("crypto.getRandomValues must be defined");
}
// src/index.ts
function createPrivateKey() {
return { sk: import_noble_bn254_drand.bn254.utils.randomPrivateKey() };
}
function createPublicKey(secretKey) {
const sk = secretKey instanceof Uint8Array ? secretKey : secretKey.sk;
const fieldElement = import_noble_bn254_drand.bn254.fields.Fr.fromBytes(sk);
const pk = import_noble_bn254_drand.bn254.G2.ProjectivePoint.BASE.multiply(fieldElement);
return { pk: pk.toRawBytes() };
}
function createPublicKeyShare(secretKeyShare) {
return {
index: secretKeyShare.index,
pk: import_noble_bn254_drand.bn254.G2.ProjectivePoint.BASE.multiply(secretKeyShare.share).toRawBytes()
};
}
function sign(secretKey, message) {
const sk = secretKey instanceof Uint8Array ? secretKey : secretKey.sk;
return import_noble_bn254_drand.bn254.signShortSignature(message, sk);
}
function signPartial(secretKeyShare, message) {
const share = secretKeyShare instanceof Uint8Array ? secretKeyShare : secretKeyShare.share;
return import_noble_bn254_drand.bn254.signShortSignature(message, share);
}
function verify(publicKey, message, signature) {
const pk = publicKey instanceof Uint8Array ? publicKey : publicKey.pk;
return import_noble_bn254_drand.bn254.verifyShortSignature(signature, message, pk);
}
function verifyPartial(publicKey, message, partialSignature) {
const sig = partialSignature instanceof Uint8Array ? partialSignature : partialSignature.signature;
const pk = publicKey instanceof Uint8Array ? publicKey : publicKey.pk;
return import_noble_bn254_drand.bn254.verifyShortSignature(sig, message, pk);
}
var Fr = import_noble_bn254_drand.bn254.fields.Fr;
function aggregateGroupSignature(partials) {
const xs = partials.map((entry) => entry.index);
let agg = import_noble_bn254_drand.bn254.G1.ProjectivePoint.ZERO;
for (let i = 0; i < partials.length; i++) {
const entry = partials[i];
const sig = import_noble_bn254_drand.bn254.G1.ProjectivePoint.fromHex(entry.signature);
const term = sig.multiply(lagrangeCoeff0(i, xs));
agg = agg.add(term);
}
return agg.toRawBytes();
}
function lagrangeCoeff0(index, xs) {
const xi = xs[index];
if (xi == null) {
throw new Error("xi expected a value");
}
let num = 1n;
let den = 1n;
for (let i = 0; i < xs.length; i++) {
if (i === index) continue;
const xj = xs[i];
if (xj == null) {
throw new Error("xj expected a value");
}
num = Fr.mul(num, Fr.neg(xj));
den = Fr.mul(den, Fr.sub(xi, xj));
}
return Fr.div(num, den);
}
function split(secretKey, numberOfShares, threshold) {
const sk = secretKey instanceof Uint8Array ? secretKey : secretKey.sk;
if (threshold > numberOfShares) {
throw new Error("threshold can'threshold be lower than node count - you probably have the parameters the wrong way round");
}
if (threshold < 2) {
throw new Error("threshold less than two means everyone can recover the secret");
}
const evaluations = [encodeBigint(sk)];
for (let i = 1; i < threshold; i++) {
evaluations.push(randomFr());
}
const shares = [];
for (let x = 1n; x <= numberOfShares; x++) {
let share = 0n;
for (let i = evaluations.length - 1; i >= 0; i--) {
const rhs = evaluations[i];
if (rhs == null) {
throw new Error("invalid split");
}
share = import_noble_bn254_drand.bn254.fields.Fr.add(import_noble_bn254_drand.bn254.fields.Fr.mul(share, x), rhs);
}
shares.push({ index: x, share });
}
return shares;
}
function randomFr() {
while (true) {
const fr = encodeBigint(randomBytes(import_noble_bn254_drand.bn254.fields.Fr.BYTES));
if (fr < import_noble_bn254_drand.bn254.fields.Fr.ORDER) {
return fr;
}
}
}
function encodeBigint(input) {
return import_noble_bn254_drand.bn254.fields.Fr.fromBytes(input);
}
export {
aggregateGroupSignature,
createPrivateKey,
createPublicKey,
createPublicKeyShare,
sign,
signPartial,
split,
verify,
verifyPartial
};
/*! Bundled license information:
@noble/hashes/utils.js:
@noble/hashes/esm/utils.js:
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/abstract/utils.js:
@noble/curves/abstract/modular.js:
@noble/curves/abstract/curve.js:
@noble/curves/abstract/weierstrass.js:
@noble/curves/abstract/bls.js:
@noble/curves/abstract/tower.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
*/
//# sourceMappingURL=index.mjs.map