UNPKG

identity-based-encryption-bn254

Version:

![build](https://github.com/randa-mu/identity-based-encryption-bn254/actions/workflows/build.yml/badge.svg)

1,358 lines (1,351 loc) 325 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 )); // 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.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.Hash = exports.nextTick = exports.swap32IfBE = exports.byteSwapIfBE = exports.swap8IfBE = exports.isLE = void 0; exports.isBytes = isBytes3; exports.anumber = anumber2; exports.abytes = abytes3; exports.ahash = ahash; exports.aexists = aexists2; exports.aoutput = aoutput2; exports.u8 = u8; exports.u32 = u322; exports.clean = clean2; exports.createView = createView; exports.rotr = rotr; exports.rotl = rotl; exports.byteSwap = byteSwap2; exports.byteSwap32 = byteSwap322; exports.bytesToHex = bytesToHex2; exports.hexToBytes = hexToBytes2; exports.asyncLoop = asyncLoop; exports.utf8ToBytes = utf8ToBytes3; exports.bytesToUtf8 = bytesToUtf8; exports.toBytes = toBytes2; exports.kdfInputToBytes = kdfInputToBytes; exports.concatBytes = concatBytes2; exports.checkOpts = checkOpts; exports.createHasher = createHasher3; exports.createOptHasher = createOptHasher; exports.createXOFer = createXOFer2; exports.randomBytes = randomBytes2; var crypto_1 = require_crypto(); 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 createView(arr) { return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); } function rotr(word, shift) { return word << 32 - shift | word >>> shift; } function rotl(word, shift) { return word << shift | word >>> 32 - shift >>> 0; } exports.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; } exports.swap8IfBE = exports.isLE ? (n) => n : (n) => byteSwap2(n); exports.byteSwapIfBE = exports.swap8IfBE; function byteSwap322(arr) { for (let i = 0; i < arr.length; i++) { arr[i] = byteSwap2(arr[i]); } return arr; } exports.swap32IfBE = exports.isLE ? (u) => u : byteSwap322; var hasHexBuiltin = /* @__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 (hasHexBuiltin) 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 (hasHexBuiltin) 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 () => { }; exports.nextTick = nextTick; async function asyncLoop(iters, tick, cb) { let ts = Date.now(); for (let i = 0; i < iters; i++) { cb(i); const diff = Date.now() - ts; if (diff >= 0 && diff < tick) continue; await (0, exports.nextTick)(); ts += diff; } } function 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 { }; exports.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; } exports.wrapConstructor = createHasher3; exports.wrapConstructorWithOpts = createOptHasher; exports.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"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.notImplemented = exports.bitMask = void 0; exports.isBytes = isBytes3; exports.abytes = abytes3; exports.abool = abool2; 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 = concatBytes2; exports.equalBytes = equalBytes2; exports.utf8ToBytes = utf8ToBytes3; exports.inRange = inRange2; exports.aInRange = aInRange2; exports.bitLen = bitLen2; exports.bitGet = bitGet2; exports.bitSet = bitSet2; exports.createHmacDrbg = createHmacDrbg2; exports.validateObject = validateObject2; exports.memoized = memoized2; var _0n8 = /* @__PURE__ */ BigInt(0); var _1n8 = /* @__PURE__ */ BigInt(1); var _2n7 = /* @__PURE__ */ BigInt(2); function isBytes3(a) { return a instanceof Uint8Array || a != null && typeof a === "object" && 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} must be valid boolean, got "${value}".`); } var hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); function bytesToHex2(bytes) { abytes3(bytes); let hex = ""; for (let i = 0; i < bytes.length; i++) { hex += hexes2[bytes[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 BigInt(hex === "" ? "0" : `0x${hex}`); } var asciis2 = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; function asciiToBase162(char) { if (char >= asciis2._0 && char <= asciis2._9) return char - asciis2._0; if (char >= asciis2._A && char <= asciis2._F) return char - (asciis2._A - 10); if (char >= asciis2._a && char <= asciis2._f) return char - (asciis2._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("padded hex string expected, got unpadded hex of length " + hl); const array = new Uint8Array(al); for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { const n1 = 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 numberToVarBytesBE2(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 valid hex string, got "${hex}". 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} expected ${expectedLength} bytes, 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 equalBytes2(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(`utf8ToBytes expected string, got ${typeof str}`); return new Uint8Array(new TextEncoder().encode(str)); } var isPosBig2 = (n) => typeof n === "bigint" && _0n8 <= 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 ${typeof n} ${n}`); } function bitLen2(n) { let len; for (len = 0; n > _0n8; n >>= _1n8, len += 1) ; return len; } function bitGet2(n, pos) { return n >> BigInt(pos) & _1n8; } function bitSet2(n, pos, value) { return n | (value ? _1n8 : _0n8) << BigInt(pos); } var bitMask2 = (n) => (_2n7 << BigInt(n - 1)) - _1n8; 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 = (...b) => hmacFn(k, v, ...b); 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 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 "${type}", expected function`); const val = object[fieldName]; if (isOptional && val === void 0) return; if (!checkVal(val, object)) { throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); } }; for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type, false); for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type, true); return object; } var notImplemented2 = () => { throw new Error("not implemented"); }; exports.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"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isNegativeLE = void 0; exports.mod = mod2; exports.pow = pow2; 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 = FpLegendre2; exports.FpIsSquare = FpIsSquare2; 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 _0n8 = BigInt(0); var _1n8 = BigInt(1); var _2n7 = BigInt(2); var _3n5 = BigInt(3); var _4n3 = BigInt(4); var _5n2 = BigInt(5); var _8n2 = BigInt(8); var _9n2 = BigInt(9); var _16n2 = BigInt(16); function mod2(a, b) { const result = a % b; return result >= _0n8 ? result : b + result; } function pow2(num, power, modulo) { if (modulo <= _0n8 || power < _0n8) throw new Error("Expected power/modulo > 0"); if (modulo === _1n8) return _0n8; let res = _1n8; while (power > _0n8) { if (power & _1n8) res = res * num % modulo; num = num * num % modulo; power >>= _1n8; } return res; } function pow22(x, power, modulo) { let res = x; while (power-- > _0n8) { res *= res; res %= modulo; } return res; } function invert2(number, modulo) { if (number === _0n8 || modulo <= _0n8) { throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); } let a = mod2(number, modulo); let b = modulo; let x = _0n8, y = _1n8, u = _1n8, v = _0n8; while (a !== _0n8) { 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 !== _1n8) throw new Error("invert: does not exist"); return mod2(x, modulo); } function tonelliShanks2(P) { const legendreC = (P - _1n8) / _2n7; let Q, S, Z; for (Q = P - _1n8, S = 0; Q % _2n7 === _0n8; Q /= _2n7, S++) ; for (Z = _2n7; Z < P && pow2(Z, legendreC, P) !== P - _1n8; Z++) ; if (S === 1) { const p1div4 = (P + _1n8) / _4n3; return function tonelliFast(Fp, n) { const root = Fp.pow(n, p1div4); if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } const Q1div2 = (Q + _1n8) / _2n7; return function tonelliSlow(Fp, n) { if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error("Cannot find square root"); let r = S; let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); let x = Fp.pow(n, Q1div2); let b = Fp.pow(n, Q); while (!Fp.eql(b, Fp.ONE)) { if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; let m = 1; for (let t2 = Fp.sqr(b); m < r; m++) { if (Fp.eql(t2, Fp.ONE)) break; t2 = Fp.sqr(t2); } const ge = Fp.pow(g, _1n8 << BigInt(r - m - 1)); g = Fp.sqr(ge); x = Fp.mul(x, ge); b = Fp.mul(b, g); r = m; } return x; }; } function FpSqrt2(P) { if (P % _4n3 === _3n5) { const p1div4 = (P + _1n8) / _4n3; return function sqrt3mod4(Fp, n) { const root = Fp.pow(n, p1div4); if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } if (P % _8n2 === _5n2) { const c1 = (P - _5n2) / _8n2; return function sqrt5mod8(Fp, n) { const n2 = Fp.mul(n, _2n7); const v = Fp.pow(n2, c1); const nv = Fp.mul(n, v); const i = Fp.mul(Fp.mul(nv, _2n7), v); const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } if (P % _16n2 === _9n2) { } return tonelliShanks2(P); } var isNegativeLE = (num, modulo) => (mod2(num, modulo) & _1n8) === _1n8; 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(f, num, power) { if (power < _0n8) throw new Error("Expected power > 0"); if (power === _0n8) return f.ONE; if (power === _1n8) return num; let p = f.ONE; let d = num; while (power > _0n8) { if (power & _1n8) p = f.mul(p, d); d = f.sqr(d); power >>= _1n8; } return p; } function FpInvertBatch2(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" ? invert2(rhs, f.ORDER) : f.inv(rhs)); } function FpLegendre2(order) { const legendreConst = (order - _1n8) / _2n7; return (f, x) => f.pow(x, legendreConst); } function FpIsSquare2(f) { const legendre = FpLegendre2(f.ORDER); return (x) => { const p = legendre(f, x); return f.eql(p, f.ZERO) || f.eql(p, f.ONE); }; } function nLength2(n, 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 <= _0n8) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); const { nBitLength: BITS, nByteLength: BYTES } = nLength2(ORDER, bitLen2); if (BYTES > 2048) throw new Error("Field lengths over 2048 bytes are not supported"); const sqrtP = FpSqrt2(ORDER); const f = Object.freeze({ ORDER, BITS, BYTES, MASK: (0, utils_js_1.bitMask)(BITS), ZERO: _0n8, ONE: _1n8, create: (num) => mod2(num, ORDER), isValid: (num) => { if (typeof num !== "bigint") throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); return _0n8 <= num && num < ORDER; }, is0: (num) => num === _0n8, isOdd: (num) => (num & _1n8) === _1n8, 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) => sqrtP(f, n)), invertBatch: (lst) => FpInvertBatch2(f, lst), // TODO: do we really need constant cmov? // We don't have const-time bigints anyway, so probably will be not very useful cmov: (a, b, c) => c ? b : a, toBytes: (num) => isLE2 ? (0, utils_js_1.numberToBytesLE)(num, BYTES) : (0, utils_js_1.numberToBytesBE)(num, BYTES), fromBytes: (bytes) => { if (bytes.length !== BYTES) throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); return isLE2 ? (0, utils_js_1.bytesToNumberLE)(bytes) : (0, utils_js_1.bytesToNumberBE)(bytes); } }); return Object.freeze(f); } function FpSqrtOdd(Fp, elm) { if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`); const root = Fp.sqrt(elm); return Fp.isOdd(root) ? root : Fp.neg(root); } function FpSqrtEven(Fp, elm) { if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`); const root = Fp.sqrt(elm); return Fp.isOdd(root) ? Fp.neg(root) : root; } function hashToPrivateScalar(hash, groupOrder, isLE2 = false) { hash = (0, utils_js_1.ensureBytes)("privateHash", hash); const hashLen = hash.length; const minLen = 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)(hash) : (0, utils_js_1.bytesToNumberBE)(hash); return mod2(num, groupOrder - _1n8) + _1n8; } 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.bytesToNumberBE)(key) : (0, utils_js_1.bytesToNumberLE)(key); const reduced = mod2(num, fieldOrder - _1n8) + _1n8; 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_xmd2; exports.expand_message_xof = expand_message_xof2; exports.hash_to_field = hash_to_field2; exports.isogenyMap = isogenyMap; exports.createHasher = createHasher3; var modular_js_1 = require_modular(); var utils_js_1 = require_utils2(); var os2ip2 = utils_js_1.bytesToNumberBE; function i2osp2(value, length) { anum2(value); anum2(length); if (value < 0 || value >= 1 << 8 * length) { throw new Error(`bad I2OSP call: value=${value} length=${length}`); } const res = Array.from({ length }).fill(0); for (let i = length - 1; i >= 0; i--) { res[i] = value & 255; value >>>= 8; } return new Uint8Array(res); } function 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_js_1.abytes)(msg); (0, utils_js_1.abytes)(DST); anum2(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, 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_js_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp2(0, 1), DST_prime)); b[0] = H((0, utils_js_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_js_1.concatBytes)(...args)); } const pseudo_random_bytes = (0, utils_js_1.concatBytes)(...b); return pseudo_random_bytes.slice(0, lenInBytes); } function expand_message_xof2(msg, DST, lenInBytes, k, H) { (0, utils_js_1.abytes)(msg); (0, utils_js_1.abytes)(DST); anum2(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(i2osp2(lenInBytes, 2)).update(DST).update(i2osp2(DST.length, 1)).digest(); } function hash_to_field2(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); anum2(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_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_js_1.mod)(os2ip2(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 createHasher3(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_field2(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_field2(msg, 1, { ...def, DST: def.encodeDST, ...options }); const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor(); P.assertValidity(); return P; }, // Same as encodeToCurve, but without hash mapToCurve(scalars) { if (!Array.isArray(scalars)) throw new Error("mapToCurve: expected array of bigints"); for (const i of scalars) if (typeof i !== "bigint") throw new Error(`mapToCurve: expected array of bigints, got ${i} in array`); const P = Point.fromAffine(mapToCurve(scalars)).clearCofactor(); P.assertValidity(); return P; } }; } } }); // node_modules/@noble/curves/abstract/curve.js var require_curve = __commonJS({ "node_modules/@noble/curves/abstract/curve.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.wNAF = wNAF2; exports.pippenger = pippenger2; exports.validateBasic = validateBasic2; var modular_js_1 = require_modular(); var utils_js_1 = require_utils2(); var _0n8 = BigInt(0); var _1n8 = BigInt(1); var pointPrecomputes2 = /* @__PURE__ */ new WeakMap(); var pointWindowSizes2 = /* @__PURE__ */ new WeakMap(); function wNAF2(c, bits) { const constTimeNegate = (condition, item) => { const neg = item.negate(); return condition ? neg : item; }; const validateW = (W) => { if (!Number.isSafeInteger(W) || W <= 0 || W > bits) throw new Error(`Wrong window size=${W}, should be [1..${bits}]`); }; const opts = (W) => { validateW(W); const windows = Math.ceil(bits / W) + 1; const windowSize = 2 ** (W - 1); return { windows, windowSize }; }; return { constTimeNegate, // non-const time multiplication ladder unsafeLadder(elm, n) { let p = c.ZERO; let d = elm; while (n > _0n8) { if (n & _1n8) p = p.add(d); d = d.double(); n >>= _1n8; } return p; }, /** * Creates a wNAF precomputation window. Used for caching. * Default window size is set by `utils.precompute()` and is equal to 8. * Number of precomputed points depends on the curve size: * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: * - 𝑊 is the window size * - 𝑛 is the bitlength of the curve order. * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. * @returns precomputed point tables flattened to a single array */ precomputeWindow(elm, W) { const { windows, windowSize } = opts(W); const points = []; let p = elm; let base = p; for (let window = 0; window < windows; window++) { base = p; points.push(base); for (let i = 1; i < windowSize; i++) { base = base.add(p); points.push(base); } p = base.double(); } return points; }, /** * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. * @param W window size * @param precomputes precomputed tables * @param n scalar (we don't check here, but should be less than curve order) * @returns real and fake (for const-time) points */ wNAF(W, precomputes, n) { const { windows, windowSize } = opts(W); let p = c.ZERO; let f = c.BASE; const mask = BigInt(2 ** W - 1); const maxNumber = 2 ** W; const shiftBy = BigInt(W); for (let window = 0; window < windows; window++) { const offset = window * windowSize; let wbits = Number(n & mask); n >>= shiftBy; if (wbits > windowSize) { wbits -= maxNumber; n += _1n8; } const offset1 = offset; const offset2 = offset + Math.abs(wbits) - 1; const cond1 = window % 2 !== 0; const cond2 = wbits < 0; if (wbits === 0) { f = f.add(constTimeNegate(cond1, precomputes[offset1])); } else { p = p.add(constTimeNegate(cond2, precomputes[offset2])); } } return { p, f }; }, wNAFCached(P, n, transform) { const W = pointWindowSizes2.get(P) || 1; let comp = pointPrecomputes2.get(P); if (!comp) { comp = this.precomputeWindow(P, W); if (W !== 1) pointPrecomputes2.set(P, transform(comp)); } return this.wNAF(W, comp, n); }, // We calculate precomputes for elliptic curve point multiplication // using windowed method. This specifies window size and // stores precomputed values. Usually only base point would be precomputed. setWindowSize(P, W) { validateW(W); pointWindowSizes2.set(P, W); pointPrecomputes2.delete(P); } }; } function pippenger2(c, field, points, scalars) { if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length) throw new Error("arrays of points and scalars must have equal length"); scalars.forEach((s, i) => { if (!field.isValid(s)) throw new Error(`wrong scalar at index ${i}`); }); points.forEach((p, i) => { if (!(p instanceof c)) throw new Error(`wrong point at index ${i}`); }); const wbits = (0, utils_js_1.bitLen)(BigInt(points.length)); const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; const MASK = (1 << windowSize) - 1; const buckets = new Array(MASK + 1).fill(c.ZERO); const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize; let sum = c.ZERO; for (let i = lastBits; i >= 0; i -= windowSize) { buckets.fill(c.ZERO); for (let j = 0; j < scalars.length; j++) { const scalar = scalars[j]; const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK)); buckets[wbits2] = buckets[wbits2].add(points[j]); } let resI = c.ZERO; for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) { sumI = sumI.add(buckets[j]); resI = resI.add(sumI); } sum = sum.add(resI); if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double(); } return sum; } function 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 = void 0; exports.weierstrassPoints = weierstrassPoints2; exports.weierstrass = weierstrass; exports.SWUFpSqrtRatio = SWUFpSqrtRatio; exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU; var curve_js_1 = require_curve(); var mod2 = 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, a } = opts; if (endo) { if (!Fp.eql(a, Fp.ZERO)) { throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); } if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); } } return Object.freeze({ ...opts }); } var { bytesToNumberBE: b2n2, hexToBytes: h2b2 } = ut; exports.DER = { // asn.1 DER encoding utils Err: class DERErr extends Error { constructor(m = "") { super(m); } }, // Basic building block is TLV (Tag-Length-Value) _tlv: { encode: (tag, data) => { const { Err: E } = exports.DER; if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag"); if (data.length & 1) throw new E("tlv.encode: unpadded data"); const dataLen = data.length / 2; const len = ut.numberToHexUnpadded(dataLen); if (len.length / 2 & 128) throw new E("tlv.encode: long form length too big"); const lenLen = dataLen > 127 ? ut.numberToHexUnpadded(len.length / 2 | 128) : ""; return `${ut.numberToHexUnpadded(tag)}${lenLen}${len}${data}`; }, // v - value, l - left bytes (unparsed) decode(tag, data) { const { Err: E } = exports.DER; let pos = 0; if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag"); if (data.length < 2 || data[pos++] !== tag) throw new E("tlv.decode: wrong tlv"); const first = data[pos++]; const isLong = !!(first & 128); let length = 0; if (!isLong) length = first; else { const lenLen = first & 127; if (!lenLen) throw new E("tlv.decode(long): indefinite length not supported"); if (lenLen > 4) throw new E("tlv.decode(long): byte length is too big"); const lengthBytes = data.subarray(pos, pos + lenLen); if (lengthBytes.length !== lenLen) throw new E("tlv.decode: length bytes not complete"); if (lengthBytes[0] === 0) throw new E("tlv.decode(long): zero leftmost byte"); for (const b of lengthBytes) length = length << 8 | b; pos += lenLen; if (length < 128) throw new E("tlv.decode(long): not minimal encoding"); } const v = data.subarray(pos, pos + length); if (v.length !== length) throw new E("tlv.decode: wrong value length"); return { v, l: data.subarray(pos + length) }; } }, // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, // since we always use positive integers here. It must always be empty: // - add zero byte if exists // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) _int: { encode(num) { const { Err: E } = exports.DER; if (num < _0n8) throw new E("integer: negative integers are not allowed"); let hex = ut.numberToHexUnpadded(num); if (Number.parseInt(hex[0], 16) & 8) hex = "00" + hex; if (hex.length & 1) throw new E("unexpected assertion"); return hex; }, decode(data) { const { Err: E } = exports.DER; if (data[0] & 128) throw new E("Invalid signature integer: negative"); if (data[0] === 0 && !(data[1] & 128)) throw new E("Invalid signature integer: unnecessary leading zero"); return b2n2(data); } }, toSig(hex) { const { Err: E, _int: int, _tlv: tlv } = exports.DER; const data = typeof hex === "string" ? h2b2(hex) : hex; ut.abytes(data); const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data); if (seqLeftBytes.length) throw new E("Invalid signature: left bytes after parsing"); const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes); const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLe