UNPKG

drand-client

Version:

A client to the drand randomness beacon network.

1,365 lines (1,357 loc) 278 kB
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, mod2) => function __require() { return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; 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 = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __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 || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, mod2 )); var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2); // node_modules/@noble/hashes/cryptoNode.js var require_cryptoNode = __commonJS({ "node_modules/@noble/hashes/cryptoNode.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.crypto = void 0; var nc2 = require("node:crypto"); exports2.crypto = nc2 && typeof nc2 === "object" && "webcrypto" in nc2 ? nc2.webcrypto : nc2 && typeof nc2 === "object" && "randomBytes" in nc2 ? nc2 : void 0; } }); // node_modules/@noble/hashes/utils.js var require_utils = __commonJS({ "node_modules/@noble/hashes/utils.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.wrapXOFConstructorWithOpts = exports2.wrapConstructorWithOpts = exports2.wrapConstructor = exports2.Hash = exports2.nextTick = exports2.swap32IfBE = exports2.byteSwapIfBE = exports2.swap8IfBE = exports2.isLE = void 0; exports2.isBytes = isBytes3; exports2.anumber = anumber2; exports2.abytes = abytes3; exports2.ahash = ahash; exports2.aexists = aexists2; exports2.aoutput = aoutput2; exports2.u8 = u8; exports2.u32 = u322; exports2.clean = clean2; exports2.createView = createView2; exports2.rotr = rotr2; exports2.rotl = rotl; exports2.byteSwap = byteSwap2; exports2.byteSwap32 = byteSwap322; exports2.bytesToHex = bytesToHex2; exports2.hexToBytes = hexToBytes2; exports2.asyncLoop = asyncLoop; exports2.utf8ToBytes = utf8ToBytes3; exports2.bytesToUtf8 = bytesToUtf8; exports2.toBytes = toBytes2; exports2.kdfInputToBytes = kdfInputToBytes; exports2.concatBytes = concatBytes2; exports2.checkOpts = checkOpts; exports2.createHasher = createHasher3; exports2.createOptHasher = createOptHasher; exports2.createXOFer = createXOFer2; exports2.randomBytes = randomBytes2; var crypto_1 = require_cryptoNode(); function isBytes3(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; } function anumber2(n) { if (!Number.isSafeInteger(n) || n < 0) throw new Error("positive integer expected, got " + n); } function abytes3(b, ...lengths) { if (!isBytes3(b)) throw new Error("Uint8Array expected"); if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length); } function ahash(h) { if (typeof h !== "function" || typeof h.create !== "function") throw new Error("Hash should be wrapped by utils.createHasher"); anumber2(h.outputLen); anumber2(h.blockLen); } function aexists2(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 aoutput2(out, instance) { abytes3(out); const min = instance.outputLen; if (out.length < min) { throw new Error("digestInto() expects output buffer of length at least " + min); } } function u8(arr) { return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); } function u322(arr) { return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); } function clean2(...arrays) { for (let i = 0; i < arrays.length; i++) { arrays[i].fill(0); } } function createView2(arr) { return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); } function rotr2(word, shift) { return word << 32 - shift | word >>> shift; } function rotl(word, shift) { return word << shift | word >>> 32 - shift >>> 0; } exports2.isLE = (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); function byteSwap2(word) { return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; } exports2.swap8IfBE = exports2.isLE ? (n) => n : (n) => byteSwap2(n); exports2.byteSwapIfBE = exports2.swap8IfBE; function byteSwap322(arr) { for (let i = 0; i < arr.length; i++) { arr[i] = byteSwap2(arr[i]); } return arr; } exports2.swap32IfBE = exports2.isLE ? (u) => u : byteSwap322; var hasHexBuiltin2 = /* @__PURE__ */ (() => ( // @ts-ignore typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" ))(); var hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); function bytesToHex2(bytes) { abytes3(bytes); if (hasHexBuiltin2) return bytes.toHex(); let hex = ""; for (let i = 0; i < bytes.length; i++) { hex += hexes2[bytes[i]]; } return hex; } var asciis2 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; function asciiToBase162(ch) { if (ch >= asciis2._0 && ch <= asciis2._9) return ch - asciis2._0; if (ch >= asciis2.A && ch <= asciis2.F) return ch - (asciis2.A - 10); if (ch >= asciis2.a && ch <= asciis2.f) return ch - (asciis2.a - 10); return; } function hexToBytes2(hex) { if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex); if (hasHexBuiltin2) return Uint8Array.fromHex(hex); const hl = hex.length; const al = hl / 2; if (hl % 2) throw new Error("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 = asciiToBase162(hex.charCodeAt(hi)); const n2 = asciiToBase162(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 () => { }; exports2.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, exports2.nextTick)(); ts += diff; } } function utf8ToBytes3(str) { if (typeof str !== "string") throw new Error("string expected"); return new Uint8Array(new TextEncoder().encode(str)); } function bytesToUtf8(bytes) { return new TextDecoder().decode(bytes); } function toBytes2(data) { if (typeof data === "string") data = utf8ToBytes3(data); abytes3(data); return data; } function kdfInputToBytes(data) { if (typeof data === "string") data = utf8ToBytes3(data); abytes3(data); return data; } function concatBytes2(...arrays) { let sum = 0; for (let i = 0; i < arrays.length; i++) { const a = arrays[i]; abytes3(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 checkOpts(defaults, opts) { if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]") throw new Error("options should be object or undefined"); const merged = Object.assign(defaults, opts); return merged; } var Hash2 = class { }; exports2.Hash = Hash2; function createHasher3(hashCons) { const hashC = (msg) => hashCons().update(toBytes2(msg)).digest(); const tmp = hashCons(); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = () => hashCons(); return hashC; } function createOptHasher(hashCons) { const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest(); const tmp = hashCons({}); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = (opts) => hashCons(opts); return hashC; } function createXOFer2(hashCons) { const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest(); const tmp = hashCons({}); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = (opts) => hashCons(opts); return hashC; } exports2.wrapConstructor = createHasher3; exports2.wrapConstructorWithOpts = createOptHasher; exports2.wrapXOFConstructorWithOpts = createXOFer2; 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 Uint8Array.from(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"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.notImplemented = exports2.bitMask = void 0; exports2.isBytes = isBytes3; exports2.abytes = abytes3; exports2.abool = abool2; exports2.numberToHexUnpadded = numberToHexUnpadded2; exports2.hexToNumber = hexToNumber2; exports2.bytesToHex = bytesToHex2; exports2.hexToBytes = hexToBytes2; exports2.bytesToNumberBE = bytesToNumberBE2; exports2.bytesToNumberLE = bytesToNumberLE2; exports2.numberToBytesBE = numberToBytesBE2; exports2.numberToBytesLE = numberToBytesLE2; exports2.numberToVarBytesBE = numberToVarBytesBE; exports2.ensureBytes = ensureBytes2; exports2.concatBytes = concatBytes2; exports2.equalBytes = equalBytes; exports2.utf8ToBytes = utf8ToBytes3; exports2.inRange = inRange2; exports2.aInRange = aInRange2; exports2.bitLen = bitLen2; exports2.bitGet = bitGet2; exports2.bitSet = bitSet; exports2.createHmacDrbg = createHmacDrbg2; exports2.validateObject = validateObject2; exports2.memoized = memoized2; var _0n9 = /* @__PURE__ */ BigInt(0); var _1n9 = /* @__PURE__ */ BigInt(1); function isBytes3(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; } function abytes3(item) { if (!isBytes3(item)) throw new Error("Uint8Array expected"); } function abool2(title, value) { if (typeof value !== "boolean") throw new Error(title + " boolean expected, got " + value); } function numberToHexUnpadded2(num) { const hex = num.toString(16); return hex.length & 1 ? "0" + hex : hex; } function hexToNumber2(hex) { if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex); return hex === "" ? _0n9 : BigInt("0x" + hex); } var hasHexBuiltin2 = ( // @ts-ignore typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" ); var hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); function bytesToHex2(bytes) { abytes3(bytes); if (hasHexBuiltin2) return bytes.toHex(); let hex = ""; for (let i = 0; i < bytes.length; i++) { hex += hexes2[bytes[i]]; } return hex; } var asciis2 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; function asciiToBase162(ch) { if (ch >= asciis2._0 && ch <= asciis2._9) return ch - asciis2._0; if (ch >= asciis2.A && ch <= asciis2.F) return ch - (asciis2.A - 10); if (ch >= asciis2.a && ch <= asciis2.f) return ch - (asciis2.a - 10); return; } function hexToBytes2(hex) { if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex); if (hasHexBuiltin2) return Uint8Array.fromHex(hex); const hl = hex.length; const al = hl / 2; if (hl % 2) throw new Error("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 = asciiToBase162(hex.charCodeAt(hi)); const n2 = asciiToBase162(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 bytesToNumberBE2(bytes) { return hexToNumber2(bytesToHex2(bytes)); } function bytesToNumberLE2(bytes) { abytes3(bytes); return hexToNumber2(bytesToHex2(Uint8Array.from(bytes).reverse())); } function numberToBytesBE2(n, len) { return hexToBytes2(n.toString(16).padStart(len * 2, "0")); } function numberToBytesLE2(n, len) { return numberToBytesBE2(n, len).reverse(); } function numberToVarBytesBE(n) { return hexToBytes2(numberToHexUnpadded2(n)); } function ensureBytes2(title, hex, expectedLength) { let res; if (typeof hex === "string") { try { res = hexToBytes2(hex); } catch (e) { throw new Error(title + " must be hex string or Uint8Array, cause: " + e); } } else if (isBytes3(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 + " of length " + expectedLength + " expected, got " + len); return res; } function concatBytes2(...arrays) { let sum = 0; for (let i = 0; i < arrays.length; i++) { const a = arrays[i]; abytes3(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 utf8ToBytes3(str) { if (typeof str !== "string") throw new Error("string expected"); return new Uint8Array(new TextEncoder().encode(str)); } var isPosBig2 = (n) => typeof n === "bigint" && _0n9 <= n; function inRange2(n, min, max) { return isPosBig2(n) && isPosBig2(min) && isPosBig2(max) && min <= n && n < max; } function aInRange2(title, n, min, max) { if (!inRange2(n, min, max)) throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); } function bitLen2(n) { let len; for (len = 0; n > _0n9; n >>= _1n9, len += 1) ; return len; } function bitGet2(n, pos) { return n >> BigInt(pos) & _1n9; } function bitSet(n, pos, value) { return n | (value ? _1n9 : _0n9) << BigInt(pos); } var bitMask2 = (n) => (_1n9 << BigInt(n)) - _1n9; exports2.bitMask = bitMask2; var u8n = (len) => new Uint8Array(len); var u8fr = (arr) => Uint8Array.from(arr); function createHmacDrbg2(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(0)) => { k = h(u8fr([0]), seed); v = h(); if (seed.length === 0) return; k = h(u8fr([1]), seed); v = h(); }; const gen2 = () => { 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 concatBytes2(...out); }; const genUntil = (seed, pred) => { reset(); reseed(seed); let res = void 0; while (!(res = pred(gen2()))) reseed(); reset(); return res; }; return genUntil; } var validatorFns2 = { 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" || isBytes3(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 validateObject2(object, validators, optValidators = {}) { const checkField = (fieldName, type, isOptional) => { const checkVal = validatorFns2[type]; if (typeof checkVal !== "function") throw new Error("invalid validator function"); const val = object[fieldName]; if (isOptional && val === void 0) return; if (!checkVal(val, object)) { throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val); } }; 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 notImplemented2 = () => { throw new Error("not implemented"); }; exports2.notImplemented = notImplemented2; function memoized2(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"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.isNegativeLE = void 0; exports2.mod = mod2; exports2.pow = pow; exports2.pow2 = pow2; exports2.invert = invert2; exports2.tonelliShanks = tonelliShanks2; exports2.FpSqrt = FpSqrt2; exports2.validateField = validateField2; exports2.FpPow = FpPow2; exports2.FpInvertBatch = FpInvertBatch2; exports2.FpDiv = FpDiv; exports2.FpLegendre = FpLegendre2; exports2.FpIsSquare = FpIsSquare2; exports2.nLength = nLength2; exports2.Field = Field2; exports2.FpSqrtOdd = FpSqrtOdd; exports2.FpSqrtEven = FpSqrtEven; exports2.hashToPrivateScalar = hashToPrivateScalar; exports2.getFieldBytesLength = getFieldBytesLength2; exports2.getMinHashLength = getMinHashLength2; exports2.mapHashToField = mapHashToField2; var utils_1 = require_utils(); var utils_ts_1 = require_utils2(); var _0n9 = BigInt(0); var _1n9 = BigInt(1); var _2n7 = /* @__PURE__ */ BigInt(2); var _3n6 = /* @__PURE__ */ BigInt(3); var _4n4 = /* @__PURE__ */ BigInt(4); var _5n2 = /* @__PURE__ */ BigInt(5); var _8n2 = /* @__PURE__ */ BigInt(8); var _9n2 = /* @__PURE__ */ BigInt(9); var _16n2 = /* @__PURE__ */ BigInt(16); function mod2(a, b) { const result = a % b; return result >= _0n9 ? result : b + result; } function pow(num, power, modulo) { if (power < _0n9) throw new Error("invalid exponent, negatives unsupported"); if (modulo <= _0n9) throw new Error("invalid modulus"); if (modulo === _1n9) return _0n9; let res = _1n9; while (power > _0n9) { if (power & _1n9) res = res * num % modulo; num = num * num % modulo; power >>= _1n9; } return res; } function pow2(x, power, modulo) { let res = x; while (power-- > _0n9) { res *= res; res %= modulo; } return res; } function invert2(number, modulo) { if (number === _0n9) throw new Error("invert: expected non-zero number"); if (modulo <= _0n9) throw new Error("invert: expected positive modulus, got " + modulo); let a = mod2(number, modulo); let b = modulo; let x = _0n9, y = _1n9, u = _1n9, v = _0n9; while (a !== _0n9) { 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 !== _1n9) throw new Error("invert: does not exist"); return mod2(x, modulo); } function tonelliShanks2(P) { let Q = P - _1n9; let S = 0; while (Q % _2n7 === _0n9) { Q /= _2n7; S++; } let Z = _2n7; const _Fp = Field2(P); while (Z < P && FpIsSquare2(_Fp, Z)) { if (Z++ > 1e3) throw new Error("Cannot find square root: probably non-prime P"); } if (S === 1) { const p1div4 = (P + _1n9) / _4n4; return function tonelliFast(Fp3, n) { const root = Fp3.pow(n, p1div4); if (!Fp3.eql(Fp3.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } const Q1div2 = (Q + _1n9) / _2n7; return function tonelliSlow(Fp3, n) { if (!FpIsSquare2(Fp3, n)) throw new Error("Cannot find square root"); let r = S; let g = Fp3.pow(Fp3.mul(Fp3.ONE, Z), Q); let x = Fp3.pow(n, Q1div2); let b = Fp3.pow(n, Q); while (!Fp3.eql(b, Fp3.ONE)) { if (Fp3.eql(b, Fp3.ZERO)) return Fp3.ZERO; let m = 1; for (let t2 = Fp3.sqr(b); m < r; m++) { if (Fp3.eql(t2, Fp3.ONE)) break; t2 = Fp3.sqr(t2); } const ge = Fp3.pow(g, _1n9 << BigInt(r - m - 1)); g = Fp3.sqr(ge); x = Fp3.mul(x, ge); b = Fp3.mul(b, g); r = m; } return x; }; } function FpSqrt2(P) { if (P % _4n4 === _3n6) { return function sqrt3mod4(Fp3, n) { const p1div4 = (P + _1n9) / _4n4; const root = Fp3.pow(n, p1div4); if (!Fp3.eql(Fp3.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } if (P % _8n2 === _5n2) { return function sqrt5mod8(Fp3, n) { const n2 = Fp3.mul(n, _2n7); const c1 = (P - _5n2) / _8n2; const v = Fp3.pow(n2, c1); const nv = Fp3.mul(n, v); const i = Fp3.mul(Fp3.mul(nv, _2n7), v); const root = Fp3.mul(nv, Fp3.sub(i, Fp3.ONE)); if (!Fp3.eql(Fp3.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } if (P % _16n2 === _9n2) { } return tonelliShanks2(P); } var isNegativeLE = (num, modulo) => (mod2(num, modulo) & _1n9) === _1n9; exports2.isNegativeLE = isNegativeLE; var FIELD_FIELDS2 = [ "create", "isValid", "is0", "neg", "inv", "sqrt", "sqr", "eql", "add", "sub", "mul", "pow", "div", "addN", "subN", "mulN", "sqrN" ]; function validateField2(field) { const initial = { ORDER: "bigint", MASK: "bigint", BYTES: "isSafeInteger", BITS: "isSafeInteger" }; const opts = FIELD_FIELDS2.reduce((map, val) => { map[val] = "function"; return map; }, initial); return (0, utils_ts_1.validateObject)(field, opts); } function FpPow2(Fp3, num, power) { if (power < _0n9) throw new Error("invalid exponent, negatives unsupported"); if (power === _0n9) return Fp3.ONE; if (power === _1n9) return num; let p = Fp3.ONE; let d = num; while (power > _0n9) { if (power & _1n9) p = Fp3.mul(p, d); d = Fp3.sqr(d); power >>= _1n9; } return p; } function FpInvertBatch2(Fp3, nums, passZero = false) { const inverted = new Array(nums.length).fill(passZero ? Fp3.ZERO : void 0); const multipliedAcc = nums.reduce((acc, num, i) => { if (Fp3.is0(num)) return acc; inverted[i] = acc; return Fp3.mul(acc, num); }, Fp3.ONE); const invertedAcc = Fp3.inv(multipliedAcc); nums.reduceRight((acc, num, i) => { if (Fp3.is0(num)) return acc; inverted[i] = Fp3.mul(acc, inverted[i]); return Fp3.mul(acc, num); }, invertedAcc); return inverted; } function FpDiv(Fp3, lhs, rhs) { return Fp3.mul(lhs, typeof rhs === "bigint" ? invert2(rhs, Fp3.ORDER) : Fp3.inv(rhs)); } function FpLegendre2(Fp3, n) { const legc = (Fp3.ORDER - _1n9) / _2n7; const powered = Fp3.pow(n, legc); const yes = Fp3.eql(powered, Fp3.ONE); const zero = Fp3.eql(powered, Fp3.ZERO); const no = Fp3.eql(powered, Fp3.neg(Fp3.ONE)); if (!yes && !zero && !no) throw new Error("Cannot find square root: probably non-prime P"); return yes ? 1 : zero ? 0 : -1; } function FpIsSquare2(Fp3, n) { const l = FpLegendre2(Fp3, n); return l === 0 || l === 1; } function nLength2(n, nBitLength) { if (nBitLength !== void 0) (0, utils_1.anumber)(nBitLength); const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; const nByteLength = Math.ceil(_nBitLength / 8); return { nBitLength: _nBitLength, nByteLength }; } function Field2(ORDER, bitLen2, isLE2 = false, redef = {}) { if (ORDER <= _0n9) throw new Error("invalid field: expected ORDER > 0, got " + ORDER); const { nBitLength: BITS, nByteLength: BYTES } = nLength2(ORDER, bitLen2); if (BYTES > 2048) throw new Error("invalid field: expected ORDER of <= 2048 bytes"); let sqrtP; const f = Object.freeze({ ORDER, isLE: isLE2, BITS, BYTES, MASK: (0, utils_ts_1.bitMask)(BITS), ZERO: _0n9, ONE: _1n9, create: (num) => mod2(num, ORDER), isValid: (num) => { if (typeof num !== "bigint") throw new Error("invalid field element: expected bigint, got " + typeof num); return _0n9 <= num && num < ORDER; }, is0: (num) => num === _0n9, isOdd: (num) => (num & _1n9) === _1n9, neg: (num) => mod2(-num, ORDER), eql: (lhs, rhs) => lhs === rhs, sqr: (num) => mod2(num * num, ORDER), add: (lhs, rhs) => mod2(lhs + rhs, ORDER), sub: (lhs, rhs) => mod2(lhs - rhs, ORDER), mul: (lhs, rhs) => mod2(lhs * rhs, ORDER), pow: (num, power) => FpPow2(f, num, power), div: (lhs, rhs) => mod2(lhs * invert2(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) => invert2(num, ORDER), sqrt: redef.sqrt || ((n) => { if (!sqrtP) sqrtP = FpSqrt2(ORDER); return sqrtP(f, n); }), toBytes: (num) => isLE2 ? (0, utils_ts_1.numberToBytesLE)(num, BYTES) : (0, utils_ts_1.numberToBytesBE)(num, BYTES), fromBytes: (bytes) => { if (bytes.length !== BYTES) throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length); return isLE2 ? (0, utils_ts_1.bytesToNumberLE)(bytes) : (0, utils_ts_1.bytesToNumberBE)(bytes); }, // TODO: we don't need it here, move out to separate fn invertBatch: (lst) => FpInvertBatch2(f, lst), // We can't move this out because Fp6, Fp12 implement it // and it's unclear what to return in there. cmov: (a, b, c) => c ? b : a }); return Object.freeze(f); } function FpSqrtOdd(Fp3, elm) { if (!Fp3.isOdd) throw new Error("Field doesn't have isOdd"); const root = Fp3.sqrt(elm); return Fp3.isOdd(root) ? root : Fp3.neg(root); } function FpSqrtEven(Fp3, elm) { if (!Fp3.isOdd) throw new Error("Field doesn't have isOdd"); const root = Fp3.sqrt(elm); return Fp3.isOdd(root) ? Fp3.neg(root) : root; } function hashToPrivateScalar(hash, groupOrder, isLE2 = false) { hash = (0, utils_ts_1.ensureBytes)("privateHash", hash); const hashLen = hash.length; const minLen = nLength2(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_ts_1.bytesToNumberLE)(hash) : (0, utils_ts_1.bytesToNumberBE)(hash); return mod2(num, groupOrder - _1n9) + _1n9; } function getFieldBytesLength2(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 getMinHashLength2(fieldOrder) { const length = getFieldBytesLength2(fieldOrder); return length + Math.ceil(length / 2); } function mapHashToField2(key, fieldOrder, isLE2 = false) { const len = key.length; const fieldLen = getFieldBytesLength2(fieldOrder); const minLen = getMinHashLength2(fieldOrder); if (len < 16 || len < minLen || len > 1024) throw new Error("expected " + minLen + "-1024 bytes of input, got " + len); const num = isLE2 ? (0, utils_ts_1.bytesToNumberLE)(key) : (0, utils_ts_1.bytesToNumberBE)(key); const reduced = mod2(num, fieldOrder - _1n9) + _1n9; return isLE2 ? (0, utils_ts_1.numberToBytesLE)(reduced, fieldLen) : (0, utils_ts_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"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.expand_message_xmd = expand_message_xmd2; exports2.expand_message_xof = expand_message_xof2; exports2.hash_to_field = hash_to_field2; exports2.isogenyMap = isogenyMap2; exports2.createHasher = createHasher3; var modular_ts_1 = require_modular(); var utils_ts_1 = require_utils2(); var os2ip2 = utils_ts_1.bytesToNumberBE; function i2osp2(value, length) { anum2(value); anum2(length); if (value < 0 || value >= 1 << 8 * length) throw new Error("invalid I2OSP input: " + value); 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 strxor2(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 anum2(item) { if (!Number.isSafeInteger(item)) throw new Error("number expected"); } function expand_message_xmd2(msg, DST, lenInBytes, H) { (0, utils_ts_1.abytes)(msg); (0, utils_ts_1.abytes)(DST); anum2(lenInBytes); if (DST.length > 255) DST = H((0, utils_ts_1.concatBytes)((0, utils_ts_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_ts_1.concatBytes)(DST, i2osp2(DST.length, 1)); const Z_pad = i2osp2(0, r_in_bytes); const l_i_b_str = i2osp2(lenInBytes, 2); const b = new Array(ell); const b_0 = H((0, utils_ts_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp2(0, 1), DST_prime)); b[0] = H((0, utils_ts_1.concatBytes)(b_0, i2osp2(1, 1), DST_prime)); for (let i = 1; i <= ell; i++) { const args = [strxor2(b_0, b[i - 1]), i2osp2(i + 1, 1), DST_prime]; b[i] = H((0, utils_ts_1.concatBytes)(...args)); } const pseudo_random_bytes = (0, utils_ts_1.concatBytes)(...b); return pseudo_random_bytes.slice(0, lenInBytes); } function expand_message_xof2(msg, DST, lenInBytes, k, H) { (0, utils_ts_1.abytes)(msg); (0, utils_ts_1.abytes)(DST); anum2(lenInBytes); if (DST.length > 255) { const dkLen = Math.ceil(2 * k / 8); DST = H.create({ dkLen }).update((0, utils_ts_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(i2osp2(lenInBytes, 2)).update(DST).update(i2osp2(DST.length, 1)).digest(); } function hash_to_field2(msg, count, options) { (0, utils_ts_1.validateObject)(options, { DST: "stringOrUint8Array", p: "bigint", m: "isSafeInteger", k: "isSafeInteger", hash: "hash" }); const { p, k, m, hash, expand, DST: _DST } = options; (0, utils_ts_1.abytes)(msg); anum2(count); const DST = typeof _DST === "string" ? (0, utils_ts_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_xmd2(msg, DST, len_in_bytes, hash); } else if (expand === "xof") { prb = expand_message_xof2(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_ts_1.mod)(os2ip2(tv), p); } u[i] = e; } return u; } function isogenyMap2(field, map) { const coeff = map.map((i) => Array.from(i).reverse()); return (x, y) => { const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); const [xd_inv, yd_inv] = (0, modular_ts_1.FpInvertBatch)(field, [xd, yd], true); x = field.mul(xn, xd_inv); y = field.mul(y, field.mul(yn, yd_inv)); return { x, y }; }; } function createHasher3(Point, mapToCurve, defaults) { if (typeof mapToCurve !== "function") throw new Error("mapToCurve() must be defined"); function map(num) { return Point.fromAffine(mapToCurve(num)); } function clear(initial) { const P = initial.clearCofactor(); if (P.equals(Point.ZERO)) return Point.ZERO; P.assertValidity(); return P; } return { defaults, // 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_field2(msg, 2, { ...defaults, DST: defaults.DST, ...options }); const u0 = map(u[0]); const u1 = map(u[1]); return clear(u0.add(u1)); }, // 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_field2(msg, 1, { ...defaults, DST: defaults.encodeDST, ...options }); return clear(map(u[0])); }, // Same as encodeToCurve, but without hash mapToCurve(scalars) { if (!Array.isArray(scalars)) throw new Error("expected array of bigints"); for (const i of scalars) if (typeof i !== "bigint") throw new Error("expected array of bigints"); return clear(map(scalars)); } }; } } }); // node_modules/@noble/curves/abstract/curve.js var require_curve = __commonJS({ "node_modules/@noble/curves/abstract/curve.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.wNAF = wNAF2; exports2.pippenger = pippenger2; exports2.precomputeMSMUnsafe = precomputeMSMUnsafe; exports2.validateBasic = validateBasic2; var modular_ts_1 = require_modular(); var utils_ts_1 = require_utils2(); var _0n9 = BigInt(0); var _1n9 = BigInt(1); function constTimeNegate2(condition, item) { const neg = item.negate(); return condition ? neg : item; } function validateW2(W, bits) { if (!Number.isSafeInteger(W) || W <= 0 || W > bits) throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W); } function calcWOpts2(W, scalarBits) { validateW2(W, scalarBits); const windows = Math.ceil(scalarBits / W) + 1; const windowSize = 2 ** (W - 1); const maxNumber = 2 ** W; const mask = (0, utils_ts_1.bitMask)(W); const shiftBy = BigInt(W); return { windows, windowSize, mask, maxNumber, shiftBy }; } function calcOffsets2(n, window, wOpts) { const { windowSize, mask, maxNumber, shiftBy } = wOpts; let wbits = Number(n & mask); let nextN = n >> shiftBy; if (wbits > windowSize) { wbits -= maxNumber; nextN += _1n9; } const offsetStart = window * windowSize; const offset = offsetStart + Math.abs(wbits) - 1; const isZero = wbits === 0; const isNeg = wbits < 0; const isNegF = window % 2 !== 0; const offsetF = offsetStart; return { nextN, offset, isZero, isNeg, isNegF, offsetF }; } function validateMSMPoints2(points, c) { if (!Array.isArray(points)) throw new Error("array expected"); points.forEach((p, i) => { if (!(p instanceof c)) throw new Error("invalid point at index " + i); }); } function validateMSMScalars2(scalars, field) { if (!Array.isArray(scalars)) throw new Error("array of scalars expected"); scalars.forEach((s, i) => { if (!field.isValid(s)) throw new Error("invalid scalar at index " + i); }); } var pointPrecomputes2 = /* @__PURE__ */ new WeakMap(); var pointWindowSizes2 = /* @__PURE__ */ new WeakMap(); function getW2(P) { return pointWindowSizes2.get(P) || 1; } function wNAF2(c, bits) { return { constTimeNegate: constTimeNegate2, hasPrecomputes(elm) { return getW2(elm) !== 1; }, // non-const time multiplication ladder unsafeLadder(elm, n, p = c.ZERO) { let d = elm; while (n > _0n9) { if (n & _1n9) p = p.add(d); d = d.double(); n >>= _1n9; } 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. * @param elm Point instance * @param W window size * @returns precomputed point tables flattened to a single array */ precomputeWindow(elm, W) { const { windows, windowSize } = calcWOpts2(W, bits); 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) { let p = c.ZERO; let f = c.BASE; const wo = calcWOpts2(W, bits); for (let window = 0; window < wo.windows; window++) { const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets2(n, window, wo); n = nextN; if (isZero) { f = f.add(constTimeNegate2(isNegF, precomputes[offsetF])); } else { p = p.add(constTimeNegate2(isNeg, precomputes[offset])); } } return { p, f }; }, /** * Implements ec unsafe (non const-time) 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) * @param acc accumulator point to add result of multiplication * @returns point */ wNAFUnsafe(W, precomputes, n, acc = c.ZERO) { const wo = calcWOpts2(W, bits); for (let window = 0; window < wo.windows; window++) { if (n === _0n9) break; const { nextN, offset, isZero, isNeg } = calcOffsets2(n, window, wo); n = nextN; if (isZero) { continue; } else { const item = precomputes[offset]; acc = acc.add(isNeg ? item.negate() : item); } } return acc; }, getPrecomputes(W, P, transform) { let comp = pointPrecomputes2.get(P); if (!comp) { comp = this.precomputeWindow(P, W); if (W !== 1) pointPrecomputes2.set(P, transform(comp)); } return comp; }, wNAFCached(P, n, transform) { const W = getW2(P); return this.wNAF(W, this.getPrecomputes(W, P, transform), n); }, wNAFCachedUnsafe(P, n, transform, prev) { const W = getW2(P); if (W === 1) return this.unsafeLadder(P, n, prev); return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev); }, // 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) { validateW2(W, bits); pointWindowSizes2.set(P, W); pointPrecomputes2.delete(P); } }; } function pippenger2(c, fieldN, points, scalars) { validateMSMPoints2(points, c); validateMSMScalars2(scalars, fieldN); if (points.length !== scalars.length) throw new Error("arrays of points and scalars must have equal length"); const zero = c.ZERO; const wbits = (0, utils_ts_1.bitLen)(BigInt(points.length)); const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; const MASK = (0, utils_ts_1.bitMask)(windowSize); const buckets = new Array(Number(MASK) + 1).fill(zero); const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize; let sum = zero; for (let i = lastBits; i >= 0; i -= windowSize) { buckets.fill(zero); for (let j = 0; j < scalars.length; j++) { const scalar = scalars[j]; const wbits2 = Number(scalar >> BigInt(i) & MASK); buckets[wbits2] = buckets[wbits2].add(points[j]); } let resI = zero; for (let j = buckets.length - 1, sumI = 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 precomputeMSMUnsafe(c, fieldN, points, windowSize) { validateW2(windowSize, fieldN.BITS); validateMSMPoints2(points, c); const zero = c.ZERO; const tableSize = 2 ** windowSize - 1; const chunks = Math.ceil(fieldN.BITS / windowSize); const MASK = (0, utils_ts_1.bitMask)(windowSize); const tables = points.map((p) => { const res = []; for (let i = 0, acc = p; i < tableSize; i++) { res.push(acc); acc = acc.add(p); } return res; }); return (scalars) => { validateMSMScalars2(scalars, fieldN); if (scalars.length > points.length) throw new Error("array of scalars must be smaller than array of points"); let res = zero; for (let i = 0; i < chunks; i++) { if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double(); const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize); for (let j = 0; j < scalars.length; j++) { const n = scalars[j]; const curr = Number(n >> shiftBy & MASK); if (!curr) continue; res = res.add(tables[j][curr - 1]); } } return res; }; } function validateBasic2(curve) { (0, modular_ts_1.validateField)(curve.Fp); (0, utils_ts_1.validateObject)(curve, { n: "bigint", h: "bigint", Gx: "field", Gy: "field" }, { nBitLength: "isSafeInteger", nByteLength: "isSafeInteger" }); return Object.freeze({ ...(0, modular_ts_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"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DER = exports2.DERErr = void 0; exports2.weierstrassPoints = weierstrassPoints2; exports2.weierstrass = weierstrass; exports2.SWUFpSqrtRatio = SWUFpSqrtRatio2; exports2.mapToCurveSimpleSWU = mapToCurveSimpleSWU2; var curve_ts_1 = require_curve(); var modular_ts_1 = require_modular(); var utils_ts_1 = require_utils2(); function validateSigVerOpts(opts) {