diff --git a/sw_scripts/additional-scripts.js b/sw_scripts/additional-scripts.js index fe5ce2e..a00e978 100644 --- a/sw_scripts/additional-scripts.js +++ b/sw_scripts/additional-scripts.js @@ -10,6 +10,7 @@ self.addEventListener("install", (event) => { "safari-notifications.js", "nacl.js", "noble-curves.js", + "noble-hashes.js", ); console.log("scripts imported", event); }); diff --git a/sw_scripts/noble-curves.js b/sw_scripts/noble-curves.js index 16a0af6..8e6f101 100644 --- a/sw_scripts/noble-curves.js +++ b/sw_scripts/noble-curves.js @@ -9,14 +9,19 @@ var nobleCurves = (() => { __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { + 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 }); + __defProp(to, key, { + get: () => from[key], + enumerable: + !(desc = __getOwnPropDesc(from, key)) || desc.enumerable, + }); } return to; }; - var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2); + var __toCommonJS = (mod2) => + __copyProps(__defProp({}, "__esModule", { value: true }), mod2); // input.js var input_exports = {}; @@ -34,7 +39,7 @@ var nobleCurves = (() => { secp256k1_schnorr: () => schnorr, utils: () => utils, x25519: () => x25519, - x448: () => x448 + x448: () => x448, }); // ../esm/abstract/utils.js @@ -58,16 +63,17 @@ var nobleCurves = (() => { numberToHexUnpadded: () => numberToHexUnpadded, numberToVarBytesBE: () => numberToVarBytesBE, utf8ToBytes: () => utf8ToBytes, - validateObject: () => validateObject + validateObject: () => validateObject, }); var _0n = BigInt(0); var _1n = BigInt(1); var _2n = BigInt(2); var u8a = (a) => a instanceof Uint8Array; - var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); + var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => + i.toString(16).padStart(2, "0"), + ); function bytesToHex(bytes2) { - if (!u8a(bytes2)) - throw new Error("Uint8Array expected"); + if (!u8a(bytes2)) throw new Error("Uint8Array expected"); let hex = ""; for (let i = 0; i < bytes2.length; i++) { hex += hexes[bytes2[i]]; @@ -88,7 +94,9 @@ var nobleCurves = (() => { 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); + 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; @@ -104,8 +112,7 @@ var nobleCurves = (() => { return hexToNumber(bytesToHex(bytes2)); } function bytesToNumberLE(bytes2) { - if (!u8a(bytes2)) - throw new Error("Uint8Array expected"); + if (!u8a(bytes2)) throw new Error("Uint8Array expected"); return hexToNumber(bytesToHex(Uint8Array.from(bytes2).reverse())); } function numberToBytesBE(n, len) { @@ -123,7 +130,9 @@ var nobleCurves = (() => { try { res = hexToBytes(hex); } catch (e) { - throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + throw new Error( + `${title} must be valid hex string, got "${hex}". Cause: ${e}`, + ); } } else if (u8a(hex)) { res = Uint8Array.from(hex); @@ -139,19 +148,15 @@ var nobleCurves = (() => { const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); let pad = 0; arrays.forEach((a) => { - if (!u8a(a)) - throw new Error("Uint8Array expected"); + if (!u8a(a)) throw new Error("Uint8Array expected"); r.set(a, pad); pad += a.length; }); return r; } function equalBytes(b1, b2) { - if (b1.length !== b2.length) - return false; - for (let i = 0; i < b1.length; i++) - if (b1[i] !== b2[i]) - return false; + if (b1.length !== b2.length) return false; + for (let i = 0; i < b1.length; i++) if (b1[i] !== b2[i]) return false; return true; } function utf8ToBytes(str) { @@ -161,15 +166,14 @@ var nobleCurves = (() => { } function bitLen(n) { let len; - for (len = 0; n > _0n; n >>= _1n, len += 1) - ; + for (len = 0; n > _0n; n >>= _1n, len += 1); return len; } function bitGet(n, pos) { - return n >> BigInt(pos) & _1n; + return (n >> BigInt(pos)) & _1n; } var bitSet = (n, pos, value) => { - return n | (value ? _1n : _0n) << BigInt(pos); + return n | ((value ? _1n : _0n) << BigInt(pos)); }; var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; var u8n = (data) => new Uint8Array(data); @@ -193,14 +197,12 @@ var nobleCurves = (() => { const reseed = (seed = u8n()) => { k = h(u8fr([0]), seed); v = h(); - if (seed.length === 0) - return; + if (seed.length === 0) return; k = h(u8fr([1]), seed); v = h(); }; const gen2 = () => { - if (i++ >= 1e3) - throw new Error("drbg: tried 1000 values"); + if (i++ >= 1e3) throw new Error("drbg: tried 1000 values"); let len = 0; const out = []; while (len < qByteLen) { @@ -215,8 +217,7 @@ var nobleCurves = (() => { reset(); reseed(seed); let res = void 0; - while (!(res = pred(gen2()))) - reseed(); + while (!(res = pred(gen2()))) reseed(); reset(); return res; }; @@ -227,11 +228,13 @@ var nobleCurves = (() => { function: (val) => typeof val === "function", boolean: (val) => typeof val === "boolean", string: (val) => typeof val === "string", - stringOrUint8Array: (val) => typeof val === "string" || val instanceof Uint8Array, + stringOrUint8Array: (val) => + typeof val === "string" || val instanceof Uint8Array, 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) + hash: (val) => + typeof val === "function" && Number.isSafeInteger(val.outputLen), }; function validateObject(object, validators, optValidators = {}) { const checkField = (fieldName, type, isOptional) => { @@ -239,10 +242,13 @@ var nobleCurves = (() => { if (typeof checkVal !== "function") throw new Error(`Invalid validator "${type}", expected function`); const val = object[fieldName]; - if (isOptional && val === void 0) - return; + if (isOptional && val === void 0) return; if (!checkVal(val, object)) { - throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + throw new Error( + `Invalid param ${String( + fieldName, + )}=${val} (${typeof val}), expected ${type}`, + ); } }; for (const [fieldName, type] of Object.entries(validators)) @@ -258,10 +264,11 @@ var nobleCurves = (() => { throw new Error(`Wrong positive integer: ${n}`); } function bytes(b, ...lengths) { - if (!(b instanceof Uint8Array)) - throw new Error("Expected Uint8Array"); + if (!(b instanceof Uint8Array)) throw new Error("Expected Uint8Array"); if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); + throw new Error( + `Expected Uint8Array of length ${lengths}, not of length=${b.length}`, + ); } function hash(hash2) { if (typeof hash2 !== "function" || typeof hash2.create !== "function") @@ -270,8 +277,7 @@ var nobleCurves = (() => { number(hash2.blockLen); } function exists(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); + if (instance.destroyed) throw new Error("Hash instance has been destroyed"); if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called"); } @@ -279,39 +285,42 @@ var nobleCurves = (() => { bytes(out); const min = instance.outputLen; if (out.length < min) { - throw new Error(`digestInto() expects output buffer of length at least ${min}`); + throw new Error( + `digestInto() expects output buffer of length at least ${min}`, + ); } } // ../node_modules/@noble/hashes/esm/crypto.js - var crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; + var crypto = + typeof globalThis === "object" && "crypto" in globalThis + ? globalThis.crypto + : void 0; // ../node_modules/@noble/hashes/esm/utils.js var u8a2 = (a) => a instanceof Uint8Array; - var u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); - var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); - var rotr = (word, shift) => word << 32 - shift | word >>> shift; + var u32 = (arr) => + new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + var createView = (arr) => + new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + var rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; - if (!isLE) - throw new Error("Non little-endian hardware is not supported"); + if (!isLE) throw new Error("Non little-endian hardware is not supported"); function utf8ToBytes2(str) { if (typeof str !== "string") throw new Error(`utf8ToBytes expected string, got ${typeof str}`); return new Uint8Array(new TextEncoder().encode(str)); } function toBytes(data) { - if (typeof data === "string") - data = utf8ToBytes2(data); - if (!u8a2(data)) - throw new Error(`expected Uint8Array, got ${typeof data}`); + if (typeof data === "string") data = utf8ToBytes2(data); + if (!u8a2(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); return data; } function concatBytes2(...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"); + if (!u8a2(a)) throw new Error("Uint8Array expected"); r.set(a, pad); pad += a.length; }); @@ -353,7 +362,7 @@ var nobleCurves = (() => { return view.setBigUint64(byteOffset, value, isLE2); const _32n2 = BigInt(32); const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n2 & _u32_max); + const wh = Number((value >> _32n2) & _u32_max); const wl = Number(value & _u32_max); const h = isLE2 ? 4 : 0; const l = isLE2 ? 0 : 4; @@ -411,8 +420,7 @@ var nobleCurves = (() => { this.process(view, 0); pos = 0; } - for (let i = pos; i < blockLen; i++) - buffer[i] = 0; + for (let i = pos; i < blockLen; i++) buffer[i] = 0; setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2); this.process(view, 0); const oview = createView(out); @@ -423,8 +431,7 @@ var nobleCurves = (() => { const state = this.get(); if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state"); - for (let i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE2); + for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE2); } digest() { const { buffer, outputLen } = this; @@ -441,90 +448,30 @@ var nobleCurves = (() => { to.pos = pos; to.finished = finished; to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer); + if (length % blockLen) to.buffer.set(buffer); return to; } }; // ../node_modules/@noble/hashes/esm/sha256.js - var Chi = (a, b, c) => a & b ^ ~a & c; - var Maj = (a, b, c) => a & b ^ a & c ^ b & c; + var Chi = (a, b, c) => (a & b) ^ (~a & c); + var Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); var SHA256_K = /* @__PURE__ */ new Uint32Array([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 + 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, + 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, + 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, + 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, + 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, + 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, + 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, + 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, + 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, + 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, + 2428436474, 2756734187, 3204031479, 3329325298, ]); var IV = /* @__PURE__ */ new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 + 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, + 528734635, 1541459225, ]); var SHA256_W = /* @__PURE__ */ new Uint32Array(64); var SHA256 = class extends SHA2 { @@ -560,33 +507,33 @@ var nobleCurves = (() => { for (let i = 16; i < 64; i++) { const W15 = SHA256_W[i - 15]; const W2 = SHA256_W[i - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; } let { A, B, C, D, E, F, G, H } = this; for (let i = 0; i < 64; i++) { const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); - const T2 = sigma0 + Maj(A, B, C) | 0; + const T2 = (sigma0 + Maj(A, B, C)) | 0; H = G; G = F; F = E; - E = D + T1 | 0; + E = (D + T1) | 0; D = C; C = B; B = A; - A = T1 + T2 | 0; + A = (T1 + T2) | 0; } - A = A + this.A | 0; - B = B + this.B | 0; - C = C + this.C | 0; - D = D + this.D | 0; - E = E + this.E | 0; - F = F + this.F | 0; - G = G + this.G | 0; - H = H + this.H | 0; + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; this.set(A, B, C, D, E, F, G, H); } roundClean() { @@ -616,13 +563,11 @@ var nobleCurves = (() => { function pow(num, power, modulo) { if (modulo <= _0n2 || power < _0n2) throw new Error("Expected power/modulo > 0"); - if (modulo === _1n2) - return _0n2; + if (modulo === _1n2) return _0n2; let res = _1n2; while (power > _0n2) { - if (power & _1n2) - res = res * num % modulo; - num = num * num % modulo; + if (power & _1n2) res = (res * num) % modulo; + num = (num * num) % modulo; power >>= _1n2; } return res; @@ -637,30 +582,32 @@ var nobleCurves = (() => { } function invert(number2, modulo) { if (number2 === _0n2 || modulo <= _0n2) { - throw new Error(`invert: expected positive integers, got n=${number2} mod=${modulo}`); + throw new Error( + `invert: expected positive integers, got n=${number2} mod=${modulo}`, + ); } let a = mod(number2, modulo); let b = modulo; - let x = _0n2, y = _1n2, u = _1n2, v = _0n2; + 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; + (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"); + if (gcd !== _1n2) throw new Error("invert: does not exist"); return mod(x, modulo); } function tonelliShanks(P3) { const legendreC = (P3 - _1n2) / _2n2; let Q, S, Z; - for (Q = P3 - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++) - ; - for (Z = _2n2; Z < P3 && pow(Z, legendreC, P3) !== P3 - _1n2; Z++) - ; + for (Q = P3 - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++); + for (Z = _2n2; Z < P3 && pow(Z, legendreC, P3) !== P3 - _1n2; Z++); if (S === 1) { const p1div4 = (P3 + _1n2) / _4n; return function tonelliFast(Fp8, n) { @@ -679,12 +626,10 @@ var nobleCurves = (() => { let x = Fp8.pow(n, Q1div2); let b = Fp8.pow(n, Q); while (!Fp8.eql(b, Fp8.ONE)) { - if (Fp8.eql(b, Fp8.ZERO)) - return Fp8.ZERO; + if (Fp8.eql(b, Fp8.ZERO)) return Fp8.ZERO; let m = 1; for (let t2 = Fp8.sqr(b); m < r; m++) { - if (Fp8.eql(t2, Fp8.ONE)) - break; + if (Fp8.eql(t2, Fp8.ONE)) break; t2 = Fp8.sqr(t2); } const ge2 = Fp8.pow(g, _1n2 << BigInt(r - m - 1)); @@ -741,14 +686,14 @@ var nobleCurves = (() => { "addN", "subN", "mulN", - "sqrN" + "sqrN", ]; function validateField(field) { const initial = { ORDER: "bigint", MASK: "bigint", BYTES: "isSafeInteger", - BITS: "isSafeInteger" + BITS: "isSafeInteger", }; const opts = FIELD_FIELDS.reduce((map, val) => { map[val] = "function"; @@ -757,17 +702,13 @@ var nobleCurves = (() => { return validateObject(field, opts); } function FpPow(f, num, power) { - if (power < _0n2) - throw new Error("Expected power > 0"); - if (power === _0n2) - return f.ONE; - if (power === _1n2) - return num; + if (power < _0n2) throw new Error("Expected power > 0"); + 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); + if (power & _1n2) p = f.mul(p, d); d = f.sqr(d); power >>= _1n2; } @@ -776,22 +717,21 @@ var nobleCurves = (() => { function FpInvertBatch(f, nums) { const tmp = new Array(nums.length); const lastMultiplied = nums.reduce((acc, num, i) => { - if (f.is0(num)) - return acc; + 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; + if (f.is0(num)) return acc; tmp[i] = f.mul(acc, tmp[i]); return f.mul(acc, num); }, inverted); return tmp; } function nLength(n, nBitLength) { - const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; + const _nBitLength = + nBitLength !== void 0 ? nBitLength : n.toString(2).length; const nByteLength = Math.ceil(_nBitLength / 8); return { nBitLength: _nBitLength, nByteLength }; } @@ -812,7 +752,9 @@ var nobleCurves = (() => { create: (num) => mod(num, ORDER), isValid: (num) => { if (typeof num !== "bigint") - throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + throw new Error( + `Invalid field element: expected bigint, got ${typeof num}`, + ); return _0n2 <= num && num < ORDER; }, is0: (num) => num === _0n2, @@ -835,19 +777,21 @@ var nobleCurves = (() => { 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, b, c) => c ? b : a, - toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), + cmov: (a, b, c) => (c ? b : a), + toBytes: (num) => + isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), fromBytes: (bytes2) => { if (bytes2.length !== BYTES) - throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes2.length}`); + throw new Error( + `Fp.fromBytes: expected ${BYTES}, got ${bytes2.length}`, + ); return isLE2 ? bytesToNumberLE(bytes2) : bytesToNumberBE(bytes2); - } + }, }); return Object.freeze(f); } function FpSqrtEven(Fp8, elm) { - if (!Fp8.isOdd) - throw new Error(`Field doesn't have isOdd`); + if (!Fp8.isOdd) throw new Error(`Field doesn't have isOdd`); const root = Fp8.sqrt(elm); return Fp8.isOdd(root) ? Fp8.neg(root) : root; } @@ -869,7 +813,9 @@ var nobleCurves = (() => { throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); const num = isLE2 ? bytesToNumberBE(key) : bytesToNumberLE(key); const reduced = mod(num, fieldOrder - _1n2) + _1n2; - return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); + return isLE2 + ? numberToBytesLE(reduced, fieldLen) + : numberToBytesBE(reduced, fieldLen); } // ../esm/abstract/curve.js @@ -892,8 +838,7 @@ var nobleCurves = (() => { let p = c.ZERO; let d = elm; while (n > _0n3) { - if (n & _1n3) - p = p.add(d); + if (n & _1n3) p = p.add(d); d = d.double(); n >>= _1n3; } @@ -969,49 +914,65 @@ var nobleCurves = (() => { } } return this.wNAF(W, comp, n); - } + }, }; } function validateBasic(curve) { validateField(curve.Fp); - validateObject(curve, { - n: "bigint", - h: "bigint", - Gx: "field", - Gy: "field" - }, { - nBitLength: "isSafeInteger", - nByteLength: "isSafeInteger" - }); + 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 } + ...{ p: curve.Fp.ORDER }, }); } // ../esm/abstract/weierstrass.js 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" - }); + validateObject( + opts, + { + a: "field", + b: "field", + }, + { + allowedPrivateKeyLengths: "array", + wrapPrivateKey: "boolean", + isTorsionFree: "function", + clearCofactor: "function", + allowInfinityPoint: "boolean", + fromBytes: "function", + toBytes: "function", + }, + ); const { endo, Fp: Fp8, a } = opts; if (endo) { if (!Fp8.eql(a, Fp8.ZERO)) { - throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); + 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"); + 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 }); @@ -1032,8 +993,7 @@ var nobleCurves = (() => { const res = data.subarray(2, len + 2); if (!len || res.length !== len) throw new E("Invalid signature integer: wrong length"); - if (res[0] & 128) - throw new E("Invalid signature integer: negative"); + if (res[0] & 128) throw new E("Invalid signature integer: negative"); if (res[0] === 0 && !(res[1] & 128)) throw new E("Invalid signature integer: unnecessary leading zero"); return { d: b2n(res), l: data.subarray(len + 2) }; @@ -1041,13 +1001,10 @@ var nobleCurves = (() => { toSig(hex) { const { Err: E } = DER; const data = typeof hex === "string" ? h2b(hex) : hex; - if (!(data instanceof Uint8Array)) - throw new Error("ui8a expected"); + if (!(data instanceof Uint8Array)) throw new Error("ui8a expected"); let l = data.length; - if (l < 2 || data[0] != 48) - throw new E("Invalid signature tag"); - if (data[1] !== l - 2) - throw new E("Invalid signature: incorrect length"); + if (l < 2 || data[0] != 48) throw new E("Invalid signature tag"); + if (data[1] !== l - 2) throw new E("Invalid signature: incorrect length"); const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); if (rBytesLeft.length) @@ -1055,7 +1012,7 @@ var nobleCurves = (() => { return { r, s }; }, hexFromSig(sig) { - const slice = (s2) => Number.parseInt(s2[0], 16) & 8 ? "00" + s2 : s2; + const slice = (s2) => (Number.parseInt(s2[0], 16) & 8 ? "00" + s2 : s2); const h = (num) => { const hex = num.toString(16); return hex.length & 1 ? `0${hex}` : hex; @@ -1067,7 +1024,7 @@ var nobleCurves = (() => { const sl = h(shl); const rl = h(rhl); return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; - } + }, }; var _0n4 = BigInt(0); var _1n4 = BigInt(1); @@ -1077,16 +1034,24 @@ var nobleCurves = (() => { function weierstrassPoints(opts) { const CURVE2 = validatePointOpts(opts); const { Fp: Fp8 } = CURVE2; - const toBytes2 = CURVE2.toBytes || ((_c, point, _isCompressed) => { - const a = point.toAffine(); - return concatBytes(Uint8Array.from([4]), Fp8.toBytes(a.x), Fp8.toBytes(a.y)); - }); - const fromBytes = CURVE2.fromBytes || ((bytes2) => { - const tail = bytes2.subarray(1); - const x = Fp8.fromBytes(tail.subarray(0, Fp8.BYTES)); - const y = Fp8.fromBytes(tail.subarray(Fp8.BYTES, 2 * Fp8.BYTES)); - return { x, y }; - }); + const toBytes2 = + CURVE2.toBytes || + ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return concatBytes( + Uint8Array.from([4]), + Fp8.toBytes(a.x), + Fp8.toBytes(a.y), + ); + }); + const fromBytes = + CURVE2.fromBytes || + ((bytes2) => { + const tail = bytes2.subarray(1); + const x = Fp8.fromBytes(tail.subarray(0, Fp8.BYTES)); + const y = Fp8.fromBytes(tail.subarray(Fp8.BYTES, 2 * Fp8.BYTES)); + return { x, y }; + }); function weierstrassEquation(x) { const { a, b } = CURVE2; const x2 = Fp8.sqr(x); @@ -1103,22 +1068,30 @@ var nobleCurves = (() => { throw new Error("Expected valid bigint: 0 < bigint < curve.n"); } function normPrivateKeyToScalar(key) { - const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE2; + const { + allowedPrivateKeyLengths: lengths, + nByteLength, + wrapPrivateKey, + n, + } = CURVE2; if (lengths && typeof key !== "bigint") { - if (key instanceof Uint8Array) - key = bytesToHex(key); + if (key instanceof Uint8Array) key = bytesToHex(key); if (typeof key !== "string" || !lengths.includes(key.length)) throw new Error("Invalid key"); key = key.padStart(nByteLength * 2, "0"); } let num; try { - num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); + num = + typeof key === "bigint" + ? key + : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); } catch (error) { - throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + throw new Error( + `private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`, + ); } - if (wrapPrivateKey) - num = mod(num, n); + if (wrapPrivateKey) num = mod(num, n); assertGE(num); return num; } @@ -1132,12 +1105,9 @@ var nobleCurves = (() => { this.px = px; this.py = py; this.pz = pz; - if (px == null || !Fp8.isValid(px)) - throw new Error("x required"); - if (py == null || !Fp8.isValid(py)) - throw new Error("y required"); - if (pz == null || !Fp8.isValid(pz)) - throw new Error("z required"); + if (px == null || !Fp8.isValid(px)) throw new Error("x required"); + if (py == null || !Fp8.isValid(py)) throw new Error("y required"); + if (pz == null || !Fp8.isValid(pz)) throw new Error("z required"); } // Does not validate if the point is on-curve. // Use fromHex instead, or call assertValidity() later. @@ -1148,8 +1118,7 @@ var nobleCurves = (() => { if (p instanceof Point2) throw new Error("projective point not allowed"); const is0 = (i) => Fp8.eql(i, Fp8.ZERO); - if (is0(x) && is0(y)) - return Point2.ZERO; + if (is0(x) && is0(y)) return Point2.ZERO; return new Point2(x, y, Fp8.ONE); } get x() { @@ -1166,7 +1135,9 @@ var nobleCurves = (() => { */ static normalizeZ(points) { const toInv = Fp8.invertBatch(points.map((p) => p.pz)); - return points.map((p, i) => p.toAffine(toInv[i])).map(Point2.fromAffine); + return points + .map((p, i) => p.toAffine(toInv[i])) + .map(Point2.fromAffine); } /** * Converts hash string or Uint8Array to Point. @@ -1189,8 +1160,7 @@ var nobleCurves = (() => { // A point on curve is valid if it conforms to equation. assertValidity() { if (this.is0()) { - if (CURVE2.allowInfinityPoint && !Fp8.is0(this.py)) - return; + if (CURVE2.allowInfinityPoint && !Fp8.is0(this.py)) return; throw new Error("bad point: ZERO"); } const { x, y } = this.toAffine(); @@ -1205,8 +1175,7 @@ var nobleCurves = (() => { } hasEvenY() { const { y } = this.toAffine(); - if (Fp8.isOdd) - return !Fp8.isOdd(y); + if (Fp8.isOdd) return !Fp8.isOdd(y); throw new Error("Field doesn't support isOdd"); } /** @@ -1234,7 +1203,9 @@ var nobleCurves = (() => { const { a, b } = CURVE2; const b3 = Fp8.mul(b, _3n2); const { px: X1, py: Y1, pz: Z1 } = this; - let X3 = Fp8.ZERO, Y3 = Fp8.ZERO, Z3 = Fp8.ZERO; + let X3 = Fp8.ZERO, + Y3 = Fp8.ZERO, + Z3 = Fp8.ZERO; let t0 = Fp8.mul(X1, X1); let t1 = Fp8.mul(Y1, Y1); let t2 = Fp8.mul(Z1, Z1); @@ -1276,7 +1247,9 @@ var nobleCurves = (() => { assertPrjPoint(other); const { px: X1, py: Y1, pz: Z1 } = this; const { px: X2, py: Y2, pz: Z2 } = other; - let X3 = Fp8.ZERO, Y3 = Fp8.ZERO, Z3 = Fp8.ZERO; + let X3 = Fp8.ZERO, + Y3 = Fp8.ZERO, + Z3 = Fp8.ZERO; const a = CURVE2.a; const b3 = Fp8.mul(CURVE2.b, _3n2); let t0 = Fp8.mul(X1, X2); @@ -1330,7 +1303,9 @@ var nobleCurves = (() => { wNAF(n) { return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { const toInv = Fp8.invertBatch(comp.map((p) => p.pz)); - return comp.map((p, i) => p.toAffine(toInv[i])).map(Point2.fromAffine); + return comp + .map((p, i) => p.toAffine(toInv[i])) + .map(Point2.fromAffine); }); } /** @@ -1340,31 +1315,24 @@ var nobleCurves = (() => { */ multiplyUnsafe(n) { const I = Point2.ZERO; - if (n === _0n4) - return I; + if (n === _0n4) return I; assertGE(n); - if (n === _1n4) - return this; + if (n === _1n4) return this; const { endo } = CURVE2; - if (!endo) - return wnaf.unsafeLadder(this, n); + if (!endo) return wnaf.unsafeLadder(this, n); let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); 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); + 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(); + if (k1neg) k1p = k1p.negate(); + if (k2neg) k2p = k2p.negate(); k2p = new Point2(Fp8.mul(k2p.px, endo.beta), k2p.py, k2p.pz); return k1p.add(k2p); } @@ -1406,7 +1374,10 @@ var nobleCurves = (() => { */ multiplyAndAddUnsafe(Q, a, b) { const G = Point2.BASE; - const mul = (P3, a2) => a2 === _0n4 || a2 === _1n4 || !P3.equals(G) ? P3.multiplyUnsafe(a2) : P3.multiply(a2); + const mul = (P3, a2) => + a2 === _0n4 || a2 === _1n4 || !P3.equals(G) + ? P3.multiplyUnsafe(a2) + : P3.multiply(a2); const sum = mul(this, a).add(mul(Q, b)); return sum.is0() ? void 0 : sum; } @@ -1416,31 +1387,26 @@ var nobleCurves = (() => { toAffine(iz) { const { px: x, py: y, pz: z } = this; const is0 = this.is0(); - if (iz == null) - iz = is0 ? Fp8.ONE : Fp8.inv(z); + if (iz == null) iz = is0 ? Fp8.ONE : Fp8.inv(z); const ax = Fp8.mul(x, iz); const ay = Fp8.mul(y, iz); const zz = Fp8.mul(z, iz); - if (is0) - return { x: Fp8.ZERO, y: Fp8.ZERO }; - if (!Fp8.eql(zz, Fp8.ONE)) - throw new Error("invZ was invalid"); + if (is0) return { x: Fp8.ZERO, y: Fp8.ZERO }; + if (!Fp8.eql(zz, Fp8.ONE)) throw new Error("invZ was invalid"); return { x: ax, y: ay }; } isTorsionFree() { const { h: cofactor, isTorsionFree } = CURVE2; - if (cofactor === _1n4) - return true; - if (isTorsionFree) - return isTorsionFree(Point2, this); - throw new Error("isTorsionFree() has not been declared for the elliptic curve"); + if (cofactor === _1n4) return true; + if (isTorsionFree) return isTorsionFree(Point2, this); + throw new Error( + "isTorsionFree() has not been declared for the elliptic curve", + ); } clearCofactor() { const { h: cofactor, clearCofactor } = CURVE2; - if (cofactor === _1n4) - return this; - if (clearCofactor) - return clearCofactor(Point2, this); + if (cofactor === _1n4) return this; + if (clearCofactor) return clearCofactor(Point2, this); return this.multiplyUnsafe(CURVE2.h); } toRawBytes(isCompressed = true) { @@ -1460,20 +1426,24 @@ var nobleCurves = (() => { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, - isWithinCurveOrder + isWithinCurveOrder, }; } function validateOpts(curve) { const opts = validateBasic(curve); - validateObject(opts, { - hash: "hash", - hmac: "function", - randomBytes: "function" - }, { - bits2int: "function", - bits2int_modN: "function", - lowS: "boolean" - }); + validateObject( + opts, + { + hash: "hash", + hmac: "function", + randomBytes: "function", + }, + { + bits2int: "function", + bits2int_modN: "function", + lowS: "boolean", + }, + ); return Object.freeze({ lowS: true, ...opts }); } function weierstrass(curveDef) { @@ -1490,7 +1460,12 @@ var nobleCurves = (() => { function invN(a) { return invert(a, CURVE_ORDER); } - const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ + const { + ProjectivePoint: Point2, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder, + } = weierstrassPoints({ ...CURVE2, toBytes(_c, point, isCompressed) { const a = point.toAffine(); @@ -1508,25 +1483,26 @@ var nobleCurves = (() => { const tail = bytes2.subarray(1); if (len === compressedLen && (head === 2 || head === 3)) { const x = bytesToNumberBE(tail); - if (!isValidFieldElement(x)) - throw new Error("Point is not on curve"); + if (!isValidFieldElement(x)) throw new Error("Point is not on curve"); const y2 = weierstrassEquation(x); let y = Fp8.sqrt(y2); const isYOdd = (y & _1n4) === _1n4; const isHeadOdd = (head & 1) === 1; - if (isHeadOdd !== isYOdd) - y = Fp8.neg(y); + if (isHeadOdd !== isYOdd) y = Fp8.neg(y); return { x, y }; } else if (len === uncompressedLen && head === 4) { const x = Fp8.fromBytes(tail.subarray(0, Fp8.BYTES)); const y = Fp8.fromBytes(tail.subarray(Fp8.BYTES, 2 * Fp8.BYTES)); return { x, y }; } else { - throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + throw new Error( + `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`, + ); } - } + }, }); - const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE2.nByteLength)); + const numToNByteStr = (num) => + bytesToHex(numberToBytesBE(num, CURVE2.nByteLength)); function isBiggerThanHalfOrder(number2) { const HALF = CURVE_ORDER >> _1n4; return number2 > HALF; @@ -1569,16 +1545,14 @@ var nobleCurves = (() => { if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error("recovery id invalid"); const radj = rec === 2 || rec === 3 ? r + CURVE2.n : r; - if (radj >= Fp8.ORDER) - throw new Error("recovery id 2 or 3 invalid"); + if (radj >= Fp8.ORDER) throw new Error("recovery id 2 or 3 invalid"); const prefix = (rec & 1) === 0 ? "02" : "03"; const R = Point2.fromHex(prefix + numToNByteStr(radj)); const ir = invN(radj); const u1 = modN2(-h * ir); const u2 = modN2(s * ir); const Q = Point2.BASE.multiplyAndAddUnsafe(R, u1, u2); - if (!Q) - throw new Error("point at infinify"); + if (!Q) throw new Error("point at infinify"); Q.assertValidity(); return Q; } @@ -1587,7 +1561,9 @@ var nobleCurves = (() => { return isBiggerThanHalfOrder(this.s); } normalizeS() { - return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this; + return this.hasHighS() + ? new Signature(this.r, modN2(-this.s), this.recovery) + : this; } // DER-encoded toDERRawBytes() { @@ -1634,7 +1610,7 @@ var nobleCurves = (() => { point._setWindowSize(windowSize); point.multiply(BigInt(3)); return point; - } + }, }; function getPublicKey(privateKey, isCompressed = true) { return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed); @@ -1643,34 +1619,34 @@ var nobleCurves = (() => { const arr = item instanceof Uint8Array; const str = typeof item === "string"; const len = (arr || str) && item.length; - if (arr) - return len === compressedLen || len === uncompressedLen; - if (str) - return len === 2 * compressedLen || len === 2 * uncompressedLen; - if (item instanceof Point2) - return true; + if (arr) return len === compressedLen || len === uncompressedLen; + if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point2) return true; return false; } function getSharedSecret(privateA, publicB, isCompressed = true) { - if (isProbPub(privateA)) - throw new Error("first arg must be private key"); - if (!isProbPub(publicB)) - throw new Error("second arg must be public key"); + if (isProbPub(privateA)) throw new Error("first arg must be private key"); + if (!isProbPub(publicB)) throw new Error("second arg must be public key"); const b = Point2.fromHex(publicB); - return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + return b + .multiply(normPrivateKeyToScalar(privateA)) + .toRawBytes(isCompressed); } - const bits2int = CURVE2.bits2int || function(bytes2) { - const num = bytesToNumberBE(bytes2); - const delta = bytes2.length * 8 - CURVE2.nBitLength; - return delta > 0 ? num >> BigInt(delta) : num; - }; - const bits2int_modN = CURVE2.bits2int_modN || function(bytes2) { - return modN2(bits2int(bytes2)); - }; + const bits2int = + CURVE2.bits2int || + function (bytes2) { + const num = bytesToNumberBE(bytes2); + const delta = bytes2.length * 8 - CURVE2.nBitLength; + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = + CURVE2.bits2int_modN || + function (bytes2) { + return modN2(bits2int(bytes2)); + }; const ORDER_MASK = bitMask(CURVE2.nBitLength); function int2octets(num) { - if (typeof num !== "bigint") - throw new Error("bigint expected"); + if (typeof num !== "bigint") throw new Error("bigint expected"); if (!(_0n4 <= num && num < ORDER_MASK)) throw new Error(`bigint expected < 2^${CURVE2.nBitLength}`); return numberToBytesBE(num, CURVE2.nByteLength); @@ -1680,11 +1656,9 @@ var nobleCurves = (() => { throw new Error("sign() legacy options not supported"); const { hash: hash2, randomBytes: randomBytes2 } = CURVE2; let { lowS, prehash, extraEntropy: ent } = opts; - if (lowS == null) - lowS = true; + if (lowS == null) lowS = true; msgHash = ensureBytes("msgHash", msgHash); - if (prehash) - msgHash = ensureBytes("prehashed msgHash", hash2(msgHash)); + if (prehash) msgHash = ensureBytes("prehashed msgHash", hash2(msgHash)); const h1int = bits2int_modN(msgHash); const d = normPrivateKeyToScalar(privateKey); const seedArgs = [int2octets(d), int2octets(h1int)]; @@ -1696,16 +1670,13 @@ var nobleCurves = (() => { const m = h1int; function k2sig(kBytes) { const k = bits2int(kBytes); - if (!isWithinCurveOrder(k)) - return; + if (!isWithinCurveOrder(k)) return; const ik = invN(k); const q = Point2.BASE.multiply(k).toAffine(); const r = modN2(q.x); - if (r === _0n4) - return; + if (r === _0n4) return; const s = modN2(ik * modN2(m + r * d)); - if (s === _0n4) - return; + if (s === _0n4) return; let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4); let normS = s; if (lowS && isBiggerThanHalfOrder(s)) { @@ -1739,11 +1710,14 @@ var nobleCurves = (() => { try { _sig = Signature.fromDER(sg); } catch (derError) { - if (!(derError instanceof DER.Err)) - throw derError; + if (!(derError instanceof DER.Err)) throw derError; _sig = Signature.fromCompact(sg); } - } else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") { + } else if ( + typeof sg === "object" && + typeof sg.r === "bigint" && + typeof sg.s === "bigint" + ) { const { r: r2, s: s2 } = sg; _sig = new Signature(r2, s2); } else { @@ -1752,21 +1726,20 @@ var nobleCurves = (() => { P3 = Point2.fromHex(publicKey); } catch (error) { if (error.message === "PARSE") - throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + throw new Error( + `signature must be Signature instance, Uint8Array or hex string`, + ); return false; } - if (lowS && _sig.hasHighS()) - return false; - if (prehash) - msgHash = CURVE2.hash(msgHash); + if (lowS && _sig.hasHighS()) return false; + if (prehash) msgHash = CURVE2.hash(msgHash); const { r, s } = _sig; const h = bits2int_modN(msgHash); const is = invN(s); const u1 = modN2(h * is); const u2 = modN2(r * is); const R = Point2.BASE.multiplyAndAddUnsafe(P3, u1, u2)?.toAffine(); - if (!R) - return false; + if (!R) return false; const v = modN2(R.x); return v === r; } @@ -1778,16 +1751,15 @@ var nobleCurves = (() => { verify, ProjectivePoint: Point2, Signature, - utils: utils2 + utils: utils2, }; } function SWUFpSqrtRatio(Fp8, Z) { const q = Fp8.ORDER; let l = _0n4; - for (let o = q - _1n4; o % _2n3 === _0n4; o /= _2n3) - l += _1n4; + 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_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; @@ -1814,7 +1786,7 @@ var nobleCurves = (() => { tv4 = Fp8.cmov(tv5, tv4, isQR); for (let i = c1; i > _1n4; i--) { let tv52 = i - _2n3; - tv52 = _2n3 << tv52 - _1n4; + tv52 = _2n3 << (tv52 - _1n4); let tvv5 = Fp8.pow(tv4, tv52); const e1 = Fp8.eql(tvv5, Fp8.ONE); tv2 = Fp8.mul(tv3, tv1); @@ -1848,8 +1820,7 @@ var nobleCurves = (() => { if (!Fp8.isValid(opts.A) || !Fp8.isValid(opts.B) || !Fp8.isValid(opts.Z)) throw new Error("mapToCurveSimpleSWU: invalid opts"); const sqrtRatio = SWUFpSqrtRatio(Fp8, opts.Z); - if (!Fp8.isOdd) - throw new Error("Fp.isOdd is not implemented!"); + if (!Fp8.isOdd) throw new Error("Fp.isOdd is not implemented!"); return (u) => { let tv1, tv2, tv3, tv4, tv5, tv6, x, y; tv1 = Fp8.sqr(u); @@ -1883,15 +1854,13 @@ var nobleCurves = (() => { // ../esm/abstract/hash-to-curve.js function validateDST(dst) { - if (dst instanceof Uint8Array) - return dst; - if (typeof dst === "string") - return utf8ToBytes(dst); + if (dst instanceof Uint8Array) return dst; + if (typeof dst === "string") return utf8ToBytes(dst); throw new Error("DST must be Uint8Array or string"); } var os2ip = bytesToNumberBE; function i2osp(value, length) { - if (value < 0 || value >= 1 << 8 * 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); @@ -1909,12 +1878,10 @@ var nobleCurves = (() => { return arr; } function isBytes(item) { - if (!(item instanceof Uint8Array)) - throw new Error("Uint8Array expected"); + if (!(item instanceof Uint8Array)) throw new Error("Uint8Array expected"); } function isNum(item) { - if (!Number.isSafeInteger(item)) - throw new Error("number expected"); + if (!Number.isSafeInteger(item)) throw new Error("number expected"); } function expand_message_xmd(msg, DST, lenInBytes, H) { isBytes(msg); @@ -1924,8 +1891,7 @@ var nobleCurves = (() => { 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 (ell > 255) - throw new Error("Invalid xmd length"); + if (ell > 255) throw new Error("Invalid xmd length"); 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); @@ -1944,12 +1910,20 @@ var nobleCurves = (() => { isBytes(DST); isNum(lenInBytes); if (DST.length > 255) { - const dkLen = Math.ceil(2 * k / 8); - DST = H.create({ dkLen }).update(utf8ToBytes("H2C-OVERSIZE-DST-")).update(DST).digest(); + 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(); + 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, { @@ -1957,7 +1931,7 @@ var nobleCurves = (() => { p: "bigint", m: "isSafeInteger", k: "isSafeInteger", - hash: "hash" + hash: "hash", }); const { p, k, m, hash: hash2, expand, DST: _DST } = options; isBytes(msg); @@ -1991,7 +1965,9 @@ var nobleCurves = (() => { 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))); + 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 }; @@ -2014,11 +1990,15 @@ var nobleCurves = (() => { // 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 u = hash_to_field(msg, 1, { + ...def, + DST: def.encodeDST, + ...options, + }); const P3 = Point2.fromAffine(mapToCurve(u[0])).clearCofactor(); P3.assertValidity(); return P3; - } + }, }; } @@ -2037,13 +2017,13 @@ var nobleCurves = (() => { this.outputLen = this.iHash.outputLen; const blockLen = this.blockLen; const pad = new Uint8Array(blockLen); - pad.set(key.length > blockLen ? hash2.create().update(key).digest() : key); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 54; + pad.set( + key.length > blockLen ? hash2.create().update(key).digest() : key, + ); + for (let i = 0; i < pad.length; i++) pad[i] ^= 54; this.iHash.update(pad); this.oHash = hash2.create(); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 54 ^ 92; + for (let i = 0; i < pad.length; i++) pad[i] ^= 54 ^ 92; this.oHash.update(pad); pad.fill(0); } @@ -2084,7 +2064,8 @@ var nobleCurves = (() => { this.iHash.destroy(); } }; - var hmac = (hash2, key, message) => new HMAC(hash2, key).update(message).digest(); + var hmac = (hash2, key, message) => + new HMAC(hash2, key).update(message).digest(); hmac.create = (hash2, key) => new HMAC(hash2, key); // ../esm/_shortw_utils.js @@ -2092,7 +2073,7 @@ var nobleCurves = (() => { return { hash: hash2, hmac: (key, ...msgs) => hmac(hash2, key, concatBytes2(...msgs)), - randomBytes + randomBytes, }; } function createCurve(curveDef, defHash) { @@ -2101,76 +2082,91 @@ var nobleCurves = (() => { } // ../esm/secp256k1.js - var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); - var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); + var secp256k1P = BigInt( + "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f", + ); + var secp256k1N = BigInt( + "0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", + ); var _1n5 = BigInt(1); var _2n4 = BigInt(2); var divNearest = (a, b) => (a + b / _2n4) / b; function sqrtMod(y) { const P3 = secp256k1P; - const _3n6 = BigInt(3), _6n = BigInt(6), _11n2 = BigInt(11), _22n2 = BigInt(22); - const _23n = BigInt(23), _44n2 = BigInt(44), _88n2 = BigInt(88); - const b2 = y * y * y % P3; - const b3 = b2 * b2 * y % P3; - const b6 = pow2(b3, _3n6, P3) * b3 % P3; - const b9 = pow2(b6, _3n6, P3) * b3 % P3; - const b11 = pow2(b9, _2n4, P3) * b2 % P3; - const b22 = pow2(b11, _11n2, P3) * b11 % P3; - const b44 = pow2(b22, _22n2, P3) * b22 % P3; - const b88 = pow2(b44, _44n2, P3) * b44 % P3; - const b176 = pow2(b88, _88n2, P3) * b88 % P3; - const b220 = pow2(b176, _44n2, P3) * b44 % P3; - const b223 = pow2(b220, _3n6, P3) * b3 % P3; - const t1 = pow2(b223, _23n, P3) * b22 % P3; - const t2 = pow2(t1, _6n, P3) * b2 % P3; + const _3n6 = BigInt(3), + _6n = BigInt(6), + _11n2 = BigInt(11), + _22n2 = BigInt(22); + const _23n = BigInt(23), + _44n2 = BigInt(44), + _88n2 = BigInt(88); + const b2 = (y * y * y) % P3; + const b3 = (b2 * b2 * y) % P3; + const b6 = (pow2(b3, _3n6, P3) * b3) % P3; + const b9 = (pow2(b6, _3n6, P3) * b3) % P3; + const b11 = (pow2(b9, _2n4, P3) * b2) % P3; + const b22 = (pow2(b11, _11n2, P3) * b11) % P3; + const b44 = (pow2(b22, _22n2, P3) * b22) % P3; + const b88 = (pow2(b44, _44n2, P3) * b44) % P3; + const b176 = (pow2(b88, _88n2, P3) * b88) % P3; + const b220 = (pow2(b176, _44n2, P3) * b44) % P3; + const b223 = (pow2(b220, _3n6, P3) * b3) % P3; + const t1 = (pow2(b223, _23n, P3) * b22) % P3; + const t2 = (pow2(t1, _6n, P3) * b2) % P3; const root = pow2(t2, _2n4, P3); - if (!Fp.eql(Fp.sqr(root), y)) - throw new Error("Cannot find square root"); + if (!Fp.eql(Fp.sqr(root), y)) throw new Error("Cannot find square root"); return root; } var Fp = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); - var secp256k1 = createCurve({ - a: BigInt(0), - b: BigInt(7), - Fp, - n: secp256k1N, - // Base point (x, y) aka generator point - Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), - Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), - h: BigInt(1), - lowS: true, - /** - * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. - * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. - * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. - * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 - */ - endo: { - beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), - splitScalar: (k) => { - const n = secp256k1N; - const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); - const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); - const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); - const b2 = a1; - const POW_2_128 = BigInt("0x100000000000000000000000000000000"); - const c1 = divNearest(b2 * k, n); - const c2 = divNearest(-b1 * k, n); - let k1 = mod(k - c1 * a1 - c2 * a2, n); - let k2 = mod(-c1 * b1 - c2 * b2, n); - const k1neg = k1 > POW_2_128; - const k2neg = k2 > POW_2_128; - if (k1neg) - k1 = n - k1; - if (k2neg) - k2 = n - k2; - if (k1 > POW_2_128 || k2 > POW_2_128) { - throw new Error("splitScalar: Endomorphism failed, k=" + k); - } - return { k1neg, k1, k2neg, k2 }; - } - } - }, sha256); + var secp256k1 = createCurve( + { + a: BigInt(0), + b: BigInt(7), + Fp, + n: secp256k1N, + // Base point (x, y) aka generator point + Gx: BigInt( + "55066263022277343669578718895168534326250603453777594175500187360389116729240", + ), + Gy: BigInt( + "32670510020758816978083085130507043184471273380659243275938904335757337482424", + ), + h: BigInt(1), + lowS: true, + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt( + "0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", + ), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); + const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); + const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); + const b2 = a1; + const POW_2_128 = BigInt("0x100000000000000000000000000000000"); + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) k1 = n - k1; + if (k2neg) k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error("splitScalar: Endomorphism failed, k=" + k); + } + return { k1neg, k1, k2neg, k2 }; + }, + }, + }, + sha256, + ); var _0n5 = BigInt(0); var fe = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1P; var ge = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1N; @@ -2197,13 +2193,11 @@ var nobleCurves = (() => { return { scalar, bytes: pointToBytes(p) }; } function lift_x(x) { - if (!fe(x)) - throw new Error("bad x: need 0 < x < p"); + if (!fe(x)) throw new Error("bad x: need 0 < x < p"); const xx = modP(x * x); const c = modP(xx * x + BigInt(7)); let y = sqrtMod(c); - if (y % _2n4 !== _0n5) - y = modP(-y); + if (y % _2n4 !== _0n5) y = modP(-y); const p = new Point(x, y, _1n5); p.assertValidity(); return p; @@ -2221,8 +2215,7 @@ var nobleCurves = (() => { const t = numTo32b(d ^ bytesToNumberBE(taggedHash("BIP0340/aux", a))); const rand = taggedHash("BIP0340/nonce", t, px, m); const k_ = modN(bytesToNumberBE(rand)); - if (k_ === _0n5) - throw new Error("sign failed: k is zero"); + if (k_ === _0n5) throw new Error("sign failed: k is zero"); const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); const e = challenge(rx, px, m); const sig = new Uint8Array(64); @@ -2239,15 +2232,12 @@ var nobleCurves = (() => { try { const P3 = lift_x(bytesToNumberBE(pub)); const r = bytesToNumberBE(sig.subarray(0, 32)); - if (!fe(r)) - return false; + if (!fe(r)) return false; const s = bytesToNumberBE(sig.subarray(32, 64)); - if (!ge(s)) - return false; + if (!ge(s)) return false; const e = challenge(numTo32b(r), pointToBytes(P3), m); const R = GmulAdd(P3, s, modN(-e)); - if (!R || !R.hasEvenY() || R.toAffine().x !== r) - return false; + if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; return true; } catch (error) { return false; @@ -2264,8 +2254,8 @@ var nobleCurves = (() => { numberToBytesBE, bytesToNumberBE, taggedHash, - mod - } + mod, + }, }))(); // ../node_modules/@noble/hashes/esm/_u64.js @@ -2273,8 +2263,11 @@ var nobleCurves = (() => { var _32n = /* @__PURE__ */ BigInt(32); function fromBig(n, le = false) { if (le) - return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; - return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { + h: Number((n >> _32n) & U32_MASK64) | 0, + l: Number(n & U32_MASK64) | 0, + }; } function split(lst, le = false) { let Ah = new Uint32Array(lst.length); @@ -2285,29 +2278,33 @@ var nobleCurves = (() => { } return [Ah, Al]; } - var toBig = (h, l) => BigInt(h >>> 0) << _32n | BigInt(l >>> 0); + var toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); var shrSH = (h, _l, s) => h >>> s; - var shrSL = (h, l, s) => h << 32 - s | l >>> s; - var rotrSH = (h, l, s) => h >>> s | l << 32 - s; - var rotrSL = (h, l, s) => h << 32 - s | l >>> s; - var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32; - var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s; + var shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); + var rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); + var rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); + var rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); + var rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); var rotr32H = (_h, l) => l; var rotr32L = (h, _l) => h; - var rotlSH = (h, l, s) => h << s | l >>> 32 - s; - var rotlSL = (h, l, s) => l << s | h >>> 32 - s; - var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; - var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; + var rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); + var rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); + var rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); + var rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); function add(Ah, Al, Bh, Bl) { const l = (Al >>> 0) + (Bl >>> 0); - return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 }; + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; } var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); - var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0; - var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); - var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0; - var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); - var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0; + var add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; + var add4L = (Al, Bl, Cl, Dl) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); + var add4H = (low, Ah, Bh, Ch, Dh) => + (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; + var add5L = (Al, Bl, Cl, Dl, El) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); + var add5H = (low, Ah, Bh, Ch, Dh, Eh) => + (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; var u64 = { fromBig, split, @@ -2330,93 +2327,96 @@ var nobleCurves = (() => { add4L, add4H, add5H, - add5L + add5L, }; var u64_default = u64; // ../node_modules/@noble/hashes/esm/sha512.js - var [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64_default.split([ - "0x428a2f98d728ae22", - "0x7137449123ef65cd", - "0xb5c0fbcfec4d3b2f", - "0xe9b5dba58189dbbc", - "0x3956c25bf348b538", - "0x59f111f1b605d019", - "0x923f82a4af194f9b", - "0xab1c5ed5da6d8118", - "0xd807aa98a3030242", - "0x12835b0145706fbe", - "0x243185be4ee4b28c", - "0x550c7dc3d5ffb4e2", - "0x72be5d74f27b896f", - "0x80deb1fe3b1696b1", - "0x9bdc06a725c71235", - "0xc19bf174cf692694", - "0xe49b69c19ef14ad2", - "0xefbe4786384f25e3", - "0x0fc19dc68b8cd5b5", - "0x240ca1cc77ac9c65", - "0x2de92c6f592b0275", - "0x4a7484aa6ea6e483", - "0x5cb0a9dcbd41fbd4", - "0x76f988da831153b5", - "0x983e5152ee66dfab", - "0xa831c66d2db43210", - "0xb00327c898fb213f", - "0xbf597fc7beef0ee4", - "0xc6e00bf33da88fc2", - "0xd5a79147930aa725", - "0x06ca6351e003826f", - "0x142929670a0e6e70", - "0x27b70a8546d22ffc", - "0x2e1b21385c26c926", - "0x4d2c6dfc5ac42aed", - "0x53380d139d95b3df", - "0x650a73548baf63de", - "0x766a0abb3c77b2a8", - "0x81c2c92e47edaee6", - "0x92722c851482353b", - "0xa2bfe8a14cf10364", - "0xa81a664bbc423001", - "0xc24b8b70d0f89791", - "0xc76c51a30654be30", - "0xd192e819d6ef5218", - "0xd69906245565a910", - "0xf40e35855771202a", - "0x106aa07032bbd1b8", - "0x19a4c116b8d2d0c8", - "0x1e376c085141ab53", - "0x2748774cdf8eeb99", - "0x34b0bcb5e19b48a8", - "0x391c0cb3c5c95a63", - "0x4ed8aa4ae3418acb", - "0x5b9cca4f7763e373", - "0x682e6ff3d6b2b8a3", - "0x748f82ee5defb2fc", - "0x78a5636f43172f60", - "0x84c87814a1f0ab72", - "0x8cc702081a6439ec", - "0x90befffa23631e28", - "0xa4506cebde82bde9", - "0xbef9a3f7b2c67915", - "0xc67178f2e372532b", - "0xca273eceea26619c", - "0xd186b8c721c0c207", - "0xeada7dd6cde0eb1e", - "0xf57d4f7fee6ed178", - "0x06f067aa72176fba", - "0x0a637dc5a2c898a6", - "0x113f9804bef90dae", - "0x1b710b35131c471b", - "0x28db77f523047d84", - "0x32caab7b40c72493", - "0x3c9ebe0a15c9bebc", - "0x431d67c49c100d4c", - "0x4cc5d4becb3e42b6", - "0x597f299cfc657e2a", - "0x5fcb6fab3ad6faec", - "0x6c44198c4a475817" - ].map((n) => BigInt(n))))(); + var [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => + u64_default.split( + [ + "0x428a2f98d728ae22", + "0x7137449123ef65cd", + "0xb5c0fbcfec4d3b2f", + "0xe9b5dba58189dbbc", + "0x3956c25bf348b538", + "0x59f111f1b605d019", + "0x923f82a4af194f9b", + "0xab1c5ed5da6d8118", + "0xd807aa98a3030242", + "0x12835b0145706fbe", + "0x243185be4ee4b28c", + "0x550c7dc3d5ffb4e2", + "0x72be5d74f27b896f", + "0x80deb1fe3b1696b1", + "0x9bdc06a725c71235", + "0xc19bf174cf692694", + "0xe49b69c19ef14ad2", + "0xefbe4786384f25e3", + "0x0fc19dc68b8cd5b5", + "0x240ca1cc77ac9c65", + "0x2de92c6f592b0275", + "0x4a7484aa6ea6e483", + "0x5cb0a9dcbd41fbd4", + "0x76f988da831153b5", + "0x983e5152ee66dfab", + "0xa831c66d2db43210", + "0xb00327c898fb213f", + "0xbf597fc7beef0ee4", + "0xc6e00bf33da88fc2", + "0xd5a79147930aa725", + "0x06ca6351e003826f", + "0x142929670a0e6e70", + "0x27b70a8546d22ffc", + "0x2e1b21385c26c926", + "0x4d2c6dfc5ac42aed", + "0x53380d139d95b3df", + "0x650a73548baf63de", + "0x766a0abb3c77b2a8", + "0x81c2c92e47edaee6", + "0x92722c851482353b", + "0xa2bfe8a14cf10364", + "0xa81a664bbc423001", + "0xc24b8b70d0f89791", + "0xc76c51a30654be30", + "0xd192e819d6ef5218", + "0xd69906245565a910", + "0xf40e35855771202a", + "0x106aa07032bbd1b8", + "0x19a4c116b8d2d0c8", + "0x1e376c085141ab53", + "0x2748774cdf8eeb99", + "0x34b0bcb5e19b48a8", + "0x391c0cb3c5c95a63", + "0x4ed8aa4ae3418acb", + "0x5b9cca4f7763e373", + "0x682e6ff3d6b2b8a3", + "0x748f82ee5defb2fc", + "0x78a5636f43172f60", + "0x84c87814a1f0ab72", + "0x8cc702081a6439ec", + "0x90befffa23631e28", + "0xa4506cebde82bde9", + "0xbef9a3f7b2c67915", + "0xc67178f2e372532b", + "0xca273eceea26619c", + "0xd186b8c721c0c207", + "0xeada7dd6cde0eb1e", + "0xf57d4f7fee6ed178", + "0x06f067aa72176fba", + "0x0a637dc5a2c898a6", + "0x113f9804bef90dae", + "0x1b710b35131c471b", + "0x28db77f523047d84", + "0x32caab7b40c72493", + "0x3c9ebe0a15c9bebc", + "0x431d67c49c100d4c", + "0x4cc5d4becb3e42b6", + "0x597f299cfc657e2a", + "0x5fcb6fab3ad6faec", + "0x6c44198c4a475817", + ].map((n) => BigInt(n)), + ))(); var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); var SHA512 = class extends SHA2 { @@ -2466,35 +2466,84 @@ var nobleCurves = (() => { process(view, offset) { for (let i = 0; i < 16; i++, offset += 4) { SHA512_W_H[i] = view.getUint32(offset); - SHA512_W_L[i] = view.getUint32(offset += 4); + SHA512_W_L[i] = view.getUint32((offset += 4)); } for (let i = 16; i < 80; i++) { const W15h = SHA512_W_H[i - 15] | 0; const W15l = SHA512_W_L[i - 15] | 0; - const s0h = u64_default.rotrSH(W15h, W15l, 1) ^ u64_default.rotrSH(W15h, W15l, 8) ^ u64_default.shrSH(W15h, W15l, 7); - const s0l = u64_default.rotrSL(W15h, W15l, 1) ^ u64_default.rotrSL(W15h, W15l, 8) ^ u64_default.shrSL(W15h, W15l, 7); + const s0h = + u64_default.rotrSH(W15h, W15l, 1) ^ + u64_default.rotrSH(W15h, W15l, 8) ^ + u64_default.shrSH(W15h, W15l, 7); + const s0l = + u64_default.rotrSL(W15h, W15l, 1) ^ + u64_default.rotrSL(W15h, W15l, 8) ^ + u64_default.shrSL(W15h, W15l, 7); const W2h = SHA512_W_H[i - 2] | 0; const W2l = SHA512_W_L[i - 2] | 0; - const s1h = u64_default.rotrSH(W2h, W2l, 19) ^ u64_default.rotrBH(W2h, W2l, 61) ^ u64_default.shrSH(W2h, W2l, 6); - const s1l = u64_default.rotrSL(W2h, W2l, 19) ^ u64_default.rotrBL(W2h, W2l, 61) ^ u64_default.shrSL(W2h, W2l, 6); - const SUMl = u64_default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); - const SUMh = u64_default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + const s1h = + u64_default.rotrSH(W2h, W2l, 19) ^ + u64_default.rotrBH(W2h, W2l, 61) ^ + u64_default.shrSH(W2h, W2l, 6); + const s1l = + u64_default.rotrSL(W2h, W2l, 19) ^ + u64_default.rotrBL(W2h, W2l, 61) ^ + u64_default.shrSL(W2h, W2l, 6); + const SUMl = u64_default.add4L( + s0l, + s1l, + SHA512_W_L[i - 7], + SHA512_W_L[i - 16], + ); + const SUMh = u64_default.add4H( + SUMl, + s0h, + s1h, + SHA512_W_H[i - 7], + SHA512_W_H[i - 16], + ); SHA512_W_H[i] = SUMh | 0; SHA512_W_L[i] = SUMl | 0; } - let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = + this; for (let i = 0; i < 80; i++) { - const sigma1h = u64_default.rotrSH(Eh, El, 14) ^ u64_default.rotrSH(Eh, El, 18) ^ u64_default.rotrBH(Eh, El, 41); - const sigma1l = u64_default.rotrSL(Eh, El, 14) ^ u64_default.rotrSL(Eh, El, 18) ^ u64_default.rotrBL(Eh, El, 41); - const CHIh = Eh & Fh ^ ~Eh & Gh; - const CHIl = El & Fl ^ ~El & Gl; - const T1ll = u64_default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); - const T1h = u64_default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const sigma1h = + u64_default.rotrSH(Eh, El, 14) ^ + u64_default.rotrSH(Eh, El, 18) ^ + u64_default.rotrBH(Eh, El, 41); + const sigma1l = + u64_default.rotrSL(Eh, El, 14) ^ + u64_default.rotrSL(Eh, El, 18) ^ + u64_default.rotrBL(Eh, El, 41); + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + const T1ll = u64_default.add5L( + Hl, + sigma1l, + CHIl, + SHA512_Kl[i], + SHA512_W_L[i], + ); + const T1h = u64_default.add5H( + T1ll, + Hh, + sigma1h, + CHIh, + SHA512_Kh[i], + SHA512_W_H[i], + ); const T1l = T1ll | 0; - const sigma0h = u64_default.rotrSH(Ah, Al, 28) ^ u64_default.rotrBH(Ah, Al, 34) ^ u64_default.rotrBH(Ah, Al, 39); - const sigma0l = u64_default.rotrSL(Ah, Al, 28) ^ u64_default.rotrBL(Ah, Al, 34) ^ u64_default.rotrBL(Ah, Al, 39); - const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; - const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; + const sigma0h = + u64_default.rotrSH(Ah, Al, 28) ^ + u64_default.rotrBH(Ah, Al, 34) ^ + u64_default.rotrBH(Ah, Al, 39); + const sigma0l = + u64_default.rotrSL(Ah, Al, 28) ^ + u64_default.rotrBL(Ah, Al, 34) ^ + u64_default.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); Hh = Gh | 0; Hl = Gl | 0; Gh = Fh | 0; @@ -2512,14 +2561,54 @@ var nobleCurves = (() => { Ah = u64_default.add3H(All, T1h, sigma0h, MAJh); Al = All | 0; } - ({ h: Ah, l: Al } = u64_default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); - ({ h: Bh, l: Bl } = u64_default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); - ({ h: Ch, l: Cl } = u64_default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); - ({ h: Dh, l: Dl } = u64_default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); - ({ h: Eh, l: El } = u64_default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); - ({ h: Fh, l: Fl } = u64_default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); - ({ h: Gh, l: Gl } = u64_default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); - ({ h: Hh, l: Hl } = u64_default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + ({ h: Ah, l: Al } = u64_default.add( + this.Ah | 0, + this.Al | 0, + Ah | 0, + Al | 0, + )); + ({ h: Bh, l: Bl } = u64_default.add( + this.Bh | 0, + this.Bl | 0, + Bh | 0, + Bl | 0, + )); + ({ h: Ch, l: Cl } = u64_default.add( + this.Ch | 0, + this.Cl | 0, + Ch | 0, + Cl | 0, + )); + ({ h: Dh, l: Dl } = u64_default.add( + this.Dh | 0, + this.Dl | 0, + Dh | 0, + Dl | 0, + )); + ({ h: Eh, l: El } = u64_default.add( + this.Eh | 0, + this.El | 0, + Eh | 0, + El | 0, + )); + ({ h: Fh, l: Fl } = u64_default.add( + this.Fh | 0, + this.Fl | 0, + Fh | 0, + Fl | 0, + )); + ({ h: Gh, l: Gl } = u64_default.add( + this.Gh | 0, + this.Gl | 0, + Gh | 0, + Gl | 0, + )); + ({ h: Hh, l: Hl } = u64_default.add( + this.Hh | 0, + this.Hl | 0, + Hh | 0, + Hl | 0, + )); this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); } roundClean() { @@ -2564,43 +2653,58 @@ var nobleCurves = (() => { var VERIFY_DEFAULT = { zip215: true }; function validateOpts2(curve) { const opts = validateBasic(curve); - validateObject(curve, { - hash: "function", - a: "bigint", - d: "bigint", - randomBytes: "function" - }, { - adjustScalarBytes: "function", - domain: "function", - uvRatio: "function", - mapToCurve: "function" - }); + validateObject( + curve, + { + hash: "function", + a: "bigint", + d: "bigint", + randomBytes: "function", + }, + { + adjustScalarBytes: "function", + domain: "function", + uvRatio: "function", + mapToCurve: "function", + }, + ); return Object.freeze({ ...opts }); } function twistedEdwards(curveDef) { const CURVE2 = validateOpts2(curveDef); - const { Fp: Fp8, n: CURVE_ORDER, prehash, hash: cHash, randomBytes: randomBytes2, nByteLength, h: cofactor } = CURVE2; - const MASK = _2n5 << BigInt(nByteLength * 8) - _1n6; + const { + Fp: Fp8, + n: CURVE_ORDER, + prehash, + hash: cHash, + randomBytes: randomBytes2, + nByteLength, + h: cofactor, + } = CURVE2; + const MASK = _2n5 << (BigInt(nByteLength * 8) - _1n6); const modP2 = Fp8.create; - const uvRatio3 = CURVE2.uvRatio || ((u, v) => { - try { - return { isValid: true, value: Fp8.sqrt(u * Fp8.inv(v)) }; - } catch (e) { - return { isValid: false, value: _0n6 }; - } - }); + const uvRatio3 = + CURVE2.uvRatio || + ((u, v) => { + try { + return { isValid: true, value: Fp8.sqrt(u * Fp8.inv(v)) }; + } catch (e) { + return { isValid: false, value: _0n6 }; + } + }); const adjustScalarBytes3 = CURVE2.adjustScalarBytes || ((bytes2) => bytes2); - const domain = CURVE2.domain || ((data, ctx, phflag) => { - if (ctx.length || phflag) - throw new Error("Contexts/pre-hash are not supported"); - return data; - }); + const domain = + CURVE2.domain || + ((data, ctx, phflag) => { + if (ctx.length || phflag) + throw new Error("Contexts/pre-hash are not supported"); + return data; + }); const inBig = (n) => typeof n === "bigint" && _0n6 < n; const inRange = (n, max) => inBig(n) && inBig(max) && n < max; const in0MaskRange = (n) => n === _0n6 || inRange(n, MASK); function assertInRange(n, max) { - if (inRange(n, max)) - return n; + if (inRange(n, max)) return n; throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`); } function assertGE0(n) { @@ -2608,8 +2712,7 @@ var nobleCurves = (() => { } const pointPrecomputes = /* @__PURE__ */ new Map(); function isPoint(other) { - if (!(other instanceof Point2)) - throw new Error("ExtendedPoint expected"); + if (!(other instanceof Point2)) throw new Error("ExtendedPoint expected"); } class Point2 { constructor(ex, ey, ez, et) { @@ -2617,14 +2720,10 @@ var nobleCurves = (() => { this.ey = ey; this.ez = ez; this.et = et; - if (!in0MaskRange(ex)) - throw new Error("x required"); - if (!in0MaskRange(ey)) - throw new Error("y required"); - if (!in0MaskRange(ez)) - throw new Error("z required"); - if (!in0MaskRange(et)) - throw new Error("t required"); + if (!in0MaskRange(ex)) throw new Error("x required"); + if (!in0MaskRange(ey)) throw new Error("y required"); + if (!in0MaskRange(ez)) throw new Error("z required"); + if (!in0MaskRange(et)) throw new Error("t required"); } get x() { return this.toAffine().x; @@ -2633,8 +2732,7 @@ var nobleCurves = (() => { return this.toAffine().y; } static fromAffine(p) { - if (p instanceof Point2) - throw new Error("extended point not allowed"); + if (p instanceof Point2) throw new Error("extended point not allowed"); const { x, y } = p || {}; if (!in0MaskRange(x) || !in0MaskRange(y)) throw new Error("invalid affine point"); @@ -2642,7 +2740,9 @@ var nobleCurves = (() => { } static normalizeZ(points) { const toInv = Fp8.invertBatch(points.map((p) => p.ez)); - return points.map((p, i) => p.toAffine(toInv[i])).map(Point2.fromAffine); + return points + .map((p, i) => p.toAffine(toInv[i])) + .map(Point2.fromAffine); } // "Private method", don't use it directly _setWindowSize(windowSize) { @@ -2653,8 +2753,7 @@ var nobleCurves = (() => { // Could be useful for fromAffine(). assertValidity() { const { a, d } = CURVE2; - if (this.is0()) - throw new Error("bad point: ZERO"); + if (this.is0()) throw new Error("bad point: ZERO"); const { ex: X, ey: Y, ez: Z, et: T } = this; const X2 = modP2(X * X); const Y2 = modP2(Y * Y); @@ -2667,8 +2766,7 @@ var nobleCurves = (() => { throw new Error("bad point: equation left != right (1)"); const XY = modP2(X * Y); const ZT = modP2(Z * T); - if (XY !== ZT) - throw new Error("bad point: equation left != right (2)"); + if (XY !== ZT) throw new Error("bad point: equation left != right (2)"); } // Compare one point to another. equals(other) { @@ -2720,8 +2818,7 @@ var nobleCurves = (() => { const A2 = modP2((Y1 - X1) * (Y2 + X2)); const B2 = modP2((Y1 + X1) * (Y2 - X2)); const F2 = modP2(B2 - A2); - if (F2 === _0n6) - return this.double(); + if (F2 === _0n6) return this.double(); const C2 = modP2(Z1 * _2n5 * T2); const D2 = modP2(T1 * _2n5 * Z2); const E2 = D2 + C2; @@ -2764,12 +2861,9 @@ var nobleCurves = (() => { // Does NOT allow scalars higher than CURVE.n. multiplyUnsafe(scalar) { let n = assertGE0(scalar); - if (n === _0n6) - return I; - if (this.equals(I) || n === _1n6) - return this; - if (this.equals(G)) - return this.wNAF(n).p; + if (n === _0n6) return I; + if (this.equals(I) || n === _1n6) return this; + if (this.equals(G)) return this.wNAF(n).p; return wnaf.unsafeLadder(this, n); } // Checks if point is of small order. @@ -2789,21 +2883,17 @@ var nobleCurves = (() => { toAffine(iz) { const { ex: x, ey: y, ez: z } = this; const is0 = this.is0(); - if (iz == null) - iz = is0 ? _8n2 : Fp8.inv(z); + if (iz == null) iz = is0 ? _8n2 : Fp8.inv(z); const ax = modP2(x * iz); const ay = modP2(y * iz); const zz = modP2(z * iz); - if (is0) - return { x: _0n6, y: _1n6 }; - if (zz !== _1n6) - throw new Error("invZ was invalid"); + if (is0) return { x: _0n6, y: _1n6 }; + if (zz !== _1n6) throw new Error("invZ was invalid"); return { x: ax, y: ay }; } clearCofactor() { const { h: cofactor2 } = CURVE2; - if (cofactor2 === _1n6) - return this; + if (cofactor2 === _1n6) return this; return this.multiplyUnsafe(cofactor2); } // Converts hash string or Uint8Array to Point. @@ -2818,23 +2908,19 @@ var nobleCurves = (() => { const y = bytesToNumberLE(normed); if (y === _0n6) { } else { - if (zip215) - assertInRange(y, MASK); - else - assertInRange(y, Fp8.ORDER); + if (zip215) assertInRange(y, MASK); + else assertInRange(y, Fp8.ORDER); } const y2 = modP2(y * y); const u = modP2(y2 - _1n6); const v = modP2(d * y2 - a); let { isValid, value: x } = uvRatio3(u, v); - if (!isValid) - throw new Error("Point.fromHex: invalid y coordinate"); + if (!isValid) throw new Error("Point.fromHex: invalid y coordinate"); const isXOdd = (x & _1n6) === _1n6; const isLastByteOdd = (lastByte & 128) !== 0; if (!zip215 && x === _0n6 && isLastByteOdd) throw new Error("Point.fromHex: x=0 and x_0=1"); - if (isLastByteOdd !== isXOdd) - x = modP2(-x); + if (isLastByteOdd !== isXOdd) x = modP2(-x); return Point2.fromAffine({ x, y }); } static fromPrivateKey(privKey) { @@ -2850,7 +2936,12 @@ var nobleCurves = (() => { return bytesToHex(this.toRawBytes()); } } - Point2.BASE = new Point2(CURVE2.Gx, CURVE2.Gy, _1n6, modP2(CURVE2.Gx * CURVE2.Gy)); + Point2.BASE = new Point2( + CURVE2.Gx, + CURVE2.Gy, + _1n6, + modP2(CURVE2.Gx * CURVE2.Gy), + ); Point2.ZERO = new Point2(_0n6, _1n6, _1n6, _0n6); const { BASE: G, ZERO: I } = Point2; const wnaf = wNAF(Point2, nByteLength * 8); @@ -2876,12 +2967,13 @@ var nobleCurves = (() => { } function hashDomainToScalar(context = new Uint8Array(), ...msgs) { const msg = concatBytes(...msgs); - return modN_LE(cHash(domain(msg, ensureBytes("context", context), !!prehash))); + return modN_LE( + cHash(domain(msg, ensureBytes("context", context), !!prehash)), + ); } function sign(msg, privKey, options = {}) { msg = ensureBytes("message", msg); - if (prehash) - msg = prehash(msg); + if (prehash) msg = prehash(msg); const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey); const r = hashDomainToScalar(options.context, prefix, msg); const R = G.multiply(r).toRawBytes(); @@ -2897,8 +2989,7 @@ var nobleCurves = (() => { const len = Fp8.BYTES; sig = ensureBytes("signature", sig, 2 * len); msg = ensureBytes("message", msg); - if (prehash) - msg = prehash(msg); + if (prehash) msg = prehash(msg); const s = bytesToNumberLE(sig.slice(len, 2 * len)); let A, R, SB; try { @@ -2908,9 +2999,13 @@ var nobleCurves = (() => { } catch (error) { return false; } - if (!zip215 && A.isSmallOrder()) - return false; - const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg); + if (!zip215 && A.isSmallOrder()) return false; + const k = hashDomainToScalar( + context, + R.toRawBytes(), + A.toRawBytes(), + msg, + ); const RkA = R.add(A.multiplyUnsafe(k)); return RkA.subtract(SB).clearCofactor().equals(Point2.ZERO); } @@ -2929,7 +3024,7 @@ var nobleCurves = (() => { point._setWindowSize(windowSize); point.multiply(BigInt(3)); return point; - } + }, }; return { CURVE: CURVE2, @@ -2937,7 +3032,7 @@ var nobleCurves = (() => { sign, verify, ExtendedPoint: Point2, - utils: utils2 + utils: utils2, }; } @@ -2945,16 +3040,20 @@ var nobleCurves = (() => { var _0n7 = BigInt(0); var _1n7 = BigInt(1); function validateOpts3(curve) { - validateObject(curve, { - a: "bigint" - }, { - montgomeryBits: "isSafeInteger", - nByteLength: "isSafeInteger", - adjustScalarBytes: "function", - domain: "function", - powPminus2: "function", - Gu: "bigint" - }); + validateObject( + curve, + { + a: "bigint", + }, + { + montgomeryBits: "isSafeInteger", + nByteLength: "isSafeInteger", + adjustScalarBytes: "function", + domain: "function", + powPminus2: "function", + Gu: "bigint", + }, + ); return Object.freeze({ ...curve }); } function montgomery(curveDef) { @@ -2973,8 +3072,7 @@ var nobleCurves = (() => { return [x_2, x_3]; } function assertFieldElement(n) { - if (typeof n === "bigint" && _0n7 <= n && n < P3) - return n; + if (typeof n === "bigint" && _0n7 <= n && n < P3) return n; throw new Error("Expected valid scalar 0 < scalar < CURVE.P"); } const a24 = (CURVE2.a - BigInt(2)) / BigInt(4); @@ -2989,7 +3087,7 @@ var nobleCurves = (() => { let swap = _0n7; let sw; for (let t = BigInt(montgomeryBits - 1); t >= _0n7; t--) { - const k_t = k >> t & _1n7; + const k_t = (k >> t) & _1n7; swap ^= k_t; sw = cswap(swap, x_2, x_3); x_2 = sw[0]; @@ -3028,14 +3126,15 @@ var nobleCurves = (() => { } function decodeUCoordinate(uEnc) { const u = ensureBytes("u coordinate", uEnc, montgomeryBytes); - if (fieldLen === montgomeryBytes) - u[fieldLen - 1] &= 127; + if (fieldLen === montgomeryBytes) u[fieldLen - 1] &= 127; return bytesToNumberLE(u); } function decodeScalar(n) { const bytes2 = ensureBytes("scalar", n); if (bytes2.length !== montgomeryBytes && bytes2.length !== fieldLen) - throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes2.length}`); + throw new Error( + `Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes2.length}`, + ); return bytesToNumberLE(adjustScalarBytes3(bytes2)); } function scalarMult(scalar, u) { @@ -3053,16 +3152,21 @@ var nobleCurves = (() => { return { scalarMult, scalarMultBase, - getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey), + getSharedSecret: (privateKey, publicKey) => + scalarMult(privateKey, publicKey), getPublicKey: (privateKey) => scalarMultBase(privateKey), utils: { randomPrivateKey: () => CURVE2.randomBytes(CURVE2.nByteLength) }, - GuBytes + GuBytes, }; } // ../esm/ed25519.js - var ED25519_P = BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"); - var ED25519_SQRT_M1 = BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"); + var ED25519_P = BigInt( + "57896044618658097711785492504343953926634992332820282019728792003956564819949", + ); + var ED25519_SQRT_M1 = BigInt( + "19681161376707505956807079304988542015446066515923890162744021073123829784752", + ); var _0n8 = BigInt(0); var _1n8 = BigInt(1); var _2n6 = BigInt(2); @@ -3073,18 +3177,18 @@ var nobleCurves = (() => { var _80n = BigInt(80); function ed25519_pow_2_252_3(x) { const P3 = ED25519_P; - const x2 = x * x % P3; - const b2 = x2 * x % P3; - const b4 = pow2(b2, _2n6, P3) * b2 % P3; - const b5 = pow2(b4, _1n8, P3) * x % P3; - const b10 = pow2(b5, _5n2, P3) * b5 % P3; - const b20 = pow2(b10, _10n, P3) * b10 % P3; - const b40 = pow2(b20, _20n, P3) * b20 % P3; - const b80 = pow2(b40, _40n, P3) * b40 % P3; - const b160 = pow2(b80, _80n, P3) * b80 % P3; - const b240 = pow2(b160, _80n, P3) * b80 % P3; - const b250 = pow2(b240, _10n, P3) * b10 % P3; - const pow_p_5_8 = pow2(b250, _2n6, P3) * x % P3; + const x2 = (x * x) % P3; + const b2 = (x2 * x) % P3; + const b4 = (pow2(b2, _2n6, P3) * b2) % P3; + const b5 = (pow2(b4, _1n8, P3) * x) % P3; + const b10 = (pow2(b5, _5n2, P3) * b5) % P3; + const b20 = (pow2(b10, _10n, P3) * b10) % P3; + const b40 = (pow2(b20, _20n, P3) * b20) % P3; + const b80 = (pow2(b40, _40n, P3) * b40) % P3; + const b160 = (pow2(b80, _80n, P3) * b80) % P3; + const b240 = (pow2(b160, _80n, P3) * b80) % P3; + const b250 = (pow2(b240, _10n, P3) * b10) % P3; + const pow_p_5_8 = (pow2(b250, _2n6, P3) * x) % P3; return { pow_p_5_8, b2 }; } function adjustScalarBytes(bytes2) { @@ -3105,12 +3209,9 @@ var nobleCurves = (() => { const useRoot1 = vx2 === u; const useRoot2 = vx2 === mod(-u, P3); const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P3); - if (useRoot1) - x = root1; - if (useRoot2 || noRoot) - x = root2; - if (isNegativeLE(x, P3)) - x = mod(-x, P3); + if (useRoot1) x = root1; + if (useRoot2 || noRoot) x = root2; + if (isNegativeLE(x, P3)) x = mod(-x, P3); return { isValid: useRoot1 || useRoot2, value: x }; } var Fp2 = Field(ED25519_P, void 0, true); @@ -3119,54 +3220,67 @@ var nobleCurves = (() => { a: BigInt(-1), // d is equal to -121665/121666 over finite field. // Negative number is P - number, and division is invert(number, P) - d: BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"), + d: BigInt( + "37095705934669439343138083508754565189542113879843219016388785533085940283555", + ), // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n Fp: Fp2, // Subgroup order: how many points curve has // 2n**252n + 27742317777372353535851937790883648493n; - n: BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"), + n: BigInt( + "7237005577332262213973186563042994240857116359379907606001950938285454250989", + ), // Cofactor h: BigInt(8), // Base point (x, y) aka generator point - Gx: BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"), - Gy: BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"), + Gx: BigInt( + "15112221349535400772501151409588531511454012693041857206046113283949847762202", + ), + Gy: BigInt( + "46316835694926478169428394003475163141307993866256225615783033603165251855960", + ), hash: sha512, randomBytes, adjustScalarBytes, // dom2 // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3. // Constant-time, u/√v - uvRatio + uvRatio, }; var ed25519 = /* @__PURE__ */ twistedEdwards(ed25519Defaults); function ed25519_domain(data, ctx, phflag) { - if (ctx.length > 255) - throw new Error("Context is too big"); - return concatBytes2(utf8ToBytes2("SigEd25519 no Ed25519 collisions"), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + if (ctx.length > 255) throw new Error("Context is too big"); + return concatBytes2( + utf8ToBytes2("SigEd25519 no Ed25519 collisions"), + new Uint8Array([phflag ? 1 : 0, ctx.length]), + ctx, + data, + ); } var ed25519ctx = /* @__PURE__ */ twistedEdwards({ ...ed25519Defaults, - domain: ed25519_domain + domain: ed25519_domain, }); var ed25519ph = /* @__PURE__ */ twistedEdwards({ ...ed25519Defaults, domain: ed25519_domain, - prehash: sha512 + prehash: sha512, }); - var x25519 = /* @__PURE__ */ (() => montgomery({ - P: ED25519_P, - a: BigInt(486662), - montgomeryBits: 255, - nByteLength: 32, - Gu: BigInt(9), - powPminus2: (x) => { - const P3 = ED25519_P; - const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); - return mod(pow2(pow_p_5_8, BigInt(3), P3) * b2, P3); - }, - adjustScalarBytes, - randomBytes - }))(); + var x25519 = /* @__PURE__ */ (() => + montgomery({ + P: ED25519_P, + a: BigInt(486662), + montgomeryBits: 255, + nByteLength: 32, + Gu: BigInt(9), + powPminus2: (x) => { + const P3 = ED25519_P; + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return mod(pow2(pow_p_5_8, BigInt(3), P3) * b2, P3); + }, + adjustScalarBytes, + randomBytes, + }))(); function edwardsToMontgomeryPub(edwardsPub) { const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub); const _1n12 = BigInt(1); @@ -3182,11 +3296,21 @@ var nobleCurves = (() => { var ELL2_C4 = (Fp2.ORDER - BigInt(5)) / BigInt(8); var ELL2_J = BigInt(486662); var ELL2_C1_EDWARDS = FpSqrtEven(Fp2, Fp2.neg(BigInt(486664))); - var SQRT_AD_MINUS_ONE = BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"); - var INVSQRT_A_MINUS_D = BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"); - var ONE_MINUS_D_SQ = BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"); - var D_MINUS_ONE_SQ = BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"); - var MAX_255B = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + var SQRT_AD_MINUS_ONE = BigInt( + "25063068953384623474111414158702152701244531502492656460079210482610430750235", + ); + var INVSQRT_A_MINUS_D = BigInt( + "54469307008909316920995813868745141605393597292927456921205312896311721017578", + ); + var ONE_MINUS_D_SQ = BigInt( + "1159843021668779879193775521855586647937357759715417654439879720876111806838", + ); + var D_MINUS_ONE_SQ = BigInt( + "40440834346308536858101042469323190826248399146238708352240133220865137265952", + ); + var MAX_255B = BigInt( + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + ); // ../node_modules/@noble/hashes/esm/sha3.js var [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; @@ -3199,18 +3323,17 @@ var nobleCurves = (() => { for (let round = 0, R = _1n9, x = 1, y = 0; round < 24; round++) { [x, y] = [y, (2 * x + 3 * y) % 5]; SHA3_PI.push(2 * (5 * y + x)); - SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); let t = _0n9; for (let j = 0; j < 7; j++) { - R = (R << _1n9 ^ (R >> _7n) * _0x71n) % _256n; - if (R & _2n7) - t ^= _1n9 << (_1n9 << /* @__PURE__ */ BigInt(j)) - _1n9; + R = ((R << _1n9) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n7) t ^= _1n9 << ((_1n9 << /* @__PURE__ */ BigInt(j)) - _1n9); } _SHA3_IOTA.push(t); } var [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); - var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s); - var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s); + var rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); + var rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); function keccakP(s, rounds = 24) { const B = new Uint32Array(5 * 2); for (let round = 24 - rounds; round < 24; round++) { @@ -3241,8 +3364,7 @@ var nobleCurves = (() => { s[PI + 1] = Tl; } for (let y = 0; y < 50; y += 10) { - for (let x = 0; x < 10; x++) - B[x] = s[y + x]; + for (let x = 0; x < 10; x++) B[x] = s[y + x]; for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; } @@ -3282,21 +3404,17 @@ var nobleCurves = (() => { const len = data.length; for (let pos = 0; pos < len; ) { const take = Math.min(blockLen - this.pos, len - pos); - for (let i = 0; i < take; i++) - state[this.pos++] ^= data[pos++]; - if (this.pos === blockLen) - this.keccak(); + for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) this.keccak(); } return this; } finish() { - if (this.finished) - return; + if (this.finished) return; this.finished = true; const { state, suffix, pos, blockLen } = this; state[pos] ^= suffix; - if ((suffix & 128) !== 0 && pos === blockLen - 1) - this.keccak(); + if ((suffix & 128) !== 0 && pos === blockLen - 1) this.keccak(); state[blockLen - 1] ^= 128; this.keccak(); } @@ -3307,8 +3425,7 @@ var nobleCurves = (() => { const bufferOut = this.state; const { blockLen } = this; for (let pos = 0, len = out.length; pos < len; ) { - if (this.posOut >= blockLen) - this.keccak(); + if (this.posOut >= blockLen) this.keccak(); const take = Math.min(blockLen - this.posOut, len - pos); out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); this.posOut += take; @@ -3327,8 +3444,7 @@ var nobleCurves = (() => { } digestInto(out) { output(out, this); - if (this.finished) - throw new Error("digest() was already called"); + if (this.finished) throw new Error("digest() was already called"); this.writeInto(out); this.destroy(); return out; @@ -3355,7 +3471,8 @@ var nobleCurves = (() => { return to; } }; - var gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); + var gen = (suffix, blockLen, outputLen) => + wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); var sha3_224 = /* @__PURE__ */ gen(6, 144, 224 / 8); var sha3_256 = /* @__PURE__ */ gen(6, 136, 256 / 8); var sha3_384 = /* @__PURE__ */ gen(6, 104, 384 / 8); @@ -3364,14 +3481,25 @@ var nobleCurves = (() => { var keccak_256 = /* @__PURE__ */ gen(1, 136, 256 / 8); var keccak_384 = /* @__PURE__ */ gen(1, 104, 384 / 8); var keccak_512 = /* @__PURE__ */ gen(1, 72, 512 / 8); - var genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true)); + var genShake = (suffix, blockLen, outputLen) => + wrapXOFConstructorWithOpts( + (opts = {}) => + new Keccak( + blockLen, + suffix, + opts.dkLen === void 0 ? outputLen : opts.dkLen, + true, + ), + ); var shake128 = /* @__PURE__ */ genShake(31, 168, 128 / 8); var shake256 = /* @__PURE__ */ genShake(31, 136, 256 / 8); // ../esm/ed448.js var shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 })); var shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 })); - var ed448P = BigInt("726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439"); + var ed448P = BigInt( + "726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439", + ); var _1n10 = BigInt(1); var _2n8 = BigInt(2); var _3n3 = BigInt(3); @@ -3383,19 +3511,19 @@ var nobleCurves = (() => { var _223n = BigInt(223); function ed448_pow_Pminus3div4(x) { const P3 = ed448P; - const b2 = x * x * x % P3; - const b3 = b2 * b2 * x % P3; - const b6 = pow2(b3, _3n3, P3) * b3 % P3; - const b9 = pow2(b6, _3n3, P3) * b3 % P3; - const b11 = pow2(b9, _2n8, P3) * b2 % P3; - const b22 = pow2(b11, _11n, P3) * b11 % P3; - const b44 = pow2(b22, _22n, P3) * b22 % P3; - const b88 = pow2(b44, _44n, P3) * b44 % P3; - const b176 = pow2(b88, _88n, P3) * b88 % P3; - const b220 = pow2(b176, _44n, P3) * b44 % P3; - const b222 = pow2(b220, _2n8, P3) * b2 % P3; - const b223 = pow2(b222, _1n10, P3) * x % P3; - return pow2(b223, _223n, P3) * b222 % P3; + const b2 = (x * x * x) % P3; + const b3 = (b2 * b2 * x) % P3; + const b6 = (pow2(b3, _3n3, P3) * b3) % P3; + const b9 = (pow2(b6, _3n3, P3) * b3) % P3; + const b11 = (pow2(b9, _2n8, P3) * b2) % P3; + const b22 = (pow2(b11, _11n, P3) * b11) % P3; + const b44 = (pow2(b22, _22n, P3) * b22) % P3; + const b88 = (pow2(b44, _44n, P3) * b44) % P3; + const b176 = (pow2(b88, _88n, P3) * b88) % P3; + const b220 = (pow2(b176, _44n, P3) * b44) % P3; + const b222 = (pow2(b220, _2n8, P3) * b2) % P3; + const b223 = (pow2(b222, _1n10, P3) * x) % P3; + return (pow2(b223, _223n, P3) * b222) % P3; } function adjustScalarBytes2(bytes2) { bytes2[0] &= 252; @@ -3418,18 +3546,26 @@ var nobleCurves = (() => { // Param: a a: BigInt(1), // -39081. Negative number is P - number - d: BigInt("726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358"), + d: BigInt( + "726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018326358", + ), // Finite field 𝔽p over which we'll do calculations; 2n**448n - 2n**224n - 1n Fp: Fp3, // Subgroup order: how many points curve has; // 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n - n: BigInt("181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779"), + n: BigInt( + "181709681073901722637330951972001133588410340171829515070372549795146003961539585716195755291692375963310293709091662304773755859649779", + ), nBitLength: 456, // Cofactor h: BigInt(4), // Base point (x, y) aka generator point - Gx: BigInt("224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710"), - Gy: BigInt("298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660"), + Gx: BigInt( + "224580040295924300187604334099896036246789641632564134246125461686950415467406032909029192869357953282578032075146446173674602635247710", + ), + Gy: BigInt( + "298819210078481492676017930443930673437544040154080242095928241372331506189835876003536878655418784733982303233503462500531545062832660", + ), // SHAKE256(dom4(phflag,context)||x, 114) hash: shake256_114, randomBytes, @@ -3438,27 +3574,36 @@ var nobleCurves = (() => { domain: (data, ctx, phflag) => { if (ctx.length > 255) throw new Error(`Context is too big: ${ctx.length}`); - return concatBytes2(utf8ToBytes2("SigEd448"), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); + return concatBytes2( + utf8ToBytes2("SigEd448"), + new Uint8Array([phflag ? 1 : 0, ctx.length]), + ctx, + data, + ); }, - uvRatio: uvRatio2 + uvRatio: uvRatio2, }; var ed448 = /* @__PURE__ */ twistedEdwards(ED448_DEF); - var ed448ph = /* @__PURE__ */ twistedEdwards({ ...ED448_DEF, prehash: shake256_64 }); - var x448 = /* @__PURE__ */ (() => montgomery({ - a: BigInt(156326), - montgomeryBits: 448, - nByteLength: 57, - P: ed448P, - Gu: BigInt(5), - powPminus2: (x) => { - const P3 = ed448P; - const Pminus3div4 = ed448_pow_Pminus3div4(x); - const Pminus3 = pow2(Pminus3div4, BigInt(2), P3); - return mod(Pminus3 * x, P3); - }, - adjustScalarBytes: adjustScalarBytes2, - randomBytes - }))(); + var ed448ph = /* @__PURE__ */ twistedEdwards({ + ...ED448_DEF, + prehash: shake256_64, + }); + var x448 = /* @__PURE__ */ (() => + montgomery({ + a: BigInt(156326), + montgomeryBits: 448, + nByteLength: 57, + P: ed448P, + Gu: BigInt(5), + powPminus2: (x) => { + const P3 = ed448P; + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, BigInt(2), P3); + return mod(Pminus3 * x, P3); + }, + adjustScalarBytes: adjustScalarBytes2, + randomBytes, + }))(); function edwardsToMontgomeryPub2(edwardsPub) { const { y } = ed448.ExtendedPoint.fromHex(edwardsPub); const _1n12 = BigInt(1); @@ -3468,81 +3613,138 @@ var nobleCurves = (() => { var ELL2_J2 = BigInt(156326); var ONE_MINUS_D = BigInt("39082"); var ONE_MINUS_TWO_D = BigInt("78163"); - var SQRT_MINUS_D = BigInt("98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214"); - var INVSQRT_MINUS_D = BigInt("315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716"); - var MAX_448B = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + var SQRT_MINUS_D = BigInt( + "98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214", + ); + var INVSQRT_MINUS_D = BigInt( + "315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716", + ); + var MAX_448B = BigInt( + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + ); // ../esm/p256.js - var Fp4 = Field(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")); + var Fp4 = Field( + BigInt( + "0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff", + ), + ); var CURVE_A = Fp4.create(BigInt("-3")); - var CURVE_B = BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"); - var p256 = createCurve({ - a: CURVE_A, - b: CURVE_B, - Fp: Fp4, - // Curve order, total count of valid points in the field - n: BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"), - // Base (generator) point (x, y) - Gx: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"), - Gy: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"), - h: BigInt(1), - lowS: false - }, sha256); + var CURVE_B = BigInt( + "0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", + ); + var p256 = createCurve( + { + a: CURVE_A, + b: CURVE_B, + Fp: Fp4, + // Curve order, total count of valid points in the field + n: BigInt( + "0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", + ), + // Base (generator) point (x, y) + Gx: BigInt( + "0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", + ), + Gy: BigInt( + "0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", + ), + h: BigInt(1), + lowS: false, + }, + sha256, + ); // ../esm/p384.js - var P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"); + var P = BigInt( + "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff", + ); var Fp5 = Field(P); var CURVE_A2 = Fp5.create(BigInt("-3")); - var CURVE_B2 = BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"); - var p384 = createCurve({ - a: CURVE_A2, - b: CURVE_B2, - Fp: Fp5, - // Curve order, total count of valid points in the field. - n: BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"), - // Base (generator) point (x, y) - Gx: BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"), - Gy: BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"), - h: BigInt(1), - lowS: false - }, sha384); + var CURVE_B2 = BigInt( + "0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef", + ); + var p384 = createCurve( + { + a: CURVE_A2, + b: CURVE_B2, + Fp: Fp5, + // Curve order, total count of valid points in the field. + n: BigInt( + "0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973", + ), + // Base (generator) point (x, y) + Gx: BigInt( + "0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7", + ), + Gy: BigInt( + "0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f", + ), + h: BigInt(1), + lowS: false, + }, + sha384, + ); // ../esm/p521.js - var P2 = BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + var P2 = BigInt( + "0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + ); var Fp6 = Field(P2); var CURVE = { a: Fp6.create(BigInt("-3")), - b: BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"), + b: BigInt( + "0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00", + ), Fp: Fp6, - n: BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"), - Gx: BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"), - Gy: BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"), - h: BigInt(1) + n: BigInt( + "0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409", + ), + Gx: BigInt( + "0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66", + ), + Gy: BigInt( + "0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650", + ), + h: BigInt(1), }; - var p521 = createCurve({ - a: CURVE.a, - b: CURVE.b, - Fp: Fp6, - // Curve order, total count of valid points in the field - n: CURVE.n, - Gx: CURVE.Gx, - Gy: CURVE.Gy, - h: CURVE.h, - lowS: false, - allowedPrivateKeyLengths: [130, 131, 132] - // P521 keys are variable-length. Normalize to 132b - }, sha512); + var p521 = createCurve( + { + a: CURVE.a, + b: CURVE.b, + Fp: Fp6, + // Curve order, total count of valid points in the field + n: CURVE.n, + Gx: CURVE.Gx, + Gy: CURVE.Gy, + h: CURVE.h, + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132], + // P521 keys are variable-length. Normalize to 132b + }, + sha512, + ); // ../esm/abstract/bls.js var _2n9 = BigInt(2); var _3n4 = BigInt(3); function bls(CURVE2) { - const { Fp: Fp8, Fr: Fr2, Fp2: Fp23, Fp6: Fp63, Fp12: Fp122 } = CURVE2.fields; + const { + Fp: Fp8, + Fr: Fr2, + Fp2: Fp23, + Fp6: Fp63, + Fp12: Fp122, + } = CURVE2.fields; const BLS_X_LEN2 = bitLen(CURVE2.params.x); function calcPairingPrecomputes(p) { const { x, y } = p; - const Qx = x, Qy = y, Qz = Fp23.ONE; - let Rx = Qx, Ry = Qy, Rz = Qz; + const Qx = x, + Qy = y, + Qz = Fp23.ONE; + let Rx = Qx, + Ry = Qy, + Rz = Qz; let ell_coeff = []; for (let i = BLS_X_LEN2 - 2; i >= 0; i--) { let t0 = Fp23.sqr(Ry); @@ -3553,11 +3755,14 @@ var nobleCurves = (() => { ell_coeff.push([ Fp23.sub(t2, t0), Fp23.mul(Fp23.sqr(Rx), _3n4), - Fp23.neg(t4) + Fp23.neg(t4), // -T4 ]); Rx = Fp23.div(Fp23.mul(Fp23.mul(Fp23.sub(t0, t3), Rx), Ry), _2n9); - Ry = Fp23.sub(Fp23.sqr(Fp23.div(Fp23.add(t0, t3), _2n9)), Fp23.mul(Fp23.sqr(t2), _3n4)); + Ry = Fp23.sub( + Fp23.sqr(Fp23.div(Fp23.add(t0, t3), _2n9)), + Fp23.mul(Fp23.sqr(t2), _3n4), + ); Rz = Fp23.mul(t0, t4); if (bitGet(CURVE2.params.x, i)) { let t02 = Fp23.sub(Ry, Fp23.mul(Qy, Rz)); @@ -3565,13 +3770,16 @@ var nobleCurves = (() => { ell_coeff.push([ Fp23.sub(Fp23.mul(t02, Qx), Fp23.mul(t12, Qy)), Fp23.neg(t02), - t12 + t12, // T1 ]); let t22 = Fp23.sqr(t12); let t32 = Fp23.mul(t22, t12); let t42 = Fp23.mul(t22, Rx); - let t5 = Fp23.add(Fp23.sub(t32, Fp23.mul(t42, _2n9)), Fp23.mul(Fp23.sqr(t02), Rz)); + let t5 = Fp23.add( + Fp23.sub(t32, Fp23.mul(t42, _2n9)), + Fp23.mul(Fp23.sqr(t02), Rz), + ); Rx = Fp23.mul(t12, t5); Ry = Fp23.sub(Fp23.mul(Fp23.sub(t42, t5), t02), Fp23.mul(t32, Ry)); Rz = Fp23.mul(Rz, t32); @@ -3586,14 +3794,23 @@ var nobleCurves = (() => { let f12 = Fp122.ONE; for (let j = 0, i = BLS_X_LEN2 - 2; i >= 0; i--, j++) { const E = ell[j]; - f12 = Fp122.multiplyBy014(f12, E[0], Fp23.mul(E[1], Px), Fp23.mul(E[2], Py)); + f12 = Fp122.multiplyBy014( + f12, + E[0], + Fp23.mul(E[1], Px), + Fp23.mul(E[2], Py), + ); if (bitGet(x, i)) { j += 1; const F = ell[j]; - f12 = Fp122.multiplyBy014(f12, F[0], Fp23.mul(F[1], Px), Fp23.mul(F[2], Py)); + f12 = Fp122.multiplyBy014( + f12, + F[0], + Fp23.mul(F[1], Px), + Fp23.mul(F[2], Py), + ); } - if (i !== 0) - f12 = Fp122.sqr(f12); + if (i !== 0) f12 = Fp122.sqr(f12); } return Fp122.conjugate(f12); } @@ -3602,28 +3819,36 @@ var nobleCurves = (() => { const length = getMinHashLength(Fr2.ORDER); return mapHashToField(CURVE2.randomBytes(length), Fr2.ORDER); }, - calcPairingPrecomputes + calcPairingPrecomputes, }; const G1_ = weierstrassPoints({ n: Fr2.ORDER, ...CURVE2.G1 }); - const G1 = Object.assign(G1_, createHasher(G1_.ProjectivePoint, CURVE2.G1.mapToCurve, { - ...CURVE2.htfDefaults, - ...CURVE2.G1.htfDefaults - })); + const G1 = Object.assign( + G1_, + createHasher(G1_.ProjectivePoint, CURVE2.G1.mapToCurve, { + ...CURVE2.htfDefaults, + ...CURVE2.G1.htfDefaults, + }), + ); function pairingPrecomputes(point) { const p = point; - if (p._PPRECOMPUTES) - return p._PPRECOMPUTES; + if (p._PPRECOMPUTES) return p._PPRECOMPUTES; p._PPRECOMPUTES = calcPairingPrecomputes(point.toAffine()); return p._PPRECOMPUTES; } const G2_ = weierstrassPoints({ n: Fr2.ORDER, ...CURVE2.G2 }); - const G2 = Object.assign(G2_, createHasher(G2_.ProjectivePoint, CURVE2.G2.mapToCurve, { - ...CURVE2.htfDefaults, - ...CURVE2.G2.htfDefaults - })); + const G2 = Object.assign( + G2_, + createHasher(G2_.ProjectivePoint, CURVE2.G2.mapToCurve, { + ...CURVE2.htfDefaults, + ...CURVE2.G2.htfDefaults, + }), + ); const { Signature } = CURVE2.G2; function pairing(Q, P3, withFinalExponent = true) { - if (Q.equals(G1.ProjectivePoint.ZERO) || P3.equals(G2.ProjectivePoint.ZERO)) + if ( + Q.equals(G1.ProjectivePoint.ZERO) || + P3.equals(G2.ProjectivePoint.ZERO) + ) throw new Error("pairing is not available for ZERO point"); Q.assertValidity(); P3.assertValidity(); @@ -3632,13 +3857,19 @@ var nobleCurves = (() => { return withFinalExponent ? Fp122.finalExponentiate(looped) : looped; } function normP1(point) { - return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point); + return point instanceof G1.ProjectivePoint + ? point + : G1.ProjectivePoint.fromHex(point); } function normP2(point) { - return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point); + return point instanceof G2.ProjectivePoint + ? point + : Signature.fromHex(point); } function normP2Hash(point, htfOpts) { - return point instanceof G2.ProjectivePoint ? point : G2.hashToCurve(ensureBytes("point", point), htfOpts); + return point instanceof G2.ProjectivePoint + ? point + : G2.hashToCurve(ensureBytes("point", point), htfOpts); } function getPublicKey(privateKey) { return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true); @@ -3647,8 +3878,7 @@ var nobleCurves = (() => { const msgPoint = normP2Hash(message, htfOpts); msgPoint.assertValidity(); const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey)); - if (message instanceof G2.ProjectivePoint) - return sigPoint; + if (message instanceof G2.ProjectivePoint) return sigPoint; return Signature.toRawBytes(sigPoint); } function verify(signature, message, publicKey, htfOpts) { @@ -3662,9 +3892,10 @@ var nobleCurves = (() => { return Fp122.eql(exp, Fp122.ONE); } function aggregatePublicKeys(publicKeys) { - if (!publicKeys.length) - throw new Error("Expected non-empty array"); - const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); + if (!publicKeys.length) throw new Error("Expected non-empty array"); + const agg = publicKeys + .map(normP1) + .reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO); const aggAffine = agg; if (publicKeys[0] instanceof G1.ProjectivePoint) { aggAffine.assertValidity(); @@ -3673,9 +3904,10 @@ var nobleCurves = (() => { return aggAffine.toRawBytes(true); } function aggregateSignatures(signatures) { - if (!signatures.length) - throw new Error("Expected non-empty array"); - const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); + if (!signatures.length) throw new Error("Expected non-empty array"); + const agg = signatures + .map(normP2) + .reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO); const aggAffine = agg; if (signatures[0] instanceof G2.ProjectivePoint) { aggAffine.assertValidity(); @@ -3694,7 +3926,13 @@ var nobleCurves = (() => { try { const paired = []; for (const message of new Set(nMessages)) { - const groupPublicKey = nMessages.reduce((groupPublicKey2, subMessage, i) => subMessage === message ? groupPublicKey2.add(nPublicKeys[i]) : groupPublicKey2, G1.ProjectivePoint.ZERO); + const groupPublicKey = nMessages.reduce( + (groupPublicKey2, subMessage, i) => + subMessage === message + ? groupPublicKey2.add(nPublicKeys[i]) + : groupPublicKey2, + G1.ProjectivePoint.ZERO, + ); paired.push(pairing(groupPublicKey, message, false)); } paired.push(pairing(G1.ProjectivePoint.BASE.negate(), sig, false)); @@ -3723,15 +3961,15 @@ var nobleCurves = (() => { Fp: Fp8, Fp2: Fp23, Fp6: Fp63, - Fp12: Fp122 + Fp12: Fp122, }, params: { x: CURVE2.params.x, r: CURVE2.params.r, G1b: CURVE2.G1.b, - G2b: CURVE2.G2.b + G2b: CURVE2.G2.b, }, - utils: utils2 + utils: utils2, }; } @@ -3743,16 +3981,22 @@ var nobleCurves = (() => { var _4n4 = BigInt(4); var _8n3 = BigInt(8); var _16n2 = BigInt(16); - var Fp_raw = BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"); + var Fp_raw = BigInt( + "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", + ); var Fp7 = Field(Fp_raw); - var Fr = Field(BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001")); + var Fr = Field( + BigInt( + "0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001", + ), + ); var Fp2Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ c0: Fp7.add(c0, r0), - c1: Fp7.add(c1, r1) + c1: Fp7.add(c1, r1), }); var Fp2Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ c0: Fp7.sub(c0, r0), - c1: Fp7.sub(c1, r1) + c1: Fp7.sub(c1, r1), }); var Fp2Multiply = ({ c0, c1 }, rhs) => { if (typeof rhs === "bigint") @@ -3761,7 +4005,10 @@ var nobleCurves = (() => { let t1 = Fp7.mul(c0, r0); let t2 = Fp7.mul(c1, r1); const o0 = Fp7.sub(t1, t2); - const o1 = Fp7.sub(Fp7.mul(Fp7.add(c0, c1), Fp7.add(r0, r1)), Fp7.add(t1, t2)); + const o1 = Fp7.sub( + Fp7.mul(Fp7.add(c0, c1), Fp7.add(r0, r1)), + Fp7.add(t1, t2), + ); return { c0: o0, c1: o1 }; }; var Fp2Square = ({ c0, c1 }) => { @@ -3796,30 +4043,33 @@ var nobleCurves = (() => { mulN: Fp2Multiply, sqrN: Fp2Square, // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? - div: (lhs, rhs) => Fp22.mul(lhs, typeof rhs === "bigint" ? Fp7.inv(Fp7.create(rhs)) : Fp22.inv(rhs)), + div: (lhs, rhs) => + Fp22.mul( + lhs, + typeof rhs === "bigint" ? Fp7.inv(Fp7.create(rhs)) : Fp22.inv(rhs), + ), inv: ({ c0: a, c1: b }) => { const factor = Fp7.inv(Fp7.create(a * a + b * b)); - return { c0: Fp7.mul(factor, Fp7.create(a)), c1: Fp7.mul(factor, Fp7.create(-b)) }; + return { + c0: Fp7.mul(factor, Fp7.create(a)), + c1: Fp7.mul(factor, Fp7.create(-b)), + }; }, sqrt: (num) => { - if (Fp22.eql(num, Fp22.ZERO)) - return Fp22.ZERO; + if (Fp22.eql(num, Fp22.ZERO)) return Fp22.ZERO; const candidateSqrt = Fp22.pow(num, (Fp22.ORDER + _8n3) / _16n2); const check = Fp22.div(Fp22.sqr(candidateSqrt), num); const R = FP2_ROOTS_OF_UNITY; const divisor = [R[0], R[2], R[4], R[6]].find((r) => Fp22.eql(r, check)); - if (!divisor) - throw new Error("No root"); + if (!divisor) throw new Error("No root"); const index = R.indexOf(divisor); const root = R[index / 2]; - if (!root) - throw new Error("Invalid root"); + if (!root) throw new Error("Invalid root"); const x1 = Fp22.div(candidateSqrt, root); const x2 = Fp22.neg(x1); const { re: re1, im: im1 } = Fp22.reim(x1); const { re: re2, im: im2 } = Fp22.reim(x2); - if (im1 > im2 || im1 === im2 && re1 > re2) - return x1; + if (im1 > im2 || (im1 === im2 && re1 > re2)) return x1; return x2; }, // Same as sgn0_m_eq_2 in RFC 9380 @@ -3828,18 +4078,21 @@ var nobleCurves = (() => { const sign_0 = x0 % _2n10; const zero_0 = x0 === _0n10; const sign_1 = x1 % _2n10; - return BigInt(sign_0 || zero_0 && sign_1) == _1n11; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n11; }, // Bytes util fromBytes(b) { if (b.length !== Fp22.BYTES) throw new Error(`fromBytes wrong length=${b.length}`); - return { c0: Fp7.fromBytes(b.subarray(0, Fp7.BYTES)), c1: Fp7.fromBytes(b.subarray(Fp7.BYTES)) }; + return { + c0: Fp7.fromBytes(b.subarray(0, Fp7.BYTES)), + c1: Fp7.fromBytes(b.subarray(Fp7.BYTES)), + }; }, toBytes: ({ c0, c1 }) => concatBytes(Fp7.toBytes(c0), Fp7.toBytes(c1)), cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ c0: Fp7.cmov(c0, r0, c), - c1: Fp7.cmov(c1, r1, c) + c1: Fp7.cmov(c1, r1, c), }), // Specific utils // toString() { @@ -3847,28 +4100,34 @@ var nobleCurves = (() => { // } reim: ({ c0, c1 }) => ({ re: c0, im: c1 }), // multiply by u + 1 - mulByNonresidue: ({ c0, c1 }) => ({ c0: Fp7.sub(c0, c1), c1: Fp7.add(c0, c1) }), + mulByNonresidue: ({ c0, c1 }) => ({ + c0: Fp7.sub(c0, c1), + c1: Fp7.add(c0, c1), + }), multiplyByB: ({ c0, c1 }) => { let t0 = Fp7.mul(c0, _4n4); let t1 = Fp7.mul(c1, _4n4); return { c0: Fp7.sub(t0, t1), c1: Fp7.add(t0, t1) }; }, fromBigTuple: (tuple) => { - if (tuple.length !== 2) - throw new Error("Invalid tuple"); + if (tuple.length !== 2) throw new Error("Invalid tuple"); const fps = tuple.map((n) => Fp7.create(n)); return { c0: fps[0], c1: fps[1] }; }, frobeniusMap: ({ c0, c1 }, power) => ({ c0, - c1: Fp7.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]) - }) + c1: Fp7.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]), + }), }; var FP2_FROBENIUS_COEFFICIENTS = [ BigInt("0x1"), - BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa") + BigInt( + "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa", + ), ].map((item) => Fp7.create(item)); - var rv1 = BigInt("0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09"); + var rv1 = BigInt( + "0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09", + ); var FP2_ROOTS_OF_UNITY = [ [_1n11, _0n10], [rv1, -rv1], @@ -3877,24 +4136,24 @@ var nobleCurves = (() => { [-_1n11, _0n10], [-rv1, rv1], [_0n10, -_1n11], - [-rv1, -rv1] + [-rv1, -rv1], ].map((pair) => Fp22.fromBigTuple(pair)); var Fp6Add = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ c0: Fp22.add(c0, r0), c1: Fp22.add(c1, r1), - c2: Fp22.add(c2, r2) + c2: Fp22.add(c2, r2), }); var Fp6Subtract = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({ c0: Fp22.sub(c0, r0), c1: Fp22.sub(c1, r1), - c2: Fp22.sub(c2, r2) + c2: Fp22.sub(c2, r2), }); var Fp6Multiply = ({ c0, c1, c2 }, rhs) => { if (typeof rhs === "bigint") { return { c0: Fp22.mul(c0, rhs), c1: Fp22.mul(c1, rhs), - c2: Fp22.mul(c2, rhs) + c2: Fp22.mul(c2, rhs), }; } const { c0: r0, c1: r1, c2: r2 } = rhs; @@ -3903,11 +4162,28 @@ var nobleCurves = (() => { const t2 = Fp22.mul(c2, r2); return { // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) - c0: Fp22.add(t0, Fp22.mulByNonresidue(Fp22.sub(Fp22.mul(Fp22.add(c1, c2), Fp22.add(r1, r2)), Fp22.add(t1, t2)))), + c0: Fp22.add( + t0, + Fp22.mulByNonresidue( + Fp22.sub( + Fp22.mul(Fp22.add(c1, c2), Fp22.add(r1, r2)), + Fp22.add(t1, t2), + ), + ), + ), // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) - c1: Fp22.add(Fp22.sub(Fp22.mul(Fp22.add(c0, c1), Fp22.add(r0, r1)), Fp22.add(t0, t1)), Fp22.mulByNonresidue(t2)), + c1: Fp22.add( + Fp22.sub( + Fp22.mul(Fp22.add(c0, c1), Fp22.add(r0, r1)), + Fp22.add(t0, t1), + ), + Fp22.mulByNonresidue(t2), + ), // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 - c2: Fp22.sub(Fp22.add(t1, Fp22.mul(Fp22.add(c0, c2), Fp22.add(r0, r2))), Fp22.add(t0, t2)) + c2: Fp22.sub( + Fp22.add(t1, Fp22.mul(Fp22.add(c0, c2), Fp22.add(r0, r2))), + Fp22.add(t0, t2), + ), }; }; var Fp6Square = ({ c0, c1, c2 }) => { @@ -3919,7 +4195,13 @@ var nobleCurves = (() => { c0: Fp22.add(Fp22.mulByNonresidue(t3), t0), c1: Fp22.add(Fp22.mulByNonresidue(t4), t1), // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 - c2: Fp22.sub(Fp22.sub(Fp22.add(Fp22.add(t1, Fp22.sqr(Fp22.add(Fp22.sub(c0, c1), c2))), t3), t0), t4) + c2: Fp22.sub( + Fp22.sub( + Fp22.add(Fp22.add(t1, Fp22.sqr(Fp22.add(Fp22.sub(c0, c1), c2))), t3), + t0, + ), + t4, + ), }; }; var Fp62 = { @@ -3930,15 +4212,25 @@ var nobleCurves = (() => { ZERO: { c0: Fp22.ZERO, c1: Fp22.ZERO, c2: Fp22.ZERO }, ONE: { c0: Fp22.ONE, c1: Fp22.ZERO, c2: Fp22.ZERO }, create: (num) => num, - isValid: ({ c0, c1, c2 }) => Fp22.isValid(c0) && Fp22.isValid(c1) && Fp22.isValid(c2), + isValid: ({ c0, c1, c2 }) => + Fp22.isValid(c0) && Fp22.isValid(c1) && Fp22.isValid(c2), is0: ({ c0, c1, c2 }) => Fp22.is0(c0) && Fp22.is0(c1) && Fp22.is0(c2), - neg: ({ c0, c1, c2 }) => ({ c0: Fp22.neg(c0), c1: Fp22.neg(c1), c2: Fp22.neg(c2) }), - eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => Fp22.eql(c0, r0) && Fp22.eql(c1, r1) && Fp22.eql(c2, r2), + neg: ({ c0, c1, c2 }) => ({ + c0: Fp22.neg(c0), + c1: Fp22.neg(c1), + c2: Fp22.neg(c2), + }), + eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => + Fp22.eql(c0, r0) && Fp22.eql(c1, r1) && Fp22.eql(c2, r2), sqrt: () => { throw new Error("Not implemented"); }, // Do we need division by bigint at all? Should be done via order: - div: (lhs, rhs) => Fp62.mul(lhs, typeof rhs === "bigint" ? Fp7.inv(Fp7.create(rhs)) : Fp62.inv(rhs)), + div: (lhs, rhs) => + Fp62.mul( + lhs, + typeof rhs === "bigint" ? Fp7.inv(Fp7.create(rhs)) : Fp62.inv(rhs), + ), pow: (num, power) => FpPow(Fp62, num, power), invertBatch: (nums) => FpInvertBatch(Fp62, nums), // Normalized @@ -3955,8 +4247,17 @@ var nobleCurves = (() => { let t0 = Fp22.sub(Fp22.sqr(c0), Fp22.mulByNonresidue(Fp22.mul(c2, c1))); let t1 = Fp22.sub(Fp22.mulByNonresidue(Fp22.sqr(c2)), Fp22.mul(c0, c1)); let t2 = Fp22.sub(Fp22.sqr(c1), Fp22.mul(c0, c2)); - let t4 = Fp22.inv(Fp22.add(Fp22.mulByNonresidue(Fp22.add(Fp22.mul(c2, t1), Fp22.mul(c1, t2))), Fp22.mul(c0, t0))); - return { c0: Fp22.mul(t4, t0), c1: Fp22.mul(t4, t1), c2: Fp22.mul(t4, t2) }; + let t4 = Fp22.inv( + Fp22.add( + Fp22.mulByNonresidue(Fp22.add(Fp22.mul(c2, t1), Fp22.mul(c1, t2))), + Fp22.mul(c0, t0), + ), + ); + return { + c0: Fp22.mul(t4, t0), + c1: Fp22.mul(t4, t1), + c2: Fp22.mul(t4, t2), + }; }, // Bytes utils fromBytes: (b) => { @@ -3965,14 +4266,15 @@ var nobleCurves = (() => { return { c0: Fp22.fromBytes(b.subarray(0, Fp22.BYTES)), c1: Fp22.fromBytes(b.subarray(Fp22.BYTES, 2 * Fp22.BYTES)), - c2: Fp22.fromBytes(b.subarray(2 * Fp22.BYTES)) + c2: Fp22.fromBytes(b.subarray(2 * Fp22.BYTES)), }; }, - toBytes: ({ c0, c1, c2 }) => concatBytes(Fp22.toBytes(c0), Fp22.toBytes(c1), Fp22.toBytes(c2)), + toBytes: ({ c0, c1, c2 }) => + concatBytes(Fp22.toBytes(c0), Fp22.toBytes(c1), Fp22.toBytes(c2)), cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({ c0: Fp22.cmov(c0, r0, c), c1: Fp22.cmov(c1, r1, c), - c2: Fp22.cmov(c2, r2, c) + c2: Fp22.cmov(c2, r2, c), }), // Utils // fromTriple(triple: [Fp2, Fp2, Fp2]) { @@ -3987,20 +4289,30 @@ var nobleCurves = (() => { return { c0: Fp22.fromBigTuple(t.slice(0, 2)), c1: Fp22.fromBigTuple(t.slice(2, 4)), - c2: Fp22.fromBigTuple(t.slice(4, 6)) + c2: Fp22.fromBigTuple(t.slice(4, 6)), }; }, frobeniusMap: ({ c0, c1, c2 }, power) => ({ c0: Fp22.frobeniusMap(c0, power), - c1: Fp22.mul(Fp22.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]), - c2: Fp22.mul(Fp22.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]) + c1: Fp22.mul( + Fp22.frobeniusMap(c1, power), + FP6_FROBENIUS_COEFFICIENTS_1[power % 6], + ), + c2: Fp22.mul( + Fp22.frobeniusMap(c2, power), + FP6_FROBENIUS_COEFFICIENTS_2[power % 6], + ), + }), + mulByNonresidue: ({ c0, c1, c2 }) => ({ + c0: Fp22.mulByNonresidue(c2), + c1: c0, + c2: c1, }), - mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp22.mulByNonresidue(c2), c1: c0, c2: c1 }), // Sparse multiplication multiplyBy1: ({ c0, c1, c2 }, b1) => ({ c0: Fp22.mulByNonresidue(Fp22.mul(c2, b1)), c1: Fp22.mul(c0, b1), - c2: Fp22.mul(c1, b1) + c2: Fp22.mul(c1, b1), }), // Sparse multiplication multiplyBy01({ c0, c1, c2 }, b0, b1) { @@ -4008,71 +4320,95 @@ var nobleCurves = (() => { let t1 = Fp22.mul(c1, b1); return { // ((c1 + c2) * b1 - T1) * (u + 1) + T0 - c0: Fp22.add(Fp22.mulByNonresidue(Fp22.sub(Fp22.mul(Fp22.add(c1, c2), b1), t1)), t0), + c0: Fp22.add( + Fp22.mulByNonresidue(Fp22.sub(Fp22.mul(Fp22.add(c1, c2), b1), t1)), + t0, + ), // (b0 + b1) * (c0 + c1) - T0 - T1 - c1: Fp22.sub(Fp22.sub(Fp22.mul(Fp22.add(b0, b1), Fp22.add(c0, c1)), t0), t1), + c1: Fp22.sub( + Fp22.sub(Fp22.mul(Fp22.add(b0, b1), Fp22.add(c0, c1)), t0), + t1, + ), // (c0 + c2) * b0 - T0 + T1 - c2: Fp22.add(Fp22.sub(Fp22.mul(Fp22.add(c0, c2), b0), t0), t1) + c2: Fp22.add(Fp22.sub(Fp22.mul(Fp22.add(c0, c2), b0), t0), t1), }; }, multiplyByFp2: ({ c0, c1, c2 }, rhs) => ({ c0: Fp22.mul(c0, rhs), c1: Fp22.mul(c1, rhs), - c2: Fp22.mul(c2, rhs) - }) + c2: Fp22.mul(c2, rhs), + }), }; var FP6_FROBENIUS_COEFFICIENTS_1 = [ [BigInt("0x1"), BigInt("0x0")], [ BigInt("0x0"), - BigInt("0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac") + BigInt( + "0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac", + ), ], [ - BigInt("0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"), - BigInt("0x0") + BigInt( + "0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe", + ), + BigInt("0x0"), ], [BigInt("0x0"), BigInt("0x1")], [ - BigInt("0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac"), - BigInt("0x0") + BigInt( + "0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac", + ), + BigInt("0x0"), ], [ BigInt("0x0"), - BigInt("0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe") - ] + BigInt( + "0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe", + ), + ], ].map((pair) => Fp22.fromBigTuple(pair)); var FP6_FROBENIUS_COEFFICIENTS_2 = [ [BigInt("0x1"), BigInt("0x0")], [ - BigInt("0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad"), - BigInt("0x0") + BigInt( + "0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad", + ), + BigInt("0x0"), ], [ - BigInt("0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac"), - BigInt("0x0") + BigInt( + "0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac", + ), + BigInt("0x0"), ], [ - BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa"), - BigInt("0x0") + BigInt( + "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa", + ), + BigInt("0x0"), ], [ - BigInt("0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"), - BigInt("0x0") + BigInt( + "0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe", + ), + BigInt("0x0"), ], [ - BigInt("0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff"), - BigInt("0x0") - ] + BigInt( + "0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff", + ), + BigInt("0x0"), + ], ].map((pair) => Fp22.fromBigTuple(pair)); var BLS_X = BigInt("0xd201000000010000"); var BLS_X_LEN = bitLen(BLS_X); var Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ c0: Fp62.add(c0, r0), - c1: Fp62.add(c1, r1) + c1: Fp62.add(c1, r1), }); var Fp12Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({ c0: Fp62.sub(c0, r0), - c1: Fp62.sub(c1, r1) + c1: Fp62.sub(c1, r1), }); var Fp12Multiply = ({ c0, c1 }, rhs) => { if (typeof rhs === "bigint") @@ -4083,15 +4419,24 @@ var nobleCurves = (() => { return { c0: Fp62.add(t1, Fp62.mulByNonresidue(t2)), // (c0 + c1) * (r0 + r1) - (T1 + T2) - c1: Fp62.sub(Fp62.mul(Fp62.add(c0, c1), Fp62.add(r0, r1)), Fp62.add(t1, t2)) + c1: Fp62.sub( + Fp62.mul(Fp62.add(c0, c1), Fp62.add(r0, r1)), + Fp62.add(t1, t2), + ), }; }; var Fp12Square = ({ c0, c1 }) => { let ab = Fp62.mul(c0, c1); return { // (c1 * v + c0) * (c0 + c1) - AB - AB * v - c0: Fp62.sub(Fp62.sub(Fp62.mul(Fp62.add(Fp62.mulByNonresidue(c1), c0), Fp62.add(c0, c1)), ab), Fp62.mulByNonresidue(ab)), - c1: Fp62.add(ab, ab) + c0: Fp62.sub( + Fp62.sub( + Fp62.mul(Fp62.add(Fp62.mulByNonresidue(c1), c0), Fp62.add(c0, c1)), + ab, + ), + Fp62.mulByNonresidue(ab), + ), + c1: Fp62.add(ab, ab), }; }; function Fp4Square(a, b) { @@ -4099,7 +4444,7 @@ var nobleCurves = (() => { const b2 = Fp22.sqr(b); return { first: Fp22.add(Fp22.mulByNonresidue(b2), a2), - second: Fp22.sub(Fp22.sub(Fp22.sqr(Fp22.add(a, b)), a2), b2) + second: Fp22.sub(Fp22.sub(Fp22.sqr(Fp22.add(a, b)), a2), b2), // (a + b)² - a² - b² }; } @@ -4114,15 +4459,22 @@ var nobleCurves = (() => { isValid: ({ c0, c1 }) => Fp62.isValid(c0) && Fp62.isValid(c1), is0: ({ c0, c1 }) => Fp62.is0(c0) && Fp62.is0(c1), neg: ({ c0, c1 }) => ({ c0: Fp62.neg(c0), c1: Fp62.neg(c1) }), - eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp62.eql(c0, r0) && Fp62.eql(c1, r1), + eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => + Fp62.eql(c0, r0) && Fp62.eql(c1, r1), sqrt: () => { throw new Error("Not implemented"); }, inv: ({ c0, c1 }) => { - let t = Fp62.inv(Fp62.sub(Fp62.sqr(c0), Fp62.mulByNonresidue(Fp62.sqr(c1)))); + let t = Fp62.inv( + Fp62.sub(Fp62.sqr(c0), Fp62.mulByNonresidue(Fp62.sqr(c1))), + ); return { c0: Fp62.mul(c0, t), c1: Fp62.neg(Fp62.mul(c1, t)) }; }, - div: (lhs, rhs) => Fp12.mul(lhs, typeof rhs === "bigint" ? Fp7.inv(Fp7.create(rhs)) : Fp12.inv(rhs)), + div: (lhs, rhs) => + Fp12.mul( + lhs, + typeof rhs === "bigint" ? Fp7.inv(Fp7.create(rhs)) : Fp12.inv(rhs), + ), pow: (num, power) => FpPow(Fp12, num, power), invertBatch: (nums) => FpInvertBatch(Fp12, nums), // Normalized @@ -4141,13 +4493,13 @@ var nobleCurves = (() => { throw new Error(`fromBytes wrong length=${b.length}`); return { c0: Fp62.fromBytes(b.subarray(0, Fp62.BYTES)), - c1: Fp62.fromBytes(b.subarray(Fp62.BYTES)) + c1: Fp62.fromBytes(b.subarray(Fp62.BYTES)), }; }, toBytes: ({ c0, c1 }) => concatBytes(Fp62.toBytes(c0), Fp62.toBytes(c1)), cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({ c0: Fp62.cmov(c0, r0, c), - c1: Fp62.cmov(c1, r1, c) + c1: Fp62.cmov(c1, r1, c), }), // Utils // toString() { @@ -4158,7 +4510,7 @@ var nobleCurves = (() => { // } fromBigTwelve: (t) => ({ c0: Fp62.fromBigSix(t.slice(0, 6)), - c1: Fp62.fromBigSix(t.slice(6, 12)) + c1: Fp62.fromBigSix(t.slice(6, 12)), }), // Raises to q**i -th power frobeniusMap(lhs, power) { @@ -4170,8 +4522,8 @@ var nobleCurves = (() => { c1: Fp62.create({ c0: Fp22.mul(c0, coeff), c1: Fp22.mul(c1, coeff), - c2: Fp22.mul(c2, coeff) - }) + c2: Fp22.mul(c2, coeff), + }), }; }, // Sparse multiplication @@ -4181,12 +4533,18 @@ var nobleCurves = (() => { return { c0: Fp62.add(Fp62.mulByNonresidue(t1), t0), // (c1 + c0) * [o0, o1+o4] - T0 - T1 - c1: Fp62.sub(Fp62.sub(Fp62.multiplyBy01(Fp62.add(c1, c0), o0, Fp22.add(o1, o4)), t0), t1) + c1: Fp62.sub( + Fp62.sub( + Fp62.multiplyBy01(Fp62.add(c1, c0), o0, Fp22.add(o1, o4)), + t0, + ), + t1, + ), }; }, multiplyByFp2: ({ c0, c1 }, rhs) => ({ c0: Fp62.multiplyByFp2(c0, rhs), - c1: Fp62.multiplyByFp2(c1, rhs) + c1: Fp62.multiplyByFp2(c1, rhs), }), conjugate: ({ c0, c1 }) => ({ c0, c1: Fp62.neg(c1) }), // A cyclotomic group is a subgroup of Fp^n defined by @@ -4204,21 +4562,20 @@ var nobleCurves = (() => { c0: Fp62.create({ c0: Fp22.add(Fp22.mul(Fp22.sub(t3, c0c0), _2n10), t3), c1: Fp22.add(Fp22.mul(Fp22.sub(t5, c0c1), _2n10), t5), - c2: Fp22.add(Fp22.mul(Fp22.sub(t7, c0c2), _2n10), t7) + c2: Fp22.add(Fp22.mul(Fp22.sub(t7, c0c2), _2n10), t7), }), c1: Fp62.create({ c0: Fp22.add(Fp22.mul(Fp22.add(t9, c1c0), _2n10), t9), c1: Fp22.add(Fp22.mul(Fp22.add(t4, c1c1), _2n10), t4), - c2: Fp22.add(Fp22.mul(Fp22.add(t6, c1c2), _2n10), t6) - }) + c2: Fp22.add(Fp22.mul(Fp22.add(t6, c1c2), _2n10), t6), + }), }; }, _cyclotomicExp(num, n) { let z = Fp12.ONE; for (let i = BLS_X_LEN - 1; i >= 0; i--) { z = Fp12._cyclotomicSquare(z); - if (bitGet(n, i)) - z = Fp12.mul(z, num); + if (bitGet(n, i)) z = Fp12.mul(z, num); } return z; }, @@ -4232,221 +4589,287 @@ var nobleCurves = (() => { const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); - const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t6 = Fp12.mul( + Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), + Fp12._cyclotomicSquare(t2), + ); const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); - const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t6_t1c_pow_q1 = Fp12.frobeniusMap( + Fp12.mul(t6, Fp12.conjugate(t1)), + 1, + ); const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); - return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); - } + return Fp12.mul( + Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), + t7_t3c_t1, + ); + }, }; var FP12_FROBENIUS_COEFFICIENTS = [ [BigInt("0x1"), BigInt("0x0")], [ - BigInt("0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8"), - BigInt("0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3") + BigInt( + "0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8", + ), + BigInt( + "0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3", + ), ], [ - BigInt("0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff"), - BigInt("0x0") + BigInt( + "0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff", + ), + BigInt("0x0"), ], [ - BigInt("0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2"), - BigInt("0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09") + BigInt( + "0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2", + ), + BigInt( + "0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09", + ), ], [ - BigInt("0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"), - BigInt("0x0") + BigInt( + "0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe", + ), + BigInt("0x0"), ], [ - BigInt("0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995"), - BigInt("0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116") + BigInt( + "0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995", + ), + BigInt( + "0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116", + ), ], [ - BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa"), - BigInt("0x0") + BigInt( + "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa", + ), + BigInt("0x0"), ], [ - BigInt("0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3"), - BigInt("0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8") + BigInt( + "0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3", + ), + BigInt( + "0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8", + ), ], [ - BigInt("0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac"), - BigInt("0x0") + BigInt( + "0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac", + ), + BigInt("0x0"), ], [ - BigInt("0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09"), - BigInt("0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2") + BigInt( + "0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09", + ), + BigInt( + "0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2", + ), ], [ - BigInt("0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad"), - BigInt("0x0") + BigInt( + "0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad", + ), + BigInt("0x0"), ], [ - BigInt("0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116"), - BigInt("0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995") - ] + BigInt( + "0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116", + ), + BigInt( + "0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995", + ), + ], ].map((n) => Fp22.fromBigTuple(n)); - var isogenyMapG2 = isogenyMap(Fp22, [ - // xNum + var isogenyMapG2 = isogenyMap( + Fp22, [ + // xNum [ - "0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6", - "0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6" - ], - [ - "0x0", - "0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a" + [ + "0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6", + "0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6", + ], + [ + "0x0", + "0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a", + ], + [ + "0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e", + "0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d", + ], + [ + "0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1", + "0x0", + ], ], + // xDen [ - "0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e", - "0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d" + [ + "0x0", + "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63", + ], + [ + "0xc", + "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f", + ], + ["0x1", "0x0"], + // LAST 1 ], + // yNum [ - "0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1", - "0x0" - ] - ], - // xDen - [ - [ - "0x0", - "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63" + [ + "0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706", + "0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706", + ], + [ + "0x0", + "0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be", + ], + [ + "0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c", + "0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f", + ], + [ + "0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10", + "0x0", + ], ], + // yDen [ - "0xc", - "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f" + [ + "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb", + "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb", + ], + [ + "0x0", + "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3", + ], + [ + "0x12", + "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99", + ], + ["0x1", "0x0"], + // LAST 1 ], - ["0x1", "0x0"] - // LAST 1 - ], - // yNum + ].map((i) => i.map((pair) => Fp22.fromBigTuple(pair.map(BigInt)))), + ); + var isogenyMapG1 = isogenyMap( + Fp7, [ + // xNum [ - "0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706", - "0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706" + "0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7", + "0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb", + "0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0", + "0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861", + "0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9", + "0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983", + "0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84", + "0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e", + "0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317", + "0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e", + "0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b", + "0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229", ], + // xDen [ - "0x0", - "0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be" + "0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c", + "0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff", + "0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19", + "0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8", + "0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e", + "0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5", + "0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a", + "0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e", + "0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641", + "0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a", + "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", + // LAST 1 ], + // yNum [ - "0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c", - "0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f" - ], - [ - "0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10", - "0x0" - ] - ], - // yDen - [ - [ - "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb", - "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb" + "0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33", + "0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696", + "0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6", + "0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb", + "0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb", + "0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0", + "0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2", + "0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29", + "0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587", + "0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30", + "0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132", + "0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e", + "0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8", + "0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133", + "0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b", + "0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604", ], + // yDen [ - "0x0", - "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3" + "0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1", + "0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d", + "0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2", + "0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416", + "0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d", + "0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac", + "0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c", + "0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9", + "0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a", + "0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55", + "0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8", + "0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092", + "0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc", + "0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7", + "0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f", + "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", + // LAST 1 ], - [ - "0x12", - "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99" - ], - ["0x1", "0x0"] - // LAST 1 - ] - ].map((i) => i.map((pair) => Fp22.fromBigTuple(pair.map(BigInt))))); - var isogenyMapG1 = isogenyMap(Fp7, [ - // xNum - [ - "0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7", - "0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb", - "0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0", - "0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861", - "0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9", - "0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983", - "0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84", - "0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e", - "0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317", - "0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e", - "0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b", - "0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229" - ], - // xDen - [ - "0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c", - "0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff", - "0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19", - "0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8", - "0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e", - "0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5", - "0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a", - "0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e", - "0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641", - "0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a", - "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001" - // LAST 1 - ], - // yNum - [ - "0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33", - "0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696", - "0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6", - "0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb", - "0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb", - "0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0", - "0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2", - "0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29", - "0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587", - "0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30", - "0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132", - "0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e", - "0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8", - "0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133", - "0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b", - "0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604" - ], - // yDen - [ - "0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1", - "0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d", - "0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2", - "0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416", - "0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d", - "0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac", - "0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c", - "0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9", - "0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a", - "0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55", - "0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8", - "0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092", - "0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc", - "0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7", - "0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f", - "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001" - // LAST 1 - ] - ].map((i) => i.map((j) => BigInt(j)))); + ].map((i) => i.map((j) => BigInt(j))), + ); var G2_SWU = mapToCurveSimpleSWU(Fp22, { A: Fp22.create({ c0: Fp7.create(_0n10), c1: Fp7.create(BigInt(240)) }), - B: Fp22.create({ c0: Fp7.create(BigInt(1012)), c1: Fp7.create(BigInt(1012)) }), - Z: Fp22.create({ c0: Fp7.create(BigInt(-2)), c1: Fp7.create(BigInt(-1)) }) + B: Fp22.create({ + c0: Fp7.create(BigInt(1012)), + c1: Fp7.create(BigInt(1012)), + }), + Z: Fp22.create({ c0: Fp7.create(BigInt(-2)), c1: Fp7.create(BigInt(-1)) }), // Z: -(2 + I) }); var G1_SWU = mapToCurveSimpleSWU(Fp7, { - A: Fp7.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")), - B: Fp7.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")), - Z: Fp7.create(BigInt(11)) + A: Fp7.create( + BigInt( + "0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d", + ), + ), + B: Fp7.create( + BigInt( + "0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0", + ), + ), + Z: Fp7.create(BigInt(11)), }); var ut_root = Fp62.create({ c0: Fp22.ZERO, c1: Fp22.ONE, c2: Fp22.ZERO }); var wsq = Fp12.create({ c0: ut_root, c1: Fp62.ZERO }); var wcu = Fp12.create({ c0: Fp62.ZERO, c1: ut_root }); var [wsq_inv, wcu_inv] = Fp12.invertBatch([wsq, wcu]); function psi(x, y) { - const x2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wsq_inv, x), 1), wsq).c0.c0; - const y2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wcu_inv, y), 1), wcu).c0.c0; + const x2 = Fp12.mul( + Fp12.frobeniusMap(Fp12.multiplyByFp2(wsq_inv, x), 1), + wsq, + ).c0.c0; + const y2 = Fp12.mul( + Fp12.frobeniusMap(Fp12.multiplyByFp2(wcu_inv, y), 1), + wcu, + ).c0.c0; return [x2, y2]; } function G2psi(c, P3) { @@ -4454,7 +4877,9 @@ var nobleCurves = (() => { const p = psi(affine.x, affine.y); return new c(p[0], p[1], Fp22.ONE); } - var PSI2_C1 = BigInt("0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac"); + var PSI2_C1 = BigInt( + "0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac", + ); function psi2(x, y) { return [Fp22.mul(x, PSI2_C1), Fp22.neg(y)]; } @@ -4484,12 +4909,14 @@ var nobleCurves = (() => { // Hash functions for: expand_message_xmd is appropriate for use with a // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others. // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247 - hash: sha256 + hash: sha256, }); var C_BIT_POS = Fp7.BITS; var I_BIT_POS = Fp7.BITS + 1; var S_BIT_POS = Fp7.BITS + 2; - var COMPRESSED_ZERO = Fp7.toBytes(bitSet(bitSet(_0n10, I_BIT_POS, true), S_BIT_POS, true)); + var COMPRESSED_ZERO = Fp7.toBytes( + bitSet(bitSet(_0n10, I_BIT_POS, true), S_BIT_POS, true), + ); function signatureG2ToRawBytes(point) { point.assertValidity(); const len = Fp7.BYTES; @@ -4499,7 +4926,7 @@ var nobleCurves = (() => { const { re: x0, im: x1 } = Fp22.reim(x); const { re: y0, im: y1 } = Fp22.reim(y); const tmp = y1 > _0n10 ? y1 * _2n10 : y0 * _2n10; - const aflag1 = Boolean(tmp / Fp7.ORDER & _1n11); + const aflag1 = Boolean((tmp / Fp7.ORDER) & _1n11); const z1 = bitSet(bitSet(x1, 381, aflag1), S_BIT_POS, true); const z2 = x0; return concatBytes(numberToBytesBE(z1, len), numberToBytesBE(z2, len)); @@ -4511,7 +4938,7 @@ var nobleCurves = (() => { Fp2: Fp22, Fp6: Fp62, Fp12, - Fr + Fr, }, // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3 @@ -4522,8 +4949,12 @@ var nobleCurves = (() => { // generator's coordinates // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 - Gx: BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"), - Gy: BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1"), + Gx: BigInt( + "0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb", + ), + Gy: BigInt( + "0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1", + ), a: Fp7.ZERO, b: _4n4, htfDefaults: { ...htfDefaults, m: 1 }, @@ -4534,8 +4965,14 @@ var nobleCurves = (() => { // It returns false for shitty points. // https://eprint.iacr.org/2021/1130.pdf isTorsionFree: (c, point) => { - const cubicRootOfUnityModP = BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"); - const phi = new c(Fp7.mul(point.px, cubicRootOfUnityModP), point.py, point.pz); + const cubicRootOfUnityModP = BigInt( + "0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe", + ); + const phi = new c( + Fp7.mul(point.px, cubicRootOfUnityModP), + point.py, + point.pz, + ); const xP = point.multiplyUnsafe(bls12_381.params.x).negate(); const u2P = xP.multiplyUnsafe(bls12_381.params.x); return u2P.equals(phi); @@ -4555,19 +4992,19 @@ var nobleCurves = (() => { const P3 = Fp7.ORDER; const compressedValue = bytesToNumberBE(bytes2); const bflag = bitGet(compressedValue, I_BIT_POS); - if (bflag === _1n11) - return { x: _0n10, y: _0n10 }; + if (bflag === _1n11) return { x: _0n10, y: _0n10 }; const x = Fp7.create(compressedValue & Fp7.MASK); - const right = Fp7.add(Fp7.pow(x, _3n5), Fp7.create(bls12_381.params.G1b)); + const right = Fp7.add( + Fp7.pow(x, _3n5), + Fp7.create(bls12_381.params.G1b), + ); let y = Fp7.sqrt(right); - if (!y) - throw new Error("Invalid compressed G1 point"); + if (!y) throw new Error("Invalid compressed G1 point"); const aflag = bitGet(compressedValue, C_BIT_POS); - if (y * _2n10 / P3 !== aflag) - y = Fp7.neg(y); + if ((y * _2n10) / P3 !== aflag) y = Fp7.neg(y); return { x: Fp7.create(x), y: Fp7.create(y) }; } else if (bytes2.length === 96) { - if ((bytes2[0] & 1 << 6) !== 0) + if ((bytes2[0] & (1 << 6)) !== 0) return bls12_381.G1.ProjectivePoint.ZERO.toAffine(); const x = bytesToNumberBE(bytes2.subarray(0, Fp7.BYTES)); const y = bytesToNumberBE(bytes2.subarray(Fp7.BYTES)); @@ -4580,22 +5017,27 @@ var nobleCurves = (() => { const isZero = point.equals(c.ZERO); const { x, y } = point.toAffine(); if (isCompressed) { - if (isZero) - return COMPRESSED_ZERO.slice(); + if (isZero) return COMPRESSED_ZERO.slice(); const P3 = Fp7.ORDER; let num; - num = bitSet(x, C_BIT_POS, Boolean(y * _2n10 / P3)); + num = bitSet(x, C_BIT_POS, Boolean((y * _2n10) / P3)); num = bitSet(num, S_BIT_POS, true); return numberToBytesBE(num, Fp7.BYTES); } else { if (isZero) { - const x2 = concatBytes(new Uint8Array([64]), new Uint8Array(2 * Fp7.BYTES - 1)); + const x2 = concatBytes( + new Uint8Array([64]), + new Uint8Array(2 * Fp7.BYTES - 1), + ); return x2; } else { - return concatBytes(numberToBytesBE(x, Fp7.BYTES), numberToBytesBE(y, Fp7.BYTES)); + return concatBytes( + numberToBytesBE(x, Fp7.BYTES), + numberToBytesBE(y, Fp7.BYTES), + ); } } - } + }, }, // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1), // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where @@ -4604,21 +5046,33 @@ var nobleCurves = (() => { G2: { Fp: Fp22, // cofactor - h: BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"), + h: BigInt( + "0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5", + ), Gx: Fp22.fromBigTuple([ - BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"), - BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e") + BigInt( + "0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8", + ), + BigInt( + "0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e", + ), ]), // y = // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582, // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 Gy: Fp22.fromBigTuple([ - BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"), - BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be") + BigInt( + "0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801", + ), + BigInt( + "0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be", + ), ]), a: Fp22.ZERO, b: Fp22.fromBigTuple([_4n4, _4n4]), - hEff: BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"), + hEff: BigInt( + "0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551", + ), htfDefaults: { ...htfDefaults }, wrapPrivateKey: true, allowInfinityPoint: true, @@ -4631,7 +5085,9 @@ var nobleCurves = (() => { // It returns false for shitty points. // https://eprint.iacr.org/2021/1130.pdf isTorsionFree: (c, P3) => { - return P3.multiplyUnsafe(bls12_381.params.x).negate().equals(G2psi(c, P3)); + return P3.multiplyUnsafe(bls12_381.params.x) + .negate() + .equals(G2psi(c, P3)); }, // Maps the point into the prime-order subgroup G2. // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11 @@ -4667,7 +5123,7 @@ var nobleCurves = (() => { const P3 = Fp7.ORDER; bytes2[0] = bytes2[0] & 31; if (bitI) { - if (bytes2.reduce((p, c) => p !== 0 ? c + 1 : c, 0) > 0) { + if (bytes2.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) { throw new Error("Invalid compressed G2 point"); } return { x: Fp22.ZERO, y: Fp22.ZERO }; @@ -4677,18 +5133,26 @@ var nobleCurves = (() => { const x = Fp22.create({ c0: Fp7.create(x_0), c1: Fp7.create(x_1) }); const right = Fp22.add(Fp22.pow(x, _3n5), b); let y = Fp22.sqrt(right); - const Y_bit = y.c1 === _0n10 ? y.c0 * _2n10 / P3 : y.c1 * _2n10 / P3 ? _1n11 : _0n10; + const Y_bit = + y.c1 === _0n10 + ? (y.c0 * _2n10) / P3 + : (y.c1 * _2n10) / P3 + ? _1n11 + : _0n10; y = bitS > 0 && Y_bit > 0 ? y : Fp22.neg(y); return { x, y }; } else if (bytes2.length === 192 && !bitC) { - if ((bytes2[0] & 1 << 6) !== 0) { + if ((bytes2[0] & (1 << 6)) !== 0) { return { x: Fp22.ZERO, y: Fp22.ZERO }; } const x1 = slc(bytes2, 0, L); const x0 = slc(bytes2, L, 2 * L); const y1 = slc(bytes2, 2 * L, 3 * L); const y0 = slc(bytes2, 3 * L, 4 * L); - return { x: Fp22.fromBigTuple([x0, x1]), y: Fp22.fromBigTuple([y0, y1]) }; + return { + x: Fp22.fromBigTuple([x0, x1]), + y: Fp22.fromBigTuple([y0, y1]), + }; } else { throw new Error("Invalid point G2, expected 96/192 bytes"); } @@ -4700,16 +5164,29 @@ var nobleCurves = (() => { if (isCompressed) { if (isZero) return concatBytes(COMPRESSED_ZERO, numberToBytesBE(_0n10, len)); - const flag = Boolean(y.c1 === _0n10 ? y.c0 * _2n10 / P3 : y.c1 * _2n10 / P3); + const flag = Boolean( + y.c1 === _0n10 ? (y.c0 * _2n10) / P3 : (y.c1 * _2n10) / P3, + ); let x_1 = bitSet(x.c1, C_BIT_POS, flag); x_1 = bitSet(x_1, S_BIT_POS, true); - return concatBytes(numberToBytesBE(x_1, len), numberToBytesBE(x.c0, len)); + return concatBytes( + numberToBytesBE(x_1, len), + numberToBytesBE(x.c0, len), + ); } else { if (isZero) - return concatBytes(new Uint8Array([64]), new Uint8Array(4 * len - 1)); + return concatBytes( + new Uint8Array([64]), + new Uint8Array(4 * len - 1), + ); const { re: x0, im: x1 } = Fp22.reim(x); const { re: y0, im: y1 } = Fp22.reim(y); - return concatBytes(numberToBytesBE(x1, len), numberToBytesBE(x0, len), numberToBytesBE(y1, len), numberToBytesBE(y0, len)); + return concatBytes( + numberToBytesBE(x1, len), + numberToBytesBE(x0, len), + numberToBytesBE(y1, len), + numberToBytesBE(y0, len), + ); } }, Signature: { @@ -4719,25 +5196,24 @@ var nobleCurves = (() => { const P3 = Fp7.ORDER; const half = hex.length / 2; if (half !== 48 && half !== 96) - throw new Error("Invalid compressed signature length, must be 96 or 192"); + throw new Error( + "Invalid compressed signature length, must be 96 or 192", + ); const z1 = bytesToNumberBE(hex.slice(0, half)); const z2 = bytesToNumberBE(hex.slice(half)); const bflag1 = bitGet(z1, I_BIT_POS); - if (bflag1 === _1n11) - return bls12_381.G2.ProjectivePoint.ZERO; + if (bflag1 === _1n11) return bls12_381.G2.ProjectivePoint.ZERO; const x1 = Fp7.create(z1 & Fp7.MASK); const x2 = Fp7.create(z2); const x = Fp22.create({ c0: x2, c1: x1 }); const y2 = Fp22.add(Fp22.pow(x, _3n5), bls12_381.params.G2b); let y = Fp22.sqrt(y2); - if (!y) - throw new Error("Failed to find a square root"); + if (!y) throw new Error("Failed to find a square root"); const { re: y0, im: y1 } = Fp22.reim(y); const aflag1 = bitGet(z1, 381); - const isGreater = y1 > _0n10 && y1 * _2n10 / P3 !== aflag1; - const isZero = y1 === _0n10 && y0 * _2n10 / P3 !== aflag1; - if (isGreater || isZero) - y = Fp22.neg(y); + const isGreater = y1 > _0n10 && (y1 * _2n10) / P3 !== aflag1; + const isZero = y1 === _0n10 && (y0 * _2n10) / P3 !== aflag1; + if (isGreater || isZero) y = Fp22.neg(y); const point = bls12_381.G2.ProjectivePoint.fromAffine({ x, y }); point.assertValidity(); return point; @@ -4747,17 +5223,17 @@ var nobleCurves = (() => { }, toHex(point) { return bytesToHex(signatureG2ToRawBytes(point)); - } - } + }, + }, }, params: { x: BLS_X, - r: Fr.ORDER + r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves }, htfDefaults, hash: sha256, - randomBytes + randomBytes, }); // input.js diff --git a/sw_scripts/noble-hashes.js b/sw_scripts/noble-hashes.js new file mode 100644 index 0000000..bc53656 --- /dev/null +++ b/sw_scripts/noble-hashes.js @@ -0,0 +1,3068 @@ +"use strict"; +var nobleHashes = (() => { + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __hasOwnProp = Object.prototype.hasOwnProperty; + 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 __toCommonJS = (mod) => + __copyProps(__defProp({}, "__esModule", { value: true }), mod); + + // input.js + var input_exports = {}; + __export(input_exports, { + argon2id: () => argon2id, + blake2b: () => blake2b, + blake2s: () => blake2s, + blake3: () => blake3, + cshake128: () => cshake128, + cshake256: () => cshake256, + eskdf: () => eskdf, + hkdf: () => hkdf, + hmac: () => hmac, + k12: () => k12, + keccak_224: () => keccak_224, + keccak_256: () => keccak_256, + keccak_384: () => keccak_384, + keccak_512: () => keccak_512, + kmac128: () => kmac128, + kmac256: () => kmac256, + m14: () => m14, + pbkdf2: () => pbkdf2, + pbkdf2Async: () => pbkdf2Async, + ripemd160: () => ripemd160, + scrypt: () => scrypt, + scryptAsync: () => scryptAsync, + sha1: () => sha1, + sha256: () => sha256, + sha3_224: () => sha3_224, + sha3_256: () => sha3_256, + sha3_384: () => sha3_384, + sha3_512: () => sha3_512, + sha512: () => sha512, + utils: () => utils, + }); + + // ../src/crypto.ts + var crypto = + typeof globalThis === "object" && "crypto" in globalThis + ? globalThis.crypto + : void 0; + + // ../esm/utils.js + var u8a = (a) => a instanceof Uint8Array; + var u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); + var u32 = (arr) => + new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); + var createView = (arr) => + new DataView(arr.buffer, arr.byteOffset, arr.byteLength); + var rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); + var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; + if (!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 (!u8a(bytes2)) throw new Error("Uint8Array expected"); + let hex = ""; + for (let i = 0; i < bytes2.length; i++) { + hex += hexes[bytes2[i]]; + } + return hex; + } + 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; + } + var nextTick = async () => {}; + 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 nextTick(); + ts += diff; + } + } + function utf8ToBytes(str) { + if (typeof str !== "string") + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); + } + function toBytes(data) { + if (typeof data === "string") data = utf8ToBytes(data); + if (!u8a(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; + } + var Hash = class { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } + }; + var toStr = {}.toString; + function checkOpts(defaults, opts) { + if (opts !== void 0 && toStr.call(opts) !== "[object Object]") + throw new Error("Options should be object or undefined"); + const merged = Object.assign(defaults, opts); + return merged; + } + function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; + } + function wrapConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; + } + function wrapXOFConstructorWithOpts(hashCons) { + const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); + const tmp = hashCons({}); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = (opts) => hashCons(opts); + return hashC; + } + function randomBytes(bytesLength = 32) { + if (crypto && typeof crypto.getRandomValues === "function") { + return crypto.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error("crypto.getRandomValues must be defined"); + } + + // ../esm/_assert.js + function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); + } + function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) throw new Error("Expected Uint8Array"); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error( + `Expected Uint8Array of length ${lengths}, not of length=${b.length}`, + ); + } + function hash(hash2) { + if (typeof hash2 !== "function" || typeof hash2.create !== "function") + throw new Error("Hash should be wrapped by utils.wrapConstructor"); + number(hash2.outputLen); + number(hash2.blockLen); + } + function exists(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 output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error( + `digestInto() expects output buffer of length at least ${min}`, + ); + } + } + + // ../esm/_blake2.js + var SIGMA = /* @__PURE__ */ new Uint8Array([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 10, 4, 8, 9, 15, + 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, + 7, 1, 9, 4, 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, 9, 0, 5, + 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, 2, 12, 6, 10, 0, 11, 8, 3, 4, + 13, 7, 5, 15, 14, 1, 9, 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, + 11, 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, 6, 15, 14, 9, 11, + 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, + 3, 12, 13, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 10, + 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + ]); + var BLAKE2 = class extends Hash { + constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.length = 0; + this.pos = 0; + this.finished = false; + this.destroyed = false; + number(blockLen); + number(outputLen); + number(keyLen); + if (outputLen < 0 || outputLen > keyLen) + throw new Error("outputLen bigger than keyLen"); + if ( + opts.key !== void 0 && + (opts.key.length < 1 || opts.key.length > keyLen) + ) + throw new Error(`key must be up 1..${keyLen} byte long or undefined`); + if (opts.salt !== void 0 && opts.salt.length !== saltLen) + throw new Error(`salt must be ${saltLen} byte long or undefined`); + if ( + opts.personalization !== void 0 && + opts.personalization.length !== persLen + ) + throw new Error( + `personalization must be ${persLen} byte long or undefined`, + ); + this.buffer32 = u32((this.buffer = new Uint8Array(blockLen))); + } + update(data) { + exists(this); + const { blockLen, buffer, buffer32 } = this; + data = toBytes(data); + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len; ) { + if (this.pos === blockLen) { + this.compress(buffer32, 0, false); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array( + buf, + dataOffset, + Math.floor((len - pos) / 4), + ); + for ( + let pos32 = 0; + pos + blockLen < len; + pos32 += buffer32.length, pos += blockLen + ) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + exists(this); + output(out, this); + const { pos, buffer32 } = this; + this.finished = true; + this.buffer.subarray(pos).fill(0); + this.compress(buffer32, 0, true); + const out32 = u32(out); + this.get().forEach((v, i) => (out32[i] = v)); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + to || (to = new this.constructor({ dkLen: outputLen })); + to.set(...this.get()); + to.length = length; + to.finished = finished; + to.destroyed = destroyed; + to.outputLen = outputLen; + to.buffer.set(buffer); + to.pos = pos; + return to; + } + }; + + // ../esm/_u64.js + var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); + var _32n = /* @__PURE__ */ BigInt(32); + function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { + h: Number((n >> _32n) & U32_MASK64) | 0, + l: Number(n & U32_MASK64) | 0, + }; + } + function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; + } + var toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); + var shrSH = (h, _l, s) => h >>> s; + var shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); + var rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); + var rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); + var rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); + var rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); + var rotr32H = (_h, l) => l; + var rotr32L = (h, _l) => h; + var rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); + var rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); + var rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); + var rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); + function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; + } + var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); + var add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; + var add4L = (Al, Bl, Cl, Dl) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); + var add4H = (low, Ah, Bh, Ch, Dh) => + (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; + var add5L = (Al, Bl, Cl, Dl, El) => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); + var add5H = (low, Ah, Bh, Ch, Dh, Eh) => + (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; + var u64 = { + fromBig, + split, + toBig, + shrSH, + shrSL, + rotrSH, + rotrSL, + rotrBH, + rotrBL, + rotr32H, + rotr32L, + rotlSH, + rotlSL, + rotlBH, + rotlBL, + add, + add3L, + add3H, + add4L, + add4H, + add5H, + add5L, + }; + var u64_default = u64; + + // ../esm/blake2b.js + var IV = /* @__PURE__ */ new Uint32Array([ + 4089235720, 1779033703, 2227873595, 3144134277, 4271175723, 1013904242, + 1595750129, 2773480762, 2917565137, 1359893119, 725511199, 2600822924, + 4215389547, 528734635, 327033209, 1541459225, + ]); + var BUF = /* @__PURE__ */ new Uint32Array(32); + function G1(a, b, c, d, msg, x) { + const Xl = msg[x], + Xh = msg[x + 1]; + let Al = BUF[2 * a], + Ah = BUF[2 * a + 1]; + let Bl = BUF[2 * b], + Bh = BUF[2 * b + 1]; + let Cl = BUF[2 * c], + Ch = BUF[2 * c + 1]; + let Dl = BUF[2 * d], + Dh = BUF[2 * d + 1]; + let ll = u64_default.add3L(Al, Bl, Xl); + Ah = u64_default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { + Dh: u64_default.rotr32H(Dh, Dl), + Dl: u64_default.rotr32L(Dh, Dl), + }); + ({ h: Ch, l: Cl } = u64_default.add(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { + Bh: u64_default.rotrSH(Bh, Bl, 24), + Bl: u64_default.rotrSL(Bh, Bl, 24), + }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); + } + function G2(a, b, c, d, msg, x) { + const Xl = msg[x], + Xh = msg[x + 1]; + let Al = BUF[2 * a], + Ah = BUF[2 * a + 1]; + let Bl = BUF[2 * b], + Bh = BUF[2 * b + 1]; + let Cl = BUF[2 * c], + Ch = BUF[2 * c + 1]; + let Dl = BUF[2 * d], + Dh = BUF[2 * d + 1]; + let ll = u64_default.add3L(Al, Bl, Xl); + Ah = u64_default.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { + Dh: u64_default.rotrSH(Dh, Dl, 16), + Dl: u64_default.rotrSL(Dh, Dl, 16), + }); + ({ h: Ch, l: Cl } = u64_default.add(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { + Bh: u64_default.rotrBH(Bh, Bl, 63), + Bl: u64_default.rotrBL(Bh, Bl, 63), + }); + (BUF[2 * a] = Al), (BUF[2 * a + 1] = Ah); + (BUF[2 * b] = Bl), (BUF[2 * b + 1] = Bh); + (BUF[2 * c] = Cl), (BUF[2 * c + 1] = Ch); + (BUF[2 * d] = Dl), (BUF[2 * d + 1] = Dh); + } + var BLAKE2b = class extends BLAKE2 { + constructor(opts = {}) { + super(128, opts.dkLen === void 0 ? 64 : opts.dkLen, opts, 64, 16, 16); + this.v0l = IV[0] | 0; + this.v0h = IV[1] | 0; + this.v1l = IV[2] | 0; + this.v1h = IV[3] | 0; + this.v2l = IV[4] | 0; + this.v2h = IV[5] | 0; + this.v3l = IV[6] | 0; + this.v3h = IV[7] | 0; + this.v4l = IV[8] | 0; + this.v4h = IV[9] | 0; + this.v5l = IV[10] | 0; + this.v5h = IV[11] | 0; + this.v6l = IV[12] | 0; + this.v6h = IV[13] | 0; + this.v7l = IV[14] | 0; + this.v7h = IV[15] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0l ^= this.outputLen | (keyLength << 8) | (1 << 16) | (1 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4l ^= salt[0]; + this.v4h ^= salt[1]; + this.v5l ^= salt[2]; + this.v5h ^= salt[3]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6l ^= pers[0]; + this.v6h ^= pers[1]; + this.v7l ^= pers[2]; + this.v7h ^= pers[3]; + } + if (opts.key) { + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BUF[i] = v)); + BUF.set(IV, 16); + let { h, l } = u64_default.fromBig(BigInt(this.length)); + BUF[24] = IV[8] ^ l; + BUF[25] = IV[9] ^ h; + if (isLast) { + BUF[28] = ~BUF[28]; + BUF[29] = ~BUF[29]; + } + let j = 0; + const s = SIGMA; + for (let i = 0; i < 12; i++) { + G1(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BUF[0] ^ BUF[16]; + this.v0h ^= BUF[1] ^ BUF[17]; + this.v1l ^= BUF[2] ^ BUF[18]; + this.v1h ^= BUF[3] ^ BUF[19]; + this.v2l ^= BUF[4] ^ BUF[20]; + this.v2h ^= BUF[5] ^ BUF[21]; + this.v3l ^= BUF[6] ^ BUF[22]; + this.v3h ^= BUF[7] ^ BUF[23]; + this.v4l ^= BUF[8] ^ BUF[24]; + this.v4h ^= BUF[9] ^ BUF[25]; + this.v5l ^= BUF[10] ^ BUF[26]; + this.v5h ^= BUF[11] ^ BUF[27]; + this.v6l ^= BUF[12] ^ BUF[28]; + this.v6h ^= BUF[13] ^ BUF[29]; + this.v7l ^= BUF[14] ^ BUF[30]; + this.v7h ^= BUF[15] ^ BUF[31]; + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } + }; + var blake2b = /* @__PURE__ */ wrapConstructorWithOpts( + (opts) => new BLAKE2b(opts), + ); + + // ../esm/blake2s.js + var IV2 = /* @__PURE__ */ new Uint32Array([ + 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, + 528734635, 1541459225, + ]); + function G12(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; + } + function G22(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; + } + function compress( + s, + offset, + msg, + rounds, + v0, + v1, + v2, + v3, + v4, + v5, + v6, + v7, + v8, + v9, + v10, + v11, + v12, + v13, + v14, + v15, + ) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ + a: v0, + b: v4, + c: v8, + d: v12, + } = G12(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ + a: v0, + b: v4, + c: v8, + d: v12, + } = G22(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ + a: v1, + b: v5, + c: v9, + d: v13, + } = G12(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ + a: v1, + b: v5, + c: v9, + d: v13, + } = G22(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ + a: v2, + b: v6, + c: v10, + d: v14, + } = G12(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ + a: v2, + b: v6, + c: v10, + d: v14, + } = G22(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ + a: v3, + b: v7, + c: v11, + d: v15, + } = G12(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ + a: v3, + b: v7, + c: v11, + d: v15, + } = G22(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ + a: v0, + b: v5, + c: v10, + d: v15, + } = G12(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ + a: v0, + b: v5, + c: v10, + d: v15, + } = G22(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ + a: v1, + b: v6, + c: v11, + d: v12, + } = G12(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ + a: v1, + b: v6, + c: v11, + d: v12, + } = G22(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ + a: v2, + b: v7, + c: v8, + d: v13, + } = G12(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ + a: v2, + b: v7, + c: v8, + d: v13, + } = G22(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ + a: v3, + b: v4, + c: v9, + d: v14, + } = G12(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ + a: v3, + b: v4, + c: v9, + d: v14, + } = G22(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { + v0, + v1, + v2, + v3, + v4, + v5, + v6, + v7, + v8, + v9, + v10, + v11, + v12, + v13, + v14, + v15, + }; + } + var BLAKE2s = class extends BLAKE2 { + constructor(opts = {}) { + super(64, opts.dkLen === void 0 ? 32 : opts.dkLen, opts, 32, 8, 8); + this.v0 = IV2[0] | 0; + this.v1 = IV2[1] | 0; + this.v2 = IV2[2] | 0; + this.v3 = IV2[3] | 0; + this.v4 = IV2[4] | 0; + this.v5 = IV2[5] | 0; + this.v6 = IV2[6] | 0; + this.v7 = IV2[7] | 0; + const keyLength = opts.key ? opts.key.length : 0; + this.v0 ^= this.outputLen | (keyLength << 8) | (1 << 16) | (1 << 24); + if (opts.salt) { + const salt = u32(toBytes(opts.salt)); + this.v4 ^= salt[0]; + this.v5 ^= salt[1]; + } + if (opts.personalization) { + const pers = u32(toBytes(opts.personalization)); + this.v6 ^= pers[0]; + this.v7 ^= pers[1]; + } + if (opts.key) { + const tmp = new Uint8Array(this.blockLen); + tmp.set(toBytes(opts.key)); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = fromBig(BigInt(this.length)); + const { + v0, + v1, + v2, + v3, + v4, + v5, + v6, + v7, + v8, + v9, + v10, + v11, + v12, + v13, + v14, + v15, + } = compress( + SIGMA, + offset, + msg, + 10, + this.v0, + this.v1, + this.v2, + this.v3, + this.v4, + this.v5, + this.v6, + this.v7, + IV2[0], + IV2[1], + IV2[2], + IV2[3], + l ^ IV2[4], + h ^ IV2[5], + isLast ? ~IV2[6] : IV2[6], + IV2[7], + ); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + this.buffer32.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } + }; + var blake2s = /* @__PURE__ */ wrapConstructorWithOpts( + (opts) => new BLAKE2s(opts), + ); + + // ../esm/blake3.js + var SIGMA2 = /* @__PURE__ */ (() => { + const Id2 = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => + [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id2; i < 7; i++, v = permute(v)) res.push(...v); + return Uint8Array.from(res); + })(); + var BLAKE3 = class _BLAKE3 extends BLAKE2 { + constructor(opts = {}, flags = 0) { + super( + 64, + opts.dkLen === void 0 ? 32 : opts.dkLen, + {}, + Number.MAX_SAFE_INTEGER, + 0, + 0, + ); + this.flags = 0 | 0; + this.chunkPos = 0; + this.chunksDone = 0; + this.stack = []; + this.posOut = 0; + this.bufferOut32 = new Uint32Array(16); + this.chunkOut = 0; + this.enableXOF = true; + this.outputLen = opts.dkLen === void 0 ? 32 : opts.dkLen; + number(this.outputLen); + if (opts.key !== void 0 && opts.context !== void 0) + throw new Error( + "Blake3: only key or context can be specified at same time", + ); + else if (opts.key !== void 0) { + const key = toBytes(opts.key).slice(); + if (key.length !== 32) throw new Error("Blake3: key should be 32 byte"); + this.IV = u32(key); + this.flags = flags | 16; + } else if (opts.context !== void 0) { + const context_key = new _BLAKE3( + { dkLen: 32 }, + 32, + /* Flags.DERIVE_KEY_CONTEXT */ + ) + .update(opts.context) + .digest(); + this.IV = u32(context_key); + this.flags = flags | 64; + } else { + this.IV = IV2.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // Unused + get() { + return []; + } + set() {} + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = fromBig(BigInt(counter), true); + const { + v0, + v1, + v2, + v3, + v4, + v5, + v6, + v7, + v8, + v9, + v10, + v11, + v12, + v13, + v14, + v15, + } = compress( + SIGMA2, + bufPos, + buf, + 7, + s[0], + s[1], + s[2], + s[3], + s[4], + s[5], + s[6], + s[7], + IV2[0], + IV2[1], + IV2[2], + IV2[3], + h, + l, + pos, + flags, + ); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + let flags = this.flags; + if (!this.chunkPos) flags |= 1; + if (this.chunkPos === 15 || isLast) flags |= 2; + if (!isLast) this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + for ( + let last, chunks = this.chunksDone + 1; + isLast || !(chunks & 1); + chunks >>= 1 + ) { + if (!(last = this.stack.pop())) break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | 4, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { + IV: IV5, + flags, + state, + chunkPos, + posOut, + chunkOut, + stack, + chunksDone, + } = this; + to.state.set(state.slice()); + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV5); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + this.state.fill(0); + this.buffer32.fill(0); + this.IV.fill(0); + this.bufferOut32.fill(0); + for (let i of this.stack) i.fill(0); + } + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = fromBig(BigInt(this.chunkOut++)); + const { + v0, + v1, + v2, + v3, + v4, + v5, + v6, + v7, + v8, + v9, + v10, + v11, + v12, + v13, + v14, + v15, + } = compress( + SIGMA2, + 0, + buffer32, + 7, + s[0], + s[1], + s[2], + s[3], + s[4], + s[5], + s[6], + s[7], + IV2[0], + IV2[1], + IV2[2], + IV2[3], + l, + h, + pos, + flags, + ); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + this.posOut = 0; + } + finish() { + if (this.finished) return; + this.finished = true; + this.buffer.fill(0, this.pos); + let flags = this.flags | 8; + if (this.stack.length) { + flags |= 4; + this.compress(this.buffer32, 0, true); + this.chunksDone = 0; + this.pos = this.blockLen; + } else { + flags |= (!this.chunkPos ? 1 : 0) | 2; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error("XOF is not possible after digest call"); + return this.writeInto(out); + } + xof(bytes2) { + number(bytes2); + return this.xofInto(new Uint8Array(bytes2)); + } + digestInto(out) { + output(out, this); + if (this.finished) throw new Error("digest() was already called"); + this.enableXOF = false; + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + }; + var blake3 = /* @__PURE__ */ wrapXOFConstructorWithOpts( + (opts) => new BLAKE3(opts), + ); + + // ../esm/hmac.js + var HMAC = class extends Hash { + constructor(hash2, _key) { + super(); + this.finished = false; + this.destroyed = false; + hash(hash2); + const key = toBytes(_key); + this.iHash = hash2.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + pad.set( + key.length > blockLen ? hash2.create().update(key).digest() : key, + ); + for (let i = 0; i < pad.length; i++) pad[i] ^= 54; + this.iHash.update(pad); + this.oHash = hash2.create(); + for (let i = 0; i < pad.length; i++) pad[i] ^= 54 ^ 92; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + exists(this); + bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } + }; + var hmac = (hash2, key, message) => + new HMAC(hash2, key).update(message).digest(); + hmac.create = (hash2, key) => new HMAC(hash2, key); + + // ../esm/hkdf.js + function extract(hash2, ikm, salt) { + hash(hash2); + if (salt === void 0) salt = new Uint8Array(hash2.outputLen); + return hmac(hash2, toBytes(salt), toBytes(ikm)); + } + var HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]); + var EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array(); + function expand(hash2, prk, info, length = 32) { + hash(hash2); + number(length); + if (length > 255 * hash2.outputLen) + throw new Error("Length should be <= 255*HashLen"); + const blocks = Math.ceil(length / hash2.outputLen); + if (info === void 0) info = EMPTY_BUFFER; + const okm = new Uint8Array(blocks * hash2.outputLen); + const HMAC2 = hmac.create(hash2, prk); + const HMACTmp = HMAC2._cloneInto(); + const T = new Uint8Array(HMAC2.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, hash2.outputLen * counter); + HMAC2._cloneInto(HMACTmp); + } + HMAC2.destroy(); + HMACTmp.destroy(); + T.fill(0); + HKDF_COUNTER.fill(0); + return okm.slice(0, length); + } + var hkdf = (hash2, ikm, salt, info, length) => + expand(hash2, extract(hash2, ikm, salt), info, length); + + // ../esm/pbkdf2.js + function pbkdf2Init(hash2, _password, _salt, _opts) { + hash(hash2); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + number(c); + number(dkLen); + number(asyncTick); + if (c < 1) throw new Error("PBKDF2: iterations (c) should be >= 1"); + const password = toBytes(_password); + const salt = toBytes(_salt); + const DK = new Uint8Array(dkLen); + const PRF = hmac.create(hash2, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; + } + function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) prfW.destroy(); + u.fill(0); + return DK; + } + function pbkdf2(hash2, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init( + hash2, + password, + salt, + opts, + ); + let prfW; + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); + } + async function pbkdf2Async(hash2, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init( + hash2, + password, + salt, + opts, + ); + let prfW; + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, () => { + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); + } + + // ../esm/_sha2.js + function setBigUint64(view, byteOffset, value, isLE2) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE2); + const _32n2 = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number((value >> _32n2) & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE2 ? 4 : 0; + const l = isLE2 ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE2); + view.setUint32(byteOffset + l, wl, isLE2); + } + var SHA2 = class extends Hash { + constructor(blockLen, outputLen, padOffset, isLE2) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE2; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + const { buffer, view, blockLen, isLE: isLE2 } = this; + let { pos } = this; + buffer[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) buffer[i] = 0; + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE2); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) to.buffer.set(buffer); + return to; + } + }; + + // ../esm/ripemd160.js + var Rho = /* @__PURE__ */ new Uint8Array([ + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + ]); + var Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); + var Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); + var idxL = [Id]; + var idxR = [Pi]; + for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) j.push(j[i].map((k) => Rho[k])); + var shifts = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], + ].map((i) => new Uint8Array(i)); + var shiftsL = /* @__PURE__ */ idxL.map((idx, i) => + idx.map((j) => shifts[i][j]), + ); + var shiftsR = /* @__PURE__ */ idxR.map((idx, i) => + idx.map((j) => shifts[i][j]), + ); + var Kl = /* @__PURE__ */ new Uint32Array([ + 0, 1518500249, 1859775393, 2400959708, 2840853838, + ]); + var Kr = /* @__PURE__ */ new Uint32Array([ + 1352829926, 1548603684, 1836072691, 2053994217, 0, + ]); + var rotl = (word, shift) => (word << shift) | (word >>> (32 - shift)); + function f(group, x, y, z) { + if (group === 0) return x ^ y ^ z; + else if (group === 1) return (x & y) | (~x & z); + else if (group === 2) return (x | ~y) ^ z; + else if (group === 3) return (x & z) | (y & ~z); + else return x ^ (y | ~z); + } + var BUF2 = /* @__PURE__ */ new Uint32Array(16); + var RIPEMD160 = class extends SHA2 { + constructor() { + super(64, 20, 8, true); + this.h0 = 1732584193 | 0; + this.h1 = 4023233417 | 0; + this.h2 = 2562383102 | 0; + this.h3 = 271733878 | 0; + this.h4 = 3285377520 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF2[i] = view.getUint32(offset, true); + let al = this.h0 | 0, + ar = al, + bl = this.h1 | 0, + br = bl, + cl = this.h2 | 0, + cr = cl, + dl = this.h3 | 0, + dr = dl, + el = this.h4 | 0, + er = el; + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], + hbr = Kr[group]; + const rl = idxL[group], + rr = idxR[group]; + const sl = shiftsL[group], + sr = shiftsR[group]; + for (let i = 0; i < 16; i++) { + const tl = + (rotl(al + f(group, bl, cl, dl) + BUF2[rl[i]] + hbl, sl[i]) + el) | + 0; + (al = el), (el = dl), (dl = rotl(cl, 10) | 0), (cl = bl), (bl = tl); + } + for (let i = 0; i < 16; i++) { + const tr = + (rotl(ar + f(rGroup, br, cr, dr) + BUF2[rr[i]] + hbr, sr[i]) + er) | + 0; + (ar = er), (er = dr), (dr = rotl(cr, 10) | 0), (cr = br), (br = tr); + } + } + this.set( + (this.h1 + cl + dr) | 0, + (this.h2 + dl + er) | 0, + (this.h3 + el + ar) | 0, + (this.h4 + al + br) | 0, + (this.h0 + bl + cr) | 0, + ); + } + roundClean() { + BUF2.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } + }; + var ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); + + // ../esm/sha256.js + var Chi = (a, b, c) => (a & b) ^ (~a & c); + var Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); + var SHA256_K = /* @__PURE__ */ new Uint32Array([ + 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, + 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, + 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, + 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, + 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, + 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, + 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, + 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, + 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, + 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, + 2428436474, 2756734187, 3204031479, 3329325298, + ]); + var IV3 = /* @__PURE__ */ new Uint32Array([ + 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, + 528734635, 1541459225, + ]); + var SHA256_W = /* @__PURE__ */ new Uint32Array(64); + var SHA256 = class extends SHA2 { + constructor() { + super(64, 32, 8, false); + this.A = IV3[0] | 0; + this.B = IV3[1] | 0; + this.C = IV3[2] | 0; + this.D = IV3[3] | 0; + this.E = IV3[4] | 0; + this.F = IV3[5] | 0; + this.G = IV3[6] | 0; + this.H = IV3[7] | 0; + } + get() { + const { A, B, C, D, E, F, G: G3, H } = this; + return [A, B, C, D, E, F, G3, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G3, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G3 | 0; + this.H = H | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + let { A, B, C, D, E, F, G: G3, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G3) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G3; + G3 = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G3 = (G3 + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G3, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } + }; + var sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); + + // ../esm/scrypt.js + var rotl2 = (a, b) => (a << b) | (a >>> (32 - b)); + function XorAndSalsa(prev, pi, input, ii, out, oi) { + let y00 = prev[pi++] ^ input[ii++], + y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], + y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], + y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], + y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], + y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], + y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], + y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], + y15 = prev[pi++] ^ input[ii++]; + let x00 = y00, + x01 = y01, + x02 = y02, + x03 = y03, + x04 = y04, + x05 = y05, + x06 = y06, + x07 = y07, + x08 = y08, + x09 = y09, + x10 = y10, + x11 = y11, + x12 = y12, + x13 = y13, + x14 = y14, + x15 = y15; + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl2((x00 + x12) | 0, 7); + x08 ^= rotl2((x04 + x00) | 0, 9); + x12 ^= rotl2((x08 + x04) | 0, 13); + x00 ^= rotl2((x12 + x08) | 0, 18); + x09 ^= rotl2((x05 + x01) | 0, 7); + x13 ^= rotl2((x09 + x05) | 0, 9); + x01 ^= rotl2((x13 + x09) | 0, 13); + x05 ^= rotl2((x01 + x13) | 0, 18); + x14 ^= rotl2((x10 + x06) | 0, 7); + x02 ^= rotl2((x14 + x10) | 0, 9); + x06 ^= rotl2((x02 + x14) | 0, 13); + x10 ^= rotl2((x06 + x02) | 0, 18); + x03 ^= rotl2((x15 + x11) | 0, 7); + x07 ^= rotl2((x03 + x15) | 0, 9); + x11 ^= rotl2((x07 + x03) | 0, 13); + x15 ^= rotl2((x11 + x07) | 0, 18); + x01 ^= rotl2((x00 + x03) | 0, 7); + x02 ^= rotl2((x01 + x00) | 0, 9); + x03 ^= rotl2((x02 + x01) | 0, 13); + x00 ^= rotl2((x03 + x02) | 0, 18); + x06 ^= rotl2((x05 + x04) | 0, 7); + x07 ^= rotl2((x06 + x05) | 0, 9); + x04 ^= rotl2((x07 + x06) | 0, 13); + x05 ^= rotl2((x04 + x07) | 0, 18); + x11 ^= rotl2((x10 + x09) | 0, 7); + x08 ^= rotl2((x11 + x10) | 0, 9); + x09 ^= rotl2((x08 + x11) | 0, 13); + x10 ^= rotl2((x09 + x08) | 0, 18); + x12 ^= rotl2((x15 + x14) | 0, 7); + x13 ^= rotl2((x12 + x15) | 0, 9); + x14 ^= rotl2((x13 + x12) | 0, 13); + x15 ^= rotl2((x14 + x13) | 0, 18); + } + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; + } + function BlockMix(input, ii, out, oi, r) { + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; + for (let i = 0; i < r; i++, head += 16, ii += 16) { + XorAndSalsa(out, tail, input, ii, out, head); + if (i > 0) tail += 16; + XorAndSalsa(out, head, input, (ii += 16), out, tail); + } + } + function scryptInit(password, salt, _opts) { + const opts = checkOpts( + { + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, + _opts, + ); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + number(N); + number(r); + number(p); + number(dkLen); + number(asyncTick); + number(maxmem); + if (onProgress !== void 0 && typeof onProgress !== "function") + throw new Error("progressCb should be function"); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if ( + N <= 1 || + (N & (N - 1)) !== 0 || + N >= 2 ** (blockSize / 8) || + N > 2 ** 32 + ) { + throw new Error( + "Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32", + ); + } + if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { + throw new Error( + "Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)", + ); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error( + "Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32", + ); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error( + `Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`, + ); + } + const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => {}; + if (onProgress) { + const totalBlockMix = 2 * N * p; + const callbackPer = Math.max(Math.floor(totalBlockMix / 1e4), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if ( + onProgress && + (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix) + ) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { + N, + r, + p, + dkLen, + blockSize32, + V, + B32, + B, + tmp, + blockMixCb, + asyncTick, + }; + } + function scryptOutput(password, dkLen, B, V, tmp) { + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; + } + function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = + scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi2 = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi2 + i]; + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi2, r); + blockMixCb(); + for (let i = 0; i < N; i++) { + const j = B32[Pi2 + blockSize32 - 16] % N; + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi2 + k] ^ V[j * blockSize32 + k]; + BlockMix(tmp, 0, B32, Pi2, r); + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); + } + async function scryptAsync(password, salt, opts) { + const { + N, + r, + p, + dkLen, + blockSize32, + V, + B32, + B, + tmp, + blockMixCb, + asyncTick, + } = scryptInit(password, salt, opts); + for (let pi = 0; pi < p; pi++) { + const Pi2 = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi2 + i]; + let pos = 0; + await asyncLoop(N - 1, asyncTick, () => { + BlockMix(V, pos, V, (pos += blockSize32), r); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi2, r); + blockMixCb(); + await asyncLoop(N, asyncTick, () => { + const j = B32[Pi2 + blockSize32 - 16] % N; + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi2 + k] ^ V[j * blockSize32 + k]; + BlockMix(tmp, 0, B32, Pi2, r); + blockMixCb(); + }); + } + return scryptOutput(password, dkLen, B, V, tmp); + } + + // ../esm/sha512.js + var [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => + u64_default.split( + [ + "0x428a2f98d728ae22", + "0x7137449123ef65cd", + "0xb5c0fbcfec4d3b2f", + "0xe9b5dba58189dbbc", + "0x3956c25bf348b538", + "0x59f111f1b605d019", + "0x923f82a4af194f9b", + "0xab1c5ed5da6d8118", + "0xd807aa98a3030242", + "0x12835b0145706fbe", + "0x243185be4ee4b28c", + "0x550c7dc3d5ffb4e2", + "0x72be5d74f27b896f", + "0x80deb1fe3b1696b1", + "0x9bdc06a725c71235", + "0xc19bf174cf692694", + "0xe49b69c19ef14ad2", + "0xefbe4786384f25e3", + "0x0fc19dc68b8cd5b5", + "0x240ca1cc77ac9c65", + "0x2de92c6f592b0275", + "0x4a7484aa6ea6e483", + "0x5cb0a9dcbd41fbd4", + "0x76f988da831153b5", + "0x983e5152ee66dfab", + "0xa831c66d2db43210", + "0xb00327c898fb213f", + "0xbf597fc7beef0ee4", + "0xc6e00bf33da88fc2", + "0xd5a79147930aa725", + "0x06ca6351e003826f", + "0x142929670a0e6e70", + "0x27b70a8546d22ffc", + "0x2e1b21385c26c926", + "0x4d2c6dfc5ac42aed", + "0x53380d139d95b3df", + "0x650a73548baf63de", + "0x766a0abb3c77b2a8", + "0x81c2c92e47edaee6", + "0x92722c851482353b", + "0xa2bfe8a14cf10364", + "0xa81a664bbc423001", + "0xc24b8b70d0f89791", + "0xc76c51a30654be30", + "0xd192e819d6ef5218", + "0xd69906245565a910", + "0xf40e35855771202a", + "0x106aa07032bbd1b8", + "0x19a4c116b8d2d0c8", + "0x1e376c085141ab53", + "0x2748774cdf8eeb99", + "0x34b0bcb5e19b48a8", + "0x391c0cb3c5c95a63", + "0x4ed8aa4ae3418acb", + "0x5b9cca4f7763e373", + "0x682e6ff3d6b2b8a3", + "0x748f82ee5defb2fc", + "0x78a5636f43172f60", + "0x84c87814a1f0ab72", + "0x8cc702081a6439ec", + "0x90befffa23631e28", + "0xa4506cebde82bde9", + "0xbef9a3f7b2c67915", + "0xc67178f2e372532b", + "0xca273eceea26619c", + "0xd186b8c721c0c207", + "0xeada7dd6cde0eb1e", + "0xf57d4f7fee6ed178", + "0x06f067aa72176fba", + "0x0a637dc5a2c898a6", + "0x113f9804bef90dae", + "0x1b710b35131c471b", + "0x28db77f523047d84", + "0x32caab7b40c72493", + "0x3c9ebe0a15c9bebc", + "0x431d67c49c100d4c", + "0x4cc5d4becb3e42b6", + "0x597f299cfc657e2a", + "0x5fcb6fab3ad6faec", + "0x6c44198c4a475817", + ].map((n) => BigInt(n)), + ))(); + var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); + var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); + var SHA512 = class extends SHA2 { + constructor() { + super(128, 64, 16, false); + this.Ah = 1779033703 | 0; + this.Al = 4089235720 | 0; + this.Bh = 3144134277 | 0; + this.Bl = 2227873595 | 0; + this.Ch = 1013904242 | 0; + this.Cl = 4271175723 | 0; + this.Dh = 2773480762 | 0; + this.Dl = 1595750129 | 0; + this.Eh = 1359893119 | 0; + this.El = 2917565137 | 0; + this.Fh = 2600822924 | 0; + this.Fl = 725511199 | 0; + this.Gh = 528734635 | 0; + this.Gl = 4215389547 | 0; + this.Hh = 1541459225 | 0; + this.Hl = 327033209 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = + u64_default.rotrSH(W15h, W15l, 1) ^ + u64_default.rotrSH(W15h, W15l, 8) ^ + u64_default.shrSH(W15h, W15l, 7); + const s0l = + u64_default.rotrSL(W15h, W15l, 1) ^ + u64_default.rotrSL(W15h, W15l, 8) ^ + u64_default.shrSL(W15h, W15l, 7); + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = + u64_default.rotrSH(W2h, W2l, 19) ^ + u64_default.rotrBH(W2h, W2l, 61) ^ + u64_default.shrSH(W2h, W2l, 6); + const s1l = + u64_default.rotrSL(W2h, W2l, 19) ^ + u64_default.rotrBL(W2h, W2l, 61) ^ + u64_default.shrSL(W2h, W2l, 6); + const SUMl = u64_default.add4L( + s0l, + s1l, + SHA512_W_L[i - 7], + SHA512_W_L[i - 16], + ); + const SUMh = u64_default.add4H( + SUMl, + s0h, + s1h, + SHA512_W_H[i - 7], + SHA512_W_H[i - 16], + ); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = + this; + for (let i = 0; i < 80; i++) { + const sigma1h = + u64_default.rotrSH(Eh, El, 14) ^ + u64_default.rotrSH(Eh, El, 18) ^ + u64_default.rotrBH(Eh, El, 41); + const sigma1l = + u64_default.rotrSL(Eh, El, 14) ^ + u64_default.rotrSL(Eh, El, 18) ^ + u64_default.rotrBL(Eh, El, 41); + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + const T1ll = u64_default.add5L( + Hl, + sigma1l, + CHIl, + SHA512_Kl[i], + SHA512_W_L[i], + ); + const T1h = u64_default.add5H( + T1ll, + Hh, + sigma1h, + CHIh, + SHA512_Kh[i], + SHA512_W_H[i], + ); + const T1l = T1ll | 0; + const sigma0h = + u64_default.rotrSH(Ah, Al, 28) ^ + u64_default.rotrBH(Ah, Al, 34) ^ + u64_default.rotrBH(Ah, Al, 39); + const sigma0l = + u64_default.rotrSL(Ah, Al, 28) ^ + u64_default.rotrBL(Ah, Al, 34) ^ + u64_default.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64_default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64_default.add3L(T1l, sigma0l, MAJl); + Ah = u64_default.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + ({ h: Ah, l: Al } = u64_default.add( + this.Ah | 0, + this.Al | 0, + Ah | 0, + Al | 0, + )); + ({ h: Bh, l: Bl } = u64_default.add( + this.Bh | 0, + this.Bl | 0, + Bh | 0, + Bl | 0, + )); + ({ h: Ch, l: Cl } = u64_default.add( + this.Ch | 0, + this.Cl | 0, + Ch | 0, + Cl | 0, + )); + ({ h: Dh, l: Dl } = u64_default.add( + this.Dh | 0, + this.Dl | 0, + Dh | 0, + Dl | 0, + )); + ({ h: Eh, l: El } = u64_default.add( + this.Eh | 0, + this.El | 0, + Eh | 0, + El | 0, + )); + ({ h: Fh, l: Fl } = u64_default.add( + this.Fh | 0, + this.Fl | 0, + Fh | 0, + Fl | 0, + )); + ({ h: Gh, l: Gl } = u64_default.add( + this.Gh | 0, + this.Gl | 0, + Gh | 0, + Gl | 0, + )); + ({ h: Hh, l: Hl } = u64_default.add( + this.Hh | 0, + this.Hl | 0, + Hh | 0, + Hl | 0, + )); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } + }; + var sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); + + // ../esm/sha3.js + var [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; + var _0n = /* @__PURE__ */ BigInt(0); + var _1n = /* @__PURE__ */ BigInt(1); + var _2n = /* @__PURE__ */ BigInt(2); + var _7n = /* @__PURE__ */ BigInt(7); + var _256n = /* @__PURE__ */ BigInt(256); + var _0x71n = /* @__PURE__ */ BigInt(113); + for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); + } + var [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); + var rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); + var rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); + function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + for (let round = 24 - rounds; round < 24; round++) { + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 10; x++) B[x] = s[y + x]; + for (let x = 0; x < 10; x++) + s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); + } + var Keccak = class _Keccak extends Hash { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + number(outputLen); + if (0 >= this.blockLen || this.blockLen >= 200) + throw new Error("Sha3 supports only keccak-f1600 function"); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) this.keccak(); + } + return this; + } + finish() { + if (this.finished) return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + state[pos] ^= suffix; + if ((suffix & 128) !== 0 && pos === blockLen - 1) this.keccak(); + state[blockLen - 1] ^= 128; + this.keccak(); + } + writeInto(out) { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error("XOF is not possible for this instance"); + return this.writeInto(out); + } + xof(bytes2) { + number(bytes2); + return this.xofInto(new Uint8Array(bytes2)); + } + digestInto(out) { + output(out, this); + if (this.finished) throw new Error("digest() was already called"); + this.writeInto(out); + this.destroy(); + return out; + } + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); + } + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } + }; + var gen = (suffix, blockLen, outputLen) => + wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); + var sha3_224 = /* @__PURE__ */ gen(6, 144, 224 / 8); + var sha3_256 = /* @__PURE__ */ gen(6, 136, 256 / 8); + var sha3_384 = /* @__PURE__ */ gen(6, 104, 384 / 8); + var sha3_512 = /* @__PURE__ */ gen(6, 72, 512 / 8); + var keccak_224 = /* @__PURE__ */ gen(1, 144, 224 / 8); + var keccak_256 = /* @__PURE__ */ gen(1, 136, 256 / 8); + var keccak_384 = /* @__PURE__ */ gen(1, 104, 384 / 8); + var keccak_512 = /* @__PURE__ */ gen(1, 72, 512 / 8); + var genShake = (suffix, blockLen, outputLen) => + wrapXOFConstructorWithOpts( + (opts = {}) => + new Keccak( + blockLen, + suffix, + opts.dkLen === void 0 ? outputLen : opts.dkLen, + true, + ), + ); + var shake128 = /* @__PURE__ */ genShake(31, 168, 128 / 8); + var shake256 = /* @__PURE__ */ genShake(31, 136, 256 / 8); + + // ../esm/sha3-addons.js + function leftEncode(n) { + const res = [n & 255]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 255); + res.unshift(res.length); + return new Uint8Array(res); + } + function rightEncode(n) { + const res = [n & 255]; + n >>= 8; + for (; n > 0; n >>= 8) res.unshift(n & 255); + res.push(res.length); + return new Uint8Array(res); + } + function chooseLen(opts, outputLen) { + return opts.dkLen === void 0 ? outputLen : opts.dkLen; + } + var toBytesOptional = (buf) => + buf !== void 0 ? toBytes(buf) : new Uint8Array([]); + var getPadding = (len, block2) => + new Uint8Array((block2 - (len % block2)) % block2); + function cshakePers(hash2, opts = {}) { + if (!opts || (!opts.personalization && !opts.NISTfn)) return hash2; + const blockLenBytes = leftEncode(hash2.blockLen); + const fn = toBytesOptional(opts.NISTfn); + const fnLen = leftEncode(8 * fn.length); + const pers = toBytesOptional(opts.personalization); + const persLen = leftEncode(8 * pers.length); + if (!fn.length && !pers.length) return hash2; + hash2.suffix = 4; + hash2 + .update(blockLenBytes) + .update(fnLen) + .update(fn) + .update(persLen) + .update(pers); + let totalLen = + blockLenBytes.length + + fnLen.length + + fn.length + + persLen.length + + pers.length; + hash2.update(getPadding(totalLen, hash2.blockLen)); + return hash2; + } + var gencShake = (suffix, blockLen, outputLen) => + wrapConstructorWithOpts((opts = {}) => + cshakePers( + new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), + opts, + ), + ); + var cshake128 = /* @__PURE__ */ (() => gencShake(31, 168, 128 / 8))(); + var cshake256 = /* @__PURE__ */ (() => gencShake(31, 136, 256 / 8))(); + var KMAC = class extends Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 31, outputLen, enableXOF); + cshakePers(this, { + NISTfn: "KMAC", + personalization: opts.personalization, + }); + key = toBytes(key); + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(8 * key.length); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); + super.finish(); + } + _cloneInto(to) { + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } + }; + function genKmac(blockLen, outputLen, xof = false) { + const kmac = (key, message, opts) => + kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => + new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; + } + var kmac128 = /* @__PURE__ */ (() => genKmac(168, 128 / 8))(); + var kmac256 = /* @__PURE__ */ (() => genKmac(136, 256 / 8))(); + function rightEncodeK12(n) { + const res = []; + for (; n > 0; n >>= 8) res.unshift(n & 255); + res.push(res.length); + return new Uint8Array(res); + } + var EMPTY = new Uint8Array([]); + var KangarooTwelve = class _KangarooTwelve extends Keccak { + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 7, outputLen, true, rounds); + this.leafLen = leafLen; + this.chunkLen = 8192; + this.chunkPos = 0; + this.chunksDone = 0; + const { personalization } = opts; + this.personalization = toBytesOptional(personalization); + } + update(data) { + data = toBytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) super.update(this.leafHash.digest()); + else { + this.suffix = 6; + super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); + } + this.leafHash = new Keccak(blockLen, 11, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) this.leafHash.update(chunk); + else super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) return; + const { personalization } = this; + this.update(personalization).update( + rightEncodeK12(personalization.length), + ); + if (this.leafHash) { + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(new Uint8Array([255, 255])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + this.personalization = EMPTY; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + to || + (to = new _KangarooTwelve(blockLen, leafLen, outputLen, rounds, {})); + super._cloneInto(to); + if (leafHash) to.leafHash = leafHash._cloneInto(to.leafHash); + to.personalization.set(this.personalization); + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } + }; + var k12 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts), + ))(); + var m14 = /* @__PURE__ */ (() => + wrapConstructorWithOpts( + (opts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts), + ))(); + + // ../esm/sha1.js + var rotl3 = (word, shift) => + (word << shift) | ((word >>> (32 - shift)) >>> 0); + var Chi2 = (a, b, c) => (a & b) ^ (~a & c); + var Maj2 = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); + var IV4 = /* @__PURE__ */ new Uint32Array([ + 1732584193, 4023233417, 2562383102, 271733878, 3285377520, + ]); + var SHA1_W = /* @__PURE__ */ new Uint32Array(80); + var SHA1 = class extends SHA2 { + constructor() { + super(64, 20, 8, false); + this.A = IV4[0] | 0; + this.B = IV4[1] | 0; + this.C = IV4[2] | 0; + this.D = IV4[3] | 0; + this.E = IV4[4] | 0; + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl3( + SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], + 1, + ); + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi2(B, C, D); + K = 1518500249; + } else if (i < 40) { + F = B ^ C ^ D; + K = 1859775393; + } else if (i < 60) { + F = Maj2(B, C, D); + K = 2400959708; + } else { + F = B ^ C ^ D; + K = 3395469782; + } + const T = (rotl3(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl3(B, 30); + B = A; + A = T; + } + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + SHA1_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0); + this.buffer.fill(0); + } + }; + var sha1 = /* @__PURE__ */ wrapConstructor(() => new SHA1()); + + // ../esm/argon2.js + var ARGON2_SYNC_POINTS = 4; + var toBytesOptional2 = (buf) => + buf !== void 0 ? toBytes(buf) : new Uint8Array([]); + function mul(a, b) { + const aL = a & 65535; + const aH = a >>> 16; + const bL = b & 65535; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const BUF4 = ((ll >>> 16) + (hl & 65535) + lh) | 0; + const h = ((hl >>> 16) + (BUF4 >>> 16) + hh) | 0; + return { h, l: (BUF4 << 16) | (ll & 65535) }; + } + function relPos(areaSize, relativePos) { + return areaSize - 1 - mul(areaSize, mul(relativePos, relativePos).h).h; + } + function mul2(a, b) { + const { h, l } = mul(a, b); + return { + h: ((h << 1) | (l >>> 31)) & 4294967295, + l: (l << 1) & 4294967295, + }; + } + function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + const Rll = add3L(Al, Bl, Cl); + return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; + } + var BUF3 = new Uint32Array(256); + function G(a, b, c, d) { + let Al = BUF3[2 * a], + Ah = BUF3[2 * a + 1]; + let Bl = BUF3[2 * b], + Bh = BUF3[2 * b + 1]; + let Cl = BUF3[2 * c], + Ch = BUF3[2 * c + 1]; + let Dl = BUF3[2 * d], + Dh = BUF3[2 * d + 1]; + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) }); + (BUF3[2 * a] = Al), (BUF3[2 * a + 1] = Ah); + (BUF3[2 * b] = Bl), (BUF3[2 * b + 1] = Bh); + (BUF3[2 * c] = Cl), (BUF3[2 * c + 1] = Ch); + (BUF3[2 * d] = Dl), (BUF3[2 * d + 1] = Dh); + } + function P( + v00, + v01, + v02, + v03, + v04, + v05, + v06, + v07, + v08, + v09, + v10, + v11, + v12, + v13, + v14, + v15, + ) { + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); + } + function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) BUF3[i] = x[xPos + i] ^ x[yPos + i]; + for (let i = 0; i < 128; i += 16) { + P( + i, + i + 1, + i + 2, + i + 3, + i + 4, + i + 5, + i + 6, + i + 7, + i + 8, + i + 9, + i + 10, + i + 11, + i + 12, + i + 13, + i + 14, + i + 15, + ); + } + for (let i = 0; i < 16; i += 2) { + P( + i, + i + 1, + i + 16, + i + 17, + i + 32, + i + 33, + i + 48, + i + 49, + i + 64, + i + 65, + i + 80, + i + 81, + i + 96, + i + 97, + i + 112, + i + 113, + ); + } + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= BUF3[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = BUF3[i] ^ x[xPos + i] ^ x[yPos + i]; + } + function Hp(A, dkLen) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + T[0] = dkLen; + if (dkLen <= 64) + return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + out.set(V.subarray(0, 32)); + pos += 32; + for (; dkLen - pos > 64; pos += 32) + out.set((V = blake2b(V)).subarray(0, 32), pos); + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + return u32(out); + } + function indexAlpha( + r, + s, + laneLen, + segmentLen, + index, + randL, + sameLane = false, + ) { + let area; + if (0 == r) { + if (0 == s) area = index - 1; + else if (sameLane) area = s * segmentLen + index - 1; + else area = s * segmentLen + (index == 0 ? -1 : 0); + } else if (sameLane) area = laneLen - segmentLen + index - 1; + else area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = + r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + const rel = relPos(area, randL); + return (startPos + rel) % laneLen; + } + function argon2Init(type, password, salt, opts) { + password = toBytes(password); + salt = toBytes(salt); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress } = + { + ...opts, + version: opts.version || 19, + dkLen: opts.dkLen || 32, + maxmem: 2 ** 32, + }; + number(p); + number(dkLen); + number(m); + number(t); + number(version); + if (dkLen < 4 || dkLen >= 2 ** 32) + throw new Error("Argon2: dkLen should be at least 4 bytes"); + if (p < 1 || p >= 2 ** 32) + throw new Error("Argon2: p (parallelism) should be at least 1"); + if (t < 1 || t >= 2 ** 32) + throw new Error("Argon2: t (iterations) should be at least 1"); + if (m < 8 * p) + throw new Error(`Argon2: memory should be at least 8*p bytes`); + if (version !== 16 && version !== 19) + throw new Error(`Argon2: unknown version=${version}`); + password = toBytes(password); + if (password.length < 0 || password.length >= 2 ** 32) + throw new Error("Argon2: password should be less than 4 GB"); + salt = toBytes(salt); + if (salt.length < 8) + throw new Error("Argon2: salt should be at least 8 bytes"); + key = toBytesOptional2(key); + personalization = toBytesOptional2(personalization); + if (onProgress !== void 0 && typeof onProgress !== "function") + throw new Error("progressCb should be function"); + const lanes = p; + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + const h = blake2b.create({}); + const BUF4 = new Uint32Array(1); + const BUF8 = u8(BUF4); + for (const i of [p, dkLen, m, t, version, type]) { + if (i < 0 || i >= 2 ** 32) + throw new Error(`Argon2: wrong parameter=${i}, expected uint32`); + BUF4[0] = i; + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF4[0] = i.length; + h.update(BUF8).update(i); + } + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + const memUsed = mP * 256; + if (memUsed < 0 || memUsed >= 2 ** 32 || memUsed > maxmem) { + throw new Error( + `Argon2: wrong params (memUsed=${memUsed} maxmem=${maxmem}), should be less than 2**32`, + ); + } + const B = new Uint32Array(memUsed); + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + H0[17] = l; + H0[16] = 0; + B.set(Hp(H0, 1024), i); + H0[16] = 1; + B.set(Hp(H0, 1024), i + 256); + } + let perBlock = () => {}; + if (onProgress) { + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen; + const callbackPer = Math.max(Math.floor(totalBlock / 1e4), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if ( + onProgress && + (!(blockCnt % callbackPer) || blockCnt === totalBlock) + ) + onProgress(blockCnt / totalBlock); + }; + } + return { + type, + mP, + p, + t, + version, + B, + laneLen, + lanes, + segmentLen, + dkLen, + perBlock, + }; + } + function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + return u8(Hp(B_final, dkLen)); + } + function processBlock( + B, + address, + l, + r, + s, + index, + laneLen, + segmentLen, + lanes, + offset, + prev, + dataIndependent, + needXor, + ) { + if (offset % laneLen) prev = offset - 1; + let randL, randH; + if (dataIndependent) { + if (index % 128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * (index % 128)]; + randH = address[2 * (index % 128) + 1]; + } else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha( + r, + s, + laneLen, + segmentLen, + index, + randL, + refLane == l, + ); + const refBlock = laneLen * refLane + refPos; + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); + } + function argon2(type, password, salt, opts) { + const { + mP, + p, + t, + version, + B, + laneLen, + lanes, + segmentLen, + dkLen, + perBlock, + } = argon2Init(type, password, salt, opts); + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + const needXor = r !== 0 && version === 19; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + const dataIndependent = type == 1 || (type == 2 && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + let offset = l * laneLen + s * segmentLen + startPos; + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for ( + let index = startPos; + index < segmentLen; + index++, offset++, prev++ + ) { + perBlock(); + processBlock( + B, + address, + l, + r, + s, + index, + laneLen, + segmentLen, + lanes, + offset, + prev, + dataIndependent, + needXor, + ); + } + } + } + } + return argon2Output(B, p, laneLen, dkLen); + } + var argon2id = (password, salt, opts) => argon2(2, password, salt, opts); + + // ../esm/eskdf.js + var SCRYPT_FACTOR = 2 ** 19; + var PBKDF2_FACTOR = 2 ** 17; + function scrypt2(password, salt) { + return scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); + } + function pbkdf22(password, salt) { + return pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); + } + function xor32(a, b) { + bytes(a, 32); + bytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; + } + function strHasLength(str, min, max) { + return typeof str === "string" && str.length >= min && str.length <= max; + } + function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) throw new Error("invalid username"); + if (!strHasLength(password, 8, 255)) throw new Error("invalid password"); + const scr = scrypt2(password + "", username + ""); + const pbk = pbkdf22(password + "", username + ""); + const res = xor32(scr, pbk); + scr.fill(0); + pbk.fill(0); + return res; + } + function getSaltInfo(protocol, accountId = 0) { + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error("invalid protocol"); + } + const allowsStr = /^password\d{0,3}|ssh|tor|file$/.test(protocol); + let salt; + if (typeof accountId === "string") { + if (!allowsStr) throw new Error("accountId must be a number"); + if (!strHasLength(accountId, 1, 255)) + throw new Error("accountId must be valid string"); + salt = toBytes(accountId); + } else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > 2 ** 32 - 1) + throw new Error("invalid accountId"); + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } else { + throw new Error( + `accountId must be a number${allowsStr ? " or string" : ""}`, + ); + } + const info = toBytes(protocol); + return { salt, info }; + } + function countBytes(num) { + if (typeof num !== "bigint" || num <= BigInt(128)) + throw new Error("invalid number"); + return Math.ceil(num.toString(2).length / 8); + } + function getKeyLength(options) { + if (!options || typeof options !== "object") return 32; + const hasLen = "keyLength" in options; + const hasMod = "modulus" in options; + if (hasLen && hasMod) + throw new Error("cannot combine keyLength and modulus options"); + if (!hasLen && !hasMod) + throw new Error("must have either keyLength or modulus option"); + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === "number" && l >= 16 && l <= 8192)) + throw new Error("invalid keyLength"); + return l; + } + function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt("0x" + bytesToHex(key)); + const res = (num % (modulus - _1)) + _1; + if (res < _1) throw new Error("expected positive number"); + const len = key.length - 8; + const hex = res.toString(16).padStart(len * 2, "0"); + const bytes2 = hexToBytes(hex); + if (bytes2.length !== len) throw new Error("invalid length of result key"); + return bytes2; + } + async function eskdf(username, password) { + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + bytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); + const keyLength = getKeyLength(options); + const key = hkdf(sha256, seed, salt, info, keyLength); + return options && "modulus" in options + ? modReduceKey(key, options.modulus) + : key; + } + function expire() { + if (seed) seed.fill(1); + seed = void 0; + } + const fingerprint = Array.from(deriveCK("fingerprint", 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, "0").toUpperCase()) + .join(":"); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); + } + + // input.js + var utils = { bytesToHex, randomBytes }; + return __toCommonJS(input_exports); +})(); +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ diff --git a/sw_scripts/safari-notifications.js b/sw_scripts/safari-notifications.js index be55d91..7a468c2 100644 --- a/sw_scripts/safari-notifications.js +++ b/sw_scripts/safari-notifications.js @@ -1,340 +1,346 @@ -async function generateSHA256Hash(data) { - const buffer = new TextEncoder().encode(data); - const hashBuffer = await crypto.subtle.digest("SHA-256", buffer); - const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array - const hashHex = hashArray - .map((byte) => byte.toString(16).padStart(2, "0")) - .join(""); - return hashHex; -} function bufferFromBase64(base64) { - const binaryString = atob(base64); - const length = binaryString.length; - const bytes = new Uint8Array(length); + const binaryString = atob(base64); + const length = binaryString.length; + const bytes = new Uint8Array(length); - for (let i = 0; i < length; i++) { - bytes[i] = binaryString.charCodeAt(i); - } + for (let i = 0; i < length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } - return bytes; + return bytes; } - function fromString(str, encoding = 'utf8') { - if (encoding === 'utf8') { - return new TextEncoder().encode(str); - } else if (encoding === 'base16') { - if (str.length % 2 !== 0) { - throw new Error('Invalid hex string length.'); - } - let bytes = new Uint8Array(str.length / 2); - for (let i = 0; i < str.length; i += 2) { - bytes[i/2] = parseInt(str.substring(i, i + 2), 16); - } - return bytes; - - } else if (encoding === 'base64url') { - str = str.replace(/-/g, '+').replace(/_/g, '/'); - while (str.length % 4) { - str += '='; - } - return new Uint8Array(bufferFromBase64(str)); - } else { - throw new Error(`Unsupported encoding "${encoding}"`); - } - } - - - /** - * Convert a Uint8Array to a string with the given encoding. - * - * @param {Uint8Array} byteArray - The Uint8Array to convert. - * @param {string} [encoding='utf8'] - The desired encoding ('utf8', 'base16', 'base64url'). - * @returns {string} - The encoded string. - * @throws {Error} - Throws an error if the encoding is unsupported. - */ - function toString(byteArray, encoding = 'utf8') { - switch (encoding) { - case 'utf8': - return decodeUTF8(byteArray); - case 'base16': - return toBase16(byteArray); - case 'base64url': - return toBase64Url(byteArray); - default: - throw new Error(`Unsupported encoding "${encoding}"`); - } - } - - /** - * Decode a Uint8Array as a UTF-8 string. - * - * @param {Uint8Array} byteArray - * @returns {string} - */ - function decodeUTF8(byteArray) { - return new TextDecoder().decode(byteArray); +function fromString(str, encoding = "utf8") { + if (encoding === "utf8") { + return new TextEncoder().encode(str); + } else if (encoding === "base16") { + if (str.length % 2 !== 0) { + throw new Error("Invalid hex string length."); } - - /** - * Convert a Uint8Array to a base16 (hex) encoded string. - * - * @param {Uint8Array} byteArray - * @returns {string} - */ - function toBase16(byteArray) { - return Array.from(byteArray).map(byte => byte.toString(16).padStart(2, '0')).join(''); + let bytes = new Uint8Array(str.length / 2); + for (let i = 0; i < str.length; i += 2) { + bytes[i / 2] = parseInt(str.substring(i, i + 2), 16); } - - /** - * Convert a Uint8Array to a base64url encoded string. - * - * @param {Uint8Array} byteArray - * @returns {string} - */ - function toBase64Url(byteArray) { - let uint8Array = new Uint8Array(byteArray); - let binaryString = ''; - for (let i = 0; i < uint8Array.length; i++) { - binaryString += String.fromCharCode(uint8Array[i]); - } - - // Encode to base64 - let base64 = btoa(binaryString); - - return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); + return bytes; + } else if (encoding === "base64url") { + str = str.replace(/-/g, "+").replace(/_/g, "/"); + while (str.length % 4) { + str += "="; } + return new Uint8Array(bufferFromBase64(str)); + } else { + throw new Error(`Unsupported encoding "${encoding}"`); + } +} - const u8a = { toString, fromString }; +/** + * Convert a Uint8Array to a string with the given encoding. + * + * @param {Uint8Array} byteArray - The Uint8Array to convert. + * @param {string} [encoding='utf8'] - The desired encoding ('utf8', 'base16', 'base64url'). + * @returns {string} - The encoded string. + * @throws {Error} - Throws an error if the encoding is unsupported. + */ +function toString(byteArray, encoding = "utf8") { + switch (encoding) { + case "utf8": + return decodeUTF8(byteArray); + case "base16": + return toBase16(byteArray); + case "base64url": + return toBase64Url(byteArray); + default: + throw new Error(`Unsupported encoding "${encoding}"`); + } +} - function sha256(payload) { - const data = typeof payload === 'string' ? u8a.fromString(payload) : payload; - return generateSHA256Hash(data); - } +/** + * Decode a Uint8Array as a UTF-8 string. + * + * @param {Uint8Array} byteArray + * @returns {string} + */ +function decodeUTF8(byteArray) { + return new TextDecoder().decode(byteArray); +} +/** + * Convert a Uint8Array to a base16 (hex) encoded string. + * + * @param {Uint8Array} byteArray + * @returns {string} + */ +function toBase16(byteArray) { + return Array.from(byteArray) + .map((byte) => byte.toString(16).padStart(2, "0")) + .join(""); +} - async function accessToken(identifier) { - const did = identifier['did']; - const privateKeyHex = identifier['keys'][0]['privateKeyHex']; +/** + * Convert a Uint8Array to a base64url encoded string. + * + * @param {Uint8Array} byteArray + * @returns {string} + */ +function toBase64Url(byteArray) { + let uint8Array = new Uint8Array(byteArray); + let binaryString = ""; + for (let i = 0; i < uint8Array.length; i++) { + binaryString += String.fromCharCode(uint8Array[i]); + } - const signer = await SimpleSigner(privateKeyHex); + // Encode to base64 + let base64 = btoa(binaryString); - const nowEpoch = Math.floor(Date.now() / 1000); - const endEpoch = nowEpoch + 60; // add one minute + return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +} - const tokenPayload = { exp: endEpoch, iat: nowEpoch, iss: did }; - const alg = undefined; // defaults to 'ES256K', more standardized but harder to verify vs ES256K-R - const jwt = await createJWT(tokenPayload, { - alg, - issuer: did, - signer, - }); - console.error(jwt); - return jwt; - } +const u8a = { toString, fromString }; +function sha256(payload) { + const data = typeof payload === "string" ? u8a.fromString(payload) : payload; + return nobleHashes.sha256(data); +} - async function createJWT(payload, options, header = {}) { - const { issuer, signer, alg, expiresIn, canonicalize } = options; +async function accessToken(identifier) { + const did = identifier["did"]; + const privateKeyHex = identifier["keys"][0]["privateKeyHex"]; - if (!signer) throw new Error('missing_signer: No Signer functionality has been configured'); - if (!issuer) throw new Error('missing_issuer: No issuing DID has been configured'); - if (!header.typ) header.typ = 'JWT'; - if (!header.alg) header.alg = alg; + const signer = await SimpleSigner(privateKeyHex); - const timestamps = { - iat: Math.floor(Date.now() / 1000), - exp: undefined, - }; + const nowEpoch = Math.floor(Date.now() / 1000); + const endEpoch = nowEpoch + 60; // add one minute - if (expiresIn) { - if (typeof expiresIn === 'number') { - timestamps.exp = (payload.nbf || timestamps.iat) + Math.floor(expiresIn); - } else { - throw new Error('invalid_argument: JWT expiresIn is not a number'); - } - } + const tokenPayload = { exp: endEpoch, iat: nowEpoch, iss: did }; + const alg = undefined; // defaults to 'ES256K', more standardized but harder to verify vs ES256K-R + const jwt = await createJWT(tokenPayload, { + alg, + issuer: did, + signer, + }); + console.error(jwt); + return jwt; +} - const fullPayload = { ...timestamps, ...payload, iss: issuer }; - return createJWS(fullPayload, signer, header, { canonicalize }); +async function createJWT(payload, options, header = {}) { + const { issuer, signer, alg, expiresIn, canonicalize } = options; + + if (!signer) + throw new Error( + "missing_signer: No Signer functionality has been configured", + ); + if (!issuer) + throw new Error("missing_issuer: No issuing DID has been configured"); + if (!header.typ) header.typ = "JWT"; + if (!header.alg) header.alg = alg; + + const timestamps = { + iat: Math.floor(Date.now() / 1000), + exp: undefined, + }; + + if (expiresIn) { + if (typeof expiresIn === "number") { + timestamps.exp = (payload.nbf || timestamps.iat) + Math.floor(expiresIn); + } else { + throw new Error("invalid_argument: JWT expiresIn is not a number"); } + } + const fullPayload = { ...timestamps, ...payload, iss: issuer }; + return createJWS(fullPayload, signer, header, { canonicalize }); +} - const defaultAlg = 'ES256K' - - - async function createJWS(payload, signer, header = {}, options = {}) { - if (!header.alg) header.alg = defaultAlg; - const encodedPayload = typeof payload === 'string' ? payload : encodeSection(payload, options.canonicalize); - const signingInput = [encodeSection(header, options.canonicalize), encodedPayload].join('.'); - - const jwtSigner = ES256KSignerAlg(false); - const signature = await jwtSigner(signingInput, signer); +const defaultAlg = "ES256K"; + +async function createJWS(payload, signer, header = {}, options = {}) { + if (!header.alg) header.alg = defaultAlg; + const encodedPayload = + typeof payload === "string" + ? payload + : encodeSection(payload, options.canonicalize); + const signingInput = [ + encodeSection(header, options.canonicalize), + encodedPayload, + ].join("."); + + const jwtSigner = ES256KSignerAlg(false); + const signature = await jwtSigner(signingInput, signer); + + // JWS Compact Serialization + // https://www.rfc-editor.org/rfc/rfc7515#section-7.1 + return [signingInput, signature].join("."); +} - // JWS Compact Serialization - // https://www.rfc-editor.org/rfc/rfc7515#section-7.1 - return [signingInput, signature].join('.'); - } +function canonicalizeData(object) { + if (typeof object === "number" && isNaN(object)) { + throw new Error("NaN is not allowed"); + } - function canonicalizeData (object) { - if (typeof object === 'number' && isNaN(object)) { - throw new Error('NaN is not allowed'); - } - - if (typeof object === 'number' && !isFinite(object)) { - throw new Error('Infinity is not allowed'); - } - - if (object === null || typeof object !== 'object') { - return JSON.stringify(object); - } - - if (object.toJSON instanceof Function) { - return serialize(object.toJSON()); - } - - if (Array.isArray(object)) { - const values = object.reduce((t, cv, ci) => { - const comma = ci === 0 ? '' : ','; - const value = cv === undefined || typeof cv === 'symbol' ? null : cv; - return `${t}${comma}${serialize(value)}`; - }, ''); - return `[${values}]`; - } - - const values = Object.keys(object).sort().reduce((t, cv) => { - if (object[cv] === undefined || - typeof object[cv] === 'symbol') { - return t; - } - const comma = t.length === 0 ? '' : ','; - return `${t}${comma}${serialize(cv)}:${serialize(object[cv])}`; - }, ''); - return `{${values}}`; - }; + if (typeof object === "number" && !isFinite(object)) { + throw new Error("Infinity is not allowed"); + } - function encodeSection(data, shouldCanonicalize = false) { - if (shouldCanonicalize) { - return encodeBase64url(canonicalizeData(data)); - } else { - return encodeBase64url(JSON.stringify(data)); - } - } + if (object === null || typeof object !== "object") { + return JSON.stringify(object); + } + if (object.toJSON instanceof Function) { + return serialize(object.toJSON()); + } - function encodeBase64url(s) { - return bytesToBase64url(u8a.fromString(s)) - } + if (Array.isArray(object)) { + const values = object.reduce((t, cv, ci) => { + const comma = ci === 0 ? "" : ","; + const value = cv === undefined || typeof cv === "symbol" ? null : cv; + return `${t}${comma}${serialize(value)}`; + }, ""); + return `[${values}]`; + } - function instanceOfEcdsaSignature(object) { - return typeof object === 'object' && 'r' in object && 's' in object; - } + const values = Object.keys(object) + .sort() + .reduce((t, cv) => { + if (object[cv] === undefined || typeof object[cv] === "symbol") { + return t; + } + const comma = t.length === 0 ? "" : ","; + return `${t}${comma}${serialize(cv)}:${serialize(object[cv])}`; + }, ""); + return `{${values}}`; +} - function ES256KSignerAlg(recoverable) { - return async function sign(payload, signer) { - const signature = await signer(payload); - if (instanceOfEcdsaSignature(signature)) { - return toJose(signature, recoverable); - } else { - if (recoverable && typeof fromJose(signature).recoveryParam === 'undefined') { - throw new Error(`not_supported: ES256K-R not supported when signer doesn't provide a recovery param`); - } - return signature; - } - }; - } +function encodeSection(data, shouldCanonicalize = false) { + if (shouldCanonicalize) { + return encodeBase64url(canonicalizeData(data)); + } else { + return encodeBase64url(JSON.stringify(data)); + } +} - function leftpad(data, size = 64) { - if (data.length === size) return data; - return '0'.repeat(size - data.length) + data; - } +function encodeBase64url(s) { + return bytesToBase64url(u8a.fromString(s)); +} +function instanceOfEcdsaSignature(object) { + return typeof object === "object" && "r" in object && "s" in object; +} - async function SimpleSigner(hexPrivateKey) { - const signer = await ES256KSigner(hexToBytes(hexPrivateKey), true); - return async (data) => { - const signature = (await signer(data)); - return fromJose(signature); - }; +function ES256KSignerAlg(recoverable) { + return async function sign(payload, signer) { + const signature = await signer(payload); + if (instanceOfEcdsaSignature(signature)) { + return toJose(signature, recoverable); + } else { + if ( + recoverable && + typeof fromJose(signature).recoveryParam === "undefined" + ) { + throw new Error( + `not_supported: ES256K-R not supported when signer doesn't provide a recovery param`, + ); + } + return signature; } + }; +} +function leftpad(data, size = 64) { + if (data.length === size) return data; + return "0".repeat(size - data.length) + data; +} - function hexToBytes(s, minLength) { - let input = s.startsWith('0x') ? s.substring(2) : s; - - if (input.length % 2 !== 0) { - input = `0${input}`; - } - - if (minLength) { - const paddedLength = Math.max(input.length, minLength * 2); - input = input.padStart(paddedLength, '00'); - } +async function SimpleSigner(hexPrivateKey) { + const signer = await ES256KSigner(hexToBytes(hexPrivateKey), true); + return async (data) => { + const signature = await signer(data); + return fromJose(signature); + }; +} - return u8a.fromString(input.toLowerCase(), 'base16'); - } +function hexToBytes(s, minLength) { + let input = s.startsWith("0x") ? s.substring(2) : s; + if (input.length % 2 !== 0) { + input = `0${input}`; + } - function ES256KSigner(privateKey, recoverable = false) { - const privateKeyBytes = privateKey; - if (privateKeyBytes.length !== 32) { - throw new Error(`bad_key: Invalid private key format. Expecting 32 bytes, but got ${privateKeyBytes.length}`); - } - - return async function(data) { - const hash = await sha256(data); - const signature = nobleCurves.secp256k1.sign(hash, privateKeyBytes); - - return toJose({ - r: leftpad(signature.r.toString(16)), - s: leftpad(signature.s.toString(16)), - recoveryParam: signature.recovery, - }, recoverable); - } - } + if (minLength) { + const paddedLength = Math.max(input.length, minLength * 2); + input = input.padStart(paddedLength, "00"); + } + return u8a.fromString(input.toLowerCase(), "base16"); +} - function toJose(signature, recoverable) { - const { r, s, recoveryParam } = signature; - const jose = new Uint8Array(recoverable ? 65 : 64); - jose.set(u8a.fromString(r, 'base16'), 0); - jose.set(u8a.fromString(s, 'base16'), 32); +function ES256KSigner(privateKey, recoverable = false) { + const privateKeyBytes = privateKey; + if (privateKeyBytes.length !== 32) { + throw new Error( + `bad_key: Invalid private key format. Expecting 32 bytes, but got ${privateKeyBytes.length}`, + ); + } - if (recoverable) { - if (typeof recoveryParam === 'undefined') { - throw new Error('Signer did not return a recoveryParam'); - } - jose[64] = recoveryParam; - } - return bytesToBase64url(jose); - } + return async function (data) { + const signature = nobleCurves.secp256k1.sign(sha256(data), privateKeyBytes); + console.error(signature); + return toJose( + { + r: leftpad(signature.r.toString(16)), + s: leftpad(signature.s.toString(16)), + recoveryParam: signature.recovery, + }, + recoverable, + ); + }; +} +function toJose(signature, recoverable) { + const { r, s, recoveryParam } = signature; + const jose = new Uint8Array(recoverable ? 65 : 64); + jose.set(u8a.fromString(r, "base16"), 0); + jose.set(u8a.fromString(s, "base16"), 32); - function bytesToBase64url(b) { - return u8a.toString(b, 'base64url'); + if (recoverable) { + if (typeof recoveryParam === "undefined") { + throw new Error("Signer did not return a recoveryParam"); } + jose[64] = recoveryParam; + } + return bytesToBase64url(jose); +} - function base64ToBytes(s) { - const inputBase64Url = s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '') - return u8a.fromString(inputBase64Url, 'base64url') - } +function bytesToBase64url(b) { + return u8a.toString(b, "base64url"); +} - function bytesToHex(b) { - return u8a.toString(b, 'base16') - } +function base64ToBytes(s) { + const inputBase64Url = s + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=/g, ""); + return u8a.fromString(inputBase64Url, "base64url"); +} - function fromJose(signature) { - const signatureBytes = base64ToBytes(signature); - if (signatureBytes.length < 64 || signatureBytes.length > 65) { - throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${signatureBytes.length}`,); - } - const r = bytesToHex(signatureBytes.slice(0, 32)); - const s = bytesToHex(signatureBytes.slice(32, 64)); - const recoveryParam = signatureBytes.length === 65 ? signatureBytes[64] : undefined; +function bytesToHex(b) { + return u8a.toString(b, "base16"); +} - return { r, s, recoveryParam }; - } +function fromJose(signature) { + const signatureBytes = base64ToBytes(signature); + if (signatureBytes.length < 64 || signatureBytes.length > 65) { + throw new TypeError( + `Wrong size for signature. Expected 64 or 65 bytes, but got ${signatureBytes.length}`, + ); + } + const r = bytesToHex(signatureBytes.slice(0, 32)); + const s = bytesToHex(signatureBytes.slice(32, 64)); + const recoveryParam = + signatureBytes.length === 65 ? signatureBytes[64] : undefined; + return { r, s, recoveryParam }; +} function validateBase64(s) { if ( @@ -436,20 +442,23 @@ async function getNotificationCount() { const decrypted = self.secretbox.open(message, nonce, secretUint8Array); const msg = decoder.decode(decrypted); - const identifier = JSON.parse(JSON.parse(msg)); + const identifier = JSON.parse(JSON.parse(msg)); - console.log(identifier); + console.log(identifier); const headers = { - "Content-Type": "application/json", + "Content-Type": "application/json", }; - headers["Authorization"] = "Bearer " + await accessToken(identifier); + headers["Authorization"] = "Bearer " + (await accessToken(identifier)); - let response = await fetch("https://test-api.endorser.ch/api/v2/report/claims", { - method: 'GET', + let response = await fetch( + "https://test-api.endorser.ch/api/v2/report/claims", + { + method: "GET", headers: headers, - }); + }, + ); console.error(did, response.status); console.error(await response.json()); diff --git a/sw_scripts/secp256k1.js b/sw_scripts/secp256k1.js deleted file mode 100644 index 673161e..0000000 --- a/sw_scripts/secp256k1.js +++ /dev/null @@ -1,283 +0,0 @@ -(function () { - randomBytes = (length) => self.crypto.getRandomValues(new Uint8Array(length)); - self.Secp256k1 = exports = {}; - - function uint256(x, base) { - return new BN(x, base); - } - - function rnd(P) { - return uint256(randomBytes(32)).umod(P); //TODO red - } - - const A = uint256(0); - const B = uint256(7); - const GX = uint256( - "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", - 16, - ); - const GY = uint256( - "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", - 16, - ); - const P = uint256( - "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", - 16, - ); - const N = uint256( - "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", - 16, - ); - //const RED = BN.red(P) - const _0 = uint256(0); - const _1 = uint256(1); - - // function for elliptic curve multiplication in jacobian coordinates using Double-and-add method - function ecmul(_p, _d) { - let R = [_0, _0, _0]; - - //return (0,0) if d=0 or (x1,y1)=(0,0) - if (_d == 0 || (_p[0] == 0 && _p[1] == 0)) { - return R; - } - let T = [ - _p[0], //x-coordinate temp - _p[1], //y-coordinate temp - _p[2], //z-coordinate temp - ]; - - const d = _d.clone(); - while (d != 0) { - if (d.testn(0)) { - //if last bit is 1 add T to result - R = ecadd(T, R); - } - T = ecdouble(T); //double temporary coordinates - d.iushrn(1); //"cut off" last bit - } - - return R; - } - - function mulmod(a, b, P) { - return a.mul(b).umod(P); //TODO red - } - - function addmod(a, b, P) { - return a.add(b).umod(P); //TODO red - } - - function invmod(a, P) { - return a.invm(P); //TODO redq - } - - function mulG(k) { - const GinJ = AtoJ(GX, GY); - const PUBinJ = ecmul(GinJ, k); - return JtoA(PUBinJ); - } - - function assert(cond, msg) { - if (!cond) { - throw Error("assertion failed: " + msg); - } - } - - function ecsign(d, z) { - assert(d != 0, "d must not be 0"); - assert(z != 0, "z must not be 0"); - while (true) { - const k = rnd(P); - const R = mulG(k); - if (R[0] == 0) continue; - const s = mulmod(invmod(k, N), addmod(z, mulmod(R[0], d, N), N), N); - if (s == 0) continue; - //FIXME: why do I need this - if (s.testn(255)) continue; - return { r: toHex(R[0]), s: toHex(s), v: R[1].testn(0) ? 1 : 0 }; - } - } - - function JtoA(p) { - const zInv = invmod(p[2], P); - const zInv2 = mulmod(zInv, zInv, P); - return [mulmod(p[0], zInv2, P), mulmod(p[1], mulmod(zInv, zInv2, P), P)]; - } - - //point doubling for elliptic curve in jacobian coordinates - //formula from https://en.wikibooks.org/wiki/Cryptography/Prime_Curve/Jacobian_Coordinates - function ecdouble(_p) { - if (_p[1] == 0) { - //return point at infinity - return [_1, _1, _0]; - } - - const z2 = mulmod(_p[2], _p[2], P); - const m = addmod( - mulmod(A, mulmod(z2, z2, P), P), - mulmod(uint256(3), mulmod(_p[0], _p[0], P), P), - P, - ); - const y2 = mulmod(_p[1], _p[1], P); - const s = mulmod(uint256(4), mulmod(_p[0], y2, P), P); - - const x = addmod(mulmod(m, m, P), negmod(mulmod(s, uint256(2), P), P), P); - return [ - x, - addmod( - mulmod(m, addmod(s, negmod(x, P), P), P), - negmod(mulmod(uint256(8), mulmod(y2, y2, P), P), P), - P, - ), - mulmod(uint256(2), mulmod(_p[1], _p[2], P), P), - ]; - } - - function negmod(a, P) { - return P.sub(a); - } - - // point addition for elliptic curve in jacobian coordinates - // formula from https://en.wikibooks.org/wiki/Cryptography/Prime_Curve/Jacobian_Coordinates - function ecadd(_p, _q) { - if (_q[0] == 0 && _q[1] == 0 && _q[2] == 0) { - return _p; - } - - let z2 = mulmod(_q[2], _q[2], P); - const u1 = mulmod(_p[0], z2, P); - const s1 = mulmod(_p[1], mulmod(z2, _q[2], P), P); - z2 = mulmod(_p[2], _p[2], P); - let u2 = mulmod(_q[0], z2, P); - let s2 = mulmod(_q[1], mulmod(z2, _p[2], P), P); - - if (u1.eq(u2)) { - if (!s1.eq(s2)) { - //return point at infinity - return [_1, _1, _0]; - } else { - return ecdouble(_p); - } - } - - u2 = addmod(u2, negmod(u1, P), P); - z2 = mulmod(u2, u2, P); - const t2 = mulmod(u1, z2, P); - z2 = mulmod(u2, z2, P); - s2 = addmod(s2, negmod(s1, P), P); - const x = addmod( - addmod(mulmod(s2, s2, P), negmod(z2, P), P), - negmod(mulmod(uint256(2), t2, P), P), - P, - ); - return [ - x, - addmod( - mulmod(s2, addmod(t2, negmod(x, P), P), P), - negmod(mulmod(s1, z2, P), P), - P, - ), - mulmod(u2, mulmod(_p[2], _q[2], P), P), - ]; - } - - function AtoJ(x, y) { - return [uint256(x), uint256(y), _1]; - } - - function isValidPoint(x, y) { - const yy = addmod(mulmod(mulmod(x, x, P), x, P), B, P); - return yy.eq(mulmod(y, y, P)); - } - - function toHex(bn) { - return ( - "00000000000000000000000000000000000000000000000000000000000000000000000000000000" + - bn.toString(16) - ).slice(-64); - } - - function decompressKey(x, yBit) { - let redP = BN.red("k256"); - x = x.toRed(redP); - const y = x.redMul(x).redMul(x).redAdd(B.toRed(redP)).redSqrt(); - const sign = y.testn(0); - return (sign != yBit ? y.redNeg() : y).fromRed(); - } - - function generatePublicKeyFromPrivateKeyData(pk) { - const p = mulG(pk); - return { x: toHex(p[0]), y: toHex(p[1]) }; - } - - function ecrecover(recId, sigr, sigs, message) { - assert(recId >= 0 && recId <= 3, "recId must be 0..3"); - assert(sigr != 0, "sigr must not be 0"); - assert(sigs != 0, "sigs must not be 0"); - // 1.0 For j from 0 to h (h == recId here and the loop is outside this function) - // 1.1 Let x = r + jn - const x = addmod(uint256(sigr), P.muln(recId >> 1), P); - // 1.2. Convert the integer x to an octet string X of length mlen using the conversion routine - // specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉. - // 1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve point R using the - // conversion routine specified in Section 2.3.4. If this conversion routine outputs “invalid”, then - // do another iteration of Step 1. - // - // More concisely, what these points mean is to use X as a compressed public key. - if (x.gte(P)) { - // Cannot have point co-ordinates larger than this as everything takes place modulo Q. - return null; - } - // Compressed keys require you to know an extra bit of data about the y-coord as there are two possibilities. - // So it's encoded in the recId. - const y = decompressKey(x, (recId & 1) == 1); - // 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers responsibility). - // if (!R.mul(N).isInfinity()) - // return null - // 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification. - const e = uint256(message); - // 1.6. For k from 1 to 2 do the following. (loop is outside this function via iterating recId) - // 1.6.1. Compute a candidate public key as: - // Q = mi(r) * (sR - eG) - // - // Where mi(x) is the modular multiplicative inverse. We transform this into the following: - // Q = (mi(r) * s ** R) + (mi(r) * -e ** G) - // Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n). In the above equation - // ** is point multiplication and + is point addition (the EC group operator). - // - // We can find the additive inverse by subtracting e from zero then taking the mod. For example the additive - // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8. - const eNeg = negmod(e, N); - const rInv = invmod(sigr, N); - const srInv = mulmod(rInv, sigs, N); - const eNegrInv = mulmod(rInv, eNeg, N); - const R = AtoJ(x, y); - const G = AtoJ(GX, GY); - const qinJ = ecadd(ecmul(G, eNegrInv), ecmul(R, srInv)); - const p = JtoA(qinJ); - return { x: toHex(p[0]), y: toHex(p[1]) }; - } - - function ecverify(Qx, Qy, sigr, sigs, z) { - if (sigs == 0 || sigr == 0) { - return false; - } - const w = invmod(sigs, N); - const u1 = mulmod(z, w, N); - const u2 = mulmod(sigr, w, N); - const Q = AtoJ(Qx, Qy); - const G = AtoJ(GX, GY); - const RinJ = ecadd(ecmul(G, u1), ecmul(Q, u2)); - const r = JtoA(RinJ); - return sigr.eq(r[0]); - } - - exports.uint256 = uint256; - exports.ecsign = ecsign; - exports.ecrecover = ecrecover; - exports.generatePublicKeyFromPrivateKeyData = - generatePublicKeyFromPrivateKeyData; - exports.decompressKey = decompressKey; - exports.isValidPoint = isValidPoint; - exports.ecverify = ecverify; -})(); diff --git a/sw_scripts/sw-bn.js b/sw_scripts/sw-bn.js deleted file mode 100644 index 2cf4100..0000000 --- a/sw_scripts/sw-bn.js +++ /dev/null @@ -1,3542 +0,0 @@ -"use strict"; - -// Utils -function assert(val, msg) { - if (!val) throw new Error(msg || "Assertion failed"); -} - -// Could use `inherits` module, but don't want to move from single file -// architecture yet. -function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; -} - -// BN - -function BN(number, base, endian) { - if (BN.isBN(number)) { - return number; - } - - this.negative = 0; - this.words = null; - this.length = 0; - - // Reduction context - this.red = null; - - if (number !== null) { - if (base === "le" || base === "be") { - endian = base; - base = 10; - } - - this._init(number || 0, base || 10, endian || "be"); - } -} -self.BN = BN; - -BN.BN = BN; -BN.wordSize = 26; - -var Buffer; -try { - if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") { - Buffer = window.Buffer; - } else { - Buffer = require("buffer").Buffer; - } -} catch (e) {} - -BN.isBN = function isBN(num) { - if (num instanceof BN) { - return true; - } - - return ( - num !== null && - typeof num === "object" && - num.constructor.wordSize === BN.wordSize && - Array.isArray(num.words) - ); -}; - -BN.max = function max(left, right) { - if (left.cmp(right) > 0) return left; - return right; -}; - -BN.min = function min(left, right) { - if (left.cmp(right) < 0) return left; - return right; -}; - -BN.prototype._init = function init(number, base, endian) { - if (typeof number === "number") { - return this._initNumber(number, base, endian); - } - - if (typeof number === "object") { - return this._initArray(number, base, endian); - } - - if (base === "hex") { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ""); - var start = 0; - if (number[0] === "-") { - start++; - this.negative = 1; - } - - if (start < number.length) { - if (base === 16) { - this._parseHex(number, start, endian); - } else { - this._parseBase(number, base, start); - if (endian === "le") { - this._initArray(this.toArray(), base, endian); - } - } - } -}; - -BN.prototype._initNumber = function _initNumber(number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [number & 0x3ffffff]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff, 1]; - this.length = 3; - } - - if (endian !== "le") return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); -}; - -BN.prototype._initArray = function _initArray(number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === "number"); - if (number.length <= 0) { - this.words = [0]; - this.length = 1; - return this; - } - - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - var off = 0; - if (endian === "be") { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === "le") { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this._strip(); -}; - -function parseHex4Bits(string, index) { - var c = string.charCodeAt(index); - // '0' - '9' - if (c >= 48 && c <= 57) { - return c - 48; - // 'A' - 'F' - } else if (c >= 65 && c <= 70) { - return c - 55; - // 'a' - 'f' - } else if (c >= 97 && c <= 102) { - return c - 87; - } else { - assert(false, "Invalid character in " + string); - } -} - -function parseHexByte(string, lowerBound, index) { - var r = parseHex4Bits(string, index); - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } - return r; -} - -BN.prototype._parseHex = function _parseHex(number, start, endian) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - // 24-bits chunks - var off = 0; - var j = 0; - - var w; - if (endian === "be") { - for (i = number.length - 1; i >= start; i -= 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } else { - var parseLength = number.length - start; - for ( - i = parseLength % 2 === 0 ? start + 1 : start; - i < number.length; - i += 2 - ) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } - - this._strip(); -}; - -function parseBase(str, start, end, mul) { - var r = 0; - var b = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) { - b = c - 49 + 0xa; - - // 'A' - } else if (c >= 17) { - b = c - 17 + 0xa; - - // '0' - '9' - } else { - b = c; - } - assert(c >= 0 && b < mul, "Invalid character"); - r += b; - } - return r; -} - -BN.prototype._parseBase = function _parseBase(number, base, start) { - // Initialize as zero - this.words = [0]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; - - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); - - for (i = 0; i < mod; i++) { - pow *= base; - } - - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - this._strip(); -}; - -BN.prototype.copy = function copy(dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; -}; - -function move(dest, src) { - dest.words = src.words; - dest.length = src.length; - dest.negative = src.negative; - dest.red = src.red; -} - -BN.prototype._move = function _move(dest) { - move(dest, this); -}; - -BN.prototype.clone = function clone() { - var r = new BN(null); - this.copy(r); - return r; -}; - -BN.prototype._expand = function _expand(size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; -}; - -// Remove leading `0` from `this` -BN.prototype._strip = function strip() { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } - return this._normSign(); -}; - -BN.prototype._normSign = function _normSign() { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; -}; - -// Check Symbol.for because not everywhere where Symbol defined -// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility -if (typeof Symbol !== "undefined" && typeof Symbol.for === "function") { - try { - BN.prototype[Symbol.for("nodejs.util.inspect.custom")] = inspect; - } catch (e) { - BN.prototype.inspect = inspect; - } -} else { - BN.prototype.inspect = inspect; -} - -function inspect() { - return (this.red ? ""; -} - -/* - - var zeros = []; - var groupSizes = []; - var groupBases = []; - - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - - */ - -var zeros = [ - "", - "0", - "00", - "000", - "0000", - "00000", - "000000", - "0000000", - "00000000", - "000000000", - "0000000000", - "00000000000", - "000000000000", - "0000000000000", - "00000000000000", - "000000000000000", - "0000000000000000", - "00000000000000000", - "000000000000000000", - "0000000000000000000", - "00000000000000000000", - "000000000000000000000", - "0000000000000000000000", - "00000000000000000000000", - "000000000000000000000000", - "0000000000000000000000000", -]; - -var groupSizes = [ - 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, -]; - -var groupBases = [ - 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, - 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, - 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, - 39135393, 45435424, 52521875, 60466176, -]; - -BN.prototype.toString = function toString(base, padding) { - base = base || 10; - padding = padding | 0 || 1; - - var out; - if (base === 16 || base === "hex") { - out = ""; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = "0" + out; - } - if (this.negative !== 0) { - out = "-" + out; - } - return out; - } - - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ""; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modrn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = "0" + out; - } - while (out.length % padding !== 0) { - out = "0" + out; - } - if (this.negative !== 0) { - out = "-" + out; - } - return out; - } - - assert(false, "Base should be between 2 and 36"); -}; - -BN.prototype.toNumber = function toNumber() { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + this.words[1] * 0x4000000; - } else if (this.length > 2) { - assert(false, "Number can only safely store up to 53 bits"); - } - return this.negative !== 0 ? -ret : ret; -}; - -BN.prototype.toJSON = function toJSON() { - return this.toString(16, 2); -}; - -if (Buffer) { - BN.prototype.toBuffer = function toBuffer(endian, length) { - return this.toArrayLike(Buffer, endian, length); - }; -} - -BN.prototype.toArray = function toArray(endian, length) { - return this.toArrayLike(Array, endian, length); -}; - -var allocate = function allocate(ArrayType, size) { - if (ArrayType.allocUnsafe) { - return ArrayType.allocUnsafe(size); - } - return new ArrayType(size); -}; - -BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { - this._strip(); - - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, "byte array longer than desired length"); - assert(reqLength > 0, "Requested array length <= 0"); - - var res = allocate(ArrayType, reqLength); - var postfix = endian === "le" ? "LE" : "BE"; - this["_toArrayLike" + postfix](res, byteLength); - return res; -}; - -BN.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength) { - var position = 0; - var carry = 0; - - for (var i = 0, shift = 0; i < this.length; i++) { - var word = (this.words[i] << shift) | carry; - - res[position++] = word & 0xff; - if (position < res.length) { - res[position++] = (word >> 8) & 0xff; - } - if (position < res.length) { - res[position++] = (word >> 16) & 0xff; - } - - if (shift === 6) { - if (position < res.length) { - res[position++] = (word >> 24) & 0xff; - } - carry = 0; - shift = 0; - } else { - carry = word >>> 24; - shift += 2; - } - } - - if (position < res.length) { - res[position++] = carry; - - while (position < res.length) { - res[position++] = 0; - } - } -}; - -BN.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength) { - var position = res.length - 1; - var carry = 0; - - for (var i = 0, shift = 0; i < this.length; i++) { - var word = (this.words[i] << shift) | carry; - - res[position--] = word & 0xff; - if (position >= 0) { - res[position--] = (word >> 8) & 0xff; - } - if (position >= 0) { - res[position--] = (word >> 16) & 0xff; - } - - if (shift === 6) { - if (position >= 0) { - res[position--] = (word >> 24) & 0xff; - } - carry = 0; - shift = 0; - } else { - carry = word >>> 24; - shift += 2; - } - } - - if (position >= 0) { - res[position--] = carry; - - while (position >= 0) { - res[position--] = 0; - } - } -}; - -if (Math.clz32) { - BN.prototype._countBits = function _countBits(w) { - return 32 - Math.clz32(w); - }; -} else { - BN.prototype._countBits = function _countBits(w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; -} - -BN.prototype._zeroBits = function _zeroBits(w) { - // Short-cut - if (w === 0) return 26; - - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } - if ((t & 0x1) === 0) { - r++; - } - return r; -}; - -// Return number of used bits in a BN -BN.prototype.bitLength = function bitLength() { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; -}; - -function toBitArray(num) { - var w = new Array(num.bitLength()); - - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; - - w[bit] = (num.words[off] >>> wbit) & 0x01; - } - - return w; -} - -// Number of trailing zero bits -BN.prototype.zeroBits = function zeroBits() { - if (this.isZero()) return 0; - - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; - } - return r; -}; - -BN.prototype.byteLength = function byteLength() { - return Math.ceil(this.bitLength() / 8); -}; - -BN.prototype.toTwos = function toTwos(width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); -}; - -BN.prototype.fromTwos = function fromTwos(width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); -}; - -BN.prototype.isNeg = function isNeg() { - return this.negative !== 0; -}; - -// Return negative clone of `this` -BN.prototype.neg = function neg() { - return this.clone().ineg(); -}; - -BN.prototype.ineg = function ineg() { - if (!this.isZero()) { - this.negative ^= 1; - } - - return this; -}; - -// Or `num` with `this` in-place -BN.prototype.iuor = function iuor(num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } - - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } - - return this._strip(); -}; - -BN.prototype.ior = function ior(num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); -}; - -// Or `num` with `this` -BN.prototype.or = function or(num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); -}; - -BN.prototype.uor = function uor(num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); -}; - -// And `num` with `this` in-place -BN.prototype.iuand = function iuand(num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } - - this.length = b.length; - - return this._strip(); -}; - -BN.prototype.iand = function iand(num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); -}; - -// And `num` with `this` -BN.prototype.and = function and(num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); -}; - -BN.prototype.uand = function uand(num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); -}; - -// Xor `num` with `this` in-place -BN.prototype.iuxor = function iuxor(num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } - - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = a.length; - - return this._strip(); -}; - -BN.prototype.ixor = function ixor(num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); -}; - -// Xor `num` with `this` -BN.prototype.xor = function xor(num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); -}; - -BN.prototype.uxor = function uxor(num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); -}; - -// Not ``this`` with ``width`` bitwidth -BN.prototype.inotn = function inotn(width) { - assert(typeof width === "number" && width >= 0); - - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); - - if (bitsLeft > 0) { - bytesNeeded--; - } - - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } - - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } - - // And remove leading zeroes - return this._strip(); -}; - -BN.prototype.notn = function notn(width) { - return this.clone().inotn(width); -}; - -// Set `bit` of `this` -BN.prototype.setn = function setn(bit, val) { - assert(typeof bit === "number" && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - this._expand(off + 1); - - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } - - return this._strip(); -}; - -// Add `num` to `this` in-place -BN.prototype.iadd = function iadd(num) { - var r; - - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); - - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - return this; -}; - -// Add `num` to `this` -BN.prototype.add = function add(num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; - } - - if (this.length > num.length) return this.clone().iadd(num); - - return num.clone().iadd(this); -}; - -// Subtract `num` from `this` in-place -BN.prototype.isub = function isub(num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } - - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = Math.max(this.length, i); - - if (a !== this) { - this.negative = 1; - } - - return this._strip(); -}; - -// Subtract `num` from `this` -BN.prototype.sub = function sub(num) { - return this.clone().isub(num); -}; - -function smallMulTo(self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; - - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; - - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - - return out._strip(); -} - -// TODO(indutny): it may be reasonable to omit it for users who don't need -// to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit -// multiplication (like elliptic secp256k1). -var comb10MulTo = function comb10MulTo(self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = (mid + Math.imul(ah0, bl0)) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = (mid + Math.imul(ah1, bl0)) | 0; - hi = Math.imul(ah1, bh0); - lo = (lo + Math.imul(al0, bl1)) | 0; - mid = (mid + Math.imul(al0, bh1)) | 0; - mid = (mid + Math.imul(ah0, bl1)) | 0; - hi = (hi + Math.imul(ah0, bh1)) | 0; - var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = (mid + Math.imul(ah2, bl0)) | 0; - hi = Math.imul(ah2, bh0); - lo = (lo + Math.imul(al1, bl1)) | 0; - mid = (mid + Math.imul(al1, bh1)) | 0; - mid = (mid + Math.imul(ah1, bl1)) | 0; - hi = (hi + Math.imul(ah1, bh1)) | 0; - lo = (lo + Math.imul(al0, bl2)) | 0; - mid = (mid + Math.imul(al0, bh2)) | 0; - mid = (mid + Math.imul(ah0, bl2)) | 0; - hi = (hi + Math.imul(ah0, bh2)) | 0; - var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = (mid + Math.imul(ah3, bl0)) | 0; - hi = Math.imul(ah3, bh0); - lo = (lo + Math.imul(al2, bl1)) | 0; - mid = (mid + Math.imul(al2, bh1)) | 0; - mid = (mid + Math.imul(ah2, bl1)) | 0; - hi = (hi + Math.imul(ah2, bh1)) | 0; - lo = (lo + Math.imul(al1, bl2)) | 0; - mid = (mid + Math.imul(al1, bh2)) | 0; - mid = (mid + Math.imul(ah1, bl2)) | 0; - hi = (hi + Math.imul(ah1, bh2)) | 0; - lo = (lo + Math.imul(al0, bl3)) | 0; - mid = (mid + Math.imul(al0, bh3)) | 0; - mid = (mid + Math.imul(ah0, bl3)) | 0; - hi = (hi + Math.imul(ah0, bh3)) | 0; - var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = (mid + Math.imul(ah4, bl0)) | 0; - hi = Math.imul(ah4, bh0); - lo = (lo + Math.imul(al3, bl1)) | 0; - mid = (mid + Math.imul(al3, bh1)) | 0; - mid = (mid + Math.imul(ah3, bl1)) | 0; - hi = (hi + Math.imul(ah3, bh1)) | 0; - lo = (lo + Math.imul(al2, bl2)) | 0; - mid = (mid + Math.imul(al2, bh2)) | 0; - mid = (mid + Math.imul(ah2, bl2)) | 0; - hi = (hi + Math.imul(ah2, bh2)) | 0; - lo = (lo + Math.imul(al1, bl3)) | 0; - mid = (mid + Math.imul(al1, bh3)) | 0; - mid = (mid + Math.imul(ah1, bl3)) | 0; - hi = (hi + Math.imul(ah1, bh3)) | 0; - lo = (lo + Math.imul(al0, bl4)) | 0; - mid = (mid + Math.imul(al0, bh4)) | 0; - mid = (mid + Math.imul(ah0, bl4)) | 0; - hi = (hi + Math.imul(ah0, bh4)) | 0; - var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = (mid + Math.imul(ah5, bl0)) | 0; - hi = Math.imul(ah5, bh0); - lo = (lo + Math.imul(al4, bl1)) | 0; - mid = (mid + Math.imul(al4, bh1)) | 0; - mid = (mid + Math.imul(ah4, bl1)) | 0; - hi = (hi + Math.imul(ah4, bh1)) | 0; - lo = (lo + Math.imul(al3, bl2)) | 0; - mid = (mid + Math.imul(al3, bh2)) | 0; - mid = (mid + Math.imul(ah3, bl2)) | 0; - hi = (hi + Math.imul(ah3, bh2)) | 0; - lo = (lo + Math.imul(al2, bl3)) | 0; - mid = (mid + Math.imul(al2, bh3)) | 0; - mid = (mid + Math.imul(ah2, bl3)) | 0; - hi = (hi + Math.imul(ah2, bh3)) | 0; - lo = (lo + Math.imul(al1, bl4)) | 0; - mid = (mid + Math.imul(al1, bh4)) | 0; - mid = (mid + Math.imul(ah1, bl4)) | 0; - hi = (hi + Math.imul(ah1, bh4)) | 0; - lo = (lo + Math.imul(al0, bl5)) | 0; - mid = (mid + Math.imul(al0, bh5)) | 0; - mid = (mid + Math.imul(ah0, bl5)) | 0; - hi = (hi + Math.imul(ah0, bh5)) | 0; - var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = (mid + Math.imul(ah6, bl0)) | 0; - hi = Math.imul(ah6, bh0); - lo = (lo + Math.imul(al5, bl1)) | 0; - mid = (mid + Math.imul(al5, bh1)) | 0; - mid = (mid + Math.imul(ah5, bl1)) | 0; - hi = (hi + Math.imul(ah5, bh1)) | 0; - lo = (lo + Math.imul(al4, bl2)) | 0; - mid = (mid + Math.imul(al4, bh2)) | 0; - mid = (mid + Math.imul(ah4, bl2)) | 0; - hi = (hi + Math.imul(ah4, bh2)) | 0; - lo = (lo + Math.imul(al3, bl3)) | 0; - mid = (mid + Math.imul(al3, bh3)) | 0; - mid = (mid + Math.imul(ah3, bl3)) | 0; - hi = (hi + Math.imul(ah3, bh3)) | 0; - lo = (lo + Math.imul(al2, bl4)) | 0; - mid = (mid + Math.imul(al2, bh4)) | 0; - mid = (mid + Math.imul(ah2, bl4)) | 0; - hi = (hi + Math.imul(ah2, bh4)) | 0; - lo = (lo + Math.imul(al1, bl5)) | 0; - mid = (mid + Math.imul(al1, bh5)) | 0; - mid = (mid + Math.imul(ah1, bl5)) | 0; - hi = (hi + Math.imul(ah1, bh5)) | 0; - lo = (lo + Math.imul(al0, bl6)) | 0; - mid = (mid + Math.imul(al0, bh6)) | 0; - mid = (mid + Math.imul(ah0, bl6)) | 0; - hi = (hi + Math.imul(ah0, bh6)) | 0; - var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = (mid + Math.imul(ah7, bl0)) | 0; - hi = Math.imul(ah7, bh0); - lo = (lo + Math.imul(al6, bl1)) | 0; - mid = (mid + Math.imul(al6, bh1)) | 0; - mid = (mid + Math.imul(ah6, bl1)) | 0; - hi = (hi + Math.imul(ah6, bh1)) | 0; - lo = (lo + Math.imul(al5, bl2)) | 0; - mid = (mid + Math.imul(al5, bh2)) | 0; - mid = (mid + Math.imul(ah5, bl2)) | 0; - hi = (hi + Math.imul(ah5, bh2)) | 0; - lo = (lo + Math.imul(al4, bl3)) | 0; - mid = (mid + Math.imul(al4, bh3)) | 0; - mid = (mid + Math.imul(ah4, bl3)) | 0; - hi = (hi + Math.imul(ah4, bh3)) | 0; - lo = (lo + Math.imul(al3, bl4)) | 0; - mid = (mid + Math.imul(al3, bh4)) | 0; - mid = (mid + Math.imul(ah3, bl4)) | 0; - hi = (hi + Math.imul(ah3, bh4)) | 0; - lo = (lo + Math.imul(al2, bl5)) | 0; - mid = (mid + Math.imul(al2, bh5)) | 0; - mid = (mid + Math.imul(ah2, bl5)) | 0; - hi = (hi + Math.imul(ah2, bh5)) | 0; - lo = (lo + Math.imul(al1, bl6)) | 0; - mid = (mid + Math.imul(al1, bh6)) | 0; - mid = (mid + Math.imul(ah1, bl6)) | 0; - hi = (hi + Math.imul(ah1, bh6)) | 0; - lo = (lo + Math.imul(al0, bl7)) | 0; - mid = (mid + Math.imul(al0, bh7)) | 0; - mid = (mid + Math.imul(ah0, bl7)) | 0; - hi = (hi + Math.imul(ah0, bh7)) | 0; - var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = (mid + Math.imul(ah8, bl0)) | 0; - hi = Math.imul(ah8, bh0); - lo = (lo + Math.imul(al7, bl1)) | 0; - mid = (mid + Math.imul(al7, bh1)) | 0; - mid = (mid + Math.imul(ah7, bl1)) | 0; - hi = (hi + Math.imul(ah7, bh1)) | 0; - lo = (lo + Math.imul(al6, bl2)) | 0; - mid = (mid + Math.imul(al6, bh2)) | 0; - mid = (mid + Math.imul(ah6, bl2)) | 0; - hi = (hi + Math.imul(ah6, bh2)) | 0; - lo = (lo + Math.imul(al5, bl3)) | 0; - mid = (mid + Math.imul(al5, bh3)) | 0; - mid = (mid + Math.imul(ah5, bl3)) | 0; - hi = (hi + Math.imul(ah5, bh3)) | 0; - lo = (lo + Math.imul(al4, bl4)) | 0; - mid = (mid + Math.imul(al4, bh4)) | 0; - mid = (mid + Math.imul(ah4, bl4)) | 0; - hi = (hi + Math.imul(ah4, bh4)) | 0; - lo = (lo + Math.imul(al3, bl5)) | 0; - mid = (mid + Math.imul(al3, bh5)) | 0; - mid = (mid + Math.imul(ah3, bl5)) | 0; - hi = (hi + Math.imul(ah3, bh5)) | 0; - lo = (lo + Math.imul(al2, bl6)) | 0; - mid = (mid + Math.imul(al2, bh6)) | 0; - mid = (mid + Math.imul(ah2, bl6)) | 0; - hi = (hi + Math.imul(ah2, bh6)) | 0; - lo = (lo + Math.imul(al1, bl7)) | 0; - mid = (mid + Math.imul(al1, bh7)) | 0; - mid = (mid + Math.imul(ah1, bl7)) | 0; - hi = (hi + Math.imul(ah1, bh7)) | 0; - lo = (lo + Math.imul(al0, bl8)) | 0; - mid = (mid + Math.imul(al0, bh8)) | 0; - mid = (mid + Math.imul(ah0, bl8)) | 0; - hi = (hi + Math.imul(ah0, bh8)) | 0; - var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = (mid + Math.imul(ah9, bl0)) | 0; - hi = Math.imul(ah9, bh0); - lo = (lo + Math.imul(al8, bl1)) | 0; - mid = (mid + Math.imul(al8, bh1)) | 0; - mid = (mid + Math.imul(ah8, bl1)) | 0; - hi = (hi + Math.imul(ah8, bh1)) | 0; - lo = (lo + Math.imul(al7, bl2)) | 0; - mid = (mid + Math.imul(al7, bh2)) | 0; - mid = (mid + Math.imul(ah7, bl2)) | 0; - hi = (hi + Math.imul(ah7, bh2)) | 0; - lo = (lo + Math.imul(al6, bl3)) | 0; - mid = (mid + Math.imul(al6, bh3)) | 0; - mid = (mid + Math.imul(ah6, bl3)) | 0; - hi = (hi + Math.imul(ah6, bh3)) | 0; - lo = (lo + Math.imul(al5, bl4)) | 0; - mid = (mid + Math.imul(al5, bh4)) | 0; - mid = (mid + Math.imul(ah5, bl4)) | 0; - hi = (hi + Math.imul(ah5, bh4)) | 0; - lo = (lo + Math.imul(al4, bl5)) | 0; - mid = (mid + Math.imul(al4, bh5)) | 0; - mid = (mid + Math.imul(ah4, bl5)) | 0; - hi = (hi + Math.imul(ah4, bh5)) | 0; - lo = (lo + Math.imul(al3, bl6)) | 0; - mid = (mid + Math.imul(al3, bh6)) | 0; - mid = (mid + Math.imul(ah3, bl6)) | 0; - hi = (hi + Math.imul(ah3, bh6)) | 0; - lo = (lo + Math.imul(al2, bl7)) | 0; - mid = (mid + Math.imul(al2, bh7)) | 0; - mid = (mid + Math.imul(ah2, bl7)) | 0; - hi = (hi + Math.imul(ah2, bh7)) | 0; - lo = (lo + Math.imul(al1, bl8)) | 0; - mid = (mid + Math.imul(al1, bh8)) | 0; - mid = (mid + Math.imul(ah1, bl8)) | 0; - hi = (hi + Math.imul(ah1, bh8)) | 0; - lo = (lo + Math.imul(al0, bl9)) | 0; - mid = (mid + Math.imul(al0, bh9)) | 0; - mid = (mid + Math.imul(ah0, bl9)) | 0; - hi = (hi + Math.imul(ah0, bh9)) | 0; - var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = (mid + Math.imul(ah9, bl1)) | 0; - hi = Math.imul(ah9, bh1); - lo = (lo + Math.imul(al8, bl2)) | 0; - mid = (mid + Math.imul(al8, bh2)) | 0; - mid = (mid + Math.imul(ah8, bl2)) | 0; - hi = (hi + Math.imul(ah8, bh2)) | 0; - lo = (lo + Math.imul(al7, bl3)) | 0; - mid = (mid + Math.imul(al7, bh3)) | 0; - mid = (mid + Math.imul(ah7, bl3)) | 0; - hi = (hi + Math.imul(ah7, bh3)) | 0; - lo = (lo + Math.imul(al6, bl4)) | 0; - mid = (mid + Math.imul(al6, bh4)) | 0; - mid = (mid + Math.imul(ah6, bl4)) | 0; - hi = (hi + Math.imul(ah6, bh4)) | 0; - lo = (lo + Math.imul(al5, bl5)) | 0; - mid = (mid + Math.imul(al5, bh5)) | 0; - mid = (mid + Math.imul(ah5, bl5)) | 0; - hi = (hi + Math.imul(ah5, bh5)) | 0; - lo = (lo + Math.imul(al4, bl6)) | 0; - mid = (mid + Math.imul(al4, bh6)) | 0; - mid = (mid + Math.imul(ah4, bl6)) | 0; - hi = (hi + Math.imul(ah4, bh6)) | 0; - lo = (lo + Math.imul(al3, bl7)) | 0; - mid = (mid + Math.imul(al3, bh7)) | 0; - mid = (mid + Math.imul(ah3, bl7)) | 0; - hi = (hi + Math.imul(ah3, bh7)) | 0; - lo = (lo + Math.imul(al2, bl8)) | 0; - mid = (mid + Math.imul(al2, bh8)) | 0; - mid = (mid + Math.imul(ah2, bl8)) | 0; - hi = (hi + Math.imul(ah2, bh8)) | 0; - lo = (lo + Math.imul(al1, bl9)) | 0; - mid = (mid + Math.imul(al1, bh9)) | 0; - mid = (mid + Math.imul(ah1, bl9)) | 0; - hi = (hi + Math.imul(ah1, bh9)) | 0; - var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = (mid + Math.imul(ah9, bl2)) | 0; - hi = Math.imul(ah9, bh2); - lo = (lo + Math.imul(al8, bl3)) | 0; - mid = (mid + Math.imul(al8, bh3)) | 0; - mid = (mid + Math.imul(ah8, bl3)) | 0; - hi = (hi + Math.imul(ah8, bh3)) | 0; - lo = (lo + Math.imul(al7, bl4)) | 0; - mid = (mid + Math.imul(al7, bh4)) | 0; - mid = (mid + Math.imul(ah7, bl4)) | 0; - hi = (hi + Math.imul(ah7, bh4)) | 0; - lo = (lo + Math.imul(al6, bl5)) | 0; - mid = (mid + Math.imul(al6, bh5)) | 0; - mid = (mid + Math.imul(ah6, bl5)) | 0; - hi = (hi + Math.imul(ah6, bh5)) | 0; - lo = (lo + Math.imul(al5, bl6)) | 0; - mid = (mid + Math.imul(al5, bh6)) | 0; - mid = (mid + Math.imul(ah5, bl6)) | 0; - hi = (hi + Math.imul(ah5, bh6)) | 0; - lo = (lo + Math.imul(al4, bl7)) | 0; - mid = (mid + Math.imul(al4, bh7)) | 0; - mid = (mid + Math.imul(ah4, bl7)) | 0; - hi = (hi + Math.imul(ah4, bh7)) | 0; - lo = (lo + Math.imul(al3, bl8)) | 0; - mid = (mid + Math.imul(al3, bh8)) | 0; - mid = (mid + Math.imul(ah3, bl8)) | 0; - hi = (hi + Math.imul(ah3, bh8)) | 0; - lo = (lo + Math.imul(al2, bl9)) | 0; - mid = (mid + Math.imul(al2, bh9)) | 0; - mid = (mid + Math.imul(ah2, bl9)) | 0; - hi = (hi + Math.imul(ah2, bh9)) | 0; - var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = (mid + Math.imul(ah9, bl3)) | 0; - hi = Math.imul(ah9, bh3); - lo = (lo + Math.imul(al8, bl4)) | 0; - mid = (mid + Math.imul(al8, bh4)) | 0; - mid = (mid + Math.imul(ah8, bl4)) | 0; - hi = (hi + Math.imul(ah8, bh4)) | 0; - lo = (lo + Math.imul(al7, bl5)) | 0; - mid = (mid + Math.imul(al7, bh5)) | 0; - mid = (mid + Math.imul(ah7, bl5)) | 0; - hi = (hi + Math.imul(ah7, bh5)) | 0; - lo = (lo + Math.imul(al6, bl6)) | 0; - mid = (mid + Math.imul(al6, bh6)) | 0; - mid = (mid + Math.imul(ah6, bl6)) | 0; - hi = (hi + Math.imul(ah6, bh6)) | 0; - lo = (lo + Math.imul(al5, bl7)) | 0; - mid = (mid + Math.imul(al5, bh7)) | 0; - mid = (mid + Math.imul(ah5, bl7)) | 0; - hi = (hi + Math.imul(ah5, bh7)) | 0; - lo = (lo + Math.imul(al4, bl8)) | 0; - mid = (mid + Math.imul(al4, bh8)) | 0; - mid = (mid + Math.imul(ah4, bl8)) | 0; - hi = (hi + Math.imul(ah4, bh8)) | 0; - lo = (lo + Math.imul(al3, bl9)) | 0; - mid = (mid + Math.imul(al3, bh9)) | 0; - mid = (mid + Math.imul(ah3, bl9)) | 0; - hi = (hi + Math.imul(ah3, bh9)) | 0; - var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = (mid + Math.imul(ah9, bl4)) | 0; - hi = Math.imul(ah9, bh4); - lo = (lo + Math.imul(al8, bl5)) | 0; - mid = (mid + Math.imul(al8, bh5)) | 0; - mid = (mid + Math.imul(ah8, bl5)) | 0; - hi = (hi + Math.imul(ah8, bh5)) | 0; - lo = (lo + Math.imul(al7, bl6)) | 0; - mid = (mid + Math.imul(al7, bh6)) | 0; - mid = (mid + Math.imul(ah7, bl6)) | 0; - hi = (hi + Math.imul(ah7, bh6)) | 0; - lo = (lo + Math.imul(al6, bl7)) | 0; - mid = (mid + Math.imul(al6, bh7)) | 0; - mid = (mid + Math.imul(ah6, bl7)) | 0; - hi = (hi + Math.imul(ah6, bh7)) | 0; - lo = (lo + Math.imul(al5, bl8)) | 0; - mid = (mid + Math.imul(al5, bh8)) | 0; - mid = (mid + Math.imul(ah5, bl8)) | 0; - hi = (hi + Math.imul(ah5, bh8)) | 0; - lo = (lo + Math.imul(al4, bl9)) | 0; - mid = (mid + Math.imul(al4, bh9)) | 0; - mid = (mid + Math.imul(ah4, bl9)) | 0; - hi = (hi + Math.imul(ah4, bh9)) | 0; - var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = (mid + Math.imul(ah9, bl5)) | 0; - hi = Math.imul(ah9, bh5); - lo = (lo + Math.imul(al8, bl6)) | 0; - mid = (mid + Math.imul(al8, bh6)) | 0; - mid = (mid + Math.imul(ah8, bl6)) | 0; - hi = (hi + Math.imul(ah8, bh6)) | 0; - lo = (lo + Math.imul(al7, bl7)) | 0; - mid = (mid + Math.imul(al7, bh7)) | 0; - mid = (mid + Math.imul(ah7, bl7)) | 0; - hi = (hi + Math.imul(ah7, bh7)) | 0; - lo = (lo + Math.imul(al6, bl8)) | 0; - mid = (mid + Math.imul(al6, bh8)) | 0; - mid = (mid + Math.imul(ah6, bl8)) | 0; - hi = (hi + Math.imul(ah6, bh8)) | 0; - lo = (lo + Math.imul(al5, bl9)) | 0; - mid = (mid + Math.imul(al5, bh9)) | 0; - mid = (mid + Math.imul(ah5, bl9)) | 0; - hi = (hi + Math.imul(ah5, bh9)) | 0; - var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = (mid + Math.imul(ah9, bl6)) | 0; - hi = Math.imul(ah9, bh6); - lo = (lo + Math.imul(al8, bl7)) | 0; - mid = (mid + Math.imul(al8, bh7)) | 0; - mid = (mid + Math.imul(ah8, bl7)) | 0; - hi = (hi + Math.imul(ah8, bh7)) | 0; - lo = (lo + Math.imul(al7, bl8)) | 0; - mid = (mid + Math.imul(al7, bh8)) | 0; - mid = (mid + Math.imul(ah7, bl8)) | 0; - hi = (hi + Math.imul(ah7, bh8)) | 0; - lo = (lo + Math.imul(al6, bl9)) | 0; - mid = (mid + Math.imul(al6, bh9)) | 0; - mid = (mid + Math.imul(ah6, bl9)) | 0; - hi = (hi + Math.imul(ah6, bh9)) | 0; - var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = (mid + Math.imul(ah9, bl7)) | 0; - hi = Math.imul(ah9, bh7); - lo = (lo + Math.imul(al8, bl8)) | 0; - mid = (mid + Math.imul(al8, bh8)) | 0; - mid = (mid + Math.imul(ah8, bl8)) | 0; - hi = (hi + Math.imul(ah8, bh8)) | 0; - lo = (lo + Math.imul(al7, bl9)) | 0; - mid = (mid + Math.imul(al7, bh9)) | 0; - mid = (mid + Math.imul(ah7, bl9)) | 0; - hi = (hi + Math.imul(ah7, bh9)) | 0; - var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = (mid + Math.imul(ah9, bl8)) | 0; - hi = Math.imul(ah9, bh8); - lo = (lo + Math.imul(al8, bl9)) | 0; - mid = (mid + Math.imul(al8, bh9)) | 0; - mid = (mid + Math.imul(ah8, bl9)) | 0; - hi = (hi + Math.imul(ah8, bh9)) | 0; - var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = (mid + Math.imul(ah9, bl9)) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; -}; - -// Polyfill comb -if (!Math.imul) { - comb10MulTo = smallMulTo; -} - -function bigMulTo(self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out._strip(); -} - -function jumboMulTo(self, num, out) { - // Temporary disable, see https://github.com/indutny/bn.js/issues/211 - // var fftm = new FFTM(); - // return fftm.mulp(self, num, out); - return bigMulTo(self, num, out); -} - -BN.prototype.mulTo = function mulTo(num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - - return res; -}; - -// Cooley-Tukey algorithm for FFT -// slightly revisited to rely on looping instead of recursion - -function FFTM(x, y) { - this.x = x; - this.y = y; -} - -FFTM.prototype.makeRBT = function makeRBT(N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; -}; - -// Returns binary-reversed representation of `x` -FFTM.prototype.revBin = function revBin(x, l, N) { - if (x === 0 || x === N - 1) return x; - - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } - - return rb; -}; - -// Performs "tweedling" phase, therefore 'emulating' -// behaviour of the recursive algorithm -FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; - } -}; - -FFTM.prototype.transform = function transform(rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos((2 * Math.PI) / l); - var itwdf = Math.sin((2 * Math.PI) / l); - - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; - - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; - - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; - - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } -}; - -FFTM.prototype.guessLen13b = function guessLen13b(n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = (N / 2) | 0; N; N = N >>> 1) { - i++; - } - - return 1 << (i + 1 + odd); -}; - -FFTM.prototype.conjugate = function conjugate(rws, iws, N) { - if (N <= 1) return; - - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; - - t = iws[i]; - - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } -}; - -FFTM.prototype.normalize13b = function normalize13b(ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = - Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; - - ws[i] = w & 0x3ffffff; - - if (w < 0x4000000) { - carry = 0; - } else { - carry = (w / 0x4000000) | 0; - } - } - - return ws; -}; - -FFTM.prototype.convert13b = function convert13b(ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - - rws[2 * i] = carry & 0x1fff; - carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; - carry = carry >>> 13; - } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); -}; - -FFTM.prototype.stub = function stub(N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - - return ph; -}; - -FFTM.prototype.mulp = function mulp(x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } - - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out._strip(); -}; - -// Multiply `this` by `num` -BN.prototype.mul = function mul(num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); -}; - -// Multiply employing FFT -BN.prototype.mulf = function mulf(num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); -}; - -// In-place Multiplication -BN.prototype.imul = function imul(num) { - return this.clone().mulTo(num, this); -}; - -BN.prototype.imuln = function imuln(num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - - assert(typeof num === "number"); - assert(num < 0x4000000); - - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - - return isNegNum ? this.ineg() : this; -}; - -BN.prototype.muln = function muln(num) { - return this.clone().imuln(num); -}; - -// `this` * `this` -BN.prototype.sqr = function sqr() { - return this.mul(this); -}; - -// `this` * `this` in-place -BN.prototype.isqr = function isqr() { - return this.imul(this.clone()); -}; - -// Math.pow(`this`, `num`) -BN.prototype.pow = function pow(num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } - - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - - res = res.mul(q); - } - } - - return res; -}; - -// Shift-left in-place -BN.prototype.iushln = function iushln(bits) { - assert(typeof bits === "number" && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; - - if (r !== 0) { - var carry = 0; - - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } - - if (carry) { - this.words[i] = carry; - this.length++; - } - } - - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; - } - - this.length += s; - } - - return this._strip(); -}; - -BN.prototype.ishln = function ishln(bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); -}; - -// Shift-right in-place -// NOTE: `hint` is a lowest bit before trailing zeroes -// NOTE: if `extended` is present - it will be filled with destroyed bits -BN.prototype.iushrn = function iushrn(bits, hint, extended) { - assert(typeof bits === "number" && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; - } - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } - - if (s === 0) { - // No-op, we should not move anything at all - } else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } - - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; - } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } - - return this._strip(); -}; - -BN.prototype.ishrn = function ishrn(bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); -}; - -// Shift-left -BN.prototype.shln = function shln(bits) { - return this.clone().ishln(bits); -}; - -BN.prototype.ushln = function ushln(bits) { - return this.clone().iushln(bits); -}; - -// Shift-right -BN.prototype.shrn = function shrn(bits) { - return this.clone().ishrn(bits); -}; - -BN.prototype.ushrn = function ushrn(bits) { - return this.clone().iushrn(bits); -}; - -// Test if n bit is set -BN.prototype.testn = function testn(bit) { - assert(typeof bit === "number" && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; - - // Check bit and return - var w = this.words[s]; - - return !!(w & q); -}; - -// Return only lowers bits of number (in-place) -BN.prototype.imaskn = function imaskn(bits) { - assert(typeof bits === "number" && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - - assert(this.negative === 0, "imaskn works only with positive numbers"); - - if (this.length <= s) { - return this; - } - - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } - - return this._strip(); -}; - -// Return only lowers bits of number -BN.prototype.maskn = function maskn(bits) { - return this.clone().imaskn(bits); -}; - -// Add plain number `num` to `this` -BN.prototype.iaddn = function iaddn(num) { - assert(typeof num === "number"); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) <= num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } - - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } - - // Add without checks - return this._iaddn(num); -}; - -BN.prototype._iaddn = function _iaddn(num) { - this.words[0] += num; - - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } - } - this.length = Math.max(this.length, i + 1); - - return this; -}; - -// Subtract plain number `num` from `this` -BN.prototype.isubn = function isubn(num) { - assert(typeof num === "number"); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); - - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; - } - - this.words[0] -= num; - - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - } - - return this._strip(); -}; - -BN.prototype.addn = function addn(num) { - return this.clone().iaddn(num); -}; - -BN.prototype.subn = function subn(num) { - return this.clone().isubn(num); -}; - -BN.prototype.iabs = function iabs() { - this.negative = 0; - - return this; -}; - -BN.prototype.abs = function abs() { - return this.clone().iabs(); -}; - -BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { - var len = num.length + shift; - var i; - - this._expand(len); - - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } - - if (carry === 0) return this._strip(); - - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.negative = 1; - - return this._strip(); -}; - -BN.prototype._wordDiv = function _wordDiv(num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } - - // Initialize quotient - var m = a.length - b.length; - var q; - - if (mode !== "mod") { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; - } - } - - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } - - for (var j = m - 1; j >= 0; j--) { - var qj = - (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); - - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; - } - } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q._strip(); - } - a._strip(); - - // Denormalize - if (mode !== "div" && shift !== 0) { - a.iushrn(shift); - } - - return { - div: q || null, - mod: a, - }; -}; - -// NOTE: 1) `mode` can be set to `mod` to request mod only, -// to `div` to request div only, or be absent to -// request both div & mod -// 2) `positive` is true if unsigned mod is requested -BN.prototype.divmod = function divmod(num, mode, positive) { - assert(!num.isZero()); - - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0), - }; - } - - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); - - if (mode !== "mod") { - div = res.div.neg(); - } - - if (mode !== "div") { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } - - return { - div: div, - mod: mod, - }; - } - - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - - if (mode !== "mod") { - div = res.div.neg(); - } - - return { - div: div, - mod: res.mod, - }; - } - - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); - - if (mode !== "div") { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } - - return { - div: res.div, - mod: mod, - }; - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this, - }; - } - - // Very short reduction - if (num.length === 1) { - if (mode === "div") { - return { - div: this.divn(num.words[0]), - mod: null, - }; - } - - if (mode === "mod") { - return { - div: null, - mod: new BN(this.modrn(num.words[0])), - }; - } - - return { - div: this.divn(num.words[0]), - mod: new BN(this.modrn(num.words[0])), - }; - } - - return this._wordDiv(num, mode); -}; - -// Find `this` / `num` -BN.prototype.div = function div(num) { - return this.divmod(num, "div", false).div; -}; - -// Find `this` % `num` -BN.prototype.mod = function mod(num) { - return this.divmod(num, "mod", false).mod; -}; - -BN.prototype.umod = function umod(num) { - return this.divmod(num, "mod", true).mod; -}; - -// Find Round(`this` / `num`) -BN.prototype.divRound = function divRound(num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; - - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div; - - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); -}; - -BN.prototype.modrn = function modrn(num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } - - return isNegNum ? -acc : acc; -}; - -// WARNING: DEPRECATED -BN.prototype.modn = function modn(num) { - return this.modrn(num); -}; - -// In-place division by number -BN.prototype.idivn = function idivn(num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } - - this._strip(); - return isNegNum ? this.ineg() : this; -}; - -BN.prototype.divn = function divn(num) { - return this.clone().idivn(num); -}; - -BN.prototype.egcd = function egcd(p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var x = this; - var y = p.clone(); - - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } - - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); - - var g = 0; - - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; - } - - var yp = y.clone(); - var xp = x.clone(); - - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } - - A.iushrn(1); - B.iushrn(1); - } - } - - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } - - C.iushrn(1); - D.iushrn(1); - } - } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } - } - - return { - a: C, - b: D, - gcd: y.iushln(g), - }; -}; - -// This is reduced incarnation of the binary EEA -// above, designated to invert members of the -// _prime_ fields F(p) at a maximal speed -BN.prototype._invmp = function _invmp(p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var a = this; - var b = p.clone(); - - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); - } - - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } - - x1.iushrn(1); - } - } - - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } - - x2.iushrn(1); - } - } - - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } - - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } - - if (res.cmpn(0) < 0) { - res.iadd(p); - } - - return res; -}; - -BN.prototype.gcd = function gcd(num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } - - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } - - a.isub(b); - } while (true); - - return b.iushln(shift); -}; - -// Invert number in the field F(num) -BN.prototype.invm = function invm(num) { - return this.egcd(num).a.umod(num); -}; - -BN.prototype.isEven = function isEven() { - return (this.words[0] & 1) === 0; -}; - -BN.prototype.isOdd = function isOdd() { - return (this.words[0] & 1) === 1; -}; - -// And first word and num -BN.prototype.andln = function andln(num) { - return this.words[0] & num; -}; - -// Increment at the bit position in-line -BN.prototype.bincn = function bincn(bit) { - assert(typeof bit === "number"); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } - - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return this; -}; - -BN.prototype.isZero = function isZero() { - return this.length === 1 && this.words[0] === 0; -}; - -BN.prototype.cmpn = function cmpn(num) { - var negative = num < 0; - - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - - this._strip(); - - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } - - assert(num <= 0x3ffffff, "Number is too big"); - - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; -}; - -// Compare two numbers and return: -// 1 - if `this` > `num` -// 0 - if `this` == `num` -// -1 - if `this` < `num` -BN.prototype.cmp = function cmp(num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; -}; - -// Unsigned comparison -BN.prototype.ucmp = function ucmp(num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; -}; - -BN.prototype.gtn = function gtn(num) { - return this.cmpn(num) === 1; -}; - -BN.prototype.gt = function gt(num) { - return this.cmp(num) === 1; -}; - -BN.prototype.gten = function gten(num) { - return this.cmpn(num) >= 0; -}; - -BN.prototype.gte = function gte(num) { - return this.cmp(num) >= 0; -}; - -BN.prototype.ltn = function ltn(num) { - return this.cmpn(num) === -1; -}; - -BN.prototype.lt = function lt(num) { - return this.cmp(num) === -1; -}; - -BN.prototype.lten = function lten(num) { - return this.cmpn(num) <= 0; -}; - -BN.prototype.lte = function lte(num) { - return this.cmp(num) <= 0; -}; - -BN.prototype.eqn = function eqn(num) { - return this.cmpn(num) === 0; -}; - -BN.prototype.eq = function eq(num) { - return this.cmp(num) === 0; -}; - -// -// A reduce context, could be using montgomery or something better, depending -// on the `m` itself. -// -BN.red = function red(num) { - return new Red(num); -}; - -BN.prototype.toRed = function toRed(ctx) { - assert(!this.red, "Already a number in reduction context"); - assert(this.negative === 0, "red works only with positives"); - return ctx.convertTo(this)._forceRed(ctx); -}; - -BN.prototype.fromRed = function fromRed() { - assert(this.red, "fromRed works only with numbers in reduction context"); - return this.red.convertFrom(this); -}; - -BN.prototype._forceRed = function _forceRed(ctx) { - this.red = ctx; - return this; -}; - -BN.prototype.forceRed = function forceRed(ctx) { - assert(!this.red, "Already a number in reduction context"); - return this._forceRed(ctx); -}; - -BN.prototype.redAdd = function redAdd(num) { - assert(this.red, "redAdd works only with red numbers"); - return this.red.add(this, num); -}; - -BN.prototype.redIAdd = function redIAdd(num) { - assert(this.red, "redIAdd works only with red numbers"); - return this.red.iadd(this, num); -}; - -BN.prototype.redSub = function redSub(num) { - assert(this.red, "redSub works only with red numbers"); - return this.red.sub(this, num); -}; - -BN.prototype.redISub = function redISub(num) { - assert(this.red, "redISub works only with red numbers"); - return this.red.isub(this, num); -}; - -BN.prototype.redShl = function redShl(num) { - assert(this.red, "redShl works only with red numbers"); - return this.red.shl(this, num); -}; - -BN.prototype.redMul = function redMul(num) { - assert(this.red, "redMul works only with red numbers"); - this.red._verify2(this, num); - return this.red.mul(this, num); -}; - -BN.prototype.redIMul = function redIMul(num) { - assert(this.red, "redMul works only with red numbers"); - this.red._verify2(this, num); - return this.red.imul(this, num); -}; - -BN.prototype.redSqr = function redSqr() { - assert(this.red, "redSqr works only with red numbers"); - this.red._verify1(this); - return this.red.sqr(this); -}; - -BN.prototype.redISqr = function redISqr() { - assert(this.red, "redISqr works only with red numbers"); - this.red._verify1(this); - return this.red.isqr(this); -}; - -// Square root over p -BN.prototype.redSqrt = function redSqrt() { - assert(this.red, "redSqrt works only with red numbers"); - this.red._verify1(this); - return this.red.sqrt(this); -}; - -BN.prototype.redInvm = function redInvm() { - assert(this.red, "redInvm works only with red numbers"); - this.red._verify1(this); - return this.red.invm(this); -}; - -// Return negative clone of `this` % `red modulo` -BN.prototype.redNeg = function redNeg() { - assert(this.red, "redNeg works only with red numbers"); - this.red._verify1(this); - return this.red.neg(this); -}; - -BN.prototype.redPow = function redPow(num) { - assert(this.red && !num.red, "redPow(normalNum)"); - this.red._verify1(this); - return this.red.pow(this, num); -}; - -// Prime numbers with efficient reduction -var primes = { - k256: null, - p224: null, - p192: null, - p25519: null, -}; - -// Pseudo-Mersenne prime -function MPrime(name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); - - this.tmp = this._tmp(); -} - -MPrime.prototype._tmp = function _tmp() { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; -}; - -MPrime.prototype.ireduce = function ireduce(num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - if (r.strip !== undefined) { - // r is a BN v4 instance - r.strip(); - } else { - // r is a BN v5 instance - r._strip(); - } - } - - return r; -}; - -MPrime.prototype.split = function split(input, out) { - input.iushrn(this.n, 0, out); -}; - -MPrime.prototype.imulK = function imulK(num) { - return num.imul(this.k); -}; - -function K256() { - MPrime.call( - this, - "k256", - "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", - ); -} -inherits(K256, MPrime); - -K256.prototype.split = function split(input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } -}; - -K256.prototype.imulK = function imulK(num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; -}; - -function P224() { - MPrime.call( - this, - "p224", - "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", - ); -} -inherits(P224, MPrime); - -function P192() { - MPrime.call( - this, - "p192", - "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", - ); -} -inherits(P192, MPrime); - -function P25519() { - // 2 ^ 255 - 19 - MPrime.call( - this, - "25519", - "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", - ); -} -inherits(P25519, MPrime); - -P25519.prototype.imulK = function imulK(num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; -}; - -// Exported mostly for testing purposes, use plain name instead -BN._prime = function prime(name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === "k256") { - prime = new K256(); - } else if (name === "p224") { - prime = new P224(); - } else if (name === "p192") { - prime = new P192(); - } else if (name === "p25519") { - prime = new P25519(); - } else { - throw new Error("Unknown prime " + name); - } - primes[name] = prime; - - return prime; -}; - -// -// Base reduction engine -// -function Red(m) { - if (typeof m === "string") { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), "modulus must be greater than 1"); - this.m = m; - this.prime = null; - } -} - -Red.prototype._verify1 = function _verify1(a) { - assert(a.negative === 0, "red works only with positives"); - assert(a.red, "red works only with red numbers"); -}; - -Red.prototype._verify2 = function _verify2(a, b) { - assert((a.negative | b.negative) === 0, "red works only with positives"); - assert(a.red && a.red === b.red, "red works only with red numbers"); -}; - -Red.prototype.imod = function imod(a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - - move(a, a.umod(this.m)._forceRed(this)); - return a; -}; - -Red.prototype.neg = function neg(a) { - if (a.isZero()) { - return a.clone(); - } - - return this.m.sub(a)._forceRed(this); -}; - -Red.prototype.add = function add(a, b) { - this._verify2(a, b); - - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); -}; - -Red.prototype.iadd = function iadd(a, b) { - this._verify2(a, b); - - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; -}; - -Red.prototype.sub = function sub(a, b) { - this._verify2(a, b); - - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); -}; - -Red.prototype.isub = function isub(a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; -}; - -Red.prototype.shl = function shl(a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); -}; - -Red.prototype.imul = function imul(a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); -}; - -Red.prototype.mul = function mul(a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); -}; - -Red.prototype.isqr = function isqr(a) { - return this.imul(a, a.clone()); -}; - -Red.prototype.sqr = function sqr(a) { - return this.mul(a, a); -}; - -Red.prototype.sqrt = function sqrt(a) { - if (a.isZero()) return a.clone(); - - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); - } - assert(!q.isZero()); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } - - return r; -}; - -Red.prototype.invm = function invm(a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } -}; - -Red.prototype.pow = function pow(a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } - - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } - - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } - - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } - - return res; -}; - -Red.prototype.convertTo = function convertTo(num) { - var r = num.umod(this.m); - - return r === num ? r.clone() : r; -}; - -Red.prototype.convertFrom = function convertFrom(num) { - var res = num.clone(); - res.red = null; - return res; -}; - -// -// Montgomery method engine -// - -BN.mont = function mont(num) { - return new Mont(num); -}; - -function Mont(m) { - Red.call(this, m); - - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } - - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); -} -inherits(Mont, Red); - -Mont.prototype.convertTo = function convertTo(num) { - return this.imod(num.ushln(this.shift)); -}; - -Mont.prototype.convertFrom = function convertFrom(num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; -}; - -Mont.prototype.imul = function imul(a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); -}; - -Mont.prototype.mul = function mul(a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); -}; - -Mont.prototype.invm = function invm(a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); -};