UNPKG

randomness-js

Version:

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

1,339 lines (1,332 loc) 1.42 MB
"use strict"; 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, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.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 = (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 )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); 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/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 nc = require("node:crypto"); exports2.crypto = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : 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.randomBytes = exports2.wrapXOFConstructorWithOpts = exports2.wrapConstructorWithOpts = exports2.wrapConstructor = exports2.checkOpts = exports2.Hash = exports2.concatBytes = exports2.toBytes = exports2.utf8ToBytes = exports2.asyncLoop = exports2.nextTick = exports2.hexToBytes = exports2.bytesToHex = exports2.isLE = exports2.rotr = exports2.createView = exports2.u32 = exports2.u8 = void 0; var crypto_1 = require_cryptoNode(); var u8a2 = (a) => a instanceof Uint8Array; var u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); exports2.u8 = u8; var u322 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); exports2.u32 = u322; var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); exports2.createView = createView; var rotr = (word, shift) => word << 32 - shift | word >>> shift; exports2.rotr = rotr; exports2.isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; if (!exports2.isLE) throw new Error("Non little-endian hardware is not supported"); var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); function bytesToHex(bytes2) { if (!u8a2(bytes2)) throw new Error("Uint8Array expected"); let hex = ""; for (let i = 0; i < bytes2.length; i++) { hex += hexes[bytes2[i]]; } return hex; } exports2.bytesToHex = bytesToHex; function hexToBytes(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; } exports2.hexToBytes = hexToBytes; 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; } } exports2.asyncLoop = asyncLoop; function utf8ToBytes2(str) { if (typeof str !== "string") throw new Error(`utf8ToBytes expected string, got ${typeof str}`); return new Uint8Array(new TextEncoder().encode(str)); } exports2.utf8ToBytes = utf8ToBytes2; function toBytes2(data) { if (typeof data === "string") data = utf8ToBytes2(data); if (!u8a2(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); return data; } exports2.toBytes = toBytes2; function concatBytes(...arrays) { const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); let pad = 0; arrays.forEach((a) => { if (!u8a2(a)) throw new Error("Uint8Array expected"); r.set(a, pad); pad += a.length; }); return r; } exports2.concatBytes = concatBytes; var Hash2 = class { // Safe version that clones internal state clone() { return this._cloneInto(); } }; exports2.Hash = Hash2; 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; } exports2.checkOpts = checkOpts; 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; } exports2.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; } exports2.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; } exports2.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts2; function randomBytes2(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"); } exports2.randomBytes = randomBytes2; } }); // 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 = isBytes; exports2.abytes = abytes; exports2.abool = abool; exports2.bytesToHex = bytesToHex; exports2.numberToHexUnpadded = numberToHexUnpadded; exports2.hexToNumber = hexToNumber; exports2.hexToBytes = hexToBytes; exports2.bytesToNumberBE = bytesToNumberBE; exports2.bytesToNumberLE = bytesToNumberLE; exports2.numberToBytesBE = numberToBytesBE; exports2.numberToBytesLE = numberToBytesLE; exports2.numberToVarBytesBE = numberToVarBytesBE; exports2.ensureBytes = ensureBytes; exports2.concatBytes = concatBytes; exports2.equalBytes = equalBytes2; exports2.utf8ToBytes = utf8ToBytes2; exports2.inRange = inRange; exports2.aInRange = aInRange; exports2.bitLen = bitLen; exports2.bitGet = bitGet; exports2.bitSet = bitSet; exports2.createHmacDrbg = createHmacDrbg; exports2.validateObject = validateObject; exports2.memoized = memoized; var _0n2 = /* @__PURE__ */ BigInt(0); var _1n2 = /* @__PURE__ */ BigInt(1); var _2n2 = /* @__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 hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); function bytesToHex(bytes2) { abytes(bytes2); let hex = ""; for (let i = 0; i < bytes2.length; i++) { hex += hexes[bytes2[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 hex === "" ? _0n2 : 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 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("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(bytes2) { return hexToNumber(bytesToHex(bytes2)); } function bytesToNumberLE(bytes2) { abytes(bytes2); return hexToNumber(bytesToHex(Uint8Array.from(bytes2).reverse())); } function numberToBytesBE(n2, len) { return hexToBytes(n2.toString(16).padStart(len * 2, "0")); } function numberToBytesLE(n2, len) { return numberToBytesBE(n2, len).reverse(); } function numberToVarBytesBE(n2) { return hexToBytes(numberToHexUnpadded(n2)); } function ensureBytes(title, hex, expectedLength) { let res; if (typeof hex === "string") { try { res = hexToBytes(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 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 equalBytes2(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 utf8ToBytes2(str) { if (typeof str !== "string") throw new Error("string expected"); return new Uint8Array(new TextEncoder().encode(str)); } var isPosBig = (n2) => typeof n2 === "bigint" && _0n2 <= 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 bitLen(n2) { let len; for (len = 0; n2 > _0n2; n2 >>= _1n2, len += 1) ; return len; } function bitGet(n2, pos) { return n2 >> BigInt(pos) & _1n2; } function bitSet(n2, pos, value) { return n2 | (value ? _1n2 : _0n2) << BigInt(pos); } var bitMask = (n2) => (_2n2 << BigInt(n2 - 1)) - _1n2; exports2.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 = (...b2) => hmacFn(k, v, ...b2); const reseed = (seed = u8n()) => { 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 concatBytes(...out); }; const genUntil = (seed, pred) => { reset(); reseed(seed); let res = void 0; while (!(res = pred(gen2()))) 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 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 notImplemented = () => { throw new Error("not implemented"); }; exports2.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"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.isNegativeLE = void 0; exports2.mod = mod; exports2.pow = pow; exports2.pow2 = pow2; exports2.invert = invert; exports2.tonelliShanks = tonelliShanks; exports2.FpSqrt = FpSqrt; exports2.validateField = validateField; exports2.FpPow = FpPow; exports2.FpInvertBatch = FpInvertBatch; exports2.FpDiv = FpDiv; exports2.FpLegendre = FpLegendre; exports2.FpIsSquare = FpIsSquare; exports2.nLength = nLength; exports2.Field = Field; exports2.FpSqrtOdd = FpSqrtOdd; exports2.FpSqrtEven = FpSqrtEven; exports2.hashToPrivateScalar = hashToPrivateScalar; exports2.getFieldBytesLength = getFieldBytesLength; exports2.getMinHashLength = getMinHashLength; exports2.mapHashToField = mapHashToField; var utils_js_1 = require_utils2(); var _0n2 = BigInt(0); var _1n2 = BigInt(1); var _2n2 = /* @__PURE__ */ BigInt(2); var _3n = /* @__PURE__ */ BigInt(3); var _4n = /* @__PURE__ */ BigInt(4); var _5n = /* @__PURE__ */ BigInt(5); var _8n = /* @__PURE__ */ BigInt(8); var _9n = /* @__PURE__ */ BigInt(9); var _16n = /* @__PURE__ */ BigInt(16); function mod(a, b2) { const result = a % b2; return result >= _0n2 ? result : b2 + result; } function pow(num, power, modulo) { if (power < _0n2) throw new Error("invalid exponent, negatives unsupported"); if (modulo <= _0n2) throw new Error("invalid modulus"); if (modulo === _1n2) return _0n2; let res = _1n2; while (power > _0n2) { if (power & _1n2) res = res * num % modulo; num = num * num % modulo; power >>= _1n2; } return res; } function pow2(x, power, modulo) { let res = x; while (power-- > _0n2) { res *= res; res %= modulo; } return res; } function invert(number2, modulo) { if (number2 === _0n2) throw new Error("invert: expected non-zero number"); if (modulo <= _0n2) throw new Error("invert: expected positive modulus, got " + modulo); let a = mod(number2, modulo); let b2 = modulo; let x = _0n2, y = _1n2, u = _1n2, v = _0n2; while (a !== _0n2) { 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 !== _1n2) throw new Error("invert: does not exist"); return mod(x, modulo); } function tonelliShanks(P) { const legendreC = (P - _1n2) / _2n2; let Q, S, Z; for (Q = P - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++) ; for (Z = _2n2; Z < P && pow(Z, legendreC, P) !== P - _1n2; Z++) { if (Z > 1e3) throw new Error("Cannot find square root: likely non-prime P"); } if (S === 1) { const p1div4 = (P + _1n2) / _4n; return function tonelliFast(Fp, n2) { const root = Fp.pow(n2, p1div4); if (!Fp.eql(Fp.sqr(root), n2)) throw new Error("Cannot find square root"); return root; }; } const Q1div2 = (Q + _1n2) / _2n2; return function tonelliSlow(Fp, n2) { if (Fp.pow(n2, 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(n2, Q1div2); let b2 = Fp.pow(n2, Q); while (!Fp.eql(b2, Fp.ONE)) { if (Fp.eql(b2, Fp.ZERO)) return Fp.ZERO; let m = 1; for (let t2 = Fp.sqr(b2); m < r; m++) { if (Fp.eql(t2, Fp.ONE)) break; t2 = Fp.sqr(t2); } const ge = Fp.pow(g, _1n2 << BigInt(r - m - 1)); g = Fp.sqr(ge); x = Fp.mul(x, ge); b2 = Fp.mul(b2, g); r = m; } return x; }; } function FpSqrt(P) { if (P % _4n === _3n) { const p1div4 = (P + _1n2) / _4n; return function sqrt3mod4(Fp, n2) { const root = Fp.pow(n2, p1div4); if (!Fp.eql(Fp.sqr(root), n2)) throw new Error("Cannot find square root"); return root; }; } if (P % _8n === _5n) { const c1 = (P - _5n) / _8n; return function sqrt5mod8(Fp, n2) { const n22 = Fp.mul(n2, _2n2); const v = Fp.pow(n22, c1); const nv = Fp.mul(n2, v); const i = Fp.mul(Fp.mul(nv, _2n2), v); const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); if (!Fp.eql(Fp.sqr(root), n2)) throw new Error("Cannot find square root"); return root; }; } if (P % _16n === _9n) { } return tonelliShanks(P); } var isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2; exports2.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 < _0n2) throw new Error("invalid exponent, negatives unsupported"); if (power === _0n2) return f.ONE; if (power === _1n2) return num; let p = f.ONE; let d = num; while (power > _0n2) { if (power & _1n2) p = f.mul(p, d); d = f.sqr(d); power >>= _1n2; } 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 - _1n2) / _2n2; 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(n2, nBitLength) { const _nBitLength = nBitLength !== void 0 ? nBitLength : n2.toString(2).length; const nByteLength = Math.ceil(_nBitLength / 8); return { nBitLength: _nBitLength, nByteLength }; } function Field(ORDER, bitLen, isLE2 = false, redef = {}) { if (ORDER <= _0n2) throw new Error("invalid field: expected ORDER > 0, got " + ORDER); const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); 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_js_1.bitMask)(BITS), ZERO: _0n2, ONE: _1n2, create: (num) => mod(num, ORDER), isValid: (num) => { if (typeof num !== "bigint") throw new Error("invalid field element: expected bigint, got " + typeof num); return _0n2 <= num && num < ORDER; }, is0: (num) => num === _0n2, isOdd: (num) => (num & _1n2) === _1n2, 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 || ((n2) => { if (!sqrtP) sqrtP = FpSqrt(ORDER); return sqrtP(f, n2); }), 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, 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(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 - _1n2) + _1n2; } 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.bytesToNumberLE)(key) : (0, utils_js_1.bytesToNumberBE)(key); const reduced = mod(num, fieldOrder - _1n2) + _1n2; 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"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.expand_message_xmd = expand_message_xmd; exports2.expand_message_xof = expand_message_xof; exports2.hash_to_field = hash_to_field; exports2.isogenyMap = isogenyMap; exports2.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, 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"); 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"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.wNAF = wNAF; exports2.pippenger = pippenger; exports2.precomputeMSMUnsafe = precomputeMSMUnsafe; exports2.validateBasic = validateBasic; var modular_js_1 = require_modular(); var utils_js_1 = require_utils2(); var _0n2 = BigInt(0); var _1n2 = 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 wNAF(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 > _0n2) { if (n2 & _1n2) p = p.add(d); d = d.double(); n2 >>= _1n2; } 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 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, n2) { const { windows, windowSize } = calcWOpts(W, bits); let p = c.ZERO; let f = c.BASE; const mask2 = 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(n2 & mask2); n2 >>= shiftBy; if (wbits > windowSize) { wbits -= maxNumber; n2 += _1n2; } 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 }; }, /** * 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 window = 0; window < windows; window++) { const offset = window * windowSize; if (n2 === _0n2) break; let wbits = Number(n2 & mask2); n2 >>= shiftBy; if (wbits > windowSize) { wbits -= maxNumber; n2 += _1n2; } 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 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"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DER = exports2.DERErr = void 0; exports2.weierstrassPoints = weierstrassPoints; exports2.weierstrass = weierstrass; exports2.SWUFpSqrtRatio = SWUFpSqrtRatio; exports2.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 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("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: b2n, hexToBytes: h2b } = ut; var DERErr = class extends Error { constructor(m = "") { super(m); } }; exports2.DERErr = DERErr; exports2.DER = { // asn.1 DER encoding utils Err: DERErr, // Basic building block is TLV (Tag-Length-Value) _tlv: { encode: (tag, data) => { const { Err: E } = exports2.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 } = exports2.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