UNPKG

di-wings

Version:

Aviary Tech's common library for decentralized identity

1,575 lines (1,567 loc) 323 kB
var __defProp = Object.defineProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true, configurable: true, set: (newValue) => all[name] = () => newValue }); }; // src/lib/common/interfaces.ts var IProofPurpose; ((IProofPurpose2) => { IProofPurpose2["verificationMethod"] = "verificationMethod"; IProofPurpose2["assertionMethod"] = "assertionMethod"; IProofPurpose2["authentication"] = "authentication"; IProofPurpose2["keyAgreement"] = "keyAgreement"; IProofPurpose2["contractAgreement"] = "contactAgreement"; IProofPurpose2["capabilityInvocation"] = "capabilityInvocation"; IProofPurpose2["capabilityDelegation"] = "capabilityDelegation"; })(IProofPurpose ||= {}); var IProofType; ((IProofType2) => { IProofType2["Ed25519Signature2018"] = "Ed25519Signature2018"; IProofType2["Ed25519Signature2020"] = "Ed25519Signature2020"; IProofType2["EcdsaSecp256k1Signature2019"] = "EcdsaSecp256k1Signature2019"; IProofType2["EcdsaSecp256k1RecoverySignature2020"] = "EcdsaSecp256k1RecoverySignature2020"; IProofType2["JsonWebSignature2020"] = "JsonWebSignature2020"; IProofType2["RsaSignature2018"] = "RsaSignature2018"; IProofType2["GpgSignature2020"] = "GpgSignature2020"; IProofType2["JcsEd25519Signature2020"] = "JcsEd25519Signature2020"; IProofType2["BbsBlsSignatureProof2020"] = "BbsBlsSignatureProof2020"; IProofType2["BbsBlsBoundSignatureProof2020"] = "BbsBlsBoundSignatureProof2020"; })(IProofType ||= {}); // src/lib/crypto/utils/encoding.ts import b58 from "b58"; import { Buffer as Buffer2 } from "buffer/index.js"; var MULTIBASE_BASE58BTC_HEADER = "z"; var MULTIBASE_BASE64URL_HEADER = "u"; var MULTICODEC_ED25519_PUB_HEADER = new Uint8Array([237, 1]); var MULTICODEC_ED25519_PRIV_HEADER = new Uint8Array([128, 38]); var MULTICODEC_X25519_PUB_HEADER = new Uint8Array([236, 1]); var MULTICODEC_X25519_PRIV_HEADER = new Uint8Array([130, 38]); var MULTICODEC_SECP256K1_PUB_HEADER = new Uint8Array([231, 1]); var MULTICODEC_SECP256K1_PRIV_HEADER = new Uint8Array([19, 1]); var MULTICODEC_BLS12381_G2_PUB_HEADER = new Uint8Array([235, 1]); var MULTICODEC_BLS12381_G2_PRIV_HEADER = new Uint8Array([138, 38]); var base64 = { encode: (unencoded) => { return Buffer2.from(unencoded || "").toString("base64"); }, decode: (encoded) => { return new Uint8Array(Buffer2.from(encoded || "", "base64").buffer); } }; var utf8 = { encode: (unencoded) => { return new TextEncoder().encode(unencoded); }, decode: (encoded) => { return new TextDecoder().decode(encoded); } }; var base64url = { encode: (unencoded) => { var encoded = base64.encode(unencoded); return encoded.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, ""); }, decode: (encoded) => { encoded = encoded.replace(/-/g, "+").replace(/_/g, "/"); while (encoded.length % 4) encoded += "="; return base64.decode(encoded); } }; var base58 = { encode: (unencoded) => { return b58.encode(unencoded); }, decode: (encoded) => { return b58.decode(encoded); } }; var multibase = { encode: (val, encoding) => { if (encoding === "base58btc") { const baseEncoded = base58.encode(val); return MULTIBASE_BASE58BTC_HEADER + baseEncoded; } else if (encoding === "base64url") { return MULTIBASE_BASE64URL_HEADER + base64url.encode(val); } throw new Error("Invalid multibase encoding."); }, decode: (val) => { if (val.startsWith(MULTIBASE_BASE58BTC_HEADER)) { return base58.decode(val.substring(1)); } else if (val.startsWith(MULTIBASE_BASE64URL_HEADER)) { return base64url.decode(val.substring(1)); } throw new Error("Multibase value does not have expected header."); } }; var multikey = { encode: (header, val) => { const mcBytes = new Uint8Array(header.length + val.length); mcBytes.set(header); mcBytes.set(val, header.length); return multibase.encode(mcBytes, "base58btc"); }, decode: (header, val) => { const mcValue = multibase.decode(val); for (let i = 0;i < header.length; i++) { if (mcValue[i] !== header[i]) { throw new Error("Multikey value does not have expected header."); } } return mcValue.slice(header.length); } }; // src/lib/crypto/utils/sha256.ts import { hash } from "@stablelib/sha256"; import { Buffer as Buffer3 } from "buffer/index.js"; var sha256Uint8Array = (val) => { return Buffer3.from(hash(Buffer3.from(val))); }; function stringToUint8Array(data) { if (typeof data === "string") { return new Uint8Array(Buffer3.from(data)); } if (!(data instanceof Uint8Array)) { throw new TypeError('"data" be a string or Uint8Array.'); } return data; } var sha256 = (val) => { return Buffer3.from(hash(Buffer3.from(val))).toString("hex"); }; var sha256buffer = (val) => { return Buffer3.from(hash(Buffer3.from(val))); }; var sha256pow = (source, target, data, user = "anon", nonce = 0, iterations = 1, budget = 1e6, positionalReferenceHash = "") => { console.log(`sha256 mining - s:${source} t:${target} d:${data} i:${iterations} n:${nonce} b:${budget} u:${user}`); let found = []; let rotation; let totalRotations = 0; const limit = budget + nonce; for (let i = nonce;i < limit && found.length !== iterations; i++) { rotation = sha256(source + sha256(data) + target + user + i); if (rotation.slice(0, target.length) === target && rotation > positionalReferenceHash) { const timestamp = Math.round(new Date().getTime() / 1000); console.log(`found slot ${rotation}`); const item = { data, datahash: sha256(data), n: i, rotation, source, target, timestamp, user }; found.push(item); } totalRotations++; } console.log(`finished mining after ${totalRotations} rotations`); return found; }; // src/lib/crypto/utils/vcs.ts import jsonld from "jsonld"; import { Buffer as Buffer4 } from "buffer/index.js"; async function canonize(input, { documentLoader }) { try { return await jsonld.canonize(input, { algorithm: "URDNA2015", format: "application/n-quads", documentLoader, useNative: false, rdfDirection: "i18n-datatype" }); } catch (error) { console.error("Error in canonize:", error.details); throw new Error(`Failed to canonize: ${error.message}`); } } async function canonizeProof(proof, { documentLoader }) { const { jws, signatureValue, proofValue, ...rest } = proof; return await canonize(rest, { documentLoader }); } async function createVerifyData({ document, proof, documentLoader }) { if (!proof["@context"]) { proof["@context"] = document["@context"]; } const c14nProofOptions = await canonizeProof(proof, { documentLoader }); const c14nDocument = await canonize(document, { documentLoader }); return Buffer4.concat([sha256buffer(c14nProofOptions), sha256buffer(c14nDocument)]); } // src/lib/crypto/keypairs/Multikey.ts import * as ed25519 from "@stablelib/ed25519"; import * as x25519 from "@stablelib/x25519"; import * as secp from "@noble/secp256k1"; import { XChaCha20Poly1305 } from "@stablelib/xchacha20poly1305"; // node_modules/@noble/curves/esm/bls12-381.js import { sha256 as sha2562 } from "@noble/hashes/sha256"; import { randomBytes } from "@noble/hashes/utils"; // node_modules/@noble/curves/esm/abstract/utils.js /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ var _0n = /* @__PURE__ */ BigInt(0); var _1n = /* @__PURE__ */ BigInt(1); var _2n = /* @__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(bytes) { abytes(bytes); let hex = ""; for (let i = 0;i < bytes.length; i++) { hex += hexes[bytes[i]]; } return hex; } function hexToNumber(hex) { if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex); return hex === "" ? _0n : 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 === undefined || n2 === undefined) { const char = hex[hi] + hex[hi + 1]; throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); } array[ai] = n1 * 16 + n2; } return array; } function bytesToNumberBE(bytes) { return hexToNumber(bytesToHex(bytes)); } function bytesToNumberLE(bytes) { abytes(bytes); return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); } function numberToBytesBE(n, len) { return hexToBytes(n.toString(16).padStart(len * 2, "0")); } function numberToBytesLE(n, len) { return numberToBytesBE(n, len).reverse(); } function 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 utf8ToBytes(str) { if (typeof str !== "string") throw new Error("string expected"); return new Uint8Array(new TextEncoder().encode(str)); } var isPosBig = (n) => typeof n === "bigint" && _0n <= n; function inRange(n, min, max) { return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; } function aInRange(title, n, min, max) { if (!inRange(n, min, max)) throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); } function bitLen(n) { let len; for (len = 0;n > _0n; n >>= _1n, len += 1) ; return len; } function bitGet(n, pos) { return n >> BigInt(pos) & _1n; } var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; 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 === undefined) 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"); }; function memoized(fn) { const map = new WeakMap; return (arg, ...args) => { const val = map.get(arg); if (val !== undefined) return val; const computed = fn(arg, ...args); map.set(arg, computed); return computed; }; } // node_modules/@noble/curves/esm/abstract/modular.js /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ 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, b) { const result = a % b; return result >= _0n2 ? result : b + 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 invert(number, modulo) { if (number === _0n2) throw new Error("invert: expected non-zero number"); if (modulo <= _0n2) throw new Error("invert: expected positive modulus, got " + modulo); let a = mod(number, modulo); let b = modulo; let x = _0n2, y = _1n2, u = _1n2, v = _0n2; while (a !== _0n2) { 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 !== _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 > 1000) throw new Error("Cannot find square root: likely non-prime P"); } if (S === 1) { const p1div4 = (P + _1n2) / _4n; return function tonelliFast(Fp, n) { const root = Fp.pow(n, p1div4); if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } const Q1div2 = (Q + _1n2) / _2n2; 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, _1n2 << BigInt(r - m - 1)); g = Fp.sqr(ge); x = Fp.mul(x, ge); b = Fp.mul(b, g); r = m; } return x; }; } function FpSqrt(P) { if (P % _4n === _3n) { const p1div4 = (P + _1n2) / _4n; return function sqrt3mod4(Fp, n) { const root = Fp.pow(n, p1div4); if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } if (P % _8n === _5n) { const c1 = (P - _5n) / _8n; return function sqrt5mod8(Fp, n) { const n2 = Fp.mul(n, _2n2); const v = Fp.pow(n2, c1); const nv = Fp.mul(n, 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), n)) throw new Error("Cannot find square root"); return root; }; } if (P % _16n === _9n) {} return tonelliShanks(P); } 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 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 FpLegendre(order) { const legendreConst = (order - _1n2) / _2n2; return (f, x) => f.pow(x, legendreConst); } function nLength(n, nBitLength) { const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; const nByteLength = Math.ceil(_nBitLength / 8); return { nBitLength: _nBitLength, nByteLength }; } function Field(ORDER, bitLen2, isLE = false, redef = {}) { if (ORDER <= _0n2) throw new Error("invalid field: expected ORDER > 0, got " + ORDER); const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); if (BYTES > 2048) throw new Error("invalid field: expected ORDER of <= 2048 bytes"); let sqrtP; const f = Object.freeze({ ORDER, isLE, BITS, BYTES, MASK: 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), sqrN: (num) => num * num, addN: (lhs, rhs) => lhs + rhs, subN: (lhs, rhs) => lhs - rhs, mulN: (lhs, rhs) => lhs * rhs, inv: (num) => invert(num, ORDER), sqrt: redef.sqrt || ((n) => { if (!sqrtP) sqrtP = FpSqrt(ORDER); return sqrtP(f, n); }), invertBatch: (lst) => FpInvertBatch(f, lst), cmov: (a, b, c) => c ? b : a, toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), fromBytes: (bytes) => { if (bytes.length !== BYTES) throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length); return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); } }); return Object.freeze(f); } 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, isLE = 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 = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key); const reduced = mod(num, fieldOrder - _1n2) + _1n2; return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); } // node_modules/@noble/curves/esm/abstract/hash-to-curve.js var os2ip = 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, b) { const arr = new Uint8Array(a.length); for (let i = 0;i < a.length; i++) { arr[i] = a[i] ^ b[i]; } return arr; } function anum(item) { if (!Number.isSafeInteger(item)) throw new Error("number expected"); } function expand_message_xmd(msg, DST, lenInBytes, H) { abytes(msg); abytes(DST); anum(lenInBytes); if (DST.length > 255) DST = H(concatBytes(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 = concatBytes(DST, i2osp(DST.length, 1)); const Z_pad = i2osp(0, r_in_bytes); const l_i_b_str = i2osp(lenInBytes, 2); const b = new Array(ell); const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime)); for (let i = 1;i <= ell; i++) { const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; b[i] = H(concatBytes(...args)); } const pseudo_random_bytes = concatBytes(...b); return pseudo_random_bytes.slice(0, lenInBytes); } function expand_message_xof(msg, DST, lenInBytes, k, H) { abytes(msg); abytes(DST); anum(lenInBytes); if (DST.length > 255) { const dkLen = Math.ceil(2 * k / 8); DST = H.create({ dkLen }).update(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) { validateObject(options, { DST: "stringOrUint8Array", p: "bigint", m: "isSafeInteger", k: "isSafeInteger", hash: "hash" }); const { p, k, m, hash: hash2, expand, DST: _DST } = options; abytes(msg); anum(count); const DST = typeof _DST === "string" ? 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] = 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 { 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; }, 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; }, 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/esm/abstract/curve.js /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ var _0n3 = BigInt(0); var _1n3 = 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 = new WeakMap; var pointWindowSizes = new WeakMap; function getW(P) { return pointWindowSizes.get(P) || 1; } function wNAF(c, bits) { return { constTimeNegate, hasPrecomputes(elm) { return getW(elm) !== 1; }, unsafeLadder(elm, n, p = c.ZERO) { let d = elm; while (n > _0n3) { if (n & _1n3) p = p.add(d); d = d.double(); n >>= _1n3; } return p; }, 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; }, wNAF(W, precomputes, n) { const { windows, windowSize } = calcWOpts(W, bits); 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 += _1n3; } 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 }; }, wNAFUnsafe(W, precomputes, n, acc = c.ZERO) { const { windows, windowSize } = calcWOpts(W, bits); 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; if (n === _0n3) break; let wbits = Number(n & mask); n >>= shiftBy; if (wbits > windowSize) { wbits -= maxNumber; n += _1n3; } 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, n, transform) { const W = getW(P); return this.wNAF(W, this.getPrecomputes(W, P, transform), n); }, wNAFCachedUnsafe(P, n, transform, prev) { const W = getW(P); if (W === 1) return this.unsafeLadder(P, n, prev); return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev); }, 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 = 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 validateBasic(curve) { validateField(curve.Fp); validateObject(curve, { n: "bigint", h: "bigint", Gx: "field", Gy: "field" }, { nBitLength: "isSafeInteger", nByteLength: "isSafeInteger" }); return Object.freeze({ ...nLength(curve.n, curve.nBitLength), ...curve, ...{ p: curve.Fp.ORDER } }); } // node_modules/@noble/curves/esm/abstract/weierstrass.js /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ function validatePointOpts(curve) { const opts = validateBasic(curve); 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 _0n4 = BigInt(0); var _1n4 = BigInt(1); var _2n3 = BigInt(2); var _3n2 = BigInt(3); var _4n2 = BigInt(4); function weierstrassPoints(opts) { const CURVE = validatePointOpts(opts); const { Fp } = CURVE; const Fn = Field(CURVE.n, CURVE.nBitLength); const toBytes = CURVE.toBytes || ((_c, point, _isCompressed) => { const a = point.toAffine(); return concatBytes(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y)); }); const fromBytes = CURVE.fromBytes || ((bytes) => { const tail = bytes.subarray(1); const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); return { x, y }; }); function weierstrassEquation(x) { const { a, b } = CURVE; const x2 = Fp.sqr(x); const x3 = Fp.mul(x2, x); return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); } if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) throw new Error("bad generator point: equation left != right"); function isWithinCurveOrder(num) { return inRange(num, _1n4, CURVE.n); } function normPrivateKeyToScalar(key) { const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; if (lengths && typeof key !== "bigint") { if (isBytes(key)) key = bytesToHex(key); if (typeof key !== "string" || !lengths.includes(key.length)) throw new Error("invalid private key"); key = key.padStart(nByteLength * 2, "0"); } let num; try { num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); } catch (error) { throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key); } if (wrapPrivateKey) num = mod(num, N); aInRange("private key", num, _1n4, N); return num; } function assertPrjPoint(other) { if (!(other instanceof Point)) throw new Error("ProjectivePoint expected"); } const toAffineMemo = memoized((p, iz) => { const { px: x, py: y, pz: z } = p; if (Fp.eql(z, Fp.ONE)) return { x, y }; const is0 = p.is0(); if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z); const ax = Fp.mul(x, iz); const ay = Fp.mul(y, iz); const zz = Fp.mul(z, iz); if (is0) return { x: Fp.ZERO, y: Fp.ZERO }; if (!Fp.eql(zz, Fp.ONE)) throw new Error("invZ was invalid"); return { x: ax, y: ay }; }); const assertValidMemo = memoized((p) => { if (p.is0()) { if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) return; throw new Error("bad point: ZERO"); } const { x, y } = p.toAffine(); if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error("bad point: x or y not FE"); const left = Fp.sqr(y); const right = weierstrassEquation(x); if (!Fp.eql(left, right)) throw new Error("bad point: equation left != right"); if (!p.isTorsionFree()) throw new Error("bad point: not in prime-order subgroup"); return true; }); class Point { constructor(px, py, pz) { this.px = px; this.py = py; this.pz = pz; if (px == null || !Fp.isValid(px)) throw new Error("x required"); if (py == null || !Fp.isValid(py)) throw new Error("y required"); if (pz == null || !Fp.isValid(pz)) throw new Error("z required"); Object.freeze(this); } static fromAffine(p) { const { x, y } = p || {}; if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error("invalid affine point"); if (p instanceof Point) throw new Error("projective point not allowed"); const is0 = (i) => Fp.eql(i, Fp.ZERO); if (is0(x) && is0(y)) return Point.ZERO; return new Point(x, y, Fp.ONE); } get x() { return this.toAffine().x; } get y() { return this.toAffine().y; } static normalizeZ(points) { const toInv = Fp.invertBatch(points.map((p) => p.pz)); return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); } static fromHex(hex) { const P = Point.fromAffine(fromBytes(ensureBytes("pointHex", hex))); P.assertValidity(); return P; } static fromPrivateKey(privateKey) { return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); } static msm(points, scalars) { return pippenger(Point, Fn, points, scalars); } _setWindowSize(windowSize) { wnaf.setWindowSize(this, windowSize); } assertValidity() { assertValidMemo(this); } hasEvenY() { const { y } = this.toAffine(); if (Fp.isOdd) return !Fp.isOdd(y); throw new Error("Field doesn't support isOdd"); } equals(other) { assertPrjPoint(other); const { px: X1, py: Y1, pz: Z1 } = this; const { px: X2, py: Y2, pz: Z2 } = other; const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); return U1 && U2; } negate() { return new Point(this.px, Fp.neg(this.py), this.pz); } double() { const { a, b } = CURVE; const b3 = Fp.mul(b, _3n2); const { px: X1, py: Y1, pz: Z1 } = this; let { ZERO: X3, ZERO: Y3, ZERO: Z3 } = Fp; let t0 = Fp.mul(X1, X1); let t1 = Fp.mul(Y1, Y1); let t2 = Fp.mul(Z1, Z1); let t3 = Fp.mul(X1, Y1); t3 = Fp.add(t3, t3); Z3 = Fp.mul(X1, Z1); Z3 = Fp.add(Z3, Z3); X3 = Fp.mul(a, Z3); Y3 = Fp.mul(b3, t2); Y3 = Fp.add(X3, Y3); X3 = Fp.sub(t1, Y3); Y3 = Fp.add(t1, Y3); Y3 = Fp.mul(X3, Y3); X3 = Fp.mul(t3, X3); Z3 = Fp.mul(b3, Z3); t2 = Fp.mul(a, t2); t3 = Fp.sub(t0, t2); t3 = Fp.mul(a, t3); t3 = Fp.add(t3, Z3); Z3 = Fp.add(t0, t0); t0 = Fp.add(Z3, t0); t0 = Fp.add(t0, t2); t0 = Fp.mul(t0, t3); Y3 = Fp.add(Y3, t0); t2 = Fp.mul(Y1, Z1); t2 = Fp.add(t2, t2); t0 = Fp.mul(t2, t3); X3 = Fp.sub(X3, t0); Z3 = Fp.mul(t2, t1); Z3 = Fp.add(Z3, Z3); Z3 = Fp.add(Z3, Z3); return new Point(X3, Y3, Z3); } add(other) { assertPrjPoint(other); const { px: X1, py: Y1, pz: Z1 } = this; const { px: X2, py: Y2, pz: Z2 } = other; let { ZERO: X3, ZERO: Y3, ZERO: Z3 } = Fp; const a = CURVE.a; const b3 = Fp.mul(CURVE.b, _3n2); let t0 = Fp.mul(X1, X2); let t1 = Fp.mul(Y1, Y2); let t2 = Fp.mul(Z1, Z2); let t3 = Fp.add(X1, Y1); let t4 = Fp.add(X2, Y2); t3 = Fp.mul(t3, t4); t4 = Fp.add(t0, t1); t3 = Fp.sub(t3, t4); t4 = Fp.add(X1, Z1); let t5 = Fp.add(X2, Z2); t4 = Fp.mul(t4, t5); t5 = Fp.add(t0, t2); t4 = Fp.sub(t4, t5); t5 = Fp.add(Y1, Z1); X3 = Fp.add(Y2, Z2); t5 = Fp.mul(t5, X3); X3 = Fp.add(t1, t2); t5 = Fp.sub(t5, X3); Z3 = Fp.mul(a, t4); X3 = Fp.mul(b3, t2); Z3 = Fp.add(X3, Z3); X3 = Fp.sub(t1, Z3); Z3 = Fp.add(t1, Z3); Y3 = Fp.mul(X3, Z3); t1 = Fp.add(t0, t0); t1 = Fp.add(t1, t0); t2 = Fp.mul(a, t2); t4 = Fp.mul(b3, t4); t1 = Fp.add(t1, t2); t2 = Fp.sub(t0, t2); t2 = Fp.mul(a, t2); t4 = Fp.add(t4, t2); t0 = Fp.mul(t1, t4); Y3 = Fp.add(Y3, t0); t0 = Fp.mul(t5, t4); X3 = Fp.mul(t3, X3); X3 = Fp.sub(X3, t0); t0 = Fp.mul(t3, t1); Z3 = Fp.mul(t5, Z3); Z3 = Fp.add(Z3, t0); return new Point(X3, Y3, Z3); } subtract(other) { return this.add(other.negate()); } is0() { return this.equals(Point.ZERO); } wNAF(n) { return wnaf.wNAFCached(this, n, Point.normalizeZ); } multiplyUnsafe(sc) { const { endo, n: N } = CURVE; aInRange("scalar", sc, _0n4, N); const I = Point.ZERO; if (sc === _0n4) return I; if (this.is0() || sc === _1n4) return this; if (!endo || wnaf.hasPrecomputes(this)) return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ); let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc); let k1p = I; let k2p = I; let d = this; while (k1 > _0n4 || k2 > _0n4) { if (k1 & _1n4) k1p = k1p.add(d); if (k2 & _1n4) k2p = k2p.add(d); d = d.double(); k1 >>= _1n4; k2 >>= _1n4; } if (k1neg) k1p = k1p.negate(); if (k2neg) k2p = k2p.negate(); k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); return k1p.add(k2p); } multiply(scalar) { const { endo, n: N } = CURVE; aInRange("scalar", scalar, _1n4, N); let point, fake; if (endo) { const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); let { p: k1p, f: f1p } = this.wNAF(k1); let { p: k2p, f: f2p } = this.wNAF(k2); k1p = wnaf.constTimeNegate(k1neg, k1p); k2p = wnaf.constTimeNegate(k2neg, k2p); k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); point = k1p.add(k2p); fake = f1p.add(f2p); } else { const { p, f } = this.wNAF(scalar); point = p; fake = f; } return Point.normalizeZ([point, fake])[0]; } multiplyAndAddUnsafe(Q, a, b) { const G = Point.BASE; const mul = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2); const sum = mul(this, a).add(mul(Q, b)); return sum.is0() ? undefined : sum; } toAffine(iz) { return toAffineMemo(this, iz); } isTorsionFree() { const { h: cofactor, isTorsionFree } = CURVE; if (cofactor === _1n4) return true; if (isTorsionFree) return isTorsionFree(Point, this); throw new Error("isTorsionFree() has not been declared for the elliptic curve"); } clearCofactor() { const { h: cofactor, clearCofactor } = CURVE; if (cofactor === _1n4) return this; if (clearCofactor) return clearCofactor(Point, this); return this.multiplyUnsafe(CURVE.h); } toRawBytes(isCompressed = true) { abool("isCompressed", isCompressed); this.assertValidity(); return toBytes(Point, this, isCompressed); } toHex(isCompressed = true) { abool("isCompressed", isCompressed); return bytesToHex(this.toRawBytes(isCompressed)); } } Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); const _bits = CURVE.nBitLength; const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); return { CURVE, ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder }; } function SWUFpSqrtRatio(Fp, Z) { const q = Fp.ORDER; let l = _0n4; for (let o = q - _1n4;o % _2n3 === _0n4; o /= _2n3) l += _1n4; const c1 = l; const _2n_pow_c1_1 = _2n3 << c1 - _1n4 - _1n4; const _2n_pow_c1 = _2n_pow_c1_1 * _2n3; const c2 = (q - _1n4) / _2n_pow_c1; const c3 = (c2 - _1n4) / _2n3; const c4 = _2n_pow_c1 - _1n4; const c5 = _2n_pow_c1_1; const c6 = Fp.pow(Z, c2); const c7 = Fp.pow(Z, (c2 + _1n4) / _2n3); let sqrtRatio = (u, v) => { let tv1 = c6; let tv2 = Fp.pow(v, c4); let tv3 = Fp.sqr(tv2); tv3 = Fp.mul(tv3, v); let tv5 = Fp.mul(u, tv3); tv5 = Fp.pow(tv5, c3); tv5 = Fp.mul(tv5, tv2); tv2 = Fp.mul(tv5, v); tv3 = Fp.mul(tv5, u); let tv4 = Fp.mul(tv3, tv2); tv5 = Fp.pow(tv4, c5); let isQR = Fp.eql(tv5, Fp.ONE); tv2 = Fp.mul(tv3, c7); tv5 = Fp.mul(tv4, tv1); tv3 = Fp.cmov(tv2, tv3, isQR); tv4 = Fp.cmov(tv5, tv4, isQR); for (let i = c1;i > _1n4; i--) { let tv52 = i - _2n3; tv52 = _2n3 << tv52 - _1n4; let tvv5 = Fp.pow(tv4, tv52); const e1 = Fp.eql(tvv5, Fp.ONE); tv2 = Fp.mul(tv3, tv1); tv1 = Fp.mul(tv1, tv1); tvv5 = Fp.mul(tv4, tv1); tv3 = Fp.cmov(tv2, tv3, e1); tv4 = Fp.cmov(tvv5, tv4, e1); } return { isValid: isQR, value: tv3 }; }; if (Fp.ORDER % _4n2 === _3n2) { const c12 = (Fp.ORDER - _3n2) / _4n2; const c22 = Fp.sqrt(Fp.neg(Z)); sqrtRatio = (u, v) => { let tv1 = Fp.sqr(v); const tv2 = Fp.mul(u, v); tv1 = Fp.mul(tv1, tv2); let y1 = Fp.pow(tv1, c12); y1 = Fp.mul(y1, tv2); const y2 = Fp.mul(y1, c22); const tv3 = Fp.mul(Fp.sqr(y1), v); const isQR = Fp.eql(tv3, u); let y = Fp.cmov(y2, y1, isQR); return { isValid: isQR, value: y }; }; } return sqrtRatio; } function mapToCurveSimpleSWU(Fp, opts) { validateField(Fp); if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) throw new Error("mapToCurveSimpleSWU: invalid opts"); const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); if (!Fp.isOdd) throw new Error("Fp.isOdd is not implemented!"); return (u) => { let tv1, tv2, tv3, tv4, tv5, tv6, x, y; tv1 = Fp.sqr(u); tv1 = Fp.mul(tv1, opts.Z); tv2 = Fp.sqr(tv1); tv2 = Fp.add(tv2, tv1); tv3 = Fp.add(tv2, Fp.ONE); tv3 = Fp.mul(tv3, opts.B); tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); tv4 = Fp.mul(tv4, opts.A); tv2 = Fp.sqr(tv3); tv6 = Fp.sqr(tv4); tv5 = Fp.mul(tv6, opts.A); tv2 = Fp.add(tv2, tv5); tv2 = Fp.mul(tv2, tv3); tv6 = Fp.mul(tv6, tv4); tv5 = Fp.mul(tv6, opts.B); tv2 = Fp.add(tv2, tv5); x = Fp.mul(tv1, tv3); const { isValid, value } = sqrtRatio(tv2, tv6); y = Fp.mul(tv1, u); y = Fp.mul(y, value); x = Fp.cmov(x, tv3, isValid); y = Fp.cmov(y, value, isValid); const e1 = Fp.isOdd(u) === Fp.isOdd(y); y = Fp.cmov(Fp.neg(y), y, e1); x = Fp.div(x, tv4); return { x, y }; }; } // node_modules/@noble/curves/esm/abstract/bls.js /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ var _0n5 = BigInt(0); var _1n5 = BigInt(1); var _2n4 = BigInt(2); var _3n3 = BigInt(3); function NAfDecomposition(a) { const res = []; for (;a > _1n5; a >>= _1n5) { if ((a & _1n5) === _0n5) res.unshift(0); else if ((a & _3n3) === _3n3) { res.unshift(-1); a += _1n5; } else res.unshift(1); } return res; } function bls(CURVE) { const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields; const BLS_X_IS_NEGATIVE = CURVE.params.xNegative; const TWIST = CURVE.params.twistType; const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 }); const G1 = Object.assign(G1_, createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, { ...CURVE.htfDefaults, ...CURVE.G1.htfDefaults })); const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 }); const G2 = Object.assign(G2_, createHasher(G2_.ProjectivePoint, CURVE.G2.mapToCurve, { ...CURVE.htfDefaults, ...CURVE.G2.htfDefaults })); let lineFunction; if (TWIST === "multiplicative") { lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py)); } else if (TWIST === "divisive") { lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0); } else throw new Error("bls: unknown twist type"); const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n4)); function pointDouble(ell, Rx, Ry, Rz) { const t0 = Fp2.sqr(Ry); const t1 = Fp2.sqr(Rz); const t2 = Fp2.mulByB(Fp2.mul(t1, _3n3)); const t3 = Fp2.mul(t2, _3n3); const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); const c0 = Fp2.sub(t2, t0); const c1 = Fp2.mul(Fp2.sqr(Rx), _3n3); const c2 = Fp2.neg(t4); ell.push([c0, c1, c2]); Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2); Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n3)); Rz = Fp2.mul(t0, t4); return { Rx, Ry, Rz }; } function pointAdd(ell, Rx, Ry, Rz, Qx, Qy) { const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)); const c1 = Fp2.neg(t0); const c2 = t1; ell.push([c0, c1, c2]); const t2 = Fp2.sqr(t1); const t3 = Fp2.mul(t2, t1); const t4 = Fp2.mul(t2, Rx); const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n4)), Fp2.mul(Fp2.sqr(t0), Rz)); Rx = Fp2.mul(t1, t5); Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); Rz = Fp2.mul(Rz, t3); return { Rx, Ry, Rz }; } const ATE_NAF = NAfDecomposition(CURVE.params.ateLoopSize); const calcPairingPrecomputes = memoized((point) => { const p = point; const { x, y } = p.toAffine(); const Qx = x, Qy = y, negQy = Fp2.neg(y); let Rx = Qx, Ry = Qy, Rz = Fp2.ONE; const ell = []; for (const bit of ATE_NAF) { const cur = []; ({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz)); if (bit) ({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy)); ell.push(cur); } if (CURVE.postPrecompute) { const last = ell[ell.length - 1]; CURVE.postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last)); } return ell; }); function millerLoopBatch(pairs, withFinalExponent = false) { let f12 = Fp12.ONE; if (pairs.length) { const ellLen = pairs[0][0].length; for (let i = 0;i < ellLen; i++) { f12 = Fp12.sqr(f12); for (const [ell, Px, Py] of pairs) { for (const [c0, c1, c2] of ell[i]) f12 = lineFunction(c0, c1, c2, f12, Px, Py); } } } if (BLS_X_IS_NEGATIVE) f12 = Fp12.conjugate(f12); return withFinalExponent ? Fp12.finalExponentiate(f12) : f12; } function pairingBatch(pairs, withFinalExponent = true) { const res = []; G1.ProjectivePoint.normalizeZ(pai