UNPKG

randomness-js

Version:

A library for consuming, verifying and using randomness from the dcipher network

1,335 lines (1,328 loc) 2.78 MB
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 __typeError = (msg) => { throw TypeError(msg); }; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; 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 __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); var __privateWrapper = (obj, member, setter, getter) => ({ set _(value) { __privateSet(obj, member, value, setter); }, get _() { return __privateGet(obj, member, getter); } }); // 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/utils.js var require_utils = __commonJS({ "node_modules/@noble/hashes/utils.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.isLE = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0; var crypto_1 = require_crypto(); var u8a3 = (a) => a instanceof Uint8Array; var u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); exports.u8 = u8; var u322 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); exports.u32 = u322; var createView2 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); exports.createView = createView2; var rotr2 = (word, shift) => word << 32 - shift | word >>> shift; exports.rotr = rotr2; exports.isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; if (!exports.isLE) throw new Error("Non little-endian hardware is not supported"); var hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); function bytesToHex2(bytes2) { if (!u8a3(bytes2)) throw new Error("Uint8Array expected"); let hex = ""; for (let i = 0; i < bytes2.length; i++) { hex += hexes2[bytes2[i]]; } return hex; } exports.bytesToHex = bytesToHex2; function hexToBytes2(hex) { if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex); const len = hex.length; if (len % 2) throw new Error("padded hex string expected, got unpadded hex of length " + len); const array = new Uint8Array(len / 2); for (let i = 0; i < array.length; i++) { const j = i * 2; const hexByte = hex.slice(j, j + 2); const byte = Number.parseInt(hexByte, 16); if (Number.isNaN(byte) || byte < 0) throw new Error("Invalid byte sequence"); array[i] = byte; } return array; } exports.hexToBytes = hexToBytes2; var nextTick2 = async () => { }; exports.nextTick = nextTick2; async function asyncLoop2(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; } } exports.asyncLoop = asyncLoop2; function utf8ToBytes3(str) { if (typeof str !== "string") throw new Error(`utf8ToBytes expected string, got ${typeof str}`); return new Uint8Array(new TextEncoder().encode(str)); } exports.utf8ToBytes = utf8ToBytes3; function toBytes2(data) { if (typeof data === "string") data = utf8ToBytes3(data); if (!u8a3(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); return data; } exports.toBytes = toBytes2; function concatBytes3(...arrays) { const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); let pad = 0; arrays.forEach((a) => { if (!u8a3(a)) throw new Error("Uint8Array expected"); r.set(a, pad); pad += a.length; }); return r; } exports.concatBytes = concatBytes3; var Hash2 = class { // Safe version that clones internal state clone() { return this._cloneInto(); } }; exports.Hash = Hash2; var toStr2 = {}.toString; function checkOpts2(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; } exports.checkOpts = checkOpts2; function wrapConstructor2(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; } exports.wrapConstructor = wrapConstructor2; function wrapConstructorWithOpts(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; } exports.wrapConstructorWithOpts = wrapConstructorWithOpts; function wrapXOFConstructorWithOpts2(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; } exports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts2; function randomBytes4(bytesLength = 32) { if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") { return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength)); } throw new Error("crypto.getRandomValues must be defined"); } exports.randomBytes = randomBytes4; } }); // 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 = bytesToHex2; exports.numberToHexUnpadded = numberToHexUnpadded2; exports.hexToNumber = hexToNumber2; exports.hexToBytes = hexToBytes2; exports.bytesToNumberBE = bytesToNumberBE2; exports.bytesToNumberLE = bytesToNumberLE2; exports.numberToBytesBE = numberToBytesBE2; exports.numberToBytesLE = numberToBytesLE2; exports.numberToVarBytesBE = numberToVarBytesBE2; exports.ensureBytes = ensureBytes2; exports.concatBytes = concatBytes3; exports.equalBytes = equalBytes3; exports.utf8ToBytes = utf8ToBytes3; exports.inRange = inRange; exports.aInRange = aInRange; exports.bitLen = bitLen2; exports.bitGet = bitGet2; exports.bitSet = bitSet2; exports.createHmacDrbg = createHmacDrbg2; exports.validateObject = validateObject2; exports.memoized = memoized; var _0n7 = /* @__PURE__ */ BigInt(0); var _1n7 = /* @__PURE__ */ BigInt(1); var _2n6 = /* @__PURE__ */ BigInt(2); function isBytes(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && 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 + " boolean expected, got " + value); } var hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); function bytesToHex2(bytes2) { abytes(bytes2); let hex = ""; for (let i = 0; i < bytes2.length; i++) { hex += hexes2[bytes2[i]]; } return hex; } 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 === "" ? _0n7 : BigInt("0x" + hex); } var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; function asciiToBase16(ch) { if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); return; } function hexToBytes2(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("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 bytesToNumberBE2(bytes2) { return hexToNumber2(bytesToHex2(bytes2)); } function bytesToNumberLE2(bytes2) { abytes(bytes2); return hexToNumber2(bytesToHex2(Uint8Array.from(bytes2).reverse())); } function numberToBytesBE2(n2, len) { return hexToBytes2(n2.toString(16).padStart(len * 2, "0")); } function numberToBytesLE2(n2, len) { return numberToBytesBE2(n2, len).reverse(); } function numberToVarBytesBE2(n2) { return hexToBytes2(numberToHexUnpadded2(n2)); } 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 (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 + " of length " + expectedLength + " expected, got " + len); return res; } function concatBytes3(...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 equalBytes3(a, b2) { if (a.length !== b2.length) return false; let diff = 0; for (let i = 0; i < a.length; i++) diff |= a[i] ^ b2[i]; return diff === 0; } function utf8ToBytes3(str) { if (typeof str !== "string") throw new Error("string expected"); return new Uint8Array(new TextEncoder().encode(str)); } var isPosBig = (n2) => typeof n2 === "bigint" && _0n7 <= n2; function inRange(n2, min, max) { return isPosBig(n2) && isPosBig(min) && isPosBig(max) && min <= n2 && n2 < max; } function aInRange(title, n2, min, max) { if (!inRange(n2, min, max)) throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n2); } function bitLen2(n2) { let len; for (len = 0; n2 > _0n7; n2 >>= _1n7, len += 1) ; return len; } function bitGet2(n2, pos) { return n2 >> BigInt(pos) & _1n7; } function bitSet2(n2, pos, value) { return n2 | (value ? _1n7 : _0n7) << BigInt(pos); } var bitMask2 = (n2) => (_2n6 << BigInt(n2 - 1)) - _1n7; exports.bitMask = bitMask2; var u8n2 = (data) => new Uint8Array(data); var u8fr2 = (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 = u8n2(hashLen); let k = u8n2(hashLen); let i = 0; const reset = () => { v.fill(1); k.fill(0); i = 0; }; const h = (...b2) => hmacFn(k, v, ...b2); const reseed = (seed = u8n2()) => { k = h(u8fr2([0]), seed); v = h(); if (seed.length === 0) return; k = h(u8fr2([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 concatBytes3(...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" || isBytes(val), isSafeInteger: (val) => Number.isSafeInteger(val), array: (val) => Array.isArray(val), field: (val, object2) => object2.Fp.isValid(val), hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) }; function validateObject2(object2, validators, optValidators = {}) { const checkField = (fieldName, type, isOptional) => { const checkVal = validatorFns2[type]; if (typeof checkVal !== "function") throw new Error("invalid validator function"); const val = object2[fieldName]; if (isOptional && val === void 0) return; if (!checkVal(val, object2)) { 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 object2; } 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 = mod2; exports.pow = pow3; exports.pow2 = pow22; exports.invert = invert2; exports.tonelliShanks = tonelliShanks2; exports.FpSqrt = FpSqrt2; exports.validateField = validateField2; exports.FpPow = FpPow2; exports.FpInvertBatch = FpInvertBatch2; exports.FpDiv = FpDiv; exports.FpLegendre = FpLegendre; exports.FpIsSquare = FpIsSquare; exports.nLength = nLength2; exports.Field = Field2; exports.FpSqrtOdd = FpSqrtOdd; exports.FpSqrtEven = FpSqrtEven; exports.hashToPrivateScalar = hashToPrivateScalar; exports.getFieldBytesLength = getFieldBytesLength2; exports.getMinHashLength = getMinHashLength2; exports.mapHashToField = mapHashToField2; var utils_js_1 = require_utils2(); var _0n7 = BigInt(0); var _1n7 = BigInt(1); var _2n6 = /* @__PURE__ */ BigInt(2); var _3n3 = /* @__PURE__ */ BigInt(3); var _4n3 = /* @__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, b2) { const result = a % b2; return result >= _0n7 ? result : b2 + result; } function pow3(num, power, modulo) { if (power < _0n7) throw new Error("invalid exponent, negatives unsupported"); if (modulo <= _0n7) throw new Error("invalid modulus"); if (modulo === _1n7) return _0n7; let res = _1n7; while (power > _0n7) { if (power & _1n7) res = res * num % modulo; num = num * num % modulo; power >>= _1n7; } return res; } function pow22(x, power, modulo) { let res = x; while (power-- > _0n7) { res *= res; res %= modulo; } return res; } function invert2(number2, modulo) { if (number2 === _0n7) throw new Error("invert: expected non-zero number"); if (modulo <= _0n7) throw new Error("invert: expected positive modulus, got " + modulo); let a = mod2(number2, modulo); let b2 = modulo; let x = _0n7, y = _1n7, u = _1n7, v = _0n7; while (a !== _0n7) { const q = b2 / a; const r = b2 % a; const m = x - u * q; const n2 = y - v * q; b2 = a, a = r, x = u, y = v, u = m, v = n2; } const gcd = b2; if (gcd !== _1n7) throw new Error("invert: does not exist"); return mod2(x, modulo); } function tonelliShanks2(P) { const legendreC = (P - _1n7) / _2n6; let Q, S2, Z; for (Q = P - _1n7, S2 = 0; Q % _2n6 === _0n7; Q /= _2n6, S2++) ; for (Z = _2n6; Z < P && pow3(Z, legendreC, P) !== P - _1n7; Z++) { if (Z > 1e3) throw new Error("Cannot find square root: likely non-prime P"); } if (S2 === 1) { const p1div4 = (P + _1n7) / _4n3; return function tonelliFast(Fp2, n2) { const root = Fp2.pow(n2, p1div4); if (!Fp2.eql(Fp2.sqr(root), n2)) throw new Error("Cannot find square root"); return root; }; } const Q1div2 = (Q + _1n7) / _2n6; return function tonelliSlow(Fp2, n2) { if (Fp2.pow(n2, legendreC) === Fp2.neg(Fp2.ONE)) throw new Error("Cannot find square root"); let r = S2; let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q); let x = Fp2.pow(n2, Q1div2); let b2 = Fp2.pow(n2, Q); while (!Fp2.eql(b2, Fp2.ONE)) { if (Fp2.eql(b2, Fp2.ZERO)) return Fp2.ZERO; let m = 1; for (let t2 = Fp2.sqr(b2); m < r; m++) { if (Fp2.eql(t2, Fp2.ONE)) break; t2 = Fp2.sqr(t2); } const ge = Fp2.pow(g, _1n7 << BigInt(r - m - 1)); g = Fp2.sqr(ge); x = Fp2.mul(x, ge); b2 = Fp2.mul(b2, g); r = m; } return x; }; } function FpSqrt2(P) { if (P % _4n3 === _3n3) { const p1div4 = (P + _1n7) / _4n3; return function sqrt3mod4(Fp2, n2) { const root = Fp2.pow(n2, p1div4); if (!Fp2.eql(Fp2.sqr(root), n2)) throw new Error("Cannot find square root"); return root; }; } if (P % _8n2 === _5n2) { const c1 = (P - _5n2) / _8n2; return function sqrt5mod8(Fp2, n2) { const n22 = Fp2.mul(n2, _2n6); const v = Fp2.pow(n22, c1); const nv = Fp2.mul(n2, v); const i = Fp2.mul(Fp2.mul(nv, _2n6), v); const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); if (!Fp2.eql(Fp2.sqr(root), n2)) throw new Error("Cannot find square root"); return root; }; } if (P % _16n2 === _9n2) { } return tonelliShanks2(P); } var isNegativeLE = (num, modulo) => (mod2(num, modulo) & _1n7) === _1n7; exports.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_js_1.validateObject)(field, opts); } function FpPow2(f2, num, power) { if (power < _0n7) throw new Error("invalid exponent, negatives unsupported"); if (power === _0n7) return f2.ONE; if (power === _1n7) return num; let p = f2.ONE; let d = num; while (power > _0n7) { if (power & _1n7) p = f2.mul(p, d); d = f2.sqr(d); power >>= _1n7; } return p; } function FpInvertBatch2(f2, nums) { const tmp = new Array(nums.length); const lastMultiplied = nums.reduce((acc, num, i) => { if (f2.is0(num)) return acc; tmp[i] = acc; return f2.mul(acc, num); }, f2.ONE); const inverted = f2.inv(lastMultiplied); nums.reduceRight((acc, num, i) => { if (f2.is0(num)) return acc; tmp[i] = f2.mul(acc, tmp[i]); return f2.mul(acc, num); }, inverted); return tmp; } function FpDiv(f2, lhs, rhs) { return f2.mul(lhs, typeof rhs === "bigint" ? invert2(rhs, f2.ORDER) : f2.inv(rhs)); } function FpLegendre(order) { const legendreConst = (order - _1n7) / _2n6; return (f2, x) => f2.pow(x, legendreConst); } function FpIsSquare(f2) { const legendre = FpLegendre(f2.ORDER); return (x) => { const p = legendre(f2, x); return f2.eql(p, f2.ZERO) || f2.eql(p, f2.ONE); }; } function nLength2(n2, nBitLength) { const _nBitLength = nBitLength !== void 0 ? nBitLength : n2.toString(2).length; const nByteLength = Math.ceil(_nBitLength / 8); return { nBitLength: _nBitLength, nByteLength }; } function Field2(ORDER, bitLen2, isLE2 = false, redef = {}) { if (ORDER <= _0n7) 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 f2 = Object.freeze({ ORDER, isLE: isLE2, BITS, BYTES, MASK: (0, utils_js_1.bitMask)(BITS), ZERO: _0n7, ONE: _1n7, create: (num) => mod2(num, ORDER), isValid: (num) => { if (typeof num !== "bigint") throw new Error("invalid field element: expected bigint, got " + typeof num); return _0n7 <= num && num < ORDER; }, is0: (num) => num === _0n7, isOdd: (num) => (num & _1n7) === _1n7, 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(f2, 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 || ((n2) => { if (!sqrtP) sqrtP = FpSqrt2(ORDER); return sqrtP(f2, n2); }), invertBatch: (lst) => FpInvertBatch2(f2, 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, b2, c) => c ? b2 : a, toBytes: (num) => isLE2 ? (0, utils_js_1.numberToBytesLE)(num, BYTES) : (0, utils_js_1.numberToBytesBE)(num, BYTES), fromBytes: (bytes2) => { if (bytes2.length !== BYTES) throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes2.length); return isLE2 ? (0, utils_js_1.bytesToNumberLE)(bytes2) : (0, utils_js_1.bytesToNumberBE)(bytes2); } }); return Object.freeze(f2); } function FpSqrtOdd(Fp2, elm) { if (!Fp2.isOdd) throw new Error("Field doesn't have isOdd"); const root = Fp2.sqrt(elm); return Fp2.isOdd(root) ? root : Fp2.neg(root); } function FpSqrtEven(Fp2, elm) { if (!Fp2.isOdd) throw new Error("Field doesn't have isOdd"); const root = Fp2.sqrt(elm); return Fp2.isOdd(root) ? Fp2.neg(root) : root; } function hashToPrivateScalar(hash2, groupOrder, isLE2 = false) { hash2 = (0, utils_js_1.ensureBytes)("privateHash", hash2); const hashLen = hash2.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_js_1.bytesToNumberLE)(hash2) : (0, utils_js_1.bytesToNumberBE)(hash2); return mod2(num, groupOrder - _1n7) + _1n7; } 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_js_1.bytesToNumberLE)(key) : (0, utils_js_1.bytesToNumberBE)(key); const reduced = mod2(num, fieldOrder - _1n7) + _1n7; 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("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 strxor(a, b2) { const arr = new Uint8Array(a.length); for (let i = 0; i < a.length; i++) { arr[i] = a[i] ^ b2[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 b2 = new Array(ell); const b_0 = H((0, utils_js_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); b2[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, b2[i - 1]), i2osp(i + 1, 1), DST_prime]; b2[i] = H((0, utils_js_1.concatBytes)(...args)); } const pseudo_random_bytes = (0, utils_js_1.concatBytes)(...b2); 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: hash2, 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, hash2); } else if (expand === "xof") { prb = expand_message_xof(msg, DST, len_in_bytes, k, hash2); } 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(Point2, 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 = Point2.fromAffine(mapToCurve(u[0])); const u1 = Point2.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 = Point2.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"); const P = Point2.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 = wNAF2; exports.pippenger = pippenger; exports.precomputeMSMUnsafe = precomputeMSMUnsafe; exports.validateBasic = validateBasic2; var modular_js_1 = require_modular(); var utils_js_1 = require_utils2(); var _0n7 = BigInt(0); var _1n7 = BigInt(1); function constTimeNegate(condition, item) { const neg = item.negate(); return condition ? neg : item; } function validateW(W, bits) { if (!Number.isSafeInteger(W) || W <= 0 || W > bits) throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W); } function calcWOpts(W, bits) { validateW(W, bits); const windows = Math.ceil(bits / W) + 1; const windowSize = 2 ** (W - 1); return { windows, windowSize }; } function validateMSMPoints(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 validateMSMScalars(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 pointPrecomputes = /* @__PURE__ */ new WeakMap(); var pointWindowSizes = /* @__PURE__ */ new WeakMap(); function getW(P) { return pointWindowSizes.get(P) || 1; } function wNAF2(c, bits) { return { constTimeNegate, hasPrecomputes(elm) { return getW(elm) !== 1; }, // non-const time multiplication ladder unsafeLadder(elm, n2, p = c.ZERO) { let d = elm; while (n2 > _0n7) { if (n2 & _1n7) p = p.add(d); d = d.double(); n2 >>= _1n7; } 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 } = calcWOpts(W, bits); const points = []; let p = elm; let base = p; for (let window2 = 0; window2 < windows; window2++) { 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, n2) { const { windows, windowSize } = calcWOpts(W, bits); let p = c.ZERO; let f2 = c.BASE; const mask2 = BigInt(2 ** W - 1); const maxNumber = 2 ** W; const shiftBy = BigInt(W); for (let window2 = 0; window2 < windows; window2++) { const offset = window2 * windowSize; let wbits = Number(n2 & mask2); n2 >>= shiftBy; if (wbits > windowSize) { wbits -= maxNumber; n2 += _1n7; } const offset1 = offset; const offset2 = offset + Math.abs(wbits) - 1; const cond1 = window2 % 2 !== 0; const cond2 = wbits < 0; if (wbits === 0) { f2 = f2.add(constTimeNegate(cond1, precomputes[offset1])); } else { p = p.add(constTimeNegate(cond2, precomputes[offset2])); } } return { p, f: f2 }; }, /** * 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, n2, acc = c.ZERO) { const { windows, windowSize } = calcWOpts(W, bits); const mask2 = BigInt(2 ** W - 1); const maxNumber = 2 ** W; const shiftBy = BigInt(W); for (let window2 = 0; window2 < windows; window2++) { const offset = window2 * windowSize; if (n2 === _0n7) break; let wbits = Number(n2 & mask2); n2 >>= shiftBy; if (wbits > windowSize) { wbits -= maxNumber; n2 += _1n7; } if (wbits === 0) continue; let curr = precomputes[offset + Math.abs(wbits) - 1]; if (wbits < 0) curr = curr.negate(); acc = acc.add(curr); } return acc; }, getPrecomputes(W, P, transform) { let comp = pointPrecomputes.get(P); if (!comp) { comp = this.precomputeWindow(P, W); if (W !== 1) pointPrecomputes.set(P, transform(comp)); } return comp; }, wNAFCached(P, n2, transform) { const W = getW(P); return this.wNAF(W, this.getPrecomputes(W, P, transform), n2); }, wNAFCachedUnsafe(P, n2, transform, prev) { const W = getW(P); if (W === 1) return this.unsafeLadder(P, n2, prev); return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n2, 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) { validateW(W, bits); pointWindowSizes.set(P, W); pointPrecomputes.delete(P); } }; } function pippenger(c, fieldN, points, scalars) { validateMSMPoints(points, c); validateMSMScalars(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_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(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) & BigInt(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) { validateW(windowSize, fieldN.BITS); validateMSMPoints(points, c); const zero = c.ZERO; const tableSize = 2 ** windowSize - 1; const chunks = Math.ceil(fieldN.BITS / windowSize); const MASK = BigInt((1 << windowSize) - 1); 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) => { validateMSMScalars(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 n2 = scalars[j]; const curr = Number(n2 >> shiftBy & MASK); if (!curr) continue; res = res.add(tables[j][curr - 1]); } } return res; }; } function validateBasic2(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 = exports.DERErr = void 0; exports.weierstrassPoints = weierstrassPoints2; exports.weierstrass = weierstrass2; exports.SWUFpSqrtRatio = SWUFpSqrtRatio; exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU; var curve_js_1 = require_curve(); var modular_js_1 = 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 validatePointOpts2(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: Fp2, a } = opts; if (endo) { if (!Fp2.eql(a, Fp2.ZERO)) { throw new Error("invalid 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("invalid endomorphism, expected beta: bigint and splitScalar: function"); } } return Object.freeze({ ...opts }); } var { bytesToNumberBE: b2n2, hexToBytes: h2b2 } = ut; var DERErr2 = class extends Error { constructor(m = "") { super(m); } }; exports.DERErr = DERErr2; exports.DER = { // asn.1 DER encoding utils Err: DERErr2, // 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) : ""; const t = ut.numberToHexUnpadded(tag); return t + 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