Files
client/www/pq-crypto.bundle.js
2026-07-12 10:11:00 -04:00

7455 lines
185 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
// node_modules/@noble/hashes/utils.js
function isBytes(a) {
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
}
function anumber(n, title = "") {
if (typeof n !== "number") {
const prefix = title && `"${title}" `;
throw new TypeError(`${prefix}expected number, got ${typeof n}`);
}
if (!Number.isSafeInteger(n) || n < 0) {
const prefix = title && `"${title}" `;
throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
}
}
function abytes(value, length, title = "") {
const bytes = isBytes(value);
const len = value?.length;
const needsLen = length !== void 0;
if (!bytes || needsLen && len !== length) {
const prefix = title && `"${title}" `;
const ofLen = needsLen ? ` of length ${length}` : "";
const got = bytes ? `length=${len}` : `type=${typeof value}`;
const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
if (!bytes)
throw new TypeError(message);
throw new RangeError(message);
}
return value;
}
function ahash(h) {
if (typeof h !== "function" || typeof h.create !== "function")
throw new TypeError("Hash must wrapped by utils.createHasher");
anumber(h.outputLen);
anumber(h.blockLen);
if (h.outputLen < 1)
throw new Error('"outputLen" must be >= 1');
if (h.blockLen < 1)
throw new Error('"blockLen" must be >= 1');
}
function aexists(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 aoutput(out, instance) {
abytes(out, void 0, "digestInto() output");
const min = instance.outputLen;
if (out.length < min) {
throw new RangeError('"digestInto() output" expected to be of length >=' + min);
}
}
function u32(arr) {
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
function clean(...arrays) {
for (let i = 0; i < arrays.length; i++) {
arrays[i].fill(0);
}
}
function createView(arr) {
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
function rotr(word, shift) {
return word << 32 - shift | word >>> shift;
}
function rotl(word, shift) {
return word << shift | word >>> 32 - shift >>> 0;
}
var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
function byteSwap(word) {
return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
}
function byteSwap32(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] = byteSwap(arr[i]);
}
return arr;
}
var swap32IfBE = isLE ? (u) => u : byteSwap32;
var hasHexBuiltin = /* @__PURE__ */ (() => (
// @ts-ignore
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
))();
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
function bytesToHex(bytes) {
abytes(bytes);
if (hasHexBuiltin)
return bytes.toHex();
let hex = "";
for (let i = 0; i < bytes.length; i++) {
hex += hexes[bytes[i]];
}
return hex;
}
var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
if (ch >= asciis._0 && ch <= asciis._9)
return ch - asciis._0;
if (ch >= asciis.A && ch <= asciis.F)
return ch - (asciis.A - 10);
if (ch >= asciis.a && ch <= asciis.f)
return ch - (asciis.a - 10);
return;
}
function hexToBytes(hex) {
if (typeof hex !== "string")
throw new TypeError("hex string expected, got " + typeof hex);
if (hasHexBuiltin) {
try {
return Uint8Array.fromHex(hex);
} catch (error) {
if (error instanceof SyntaxError)
throw new RangeError(error.message);
throw error;
}
}
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
throw new RangeError("hex string expected, got unpadded hex of length " + hl);
const array = new Uint8Array(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
const n1 = asciiToBase16(hex.charCodeAt(hi));
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
if (n1 === void 0 || n2 === void 0) {
const char = hex[hi] + hex[hi + 1];
throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
}
array[ai] = n1 * 16 + n2;
}
return array;
}
function utf8ToBytes(str) {
if (typeof str !== "string")
throw new TypeError("string expected");
return new Uint8Array(new TextEncoder().encode(str));
}
function kdfInputToBytes(data, errorTitle = "") {
if (typeof data === "string")
return utf8ToBytes(data);
return abytes(data, void 0, errorTitle);
}
function concatBytes(...arrays) {
let sum = 0;
for (let i = 0; i < arrays.length; i++) {
const a = arrays[i];
abytes(a);
sum += a.length;
}
const res = new Uint8Array(sum);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const a = arrays[i];
res.set(a, pad);
pad += a.length;
}
return res;
}
function checkOpts(defaults, opts2) {
if (opts2 !== void 0 && {}.toString.call(opts2) !== "[object Object]")
throw new TypeError("options must be object or undefined");
const merged = Object.assign(defaults, opts2);
return merged;
}
function createHasher(hashCons, info = {}) {
const hashC = (msg, opts2) => hashCons(opts2).update(msg).digest();
const tmp = hashCons(void 0);
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.canXOF = tmp.canXOF;
hashC.create = (opts2) => hashCons(opts2);
Object.assign(hashC, info);
return Object.freeze(hashC);
}
function randomBytes(bytesLength = 32) {
anumber(bytesLength, "bytesLength");
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
if (typeof cr?.getRandomValues !== "function")
throw new Error("crypto.getRandomValues must be defined");
if (bytesLength > 65536)
throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
return cr.getRandomValues(new Uint8Array(bytesLength));
}
var oidNist = (suffix) => ({
// Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
// Larger suffix values would need base-128 OID encoding and a different length byte.
oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
});
// node_modules/@noble/hashes/hmac.js
var _HMAC = class {
constructor(hash, key) {
__publicField(this, "oHash");
__publicField(this, "iHash");
__publicField(this, "blockLen");
__publicField(this, "outputLen");
__publicField(this, "canXOF", false);
__publicField(this, "finished", false);
__publicField(this, "destroyed", false);
ahash(hash);
abytes(key, void 0, "key");
this.iHash = hash.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 ? hash.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54;
this.iHash.update(pad);
this.oHash = hash.create();
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54 ^ 92;
this.oHash.update(pad);
clean(pad);
}
update(buf) {
aexists(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
aexists(this);
aoutput(out, this);
this.finished = true;
const buf = out.subarray(0, this.outputLen);
this.iHash.digestInto(buf);
this.oHash.update(buf);
this.oHash.digestInto(buf);
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;
}
clone() {
return this._cloneInto();
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
};
var hmac = /* @__PURE__ */ (() => {
const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
hmac_.create = (hash, key) => new _HMAC(hash, key);
return hmac_;
})();
// node_modules/@noble/hashes/pbkdf2.js
function pbkdf2Init(hash, _password, _salt, _opts) {
ahash(hash);
const opts2 = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
const { c, dkLen, asyncTick } = opts2;
anumber(c, "c");
anumber(dkLen, "dkLen");
anumber(asyncTick, "asyncTick");
if (c < 1)
throw new Error("iterations (c) must be >= 1");
if (dkLen < 1)
throw new Error('"dkLen" must be >= 1');
if (dkLen > (2 ** 32 - 1) * hash.outputLen)
throw new Error("derived key too long");
const password = kdfInputToBytes(_password, "password");
const salt = kdfInputToBytes(_salt, "salt");
const DK = new Uint8Array(dkLen);
const PRF = hmac.create(hash, 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();
clean(u);
return DK;
}
function pbkdf2(hash, password, salt, opts2) {
const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts2);
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);
}
// node_modules/@noble/hashes/_md.js
function Chi(a, b, c) {
return a & b ^ ~a & c;
}
function Maj(a, b, c) {
return a & b ^ a & c ^ b & c;
}
var HashMD = class {
constructor(blockLen, outputLen, padOffset, isLE2) {
__publicField(this, "blockLen");
__publicField(this, "outputLen");
__publicField(this, "canXOF", false);
__publicField(this, "padOffset");
__publicField(this, "isLE");
// For partial updates less than block size
__publicField(this, "buffer");
__publicField(this, "view");
__publicField(this, "finished", false);
__publicField(this, "length", 0);
__publicField(this, "pos", 0);
__publicField(this, "destroyed", false);
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE2;
this.buffer = new Uint8Array(blockLen);
this.view = createView(this.buffer);
}
update(data) {
aexists(this);
abytes(data);
const { view, buffer, blockLen } = this;
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) {
aexists(this);
aoutput(out, this);
this.finished = true;
const { buffer, view, blockLen, isLE: isLE2 } = this;
let { pos } = this;
buffer[pos++] = 128;
clean(this.buffer.subarray(pos));
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
view.setBigUint64(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 must 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.destroyed = destroyed;
to.finished = finished;
to.length = length;
to.pos = pos;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
clone() {
return this._cloneInto();
}
};
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
1779033703,
3144134277,
1013904242,
2773480762,
1359893119,
2600822924,
528734635,
1541459225
]);
var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1779033703,
4089235720,
3144134277,
2227873595,
1013904242,
4271175723,
2773480762,
1595750129,
1359893119,
2917565137,
2600822924,
725511199,
528734635,
4215389547,
1541459225,
327033209
]);
// node_modules/@noble/hashes/_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) {
const len = lst.length;
let Ah = new Uint32Array(len);
let Al = new Uint32Array(len);
for (let i = 0; i < len; i++) {
const { h, l } = fromBig(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
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 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;
// node_modules/@noble/hashes/sha2.js
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
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 SHA256_W = /* @__PURE__ */ new Uint32Array(64);
var SHA2_32B = class extends HashMD {
constructor(outputLen) {
super(64, outputLen, 8, false);
}
get() {
const { A, B, C, D: D2, E, F: F3, G, H } = this;
return [A, B, C, D2, E, F3, G, H];
}
// prettier-ignore
set(A, B, C, D2, E, F3, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D2 | 0;
this.E = E | 0;
this.F = F3 | 0;
this.G = G | 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: D2, E, F: F3, 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, F3, 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;
H = G;
G = F3;
F3 = E;
E = D2 + T1 | 0;
D2 = C;
C = B;
B = A;
A = T1 + T2 | 0;
}
A = A + this.A | 0;
B = B + this.B | 0;
C = C + this.C | 0;
D2 = D2 + this.D | 0;
E = E + this.E | 0;
F3 = F3 + this.F | 0;
G = G + this.G | 0;
H = H + this.H | 0;
this.set(A, B, C, D2, E, F3, G, H);
}
roundClean() {
clean(SHA256_W);
}
destroy() {
this.destroyed = true;
this.set(0, 0, 0, 0, 0, 0, 0, 0);
clean(this.buffer);
}
};
var _SHA256 = class extends SHA2_32B {
constructor() {
super(32);
// We cannot use array here since array allows indexing by variable
// which means optimizer/compiler cannot use registers.
__publicField(this, "A", SHA256_IV[0] | 0);
__publicField(this, "B", SHA256_IV[1] | 0);
__publicField(this, "C", SHA256_IV[2] | 0);
__publicField(this, "D", SHA256_IV[3] | 0);
__publicField(this, "E", SHA256_IV[4] | 0);
__publicField(this, "F", SHA256_IV[5] | 0);
__publicField(this, "G", SHA256_IV[6] | 0);
__publicField(this, "H", SHA256_IV[7] | 0);
}
};
var K512 = /* @__PURE__ */ (() => 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 = /* @__PURE__ */ (() => K512[0])();
var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
var SHA2_64B = class extends HashMD {
constructor(outputLen) {
super(128, outputLen, 16, false);
}
// 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 = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
const W2h = SHA512_W_H[i - 2] | 0;
const W2l = SHA512_W_L[i - 2] | 0;
const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
const SUMh = 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 = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
const CHIh = Eh & Fh ^ ~Eh & Gh;
const CHIl = El & Fl ^ ~El & Gl;
const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
const T1l = T1ll | 0;
const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ 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 } = 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 = add3L(T1l, sigma0l, MAJl);
Ah = add3H(All, T1h, sigma0h, MAJh);
Al = All | 0;
}
({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
({ h: Hh, l: Hl } = 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() {
clean(SHA512_W_H, SHA512_W_L);
}
destroy() {
this.destroyed = true;
clean(this.buffer);
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
};
var _SHA512 = class extends SHA2_64B {
constructor() {
super(64);
__publicField(this, "Ah", SHA512_IV[0] | 0);
__publicField(this, "Al", SHA512_IV[1] | 0);
__publicField(this, "Bh", SHA512_IV[2] | 0);
__publicField(this, "Bl", SHA512_IV[3] | 0);
__publicField(this, "Ch", SHA512_IV[4] | 0);
__publicField(this, "Cl", SHA512_IV[5] | 0);
__publicField(this, "Dh", SHA512_IV[6] | 0);
__publicField(this, "Dl", SHA512_IV[7] | 0);
__publicField(this, "Eh", SHA512_IV[8] | 0);
__publicField(this, "El", SHA512_IV[9] | 0);
__publicField(this, "Fh", SHA512_IV[10] | 0);
__publicField(this, "Fl", SHA512_IV[11] | 0);
__publicField(this, "Gh", SHA512_IV[12] | 0);
__publicField(this, "Gl", SHA512_IV[13] | 0);
__publicField(this, "Hh", SHA512_IV[14] | 0);
__publicField(this, "Hl", SHA512_IV[15] | 0);
}
};
var sha256 = /* @__PURE__ */ createHasher(
() => new _SHA256(),
/* @__PURE__ */ oidNist(1)
);
var sha512 = /* @__PURE__ */ createHasher(
() => new _SHA512(),
/* @__PURE__ */ oidNist(3)
);
// node_modules/@scure/base/index.js
function isBytes2(a) {
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
}
function isArrayOf(isString, arr) {
if (!Array.isArray(arr))
return false;
if (arr.length === 0)
return true;
if (isString) {
return arr.every((item) => typeof item === "string");
} else {
return arr.every((item) => Number.isSafeInteger(item));
}
}
function afn(input) {
if (typeof input !== "function")
throw new TypeError("function expected");
return true;
}
function astr(label, input) {
if (typeof input !== "string")
throw new TypeError(`${label}: string expected`);
return true;
}
function anumber2(n) {
if (typeof n !== "number")
throw new TypeError(`number expected, got ${typeof n}`);
if (!Number.isSafeInteger(n))
throw new RangeError(`invalid integer: ${n}`);
}
function aArr(input) {
if (!Array.isArray(input))
throw new TypeError("array expected");
}
function astrArr(label, input) {
if (!isArrayOf(true, input))
throw new TypeError(`${label}: array of strings expected`);
}
function anumArr(label, input) {
if (!isArrayOf(false, input))
throw new TypeError(`${label}: array of numbers expected`);
}
// @__NO_SIDE_EFFECTS__
function chain(...args) {
const id2 = (a) => a;
const wrap = (a, b) => (c) => a(b(c));
const encode = args.map((x) => x.encode).reduceRight(wrap, id2);
const decode = args.map((x) => x.decode).reduce(wrap, id2);
return { encode, decode };
}
// @__NO_SIDE_EFFECTS__
function alphabet(letters) {
const lettersA = typeof letters === "string" ? letters.split("") : letters;
const len = lettersA.length;
astrArr("alphabet", lettersA);
const indexes = new Map(lettersA.map((l, i) => [l, i]));
return {
encode: (digits) => {
aArr(digits);
return digits.map((i) => {
if (!Number.isSafeInteger(i) || i < 0 || i >= len)
throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
return lettersA[i];
});
},
decode: (input) => {
aArr(input);
return input.map((letter) => {
astr("alphabet.decode", letter);
const i = indexes.get(letter);
if (i === void 0)
throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
return i;
});
}
};
}
// @__NO_SIDE_EFFECTS__
function join(separator = "") {
astr("join", separator);
return {
encode: (from) => {
astrArr("join.decode", from);
return from.join(separator);
},
decode: (to) => {
astr("join.decode", to);
return to.split(separator);
}
};
}
// @__NO_SIDE_EFFECTS__
function padding(bits, chr = "=") {
anumber2(bits);
astr("padding", chr);
return {
encode(data) {
astrArr("padding.encode", data);
while (data.length * bits % 8)
data.push(chr);
return data;
},
decode(input) {
astrArr("padding.decode", input);
let end = input.length;
if (end * bits % 8)
throw new Error("padding: invalid, string should have whole number of bytes");
for (; end > 0 && input[end - 1] === chr; end--) {
const last = end - 1;
const byte = last * bits;
if (byte % 8 === 0)
throw new Error("padding: invalid, string has too much padding");
}
return input.slice(0, end);
}
};
}
function convertRadix(data, from, to) {
if (from < 2)
throw new RangeError(`convertRadix: invalid from=${from}, base cannot be less than 2`);
if (to < 2)
throw new RangeError(`convertRadix: invalid to=${to}, base cannot be less than 2`);
aArr(data);
if (!data.length)
return [];
let pos = 0;
const res = [];
const digits = Array.from(data, (d) => {
anumber2(d);
if (d < 0 || d >= from)
throw new Error(`invalid integer: ${d}`);
return d;
});
const dlen = digits.length;
while (true) {
let carry = 0;
let done = true;
for (let i = pos; i < dlen; i++) {
const digit = digits[i];
const fromCarry = from * carry;
const digitBase = fromCarry + digit;
if (!Number.isSafeInteger(digitBase) || fromCarry / from !== carry || digitBase - digit !== fromCarry) {
throw new Error("convertRadix: carry overflow");
}
const div = digitBase / to;
carry = digitBase % to;
const rounded = Math.floor(div);
digits[i] = rounded;
if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
throw new Error("convertRadix: carry overflow");
if (!done)
continue;
else if (!rounded)
pos = i;
else
done = false;
}
res.push(carry);
if (done)
break;
}
for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
res.push(0);
return res.reverse();
}
var gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
var radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to));
var powers = /* @__PURE__ */ (() => {
let res = [];
for (let i = 0; i < 40; i++)
res.push(2 ** i);
return res;
})();
function convertRadix2(data, from, to, padding2) {
aArr(data);
if (from <= 0 || from > 32)
throw new RangeError(`convertRadix2: wrong from=${from}`);
if (to <= 0 || to > 32)
throw new RangeError(`convertRadix2: wrong to=${to}`);
if (/* @__PURE__ */ radix2carry(from, to) > 32) {
throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${/* @__PURE__ */ radix2carry(from, to)}`);
}
let carry = 0;
let pos = 0;
const max = powers[from];
const mask = powers[to] - 1;
const res = [];
for (const n of data) {
anumber2(n);
if (n >= max)
throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
carry = carry << from | n;
if (pos + from > 32)
throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
pos += from;
for (; pos >= to; pos -= to)
res.push((carry >> pos - to & mask) >>> 0);
const pow = powers[pos];
if (pow === void 0)
throw new Error("invalid carry");
carry &= pow - 1;
}
carry = carry << to - pos & mask;
if (!padding2 && pos >= from)
throw new Error("Excess padding");
if (!padding2 && carry > 0)
throw new Error(`Non-zero padding: ${carry}`);
if (padding2 && pos > 0)
res.push(carry >>> 0);
return res;
}
// @__NO_SIDE_EFFECTS__
function radix(num) {
anumber2(num);
const _256 = 2 ** 8;
return {
encode: (bytes) => {
if (!isBytes2(bytes))
throw new TypeError("radix.encode input should be Uint8Array");
return convertRadix(Array.from(bytes), _256, num);
},
decode: (digits) => {
anumArr("radix.decode", digits);
return Uint8Array.from(convertRadix(digits, num, _256));
}
};
}
// @__NO_SIDE_EFFECTS__
function radix2(bits, revPadding = false) {
anumber2(bits);
if (bits <= 0 || bits > 32)
throw new RangeError("radix2: bits should be in (0..32]");
if (/* @__PURE__ */ radix2carry(8, bits) > 32 || /* @__PURE__ */ radix2carry(bits, 8) > 32)
throw new RangeError("radix2: carry overflow");
return {
encode: (bytes) => {
if (!isBytes2(bytes))
throw new TypeError("radix2.encode input should be Uint8Array");
return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
},
decode: (digits) => {
anumArr("radix2.decode", digits);
return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
}
};
}
function checksum(len, fn) {
anumber2(len);
if (len <= 0)
throw new RangeError(`checksum length must be positive: ${len}`);
afn(fn);
const _fn = fn;
return {
encode(data) {
if (!isBytes2(data))
throw new TypeError("checksum.encode: input should be Uint8Array");
const sum = _fn(data).slice(0, len);
const res = new Uint8Array(data.length + len);
res.set(data);
res.set(sum, data.length);
return res;
},
decode(data) {
if (!isBytes2(data))
throw new TypeError("checksum.decode: input should be Uint8Array");
const payload = data.slice(0, -len);
const oldChecksum = data.slice(-len);
const newChecksum = _fn(payload).slice(0, len);
for (let i = 0; i < len; i++)
if (newChecksum[i] !== oldChecksum[i])
throw new Error("Invalid checksum");
return payload;
}
};
}
var utils = /* @__PURE__ */ Object.freeze({
alphabet,
chain,
checksum,
convertRadix,
convertRadix2,
radix,
radix2,
join,
padding
});
var genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain(/* @__PURE__ */ radix(58), /* @__PURE__ */ alphabet(abc), /* @__PURE__ */ join(""));
var base58 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"));
var createBase58check = (sha2562) => {
afn(sha2562);
const _sha256 = sha2562;
return /* @__PURE__ */ chain(checksum(4, (data) => _sha256(_sha256(data))), base58);
};
// node_modules/@scure/bip39/index.js
var isJapanese = (wordlist2) => wordlist2[0] === "\u3042\u3044\u3053\u304F\u3057\u3093";
function nfkd(str) {
if (typeof str !== "string")
throw new TypeError("invalid mnemonic type: " + typeof str);
return str.normalize("NFKD");
}
function normalize(str) {
const norm = nfkd(str);
const words = norm.split(" ");
if (![12, 15, 18, 21, 24].includes(words.length))
throw new Error("Invalid mnemonic");
return { nfkd: norm, words };
}
function aentropy(ent) {
abytes(ent);
if (![16, 20, 24, 28, 32].includes(ent.length))
throw new RangeError("invalid entropy length");
}
function generateMnemonic(wordlist2, strength = 128) {
anumber(strength);
if (strength % 32 !== 0 || strength > 256)
throw new RangeError("Invalid entropy");
return entropyToMnemonic(randomBytes(strength / 8), wordlist2);
}
var calcChecksum = (entropy) => {
const bitsLeft = 8 - entropy.length / 4;
return new Uint8Array([sha256(entropy)[0] >> bitsLeft << bitsLeft]);
};
function getCoder(wordlist2) {
if (!Array.isArray(wordlist2) || wordlist2.length !== 2048 || typeof wordlist2[0] !== "string")
throw new TypeError("Wordlist: expected array of 2048 strings");
wordlist2.forEach((i) => {
if (typeof i !== "string")
throw new TypeError("wordlist: non-string element: " + i);
});
return utils.chain(utils.checksum(1, calcChecksum), utils.radix2(11, true), utils.alphabet(wordlist2));
}
function mnemonicToEntropy(mnemonic, wordlist2) {
const { words } = normalize(mnemonic);
const entropy = getCoder(wordlist2).decode(words);
aentropy(entropy);
return entropy;
}
function entropyToMnemonic(entropy, wordlist2) {
aentropy(entropy);
const words = getCoder(wordlist2).encode(entropy);
return words.join(isJapanese(wordlist2) ? "\u3000" : " ");
}
function validateMnemonic(mnemonic, wordlist2) {
try {
mnemonicToEntropy(mnemonic, wordlist2);
} catch (e) {
return false;
}
return true;
}
var psalt = (passphrase) => nfkd("mnemonic" + passphrase);
function mnemonicToSeedSync(mnemonic, passphrase = "") {
return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {
c: 2048,
dkLen: 64
});
}
// node_modules/@scure/bip39/wordlists/english.js
var wordlist = /* @__PURE__ */ Object.freeze(`abandon
ability
able
about
above
absent
absorb
abstract
absurd
abuse
access
accident
account
accuse
achieve
acid
acoustic
acquire
across
act
action
actor
actress
actual
adapt
add
addict
address
adjust
admit
adult
advance
advice
aerobic
affair
afford
afraid
again
age
agent
agree
ahead
aim
air
airport
aisle
alarm
album
alcohol
alert
alien
all
alley
allow
almost
alone
alpha
already
also
alter
always
amateur
amazing
among
amount
amused
analyst
anchor
ancient
anger
angle
angry
animal
ankle
announce
annual
another
answer
antenna
antique
anxiety
any
apart
apology
appear
apple
approve
april
arch
arctic
area
arena
argue
arm
armed
armor
army
around
arrange
arrest
arrive
arrow
art
artefact
artist
artwork
ask
aspect
assault
asset
assist
assume
asthma
athlete
atom
attack
attend
attitude
attract
auction
audit
august
aunt
author
auto
autumn
average
avocado
avoid
awake
aware
away
awesome
awful
awkward
axis
baby
bachelor
bacon
badge
bag
balance
balcony
ball
bamboo
banana
banner
bar
barely
bargain
barrel
base
basic
basket
battle
beach
bean
beauty
because
become
beef
before
begin
behave
behind
believe
below
belt
bench
benefit
best
betray
better
between
beyond
bicycle
bid
bike
bind
biology
bird
birth
bitter
black
blade
blame
blanket
blast
bleak
bless
blind
blood
blossom
blouse
blue
blur
blush
board
boat
body
boil
bomb
bone
bonus
book
boost
border
boring
borrow
boss
bottom
bounce
box
boy
bracket
brain
brand
brass
brave
bread
breeze
brick
bridge
brief
bright
bring
brisk
broccoli
broken
bronze
broom
brother
brown
brush
bubble
buddy
budget
buffalo
build
bulb
bulk
bullet
bundle
bunker
burden
burger
burst
bus
business
busy
butter
buyer
buzz
cabbage
cabin
cable
cactus
cage
cake
call
calm
camera
camp
can
canal
cancel
candy
cannon
canoe
canvas
canyon
capable
capital
captain
car
carbon
card
cargo
carpet
carry
cart
case
cash
casino
castle
casual
cat
catalog
catch
category
cattle
caught
cause
caution
cave
ceiling
celery
cement
census
century
cereal
certain
chair
chalk
champion
change
chaos
chapter
charge
chase
chat
cheap
check
cheese
chef
cherry
chest
chicken
chief
child
chimney
choice
choose
chronic
chuckle
chunk
churn
cigar
cinnamon
circle
citizen
city
civil
claim
clap
clarify
claw
clay
clean
clerk
clever
click
client
cliff
climb
clinic
clip
clock
clog
close
cloth
cloud
clown
club
clump
cluster
clutch
coach
coast
coconut
code
coffee
coil
coin
collect
color
column
combine
come
comfort
comic
common
company
concert
conduct
confirm
congress
connect
consider
control
convince
cook
cool
copper
copy
coral
core
corn
correct
cost
cotton
couch
country
couple
course
cousin
cover
coyote
crack
cradle
craft
cram
crane
crash
crater
crawl
crazy
cream
credit
creek
crew
cricket
crime
crisp
critic
crop
cross
crouch
crowd
crucial
cruel
cruise
crumble
crunch
crush
cry
crystal
cube
culture
cup
cupboard
curious
current
curtain
curve
cushion
custom
cute
cycle
dad
damage
damp
dance
danger
daring
dash
daughter
dawn
day
deal
debate
debris
decade
december
decide
decline
decorate
decrease
deer
defense
define
defy
degree
delay
deliver
demand
demise
denial
dentist
deny
depart
depend
deposit
depth
deputy
derive
describe
desert
design
desk
despair
destroy
detail
detect
develop
device
devote
diagram
dial
diamond
diary
dice
diesel
diet
differ
digital
dignity
dilemma
dinner
dinosaur
direct
dirt
disagree
discover
disease
dish
dismiss
disorder
display
distance
divert
divide
divorce
dizzy
doctor
document
dog
doll
dolphin
domain
donate
donkey
donor
door
dose
double
dove
draft
dragon
drama
drastic
draw
dream
dress
drift
drill
drink
drip
drive
drop
drum
dry
duck
dumb
dune
during
dust
dutch
duty
dwarf
dynamic
eager
eagle
early
earn
earth
easily
east
easy
echo
ecology
economy
edge
edit
educate
effort
egg
eight
either
elbow
elder
electric
elegant
element
elephant
elevator
elite
else
embark
embody
embrace
emerge
emotion
employ
empower
empty
enable
enact
end
endless
endorse
enemy
energy
enforce
engage
engine
enhance
enjoy
enlist
enough
enrich
enroll
ensure
enter
entire
entry
envelope
episode
equal
equip
era
erase
erode
erosion
error
erupt
escape
essay
essence
estate
eternal
ethics
evidence
evil
evoke
evolve
exact
example
excess
exchange
excite
exclude
excuse
execute
exercise
exhaust
exhibit
exile
exist
exit
exotic
expand
expect
expire
explain
expose
express
extend
extra
eye
eyebrow
fabric
face
faculty
fade
faint
faith
fall
false
fame
family
famous
fan
fancy
fantasy
farm
fashion
fat
fatal
father
fatigue
fault
favorite
feature
february
federal
fee
feed
feel
female
fence
festival
fetch
fever
few
fiber
fiction
field
figure
file
film
filter
final
find
fine
finger
finish
fire
firm
first
fiscal
fish
fit
fitness
fix
flag
flame
flash
flat
flavor
flee
flight
flip
float
flock
floor
flower
fluid
flush
fly
foam
focus
fog
foil
fold
follow
food
foot
force
forest
forget
fork
fortune
forum
forward
fossil
foster
found
fox
fragile
frame
frequent
fresh
friend
fringe
frog
front
frost
frown
frozen
fruit
fuel
fun
funny
furnace
fury
future
gadget
gain
galaxy
gallery
game
gap
garage
garbage
garden
garlic
garment
gas
gasp
gate
gather
gauge
gaze
general
genius
genre
gentle
genuine
gesture
ghost
giant
gift
giggle
ginger
giraffe
girl
give
glad
glance
glare
glass
glide
glimpse
globe
gloom
glory
glove
glow
glue
goat
goddess
gold
good
goose
gorilla
gospel
gossip
govern
gown
grab
grace
grain
grant
grape
grass
gravity
great
green
grid
grief
grit
grocery
group
grow
grunt
guard
guess
guide
guilt
guitar
gun
gym
habit
hair
half
hammer
hamster
hand
happy
harbor
hard
harsh
harvest
hat
have
hawk
hazard
head
health
heart
heavy
hedgehog
height
hello
helmet
help
hen
hero
hidden
high
hill
hint
hip
hire
history
hobby
hockey
hold
hole
holiday
hollow
home
honey
hood
hope
horn
horror
horse
hospital
host
hotel
hour
hover
hub
huge
human
humble
humor
hundred
hungry
hunt
hurdle
hurry
hurt
husband
hybrid
ice
icon
idea
identify
idle
ignore
ill
illegal
illness
image
imitate
immense
immune
impact
impose
improve
impulse
inch
include
income
increase
index
indicate
indoor
industry
infant
inflict
inform
inhale
inherit
initial
inject
injury
inmate
inner
innocent
input
inquiry
insane
insect
inside
inspire
install
intact
interest
into
invest
invite
involve
iron
island
isolate
issue
item
ivory
jacket
jaguar
jar
jazz
jealous
jeans
jelly
jewel
job
join
joke
journey
joy
judge
juice
jump
jungle
junior
junk
just
kangaroo
keen
keep
ketchup
key
kick
kid
kidney
kind
kingdom
kiss
kit
kitchen
kite
kitten
kiwi
knee
knife
knock
know
lab
label
labor
ladder
lady
lake
lamp
language
laptop
large
later
latin
laugh
laundry
lava
law
lawn
lawsuit
layer
lazy
leader
leaf
learn
leave
lecture
left
leg
legal
legend
leisure
lemon
lend
length
lens
leopard
lesson
letter
level
liar
liberty
library
license
life
lift
light
like
limb
limit
link
lion
liquid
list
little
live
lizard
load
loan
lobster
local
lock
logic
lonely
long
loop
lottery
loud
lounge
love
loyal
lucky
luggage
lumber
lunar
lunch
luxury
lyrics
machine
mad
magic
magnet
maid
mail
main
major
make
mammal
man
manage
mandate
mango
mansion
manual
maple
marble
march
margin
marine
market
marriage
mask
mass
master
match
material
math
matrix
matter
maximum
maze
meadow
mean
measure
meat
mechanic
medal
media
melody
melt
member
memory
mention
menu
mercy
merge
merit
merry
mesh
message
metal
method
middle
midnight
milk
million
mimic
mind
minimum
minor
minute
miracle
mirror
misery
miss
mistake
mix
mixed
mixture
mobile
model
modify
mom
moment
monitor
monkey
monster
month
moon
moral
more
morning
mosquito
mother
motion
motor
mountain
mouse
move
movie
much
muffin
mule
multiply
muscle
museum
mushroom
music
must
mutual
myself
mystery
myth
naive
name
napkin
narrow
nasty
nation
nature
near
neck
need
negative
neglect
neither
nephew
nerve
nest
net
network
neutral
never
news
next
nice
night
noble
noise
nominee
noodle
normal
north
nose
notable
note
nothing
notice
novel
now
nuclear
number
nurse
nut
oak
obey
object
oblige
obscure
observe
obtain
obvious
occur
ocean
october
odor
off
offer
office
often
oil
okay
old
olive
olympic
omit
once
one
onion
online
only
open
opera
opinion
oppose
option
orange
orbit
orchard
order
ordinary
organ
orient
original
orphan
ostrich
other
outdoor
outer
output
outside
oval
oven
over
own
owner
oxygen
oyster
ozone
pact
paddle
page
pair
palace
palm
panda
panel
panic
panther
paper
parade
parent
park
parrot
party
pass
patch
path
patient
patrol
pattern
pause
pave
payment
peace
peanut
pear
peasant
pelican
pen
penalty
pencil
people
pepper
perfect
permit
person
pet
phone
photo
phrase
physical
piano
picnic
picture
piece
pig
pigeon
pill
pilot
pink
pioneer
pipe
pistol
pitch
pizza
place
planet
plastic
plate
play
please
pledge
pluck
plug
plunge
poem
poet
point
polar
pole
police
pond
pony
pool
popular
portion
position
possible
post
potato
pottery
poverty
powder
power
practice
praise
predict
prefer
prepare
present
pretty
prevent
price
pride
primary
print
priority
prison
private
prize
problem
process
produce
profit
program
project
promote
proof
property
prosper
protect
proud
provide
public
pudding
pull
pulp
pulse
pumpkin
punch
pupil
puppy
purchase
purity
purpose
purse
push
put
puzzle
pyramid
quality
quantum
quarter
question
quick
quit
quiz
quote
rabbit
raccoon
race
rack
radar
radio
rail
rain
raise
rally
ramp
ranch
random
range
rapid
rare
rate
rather
raven
raw
razor
ready
real
reason
rebel
rebuild
recall
receive
recipe
record
recycle
reduce
reflect
reform
refuse
region
regret
regular
reject
relax
release
relief
rely
remain
remember
remind
remove
render
renew
rent
reopen
repair
repeat
replace
report
require
rescue
resemble
resist
resource
response
result
retire
retreat
return
reunion
reveal
review
reward
rhythm
rib
ribbon
rice
rich
ride
ridge
rifle
right
rigid
ring
riot
ripple
risk
ritual
rival
river
road
roast
robot
robust
rocket
romance
roof
rookie
room
rose
rotate
rough
round
route
royal
rubber
rude
rug
rule
run
runway
rural
sad
saddle
sadness
safe
sail
salad
salmon
salon
salt
salute
same
sample
sand
satisfy
satoshi
sauce
sausage
save
say
scale
scan
scare
scatter
scene
scheme
school
science
scissors
scorpion
scout
scrap
screen
script
scrub
sea
search
season
seat
second
secret
section
security
seed
seek
segment
select
sell
seminar
senior
sense
sentence
series
service
session
settle
setup
seven
shadow
shaft
shallow
share
shed
shell
sheriff
shield
shift
shine
ship
shiver
shock
shoe
shoot
shop
short
shoulder
shove
shrimp
shrug
shuffle
shy
sibling
sick
side
siege
sight
sign
silent
silk
silly
silver
similar
simple
since
sing
siren
sister
situate
six
size
skate
sketch
ski
skill
skin
skirt
skull
slab
slam
sleep
slender
slice
slide
slight
slim
slogan
slot
slow
slush
small
smart
smile
smoke
smooth
snack
snake
snap
sniff
snow
soap
soccer
social
sock
soda
soft
solar
soldier
solid
solution
solve
someone
song
soon
sorry
sort
soul
sound
soup
source
south
space
spare
spatial
spawn
speak
special
speed
spell
spend
sphere
spice
spider
spike
spin
spirit
split
spoil
sponsor
spoon
sport
spot
spray
spread
spring
spy
square
squeeze
squirrel
stable
stadium
staff
stage
stairs
stamp
stand
start
state
stay
steak
steel
stem
step
stereo
stick
still
sting
stock
stomach
stone
stool
story
stove
strategy
street
strike
strong
struggle
student
stuff
stumble
style
subject
submit
subway
success
such
sudden
suffer
sugar
suggest
suit
summer
sun
sunny
sunset
super
supply
supreme
sure
surface
surge
surprise
surround
survey
suspect
sustain
swallow
swamp
swap
swarm
swear
sweet
swift
swim
swing
switch
sword
symbol
symptom
syrup
system
table
tackle
tag
tail
talent
talk
tank
tape
target
task
taste
tattoo
taxi
teach
team
tell
ten
tenant
tennis
tent
term
test
text
thank
that
theme
then
theory
there
they
thing
this
thought
three
thrive
throw
thumb
thunder
ticket
tide
tiger
tilt
timber
time
tiny
tip
tired
tissue
title
toast
tobacco
today
toddler
toe
together
toilet
token
tomato
tomorrow
tone
tongue
tonight
tool
tooth
top
topic
topple
torch
tornado
tortoise
toss
total
tourist
toward
tower
town
toy
track
trade
traffic
tragic
train
transfer
trap
trash
travel
tray
treat
tree
trend
trial
tribe
trick
trigger
trim
trip
trophy
trouble
truck
true
truly
trumpet
trust
truth
try
tube
tuition
tumble
tuna
tunnel
turkey
turn
turtle
twelve
twenty
twice
twin
twist
two
type
typical
ugly
umbrella
unable
unaware
uncle
uncover
under
undo
unfair
unfold
unhappy
uniform
unique
unit
universe
unknown
unlock
until
unusual
unveil
update
upgrade
uphold
upon
upper
upset
urban
urge
usage
use
used
useful
useless
usual
utility
vacant
vacuum
vague
valid
valley
valve
van
vanish
vapor
various
vast
vault
vehicle
velvet
vendor
venture
venue
verb
verify
version
very
vessel
veteran
viable
vibrant
vicious
victory
video
view
village
vintage
violin
virtual
virus
visa
visit
visual
vital
vivid
vocal
voice
void
volcano
volume
vote
voyage
wage
wagon
wait
walk
wall
walnut
want
warfare
warm
warrior
wash
wasp
waste
water
wave
way
wealth
weapon
wear
weasel
weather
web
wedding
weekend
weird
welcome
west
wet
whale
what
wheat
wheel
when
where
whip
whisper
wide
width
wife
wild
will
win
window
wine
wing
wink
winner
winter
wire
wisdom
wise
wish
witness
wolf
woman
wonder
wood
wool
word
work
world
worry
worth
wrap
wreck
wrestle
wrist
write
wrong
yard
year
yellow
you
young
youth
zebra
zero
zone
zoo`.split("\n"));
// node_modules/@noble/curves/utils.js
var abytes2 = (value, length, title) => abytes(value, length, title);
var anumber3 = anumber;
var bytesToHex2 = bytesToHex;
var concatBytes2 = (...arrays) => concatBytes(...arrays);
var hexToBytes2 = (hex) => hexToBytes(hex);
var isBytes3 = isBytes;
var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
var _0n = /* @__PURE__ */ BigInt(0);
var _1n = /* @__PURE__ */ BigInt(1);
function abool(value, title = "") {
if (typeof value !== "boolean") {
const prefix = title && `"${title}" `;
throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
}
return value;
}
function abignumber(n) {
if (typeof n === "bigint") {
if (!isPosBig(n))
throw new RangeError("positive bigint expected, got " + n);
} else
anumber3(n);
return n;
}
function asafenumber(value, title = "") {
if (typeof value !== "number") {
const prefix = title && `"${title}" `;
throw new TypeError(prefix + "expected number, got type=" + typeof value);
}
if (!Number.isSafeInteger(value)) {
const prefix = title && `"${title}" `;
throw new RangeError(prefix + "expected safe integer, got " + value);
}
}
function numberToHexUnpadded(num) {
const hex = abignumber(num).toString(16);
return hex.length & 1 ? "0" + hex : hex;
}
function hexToNumber(hex) {
if (typeof hex !== "string")
throw new TypeError("hex string expected, got " + typeof hex);
return hex === "" ? _0n : BigInt("0x" + hex);
}
function bytesToNumberBE(bytes) {
return hexToNumber(bytesToHex(bytes));
}
function bytesToNumberLE(bytes) {
return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
}
function numberToBytesBE(n, len) {
anumber(len);
if (len === 0)
throw new RangeError("zero length");
n = abignumber(n);
const hex = n.toString(16);
if (hex.length > len * 2)
throw new RangeError("number too large");
return hexToBytes(hex.padStart(len * 2, "0"));
}
function numberToBytesLE(n, len) {
return numberToBytesBE(n, len).reverse();
}
function copyBytes(bytes) {
return Uint8Array.from(abytes2(bytes));
}
var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
function inRange(n, min, max) {
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
function aInRange(title, n, min, max) {
if (!inRange(n, min, max))
throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
}
function bitLen(n) {
if (n < _0n)
throw new Error("expected non-negative bigint, got " + n);
let len;
for (len = 0; n > _0n; n >>= _1n, len += 1)
;
return len;
}
var bitMask = (n) => (_1n << BigInt(n)) - _1n;
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
anumber(hashLen, "hashLen");
anumber(qByteLen, "qByteLen");
if (typeof hmacFn !== "function")
throw new TypeError("hmacFn must be a function");
const u8n = (len) => new Uint8Array(len);
const NULL = Uint8Array.of();
const byte0 = Uint8Array.of(0);
const byte1 = Uint8Array.of(1);
const _maxDrbgIters = 1e3;
let v = u8n(hashLen);
let k = u8n(hashLen);
let i = 0;
const reset = () => {
v.fill(1);
k.fill(0);
i = 0;
};
const h = (...msgs) => hmacFn(k, concatBytes2(v, ...msgs));
const reseed = (seed = NULL) => {
k = h(byte0, seed);
v = h();
if (seed.length === 0)
return;
k = h(byte1, seed);
v = h();
};
const gen2 = () => {
if (i++ >= _maxDrbgIters)
throw new Error("drbg: tried max amount of iterations");
let len = 0;
const out = [];
while (len < qByteLen) {
v = h();
const sl = v.slice();
out.push(sl);
len += v.length;
}
return concatBytes2(...out);
};
const genUntil = (seed, pred) => {
reset();
reseed(seed);
let res = void 0;
while ((res = pred(gen2())) === void 0)
reseed();
reset();
return res;
};
return genUntil;
}
function validateObject(object, fields = {}, optFields = {}) {
if (Object.prototype.toString.call(object) !== "[object Object]")
throw new TypeError("expected valid options object");
function checkField(fieldName, expectedType, isOpt) {
if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
const val = object[fieldName];
if (isOpt && val === void 0)
return;
const current = typeof val;
if (current !== expectedType || val === null)
throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
}
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
iter(fields, false);
iter(optFields, true);
}
// node_modules/@noble/curves/abstract/modular.js
var _0n2 = /* @__PURE__ */ BigInt(0);
var _1n2 = /* @__PURE__ */ BigInt(1);
var _2n = /* @__PURE__ */ BigInt(2);
var _3n = /* @__PURE__ */ BigInt(3);
var _4n = /* @__PURE__ */ BigInt(4);
var _5n = /* @__PURE__ */ BigInt(5);
var _7n = /* @__PURE__ */ BigInt(7);
var _8n = /* @__PURE__ */ BigInt(8);
var _9n = /* @__PURE__ */ BigInt(9);
var _16n = /* @__PURE__ */ BigInt(16);
function mod(a, b) {
if (b <= _0n2)
throw new Error("mod: expected positive modulus, got " + b);
const result = a % b;
return result >= _0n2 ? result : b + result;
}
function pow2(x, power, modulo) {
if (power < _0n2)
throw new Error("pow2: expected non-negative exponent, got " + power);
let res = x;
while (power-- > _0n2) {
res *= res;
res %= modulo;
}
return res;
}
function invert(number, modulo) {
if (number === _0n2)
throw new Error("invert: expected non-zero number");
if (modulo <= _0n2)
throw new Error("invert: expected positive modulus, got " + modulo);
let a = mod(number, modulo);
let b = modulo;
let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
while (a !== _0n2) {
const q = b / a;
const r = b - a * q;
const m = x - u * q;
const n = y - v * q;
b = a, a = r, x = u, y = v, u = m, v = n;
}
const gcd2 = b;
if (gcd2 !== _1n2)
throw new Error("invert: does not exist");
return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
const F3 = Fp;
if (!F3.eql(F3.sqr(root), n))
throw new Error("Cannot find square root");
}
function sqrt3mod4(Fp, n) {
const F3 = Fp;
const p1div4 = (F3.ORDER + _1n2) / _4n;
const root = F3.pow(n, p1div4);
assertIsSquare(F3, root, n);
return root;
}
function sqrt5mod8(Fp, n) {
const F3 = Fp;
const p5div8 = (F3.ORDER - _5n) / _8n;
const n2 = F3.mul(n, _2n);
const v = F3.pow(n2, p5div8);
const nv = F3.mul(n, v);
const i = F3.mul(F3.mul(nv, _2n), v);
const root = F3.mul(nv, F3.sub(i, F3.ONE));
assertIsSquare(F3, root, n);
return root;
}
function sqrt9mod16(P) {
const Fp_ = Field(P);
const tn = tonelliShanks(P);
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
const c2 = tn(Fp_, c1);
const c3 = tn(Fp_, Fp_.neg(c1));
const c4 = (P + _7n) / _16n;
return ((Fp, n) => {
const F3 = Fp;
let tv1 = F3.pow(n, c4);
let tv2 = F3.mul(tv1, c1);
const tv3 = F3.mul(tv1, c2);
const tv4 = F3.mul(tv1, c3);
const e1 = F3.eql(F3.sqr(tv2), n);
const e2 = F3.eql(F3.sqr(tv3), n);
tv1 = F3.cmov(tv1, tv2, e1);
tv2 = F3.cmov(tv4, tv3, e2);
const e3 = F3.eql(F3.sqr(tv2), n);
const root = F3.cmov(tv1, tv2, e3);
assertIsSquare(F3, root, n);
return root;
});
}
function tonelliShanks(P) {
if (P < _3n)
throw new Error("sqrt is not defined for small field");
let Q3 = P - _1n2;
let S = 0;
while (Q3 % _2n === _0n2) {
Q3 /= _2n;
S++;
}
let Z = _2n;
const _Fp = Field(P);
while (FpLegendre(_Fp, Z) === 1) {
if (Z++ > 1e3)
throw new Error("Cannot find square root: probably non-prime P");
}
if (S === 1)
return sqrt3mod4;
let cc = _Fp.pow(Z, Q3);
const Q1div2 = (Q3 + _1n2) / _2n;
return function tonelliSlow(Fp, n) {
const F3 = Fp;
if (F3.is0(n))
return n;
if (FpLegendre(F3, n) !== 1)
throw new Error("Cannot find square root");
let M = S;
let c = F3.mul(F3.ONE, cc);
let t = F3.pow(n, Q3);
let R = F3.pow(n, Q1div2);
while (!F3.eql(t, F3.ONE)) {
if (F3.is0(t))
return F3.ZERO;
let i = 1;
let t_tmp = F3.sqr(t);
while (!F3.eql(t_tmp, F3.ONE)) {
i++;
t_tmp = F3.sqr(t_tmp);
if (i === M)
throw new Error("Cannot find square root");
}
const exponent = _1n2 << BigInt(M - i - 1);
const b = F3.pow(c, exponent);
M = i;
c = F3.sqr(b);
t = F3.mul(t, c);
R = F3.mul(R, b);
}
return R;
};
}
function FpSqrt(P) {
if (P % _4n === _3n)
return sqrt3mod4;
if (P % _8n === _5n)
return sqrt5mod8;
if (P % _16n === _9n)
return sqrt9mod16(P);
return tonelliShanks(P);
}
var FIELD_FIELDS = [
"create",
"isValid",
"is0",
"neg",
"inv",
"sqrt",
"sqr",
"eql",
"add",
"sub",
"mul",
"pow",
"div",
"addN",
"subN",
"mulN",
"sqrN"
];
function validateField(field) {
const initial = {
ORDER: "bigint",
BYTES: "number",
BITS: "number"
};
const opts2 = FIELD_FIELDS.reduce((map, val) => {
map[val] = "function";
return map;
}, initial);
validateObject(field, opts2);
asafenumber(field.BYTES, "BYTES");
asafenumber(field.BITS, "BITS");
if (field.BYTES < 1 || field.BITS < 1)
throw new Error("invalid field: expected BYTES/BITS > 0");
if (field.ORDER <= _1n2)
throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
return field;
}
function FpPow(Fp, num, power) {
const F3 = Fp;
if (power < _0n2)
throw new Error("invalid exponent, negatives unsupported");
if (power === _0n2)
return F3.ONE;
if (power === _1n2)
return num;
let p = F3.ONE;
let d = num;
while (power > _0n2) {
if (power & _1n2)
p = F3.mul(p, d);
d = F3.sqr(d);
power >>= _1n2;
}
return p;
}
function FpInvertBatch(Fp, nums, passZero = false) {
const F3 = Fp;
const inverted = new Array(nums.length).fill(passZero ? F3.ZERO : void 0);
const multipliedAcc = nums.reduce((acc, num, i) => {
if (F3.is0(num))
return acc;
inverted[i] = acc;
return F3.mul(acc, num);
}, F3.ONE);
const invertedAcc = F3.inv(multipliedAcc);
nums.reduceRight((acc, num, i) => {
if (F3.is0(num))
return acc;
inverted[i] = F3.mul(acc, inverted[i]);
return F3.mul(acc, num);
}, invertedAcc);
return inverted;
}
function FpLegendre(Fp, n) {
const F3 = Fp;
const p1mod2 = (F3.ORDER - _1n2) / _2n;
const powered = F3.pow(n, p1mod2);
const yes = F3.eql(powered, F3.ONE);
const zero = F3.eql(powered, F3.ZERO);
const no = F3.eql(powered, F3.neg(F3.ONE));
if (!yes && !zero && !no)
throw new Error("invalid Legendre symbol result");
return yes ? 1 : zero ? 0 : -1;
}
function nLength(n, nBitLength) {
if (nBitLength !== void 0)
anumber3(nBitLength);
if (n <= _0n2)
throw new Error("invalid n length: expected positive n, got " + n);
if (nBitLength !== void 0 && nBitLength < 1)
throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
const bits = bitLen(n);
if (nBitLength !== void 0 && nBitLength < bits)
throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
const nByteLength = Math.ceil(_nBitLength / 8);
return { nBitLength: _nBitLength, nByteLength };
}
var FIELD_SQRT = /* @__PURE__ */ new WeakMap();
var _Field = class {
constructor(ORDER, opts2 = {}) {
__publicField(this, "ORDER");
__publicField(this, "BITS");
__publicField(this, "BYTES");
__publicField(this, "isLE");
__publicField(this, "ZERO", _0n2);
__publicField(this, "ONE", _1n2);
__publicField(this, "_lengths");
__publicField(this, "_mod");
if (ORDER <= _1n2)
throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
let _nbitLength = void 0;
this.isLE = false;
if (opts2 != null && typeof opts2 === "object") {
if (typeof opts2.BITS === "number")
_nbitLength = opts2.BITS;
if (typeof opts2.sqrt === "function")
Object.defineProperty(this, "sqrt", { value: opts2.sqrt, enumerable: true });
if (typeof opts2.isLE === "boolean")
this.isLE = opts2.isLE;
if (opts2.allowedLengths)
this._lengths = Object.freeze(opts2.allowedLengths.slice());
if (typeof opts2.modFromBytes === "boolean")
this._mod = opts2.modFromBytes;
}
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
if (nByteLength > 2048)
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
this.ORDER = ORDER;
this.BITS = nBitLength;
this.BYTES = nByteLength;
Object.freeze(this);
}
create(num) {
return mod(num, this.ORDER);
}
isValid(num) {
if (typeof num !== "bigint")
throw new TypeError("invalid field element: expected bigint, got " + typeof num);
return _0n2 <= num && num < this.ORDER;
}
is0(num) {
return num === _0n2;
}
// is valid and invertible
isValidNot0(num) {
return !this.is0(num) && this.isValid(num);
}
isOdd(num) {
return (num & _1n2) === _1n2;
}
neg(num) {
return mod(-num, this.ORDER);
}
eql(lhs, rhs) {
return lhs === rhs;
}
sqr(num) {
return mod(num * num, this.ORDER);
}
add(lhs, rhs) {
return mod(lhs + rhs, this.ORDER);
}
sub(lhs, rhs) {
return mod(lhs - rhs, this.ORDER);
}
mul(lhs, rhs) {
return mod(lhs * rhs, this.ORDER);
}
pow(num, power) {
return FpPow(this, num, power);
}
div(lhs, rhs) {
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
}
// Same as above, but doesn't normalize
sqrN(num) {
return num * num;
}
addN(lhs, rhs) {
return lhs + rhs;
}
subN(lhs, rhs) {
return lhs - rhs;
}
mulN(lhs, rhs) {
return lhs * rhs;
}
inv(num) {
return invert(num, this.ORDER);
}
sqrt(num) {
let sqrt = FIELD_SQRT.get(this);
if (!sqrt)
FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
return sqrt(this, num);
}
toBytes(num) {
return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
}
fromBytes(bytes, skipValidation = false) {
abytes2(bytes);
const { _lengths: allowedLengths, BYTES, isLE: isLE2, ORDER, _mod: modFromBytes } = this;
if (allowedLengths) {
if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
}
const padded = new Uint8Array(BYTES);
padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
bytes = padded;
}
if (bytes.length !== BYTES)
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
if (modFromBytes)
scalar = mod(scalar, ORDER);
if (!skipValidation) {
if (!this.isValid(scalar))
throw new Error("invalid field element: outside of range 0..ORDER");
}
return scalar;
}
// TODO: we don't need it here, move out to separate fn
invertBatch(lst) {
return FpInvertBatch(this, lst);
}
// We can't move this out because Fp6, Fp12 implement it
// and it's unclear what to return in there.
cmov(a, b, condition) {
abool(condition, "condition");
return condition ? b : a;
}
};
Object.freeze(_Field.prototype);
function Field(ORDER, opts2 = {}) {
return new _Field(ORDER, opts2);
}
function getFieldBytesLength(fieldOrder) {
if (typeof fieldOrder !== "bigint")
throw new Error("field order must be bigint");
if (fieldOrder <= _1n2)
throw new Error("field order must be greater than 1");
const bitLength = bitLen(fieldOrder - _1n2);
return Math.ceil(bitLength / 8);
}
function getMinHashLength(fieldOrder) {
const length = getFieldBytesLength(fieldOrder);
return length + Math.ceil(length / 2);
}
function mapHashToField(key, fieldOrder, isLE2 = false) {
abytes2(key);
const len = key.length;
const fieldLen = getFieldBytesLength(fieldOrder);
const minLen = Math.max(getMinHashLength(fieldOrder), 16);
if (len < minLen || len > 1024)
throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key);
const reduced = mod(num, fieldOrder - _1n2) + _1n2;
return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
// node_modules/@noble/curves/abstract/curve.js
var _0n3 = /* @__PURE__ */ BigInt(0);
var _1n3 = /* @__PURE__ */ BigInt(1);
function negateCt(condition, item) {
const neg = item.negate();
return condition ? neg : item;
}
function normalizeZ(c, points) {
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
}
function calcWOpts(W, scalarBits) {
validateW(W, scalarBits);
const windows = Math.ceil(scalarBits / W) + 1;
const windowSize = 2 ** (W - 1);
const maxNumber = 2 ** W;
const mask = bitMask(W);
const shiftBy = BigInt(W);
return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
let wbits = Number(n & mask);
let nextN = n >> shiftBy;
if (wbits > windowSize) {
wbits -= maxNumber;
nextN += _1n3;
}
const offsetStart = window * windowSize;
const offset = offsetStart + Math.abs(wbits) - 1;
const isZero = wbits === 0;
const isNeg = wbits < 0;
const isNegF = window % 2 !== 0;
const offsetF = offsetStart;
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
var pointPrecomputes = /* @__PURE__ */ new WeakMap();
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
function getW(P) {
return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
if (n !== _0n3)
throw new Error("invalid wNAF");
}
var wNAF = class {
// Parametrized with a given Point class (not individual point)
constructor(Point2, bits) {
__publicField(this, "BASE");
__publicField(this, "ZERO");
__publicField(this, "Fn");
__publicField(this, "bits");
this.BASE = Point2.BASE;
this.ZERO = Point2.ZERO;
this.Fn = Point2.Fn;
this.bits = bits;
}
// non-const time multiplication ladder
_unsafeLadder(elm, n, p = this.ZERO) {
let d = elm;
while (n > _0n3) {
if (n & _1n3)
p = p.add(d);
d = d.double();
n >>= _1n3;
}
return p;
}
/**
* Creates a wNAF precomputation window. Used for caching.
* Default window size is set by `utils.precompute()` and is equal to 8.
* Number of precomputed points depends on the curve size:
* 2^(𝑊1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
* - 𝑊 is the window size
* - 𝑛 is the bitlength of the curve order.
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
* @param point - Point instance
* @param W - window size
* @returns precomputed point tables flattened to a single array
*/
precomputeWindow(point, W) {
const { windows, windowSize } = calcWOpts(W, this.bits);
const points = [];
let p = point;
let base = p;
for (let window = 0; window < windows; window++) {
base = p;
points.push(base);
for (let i = 1; i < windowSize; i++) {
base = base.add(p);
points.push(base);
}
p = base.double();
}
return points;
}
/**
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
* More compact implementation:
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
* @returns real and fake (for const-time) points
*/
wNAF(W, precomputes, n) {
if (!this.Fn.isValid(n))
throw new Error("invalid scalar");
let p = this.ZERO;
let f = this.BASE;
const wo = calcWOpts(W, this.bits);
for (let window = 0; window < wo.windows; window++) {
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
n = nextN;
if (isZero) {
f = f.add(negateCt(isNegF, precomputes[offsetF]));
} else {
p = p.add(negateCt(isNeg, precomputes[offset]));
}
}
assert0(n);
return { p, f };
}
/**
* Implements unsafe EC multiplication using precomputed tables
* and w-ary non-adjacent form.
* @param acc - accumulator point to add result of multiplication
* @returns point
*/
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
const wo = calcWOpts(W, this.bits);
for (let window = 0; window < wo.windows; window++) {
if (n === _0n3)
break;
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
n = nextN;
if (isZero) {
continue;
} else {
const item = precomputes[offset];
acc = acc.add(isNeg ? item.negate() : item);
}
}
assert0(n);
return acc;
}
getPrecomputes(W, point, transform) {
let comp = pointPrecomputes.get(point);
if (!comp) {
comp = this.precomputeWindow(point, W);
if (W !== 1) {
if (typeof transform === "function")
comp = transform(comp);
pointPrecomputes.set(point, comp);
}
}
return comp;
}
cached(point, scalar, transform) {
const W = getW(point);
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
}
unsafe(point, scalar, transform, prev) {
const W = getW(point);
if (W === 1)
return this._unsafeLadder(point, scalar, prev);
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
}
// We calculate precomputes for elliptic curve point multiplication
// using windowed method. This specifies window size and
// stores precomputed values. Usually only base point would be precomputed.
createCache(P, W) {
validateW(W, this.bits);
pointWindowSizes.set(P, W);
pointPrecomputes.delete(P);
}
hasCache(elm) {
return getW(elm) !== 1;
}
};
function mulEndoUnsafe(Point2, point, k1, k2) {
let acc = point;
let p1 = Point2.ZERO;
let p2 = Point2.ZERO;
while (k1 > _0n3 || k2 > _0n3) {
if (k1 & _1n3)
p1 = p1.add(acc);
if (k2 & _1n3)
p2 = p2.add(acc);
acc = acc.double();
k1 >>= _1n3;
k2 >>= _1n3;
}
return { p1, p2 };
}
function createField(order, field, isLE2) {
if (field) {
if (field.ORDER !== order)
throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
validateField(field);
return field;
} else {
return Field(order, { isLE: isLE2 });
}
}
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
if (FpFnLE === void 0)
FpFnLE = type === "edwards";
if (!CURVE || typeof CURVE !== "object")
throw new Error(`expected valid ${type} CURVE object`);
for (const p of ["p", "n", "h"]) {
const val = CURVE[p];
if (!(typeof val === "bigint" && val > _0n3))
throw new Error(`CURVE.${p} must be positive bigint`);
}
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
const _b = type === "weierstrass" ? "b" : "d";
const params = ["Gx", "Gy", "a", _b];
for (const p of params) {
if (!Fp.isValid(CURVE[p]))
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
}
CURVE = Object.freeze(Object.assign({}, CURVE));
return { CURVE, Fp, Fn: Fn2 };
}
function createKeygen(randomSecretKey, getPublicKey) {
return function keygen(seed) {
const secretKey = randomSecretKey(seed);
return { secretKey, publicKey: getPublicKey(secretKey) };
};
}
// node_modules/@noble/curves/abstract/fft.js
function checkU32(n) {
if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295)
throw new Error("wrong u32 integer:" + n);
return n;
}
function isPowerOfTwo(x) {
checkU32(x);
return (x & x - 1) === 0 && x !== 0;
}
function reverseBits(n, bits) {
checkU32(n);
if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);
let reversed = 0;
for (let i = 0; i < bits; i++, n >>>= 1)
reversed = reversed << 1 | n & 1;
return reversed >>> 0;
}
function log2(n) {
checkU32(n);
return 31 - Math.clz32(n);
}
function bitReversalInplace(values) {
const n = values.length;
if (!isPowerOfTwo(n))
throw new Error("expected positive power-of-two length, got " + n);
const bits = log2(n);
for (let i = 0; i < n; i++) {
const j = reverseBits(i, bits);
if (i < j) {
const tmp = values[i];
values[i] = values[j];
values[j] = tmp;
}
}
return values;
}
var FFTCore = (F3, coreOpts) => {
const { N: N3, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
const bits = log2(N3);
if (!isPowerOfTwo(N3))
throw new Error("FFT: Polynomial size should be power of two");
if (roots.length !== N3)
throw new Error(`FFT: wrong roots length: expected ${N3}, got ${roots.length}`);
const isDit = dit !== invertButterflies;
isDit;
return (values) => {
if (values.length !== N3)
throw new Error("FFT: wrong Polynomial length");
if (dit && brp)
bitReversalInplace(values);
for (let i = 0, g = 1; i < bits - skipStages; i++) {
const s = dit ? i + 1 + skipStages : bits - i;
const m = 1 << s;
const m2 = m >> 1;
const stride = N3 >> s;
for (let k = 0; k < N3; k += m) {
for (let j = 0, grp = g++; j < m2; j++) {
const rootPos = invertButterflies ? dit ? N3 - grp : grp : j * stride;
const i0 = k + j;
const i1 = k + j + m2;
const omega = roots[rootPos];
const b = values[i1];
const a = values[i0];
if (isDit) {
const t = F3.mul(b, omega);
values[i0] = F3.add(a, t);
values[i1] = F3.sub(a, t);
} else if (invertButterflies) {
values[i0] = F3.add(b, a);
values[i1] = F3.mul(F3.sub(b, a), omega);
} else {
values[i0] = F3.add(a, b);
values[i1] = F3.mul(F3.sub(a, b), omega);
}
}
}
}
if (!dit && brp)
bitReversalInplace(values);
return values;
};
};
// node_modules/@noble/curves/abstract/weierstrass.js
var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
function _splitEndoScalar(k, basis, n) {
aInRange("scalar", k, _0n4, n);
const [[a1, b1], [a2, b2]] = basis;
const c1 = divNearest(b2 * k, n);
const c2 = divNearest(-b1 * k, n);
let k1 = k - c1 * a1 - c2 * a2;
let k2 = -c1 * b1 - c2 * b2;
const k1neg = k1 < _0n4;
const k2neg = k2 < _0n4;
if (k1neg)
k1 = -k1;
if (k2neg)
k2 = -k2;
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
throw new Error("splitScalar (endomorphism): failed for k");
}
return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
if (!["compact", "recovered", "der"].includes(format))
throw new Error('Signature format must be "compact", "recovered", or "der"');
return format;
}
function validateSigOpts(opts2, def) {
validateObject(opts2);
const optsn = {};
for (let optName of Object.keys(def)) {
optsn[optName] = opts2[optName] === void 0 ? def[optName] : opts2[optName];
}
abool(optsn.lowS, "lowS");
abool(optsn.prehash, "prehash");
if (optsn.format !== void 0)
validateSigFormat(optsn.format);
return optsn;
}
var DERErr = class extends Error {
constructor(m = "") {
super(m);
}
};
var DER = {
// asn.1 DER encoding utils
Err: DERErr,
// Basic building block is TLV (Tag-Length-Value)
_tlv: {
encode: (tag, data) => {
const { Err: E } = DER;
asafenumber(tag, "tag");
if (tag < 0 || tag > 255)
throw new E("tlv.encode: wrong tag");
if (typeof data !== "string")
throw new TypeError('"data" expected string, got type=' + typeof data);
if (data.length & 1)
throw new E("tlv.encode: unpadded data");
const dataLen = data.length / 2;
const len = numberToHexUnpadded(dataLen);
if (len.length / 2 & 128)
throw new E("tlv.encode: long form length too big");
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
const t = numberToHexUnpadded(tag);
return t + lenLen + len + data;
},
// v - value, l - left bytes (unparsed)
decode(tag, data) {
const { Err: E } = DER;
data = abytes2(data, void 0, "DER data");
let pos = 0;
if (tag < 0 || tag > 255)
throw new E("tlv.encode: wrong tag");
if (data.length < 2 || data[pos++] !== tag)
throw new E("tlv.decode: wrong tlv");
const first = data[pos++];
const isLong = !!(first & 128);
let length = 0;
if (!isLong)
length = first;
else {
const lenLen = first & 127;
if (!lenLen)
throw new E("tlv.decode(long): indefinite length not supported");
if (lenLen > 4)
throw new E("tlv.decode(long): byte length is too big");
const lengthBytes = data.subarray(pos, pos + lenLen);
if (lengthBytes.length !== lenLen)
throw new E("tlv.decode: length bytes not complete");
if (lengthBytes[0] === 0)
throw new E("tlv.decode(long): zero leftmost byte");
for (const b of lengthBytes)
length = length << 8 | b;
pos += lenLen;
if (length < 128)
throw new E("tlv.decode(long): not minimal encoding");
}
const v = data.subarray(pos, pos + length);
if (v.length !== length)
throw new E("tlv.decode: wrong value length");
return { v, l: data.subarray(pos + length) };
}
},
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
// since we always use positive integers here. It must always be empty:
// - add zero byte if exists
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
_int: {
encode(num) {
const { Err: E } = DER;
abignumber(num);
if (num < _0n4)
throw new E("integer: negative integers are not allowed");
let hex = numberToHexUnpadded(num);
if (Number.parseInt(hex[0], 16) & 8)
hex = "00" + hex;
if (hex.length & 1)
throw new E("unexpected DER parsing assertion: unpadded hex");
return hex;
},
decode(data) {
const { Err: E } = DER;
if (data.length < 1)
throw new E("invalid signature integer: empty");
if (data[0] & 128)
throw new E("invalid signature integer: negative");
if (data.length > 1 && data[0] === 0 && !(data[1] & 128))
throw new E("invalid signature integer: unnecessary leading zero");
return bytesToNumberBE(data);
}
},
toSig(bytes) {
const { Err: E, _int: int, _tlv: tlv } = DER;
const data = abytes2(bytes, void 0, "signature");
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
if (seqLeftBytes.length)
throw new E("invalid signature: left bytes after parsing");
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
if (sLeftBytes.length)
throw new E("invalid signature: left bytes after parsing");
return { r: int.decode(rBytes), s: int.decode(sBytes) };
},
hexFromSig(sig) {
const { _tlv: tlv, _int: int } = DER;
const rs = tlv.encode(2, int.encode(sig.r));
const ss = tlv.encode(2, int.encode(sig.s));
const seq = rs + ss;
return tlv.encode(48, seq);
}
};
Object.freeze(DER._tlv);
Object.freeze(DER._int);
Object.freeze(DER);
var _0n4 = /* @__PURE__ */ BigInt(0);
var _1n4 = /* @__PURE__ */ BigInt(1);
var _2n2 = /* @__PURE__ */ BigInt(2);
var _3n2 = /* @__PURE__ */ BigInt(3);
var _4n2 = /* @__PURE__ */ BigInt(4);
function weierstrass(params, extraOpts = {}) {
const validated = createCurveFields("weierstrass", params, extraOpts);
const Fp = validated.Fp;
const Fn2 = validated.Fn;
let CURVE = validated.CURVE;
const { h: cofactor, n: CURVE_ORDER } = CURVE;
validateObject(extraOpts, {}, {
allowInfinityPoint: "boolean",
clearCofactor: "function",
isTorsionFree: "function",
fromBytes: "function",
toBytes: "function",
endo: "object"
});
const { endo, allowInfinityPoint } = extraOpts;
if (endo) {
if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
throw new Error('invalid endo: expected "beta": bigint and "basises": array');
}
}
const lengths = getWLengths(Fp, Fn2);
function assertCompressionIsSupported() {
if (!Fp.isOdd)
throw new Error("compression is not supported: Field does not have .isOdd()");
}
function pointToBytes(_c, point, isCompressed) {
if (allowInfinityPoint && point.is0())
return Uint8Array.of(0);
const { x, y } = point.toAffine();
const bx = Fp.toBytes(x);
abool(isCompressed, "isCompressed");
if (isCompressed) {
assertCompressionIsSupported();
const hasEvenY = !Fp.isOdd(y);
return concatBytes2(pprefix(hasEvenY), bx);
} else {
return concatBytes2(Uint8Array.of(4), bx, Fp.toBytes(y));
}
}
function pointFromBytes(bytes) {
abytes2(bytes, void 0, "Point");
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
const length = bytes.length;
const head = bytes[0];
const tail = bytes.subarray(1);
if (allowInfinityPoint && length === 1 && head === 0)
return { x: Fp.ZERO, y: Fp.ZERO };
if (length === comp && (head === 2 || head === 3)) {
const x = Fp.fromBytes(tail);
if (!Fp.isValid(x))
throw new Error("bad point: is not on curve, wrong x");
const y2 = weierstrassEquation(x);
let y;
try {
y = Fp.sqrt(y2);
} catch (sqrtError) {
const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
throw new Error("bad point: is not on curve, sqrt error" + err);
}
assertCompressionIsSupported();
const evenY = Fp.isOdd(y);
const evenH = (head & 1) === 1;
if (evenH !== evenY)
y = Fp.neg(y);
return { x, y };
} else if (length === uncomp && head === 4) {
const L = Fp.BYTES;
const x = Fp.fromBytes(tail.subarray(0, L));
const y = Fp.fromBytes(tail.subarray(L, L * 2));
if (!isValidXY(x, y))
throw new Error("bad point: is not on curve");
return { x, y };
} else {
throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
}
}
const encodePoint = extraOpts.toBytes === void 0 ? pointToBytes : extraOpts.toBytes;
const decodePoint = extraOpts.fromBytes === void 0 ? pointFromBytes : extraOpts.fromBytes;
function weierstrassEquation(x) {
const x2 = Fp.sqr(x);
const x3 = Fp.mul(x2, x);
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
}
function isValidXY(x, y) {
const left = Fp.sqr(y);
const right = weierstrassEquation(x);
return Fp.eql(left, right);
}
if (!isValidXY(CURVE.Gx, CURVE.Gy))
throw new Error("bad curve params: generator point");
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
if (Fp.is0(Fp.add(_4a3, _27b2)))
throw new Error("bad curve params: a or b");
function acoord(title, n, banZero = false) {
if (!Fp.isValid(n) || banZero && Fp.is0(n))
throw new Error(`bad point coordinate ${title}`);
return n;
}
function aprjpoint(other) {
if (!(other instanceof Point2))
throw new Error("Weierstrass Point expected");
}
function splitEndoScalarN(k) {
if (!endo || !endo.basises)
throw new Error("no endo");
return _splitEndoScalar(k, endo.basises, Fn2.ORDER);
}
function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
k2p = new Point2(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
k1p = negateCt(k1neg, k1p);
k2p = negateCt(k2neg, k2p);
return k1p.add(k2p);
}
const _Point = class _Point {
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
constructor(X, Y, Z) {
__publicField(this, "X");
__publicField(this, "Y");
__publicField(this, "Z");
this.X = acoord("x", X);
this.Y = acoord("y", Y, true);
this.Z = acoord("z", Z);
Object.freeze(this);
}
static CURVE() {
return CURVE;
}
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
static fromAffine(p) {
const { x, y } = p || {};
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
throw new Error("invalid affine point");
if (p instanceof _Point)
throw new Error("projective point not allowed");
if (Fp.is0(x) && Fp.is0(y))
return _Point.ZERO;
return new _Point(x, y, Fp.ONE);
}
static fromBytes(bytes) {
const P = _Point.fromAffine(decodePoint(abytes2(bytes, void 0, "point")));
P.assertValidity();
return P;
}
static fromHex(hex) {
return _Point.fromBytes(hexToBytes2(hex));
}
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
/**
*
* @param windowSize
* @param isLazy - true will defer table computation until the first multiplication
* @returns
*/
precompute(windowSize = 8, isLazy = true) {
wnaf.createCache(this, windowSize);
if (!isLazy)
this.multiply(_3n2);
return this;
}
// TODO: return `this`
/** A point on curve is valid if it conforms to equation. */
assertValidity() {
const p = this;
if (p.is0()) {
if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))
return;
throw new Error("bad point: ZERO");
}
const { x, y } = p.toAffine();
if (!Fp.isValid(x) || !Fp.isValid(y))
throw new Error("bad point: x or y not field elements");
if (!isValidXY(x, y))
throw new Error("bad point: equation left != right");
if (!p.isTorsionFree())
throw new Error("bad point: not in prime-order subgroup");
}
hasEvenY() {
const { y } = this.toAffine();
if (!Fp.isOdd)
throw new Error("Field doesn't support isOdd");
return !Fp.isOdd(y);
}
/** Compare one point to another. */
equals(other) {
aprjpoint(other);
const { X: X1, Y: Y1, Z: Z1 } = this;
const { X: X2, Y: Y2, Z: Z2 } = other;
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
return U1 && U2;
}
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
negate() {
return new _Point(this.X, Fp.neg(this.Y), this.Z);
}
// Renes-Costello-Batina exception-free doubling formula.
// There is 30% faster Jacobian formula, but it is not complete.
// https://eprint.iacr.org/2015/1060, algorithm 3
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
double() {
const { a, b } = CURVE;
const b3 = Fp.mul(b, _3n2);
const { X: X1, Y: Y1, Z: Z1 } = this;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
let t0 = Fp.mul(X1, X1);
let t1 = Fp.mul(Y1, Y1);
let t2 = Fp.mul(Z1, Z1);
let t3 = Fp.mul(X1, Y1);
t3 = Fp.add(t3, t3);
Z3 = Fp.mul(X1, Z1);
Z3 = Fp.add(Z3, Z3);
X3 = Fp.mul(a, Z3);
Y3 = Fp.mul(b3, t2);
Y3 = Fp.add(X3, Y3);
X3 = Fp.sub(t1, Y3);
Y3 = Fp.add(t1, Y3);
Y3 = Fp.mul(X3, Y3);
X3 = Fp.mul(t3, X3);
Z3 = Fp.mul(b3, Z3);
t2 = Fp.mul(a, t2);
t3 = Fp.sub(t0, t2);
t3 = Fp.mul(a, t3);
t3 = Fp.add(t3, Z3);
Z3 = Fp.add(t0, t0);
t0 = Fp.add(Z3, t0);
t0 = Fp.add(t0, t2);
t0 = Fp.mul(t0, t3);
Y3 = Fp.add(Y3, t0);
t2 = Fp.mul(Y1, Z1);
t2 = Fp.add(t2, t2);
t0 = Fp.mul(t2, t3);
X3 = Fp.sub(X3, t0);
Z3 = Fp.mul(t2, t1);
Z3 = Fp.add(Z3, Z3);
Z3 = Fp.add(Z3, Z3);
return new _Point(X3, Y3, Z3);
}
// Renes-Costello-Batina exception-free addition formula.
// There is 30% faster Jacobian formula, but it is not complete.
// https://eprint.iacr.org/2015/1060, algorithm 1
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
add(other) {
aprjpoint(other);
const { X: X1, Y: Y1, Z: Z1 } = this;
const { X: X2, Y: Y2, Z: Z2 } = other;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
const a = CURVE.a;
const b3 = Fp.mul(CURVE.b, _3n2);
let t0 = Fp.mul(X1, X2);
let t1 = Fp.mul(Y1, Y2);
let t2 = Fp.mul(Z1, Z2);
let t3 = Fp.add(X1, Y1);
let t4 = Fp.add(X2, Y2);
t3 = Fp.mul(t3, t4);
t4 = Fp.add(t0, t1);
t3 = Fp.sub(t3, t4);
t4 = Fp.add(X1, Z1);
let t5 = Fp.add(X2, Z2);
t4 = Fp.mul(t4, t5);
t5 = Fp.add(t0, t2);
t4 = Fp.sub(t4, t5);
t5 = Fp.add(Y1, Z1);
X3 = Fp.add(Y2, Z2);
t5 = Fp.mul(t5, X3);
X3 = Fp.add(t1, t2);
t5 = Fp.sub(t5, X3);
Z3 = Fp.mul(a, t4);
X3 = Fp.mul(b3, t2);
Z3 = Fp.add(X3, Z3);
X3 = Fp.sub(t1, Z3);
Z3 = Fp.add(t1, Z3);
Y3 = Fp.mul(X3, Z3);
t1 = Fp.add(t0, t0);
t1 = Fp.add(t1, t0);
t2 = Fp.mul(a, t2);
t4 = Fp.mul(b3, t4);
t1 = Fp.add(t1, t2);
t2 = Fp.sub(t0, t2);
t2 = Fp.mul(a, t2);
t4 = Fp.add(t4, t2);
t0 = Fp.mul(t1, t4);
Y3 = Fp.add(Y3, t0);
t0 = Fp.mul(t5, t4);
X3 = Fp.mul(t3, X3);
X3 = Fp.sub(X3, t0);
t0 = Fp.mul(t3, t1);
Z3 = Fp.mul(t5, Z3);
Z3 = Fp.add(Z3, t0);
return new _Point(X3, Y3, Z3);
}
subtract(other) {
aprjpoint(other);
return this.add(other.negate());
}
is0() {
return this.equals(_Point.ZERO);
}
/**
* Constant time multiplication.
* Uses wNAF method. Windowed method may be 10% faster,
* but takes 2x longer to generate and consumes 2x memory.
* Uses precomputes when available.
* Uses endomorphism for Koblitz curves.
* @param scalar - by which the point would be multiplied
* @returns New point
*/
multiply(scalar) {
const { endo: endo2 } = extraOpts;
if (!Fn2.isValidNot0(scalar))
throw new RangeError("invalid scalar: out of range");
let point, fake;
const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(_Point, p));
if (endo2) {
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
const { p: k1p, f: k1f } = mul(k1);
const { p: k2p, f: k2f } = mul(k2);
fake = k1f.add(k2f);
point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
} else {
const { p, f } = mul(scalar);
point = p;
fake = f;
}
return normalizeZ(_Point, [point, fake])[0];
}
/**
* Non-constant-time multiplication. Uses double-and-add algorithm.
* It's faster, but should only be used when you don't care about
* an exposed secret key e.g. sig verification, which works over *public* keys.
*/
multiplyUnsafe(scalar) {
const { endo: endo2 } = extraOpts;
const p = this;
const sc = scalar;
if (!Fn2.isValid(sc))
throw new RangeError("invalid scalar: out of range");
if (sc === _0n4 || p.is0())
return _Point.ZERO;
if (sc === _1n4)
return p;
if (wnaf.hasCache(this))
return this.multiply(sc);
if (endo2) {
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
const { p1, p2 } = mulEndoUnsafe(_Point, p, k1, k2);
return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
} else {
return wnaf.unsafe(p, sc);
}
}
/**
* Converts Projective point to affine (x, y) coordinates.
* (X, Y, Z) ∋ (x=X/Z, y=Y/Z).
* @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
*/
toAffine(invertedZ) {
const p = this;
let iz = invertedZ;
const { X, Y, Z } = p;
if (Fp.eql(Z, Fp.ONE))
return { x: X, y: Y };
const is0 = p.is0();
if (iz == null)
iz = is0 ? Fp.ONE : Fp.inv(Z);
const x = Fp.mul(X, iz);
const y = Fp.mul(Y, iz);
const zz = Fp.mul(Z, iz);
if (is0)
return { x: Fp.ZERO, y: Fp.ZERO };
if (!Fp.eql(zz, Fp.ONE))
throw new Error("invZ was invalid");
return { x, y };
}
/**
* Checks whether Point is free of torsion elements (is in prime subgroup).
* Always torsion-free for cofactor=1 curves.
*/
isTorsionFree() {
const { isTorsionFree } = extraOpts;
if (cofactor === _1n4)
return true;
if (isTorsionFree)
return isTorsionFree(_Point, this);
return wnaf.unsafe(this, CURVE_ORDER).is0();
}
clearCofactor() {
const { clearCofactor } = extraOpts;
if (cofactor === _1n4)
return this;
if (clearCofactor)
return clearCofactor(_Point, this);
return this.multiplyUnsafe(cofactor);
}
isSmallOrder() {
if (cofactor === _1n4)
return this.is0();
return this.clearCofactor().is0();
}
toBytes(isCompressed = true) {
abool(isCompressed, "isCompressed");
this.assertValidity();
return encodePoint(_Point, this, isCompressed);
}
toHex(isCompressed = true) {
return bytesToHex2(this.toBytes(isCompressed));
}
toString() {
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
}
};
// base / generator point
__publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, Fp.ONE));
// zero / infinity / identity point
__publicField(_Point, "ZERO", new _Point(Fp.ZERO, Fp.ONE, Fp.ZERO));
// 0, 1, 0
// math field
__publicField(_Point, "Fp", Fp);
// scalar field
__publicField(_Point, "Fn", Fn2);
let Point2 = _Point;
const bits = Fn2.BITS;
const wnaf = new wNAF(Point2, extraOpts.endo ? Math.ceil(bits / 2) : bits);
if (bits >= 8)
Point2.BASE.precompute(8);
Object.freeze(Point2.prototype);
Object.freeze(Point2);
return Point2;
}
function pprefix(hasEvenY) {
return Uint8Array.of(hasEvenY ? 2 : 3);
}
function getWLengths(Fp, Fn2) {
return {
secretKey: Fn2.BYTES,
publicKey: 1 + Fp.BYTES,
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
publicKeyHasPrefix: true,
// Raw compact `(r || s)` signature width; DER and recovered signatures use
// different lengths outside this helper.
signature: 2 * Fn2.BYTES
};
}
function ecdh(Point2, ecdhOpts = {}) {
const { Fn: Fn2 } = Point2;
const randomBytes_ = ecdhOpts.randomBytes === void 0 ? randomBytes2 : ecdhOpts.randomBytes;
const lengths = Object.assign(getWLengths(Point2.Fp, Fn2), {
seed: Math.max(getMinHashLength(Fn2.ORDER), 16)
});
function isValidSecretKey(secretKey) {
try {
const num = Fn2.fromBytes(secretKey);
return Fn2.isValidNot0(num);
} catch (error) {
return false;
}
}
function isValidPublicKey(publicKey, isCompressed) {
const { publicKey: comp, publicKeyUncompressed } = lengths;
try {
const l = publicKey.length;
if (isCompressed === true && l !== comp)
return false;
if (isCompressed === false && l !== publicKeyUncompressed)
return false;
return !!Point2.fromBytes(publicKey);
} catch (error) {
return false;
}
}
function randomSecretKey(seed) {
seed = seed === void 0 ? randomBytes_(lengths.seed) : seed;
return mapHashToField(abytes2(seed, lengths.seed, "seed"), Fn2.ORDER);
}
function getPublicKey(secretKey, isCompressed = true) {
return Point2.BASE.multiply(Fn2.fromBytes(secretKey)).toBytes(isCompressed);
}
function isProbPub(item) {
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
const allowedLengths = Fn2._lengths;
if (!isBytes3(item))
return void 0;
const l = abytes2(item, void 0, "key").length;
const isPub = l === publicKey || l === publicKeyUncompressed;
const isSec = l === secretKey || !!allowedLengths?.includes(l);
if (isPub && isSec)
return void 0;
return isPub;
}
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
if (isProbPub(secretKeyA) === true)
throw new Error("first arg must be private key");
if (isProbPub(publicKeyB) === false)
throw new Error("second arg must be public key");
const s = Fn2.fromBytes(secretKeyA);
const b = Point2.fromBytes(publicKeyB);
return b.multiply(s).toBytes(isCompressed);
}
const utils2 = {
isValidSecretKey,
isValidPublicKey,
randomSecretKey
};
const keygen = createKeygen(randomSecretKey, getPublicKey);
Object.freeze(utils2);
Object.freeze(lengths);
return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point: Point2, utils: utils2, lengths });
}
function ecdsa(Point2, hash, ecdsaOpts = {}) {
const hash_ = hash;
ahash(hash_);
validateObject(ecdsaOpts, {}, {
hmac: "function",
lowS: "boolean",
randomBytes: "function",
bits2int: "function",
bits2int_modN: "function"
});
ecdsaOpts = Object.assign({}, ecdsaOpts);
const randomBytes4 = ecdsaOpts.randomBytes === void 0 ? randomBytes2 : ecdsaOpts.randomBytes;
const hmac2 = ecdsaOpts.hmac === void 0 ? (key, msg) => hmac(hash_, key, msg) : ecdsaOpts.hmac;
const { Fp, Fn: Fn2 } = Point2;
const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn2;
const { keygen, getPublicKey, getSharedSecret, utils: utils2, lengths } = ecdh(Point2, ecdsaOpts);
const defaultSigOpts = {
prehash: true,
lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
format: "compact",
extraEntropy: false
};
const hasLargeRecoveryLifts = CURVE_ORDER * _2n2 + _1n4 < Fp.ORDER;
function isBiggerThanHalfOrder(number) {
const HALF = CURVE_ORDER >> _1n4;
return number > HALF;
}
function validateRS(title, num) {
if (!Fn2.isValidNot0(num))
throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
return num;
}
function assertRecoverableCurve() {
if (hasLargeRecoveryLifts)
throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
}
function validateSigLength(bytes, format) {
validateSigFormat(format);
const size = lengths.signature;
const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
return abytes2(bytes, sizer);
}
class Signature {
constructor(r, s, recovery) {
__publicField(this, "r");
__publicField(this, "s");
__publicField(this, "recovery");
this.r = validateRS("r", r);
this.s = validateRS("s", s);
if (recovery != null) {
assertRecoverableCurve();
if (![0, 1, 2, 3].includes(recovery))
throw new Error("invalid recovery id");
this.recovery = recovery;
}
Object.freeze(this);
}
static fromBytes(bytes, format = defaultSigOpts.format) {
validateSigLength(bytes, format);
let recid;
if (format === "der") {
const { r: r2, s: s2 } = DER.toSig(abytes2(bytes));
return new Signature(r2, s2);
}
if (format === "recovered") {
recid = bytes[0];
format = "compact";
bytes = bytes.subarray(1);
}
const L = lengths.signature / 2;
const r = bytes.subarray(0, L);
const s = bytes.subarray(L, L * 2);
return new Signature(Fn2.fromBytes(r), Fn2.fromBytes(s), recid);
}
static fromHex(hex, format) {
return this.fromBytes(hexToBytes2(hex), format);
}
assertRecovery() {
const { recovery } = this;
if (recovery == null)
throw new Error("invalid recovery id: must be present");
return recovery;
}
addRecoveryBit(recovery) {
return new Signature(this.r, this.s, recovery);
}
// Unlike the top-level helper below, this method expects a digest that has
// already been hashed to the curve's message representative.
recoverPublicKey(messageHash) {
const { r, s } = this;
const recovery = this.assertRecovery();
const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
if (!Fp.isValid(radj))
throw new Error("invalid recovery id: sig.r+curve.n != R.x");
const x = Fp.toBytes(radj);
const R = Point2.fromBytes(concatBytes2(pprefix((recovery & 1) === 0), x));
const ir = Fn2.inv(radj);
const h = bits2int_modN(abytes2(messageHash, void 0, "msgHash"));
const u1 = Fn2.create(-h * ir);
const u2 = Fn2.create(s * ir);
const Q3 = Point2.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
if (Q3.is0())
throw new Error("invalid recovery: point at infinify");
Q3.assertValidity();
return Q3;
}
// Signatures should be low-s, to prevent malleability.
hasHighS() {
return isBiggerThanHalfOrder(this.s);
}
toBytes(format = defaultSigOpts.format) {
validateSigFormat(format);
if (format === "der")
return hexToBytes2(DER.hexFromSig(this));
const { r, s } = this;
const rb = Fn2.toBytes(r);
const sb = Fn2.toBytes(s);
if (format === "recovered") {
assertRecoverableCurve();
return concatBytes2(Uint8Array.of(this.assertRecovery()), rb, sb);
}
return concatBytes2(rb, sb);
}
toHex(format) {
return bytesToHex2(this.toBytes(format));
}
}
Object.freeze(Signature.prototype);
Object.freeze(Signature);
const bits2int = ecdsaOpts.bits2int === void 0 ? function bits2int_def(bytes) {
if (bytes.length > 8192)
throw new Error("input is too large");
const num = bytesToNumberBE(bytes);
const delta = bytes.length * 8 - fnBits;
return delta > 0 ? num >> BigInt(delta) : num;
} : ecdsaOpts.bits2int;
const bits2int_modN = ecdsaOpts.bits2int_modN === void 0 ? function bits2int_modN_def(bytes) {
return Fn2.create(bits2int(bytes));
} : ecdsaOpts.bits2int_modN;
const ORDER_MASK = bitMask(fnBits);
function int2octets(num) {
aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
return Fn2.toBytes(num);
}
function validateMsgAndHash(message, prehash) {
abytes2(message, void 0, "message");
return prehash ? abytes2(hash_(message), void 0, "prehashed message") : message;
}
function prepSig(message, secretKey, opts2) {
const { lowS, prehash, extraEntropy } = validateSigOpts(opts2, defaultSigOpts);
message = validateMsgAndHash(message, prehash);
const h1int = bits2int_modN(message);
const d = Fn2.fromBytes(secretKey);
if (!Fn2.isValidNot0(d))
throw new Error("invalid private key");
const seedArgs = [int2octets(d), int2octets(h1int)];
if (extraEntropy != null && extraEntropy !== false) {
const e = extraEntropy === true ? randomBytes4(lengths.secretKey) : extraEntropy;
seedArgs.push(abytes2(e, void 0, "extraEntropy"));
}
const seed = concatBytes2(...seedArgs);
const m = h1int;
function k2sig(kBytes) {
const k = bits2int(kBytes);
if (!Fn2.isValidNot0(k))
return;
const ik = Fn2.inv(k);
const q = Point2.BASE.multiply(k).toAffine();
const r = Fn2.create(q.x);
if (r === _0n4)
return;
const s = Fn2.create(ik * Fn2.create(m + r * d));
if (s === _0n4)
return;
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
let normS = s;
if (lowS && isBiggerThanHalfOrder(s)) {
normS = Fn2.neg(s);
recovery ^= 1;
}
return new Signature(r, normS, hasLargeRecoveryLifts ? void 0 : recovery);
}
return { seed, k2sig };
}
function sign(message, secretKey, opts2 = {}) {
const { seed, k2sig } = prepSig(message, secretKey, opts2);
const drbg = createHmacDrbg(hash_.outputLen, Fn2.BYTES, hmac2);
const sig = drbg(seed, k2sig);
return sig.toBytes(opts2.format);
}
function verify(signature, message, publicKey, opts2 = {}) {
const { lowS, prehash, format } = validateSigOpts(opts2, defaultSigOpts);
publicKey = abytes2(publicKey, void 0, "publicKey");
message = validateMsgAndHash(message, prehash);
if (!isBytes3(signature)) {
const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
throw new Error("verify expects Uint8Array signature" + end);
}
validateSigLength(signature, format);
try {
const sig = Signature.fromBytes(signature, format);
const P = Point2.fromBytes(publicKey);
if (lowS && sig.hasHighS())
return false;
const { r, s } = sig;
const h = bits2int_modN(message);
const is = Fn2.inv(s);
const u1 = Fn2.create(h * is);
const u2 = Fn2.create(r * is);
const R = Point2.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
if (R.is0())
return false;
const v = Fn2.create(R.x);
return v === r;
} catch (e) {
return false;
}
}
function recoverPublicKey(signature, message, opts2 = {}) {
const { prehash } = validateSigOpts(opts2, defaultSigOpts);
message = validateMsgAndHash(message, prehash);
return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
}
return Object.freeze({
keygen,
getPublicKey,
getSharedSecret,
utils: utils2,
lengths,
Point: Point2,
sign,
verify,
recoverPublicKey,
Signature,
hash: hash_
});
}
// node_modules/@noble/curves/secp256k1.js
var secp256k1_CURVE = {
p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
h: BigInt(1),
a: BigInt(0),
b: BigInt(7),
Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
};
var secp256k1_ENDO = {
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
basises: [
[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
]
};
var _2n3 = /* @__PURE__ */ BigInt(2);
function sqrtMod(y) {
const P = secp256k1_CURVE.p;
const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
const b2 = y * y * y % P;
const b3 = b2 * b2 * y % P;
const b6 = pow2(b3, _3n3, P) * b3 % P;
const b9 = pow2(b6, _3n3, P) * b3 % P;
const b11 = pow2(b9, _2n3, P) * b2 % P;
const b22 = pow2(b11, _11n, P) * b11 % P;
const b44 = pow2(b22, _22n, P) * b22 % P;
const b88 = pow2(b44, _44n, P) * b44 % P;
const b176 = pow2(b88, _88n, P) * b88 % P;
const b220 = pow2(b176, _44n, P) * b44 % P;
const b223 = pow2(b220, _3n3, P) * b3 % P;
const t1 = pow2(b223, _23n, P) * b22 % P;
const t2 = pow2(t1, _6n, P) * b2 % P;
const root = pow2(t2, _2n3, P);
if (!Fpk1.eql(Fpk1.sqr(root), y))
throw new Error("Cannot find square root");
return root;
}
var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
Fp: Fpk1,
endo: secp256k1_ENDO
});
var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);
// node_modules/@noble/hashes/legacy.js
var Rho160 = /* @__PURE__ */ Uint8Array.from([
7,
4,
13,
1,
10,
6,
15,
3,
12,
0,
9,
5,
2,
14,
11,
8
]);
var Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();
var Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();
var idxLR = /* @__PURE__ */ (() => {
const L = [Id160];
const R = [Pi160];
const res = [L, R];
for (let i = 0; i < 4; i++)
for (let j of res)
j.push(j[i].map((k) => Rho160[k]));
return res;
})();
var idxL = /* @__PURE__ */ (() => idxLR[0])();
var idxR = /* @__PURE__ */ (() => idxLR[1])();
var shifts160 = /* @__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) => Uint8Array.from(i));
var shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));
var shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));
var Kl160 = /* @__PURE__ */ Uint32Array.from([
0,
1518500249,
1859775393,
2400959708,
2840853838
]);
var Kr160 = /* @__PURE__ */ Uint32Array.from([
1352829926,
1548603684,
1836072691,
2053994217,
0
]);
function ripemd_f(group, x, y, z) {
if (group === 0)
return x ^ y ^ z;
if (group === 1)
return x & y | ~x & z;
if (group === 2)
return (x | ~y) ^ z;
if (group === 3)
return x & z | y & ~z;
return x ^ (y | ~z);
}
var BUF_160 = /* @__PURE__ */ new Uint32Array(16);
var _RIPEMD160 = class extends HashMD {
constructor() {
super(64, 20, 8, true);
__publicField(this, "h0", 1732584193 | 0);
__publicField(this, "h1", 4023233417 | 0);
__publicField(this, "h2", 2562383102 | 0);
__publicField(this, "h3", 271733878 | 0);
__publicField(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)
BUF_160[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 = Kl160[group], hbr = Kr160[group];
const rl = idxL[group], rr = idxR[group];
const sl = shiftsL160[group], sr = shiftsR160[group];
for (let i = 0; i < 16; i++) {
const tl = rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[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 + ripemd_f(rGroup, br, cr, dr) + BUF_160[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() {
clean(BUF_160);
}
destroy() {
this.destroyed = true;
clean(this.buffer);
this.set(0, 0, 0, 0, 0);
}
};
var ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160());
// node_modules/@scure/bip32/index.js
var Point = /* @__PURE__ */ (() => secp256k1.Point)();
var Fn = /* @__PURE__ */ (() => Point.Fn)();
var base58check = /* @__PURE__ */ createBase58check(sha256);
var MASTER_SECRET = /* @__PURE__ */ (() => {
return Uint8Array.from("Bitcoin seed".split(""), (char) => char.charCodeAt(0));
})();
var BITCOIN_VERSIONS = { private: 76066276, public: 76067358 };
var HARDENED_OFFSET = 2147483648;
var hash160 = (data) => ripemd160(sha256(data));
var fromU32 = (data) => createView(data).getUint32(0, false);
var toU32 = (n) => {
if (typeof n !== "number")
throw new TypeError("invalid number, should be from 0 to 2**32-1, got " + n);
if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1)
throw new RangeError("invalid number, should be from 0 to 2**32-1, got " + n);
const buf = new Uint8Array(4);
createView(buf).setUint32(0, n, false);
return buf;
};
var HDKey = class _HDKey {
constructor(opt) {
__publicField(this, "versions");
__publicField(this, "depth", 0);
__publicField(this, "index", 0);
__publicField(this, "chainCode", null);
__publicField(this, "parentFingerprint", 0);
__publicField(this, "_privateKey");
__publicField(this, "_publicKey");
__publicField(this, "pubHash");
if (!opt || typeof opt !== "object") {
throw new Error("HDKey.constructor must not be called directly");
}
this.versions = opt.versions || BITCOIN_VERSIONS;
this.depth = opt.depth || 0;
this.chainCode = opt.chainCode ? Uint8Array.from(opt.chainCode) : null;
this.index = opt.index || 0;
this.parentFingerprint = opt.parentFingerprint || 0;
if (!this.depth) {
if (this.parentFingerprint || this.index) {
throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");
}
}
if (this.depth > 255) {
throw new Error("HDKey: depth exceeds the serializable value 255");
}
if (opt.publicKey && opt.privateKey) {
throw new Error("HDKey: publicKey and privateKey at same time.");
}
if (opt.privateKey) {
if (!secp256k1.utils.isValidSecretKey(opt.privateKey))
throw new Error("Invalid private key");
this._privateKey = Uint8Array.from(opt.privateKey);
this._publicKey = secp256k1.getPublicKey(this._privateKey, true);
} else if (opt.publicKey) {
this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true);
} else {
throw new Error("HDKey: no public or private key provided");
}
this.pubHash = hash160(this._publicKey);
}
get fingerprint() {
if (!this.pubHash) {
throw new Error("No publicKey set!");
}
return fromU32(this.pubHash);
}
get identifier() {
return this.pubHash;
}
get pubKeyHash() {
return this.pubHash;
}
// Returns the live private key buffer for this instance.
// Copy it first if you need an immutable snapshot.
get privateKey() {
return this._privateKey || null;
}
get publicKey() {
return this._publicKey || null;
}
get privateExtendedKey() {
const priv = this._privateKey;
if (!priv) {
throw new Error("No private key");
}
return base58check.encode(this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv)));
}
get publicExtendedKey() {
if (!this._publicKey) {
throw new Error("No public key");
}
return base58check.encode(this.serialize(this.versions.public, this._publicKey));
}
static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) {
abytes(seed);
if (8 * seed.length < 128 || 8 * seed.length > 512) {
throw new RangeError("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got " + seed.length);
}
const I = hmac(sha512, MASTER_SECRET, seed);
const privateKey = I.slice(0, 32);
const chainCode = I.slice(32);
return new _HDKey({ versions, chainCode, privateKey });
}
static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) {
const keyBuffer = base58check.decode(base58key);
const keyView = createView(keyBuffer);
const version = keyView.getUint32(0, false);
const opt = {
versions,
depth: keyBuffer[4],
parentFingerprint: keyView.getUint32(5, false),
index: keyView.getUint32(9, false),
chainCode: keyBuffer.slice(13, 45)
};
const key = keyBuffer.slice(45);
const isPriv = key[0] === 0;
if (version !== versions[isPriv ? "private" : "public"]) {
throw new Error("Version mismatch");
}
if (isPriv) {
return new _HDKey({ ...opt, privateKey: key.slice(1) });
} else {
return new _HDKey({ ...opt, publicKey: key });
}
}
static fromJSON(json) {
return _HDKey.fromExtendedKey(json.xpriv);
}
derive(path) {
if (!/^[mM]'?/.test(path)) {
throw new Error('Path must start with "m" or "M"');
}
if (/^[mM]'?$/.test(path)) {
return this;
}
const parts = path.replace(/^[mM]'?\//, "").split("/");
let child = this;
for (const c of parts) {
const m = /^(\d+)('?)$/.exec(c);
const m1 = m && m[1];
if (!m || m.length !== 3 || typeof m1 !== "string")
throw new Error("invalid child index: " + c);
let idx = +m1;
if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {
throw new Error("Invalid index");
}
if (m[2] === "'") {
idx += HARDENED_OFFSET;
}
child = child.deriveChild(idx);
}
return child;
}
/**
* @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it.
*/
deriveChild(index, _I) {
if (!this._publicKey || !this.chainCode) {
throw new Error("No publicKey or chainCode set");
}
let data = toU32(index);
if (index >= HARDENED_OFFSET) {
const priv = this._privateKey;
if (!priv) {
throw new Error("Could not derive hardened child key");
}
data = concatBytes(Uint8Array.of(0), priv, data);
} else {
data = concatBytes(this._publicKey, data);
}
const out = _I || hmac(sha512, this.chainCode, data);
abytes(out, 64);
const childTweak = out.slice(0, 32);
const chainCode = out.slice(32);
const opt = {
versions: this.versions,
chainCode,
depth: this.depth + 1,
parentFingerprint: this.fingerprint,
index
};
if (opt.depth > 255) {
throw new Error("HDKey: depth exceeds the serializable value 255");
}
try {
const ctweak = Fn.fromBytes(childTweak);
if (this._privateKey) {
const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak);
if (!Fn.isValidNot0(added)) {
throw new Error("The tweak was out of range or the resulted private key is invalid");
}
opt.privateKey = Fn.toBytes(added);
} else {
const point = Point.fromBytes(this._publicKey);
const added = ctweak === 0n ? point : point.add(Point.BASE.multiply(ctweak));
if (added.equals(Point.ZERO)) {
throw new Error("The tweak was equal to negative P, which made the result key invalid");
}
opt.publicKey = added.toBytes(true);
}
return new _HDKey(opt);
} catch (err) {
return this.deriveChild(index + 1);
}
}
sign(hash) {
if (!this._privateKey) {
throw new Error("No privateKey set!");
}
abytes(hash, 32);
return secp256k1.sign(hash, this._privateKey, { prehash: false });
}
verify(hash, signature) {
abytes(hash, 32);
abytes(signature, 64);
if (!this._publicKey) {
throw new Error("No publicKey set!");
}
return secp256k1.verify(signature, hash, this._publicKey, { prehash: false });
}
wipePrivateData() {
if (this._privateKey) {
this._privateKey.fill(0);
this._privateKey = void 0;
}
return this;
}
toJSON() {
return {
xpriv: this.privateExtendedKey,
xpub: this.publicExtendedKey
};
}
serialize(version, key) {
if (!this.chainCode) {
throw new Error("No chainCode set");
}
abytes(key, 33);
return concatBytes(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key);
}
};
// node_modules/@noble/hashes/hkdf.js
function extract(hash, ikm, salt) {
ahash(hash);
if (salt === void 0)
salt = new Uint8Array(hash.outputLen);
return hmac(hash, salt, ikm);
}
var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
function expand(hash, prk, info, length = 32) {
ahash(hash);
anumber(length, "length");
abytes(prk, void 0, "prk");
const olen = hash.outputLen;
if (prk.length < olen)
throw new Error('"prk" must be at least HashLen octets');
if (length > 255 * olen)
throw new Error("Length must be <= 255*HashLen");
const blocks = Math.ceil(length / olen);
if (info === void 0)
info = EMPTY_BUFFER;
else
abytes(info, void 0, "info");
const okm = new Uint8Array(blocks * olen);
const HMAC = hmac.create(hash, prk);
const HMACTmp = HMAC._cloneInto();
const T = new Uint8Array(HMAC.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, olen * counter);
HMAC._cloneInto(HMACTmp);
}
HMAC.destroy();
HMACTmp.destroy();
clean(T, HKDF_COUNTER);
return okm.slice(0, length);
}
var hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
// node_modules/@noble/hashes/sha3.js
var _0n5 = BigInt(0);
var _1n5 = BigInt(1);
var _2n4 = BigInt(2);
var _7n2 = BigInt(7);
var _256n = BigInt(256);
var _0x71n = BigInt(113);
var SHA3_PI = [];
var SHA3_ROTL = [];
var _SHA3_IOTA = [];
for (let round = 0, R = _1n5, 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 = _0n5;
for (let j = 0; j < 7; j++) {
R = (R << _1n5 ^ (R >> _7n2) * _0x71n) % _256n;
if (R & _2n4)
t ^= _1n5 << (_1n5 << BigInt(j)) - _1n5;
}
_SHA3_IOTA.push(t);
}
var IOTAS = split(_SHA3_IOTA, true);
var SHA3_IOTA_H = IOTAS[0];
var SHA3_IOTA_L = IOTAS[1];
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) {
anumber(rounds, "rounds");
if (rounds < 1 || rounds > 24)
throw new Error('"rounds" expected integer 1..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) {
const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
s[y] ^= ~s[y + 2] & s[y + 4];
s[y + 1] ^= ~s[y + 3] & s[y + 5];
s[y + 2] ^= ~s[y + 4] & s[y + 6];
s[y + 3] ^= ~s[y + 5] & s[y + 7];
s[y + 4] ^= ~s[y + 6] & s[y + 8];
s[y + 5] ^= ~s[y + 7] & s[y + 9];
s[y + 6] ^= ~s[y + 8] & b0;
s[y + 7] ^= ~s[y + 9] & b1;
s[y + 8] ^= ~b0 & b2;
s[y + 9] ^= ~b1 & b3;
}
s[0] ^= SHA3_IOTA_H[round];
s[1] ^= SHA3_IOTA_L[round];
}
clean(B);
}
var Keccak = class _Keccak {
// NOTE: we accept arguments in bytes instead of bits here.
constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
__publicField(this, "state");
__publicField(this, "pos", 0);
__publicField(this, "posOut", 0);
__publicField(this, "finished", false);
__publicField(this, "state32");
__publicField(this, "destroyed", false);
__publicField(this, "blockLen");
__publicField(this, "suffix");
__publicField(this, "outputLen");
__publicField(this, "canXOF");
__publicField(this, "enableXOF", false);
__publicField(this, "rounds");
this.blockLen = blockLen;
this.suffix = suffix;
this.outputLen = outputLen;
this.enableXOF = enableXOF;
this.canXOF = enableXOF;
this.rounds = rounds;
anumber(outputLen, "outputLen");
if (!(0 < blockLen && blockLen < 200))
throw new Error("only keccak-f1600 function is supported");
this.state = new Uint8Array(200);
this.state32 = u32(this.state);
}
clone() {
return this._cloneInto();
}
keccak() {
swap32IfBE(this.state32);
keccakP(this.state32, this.rounds);
swap32IfBE(this.state32);
this.posOut = 0;
this.pos = 0;
}
update(data) {
aexists(this);
abytes(data);
const { blockLen, state } = this;
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) {
aexists(this, false);
abytes(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(bytes) {
anumber(bytes);
return this.xofInto(new Uint8Array(bytes));
}
digestInto(out) {
aoutput(out, this);
if (this.finished)
throw new Error("digest() was already called");
this.writeInto(out.subarray(0, this.outputLen));
this.destroy();
}
digest() {
const out = new Uint8Array(this.outputLen);
this.digestInto(out);
return out;
}
destroy() {
this.destroyed = true;
clean(this.state);
}
_cloneInto(to) {
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
to.blockLen = blockLen;
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.canXOF = this.canXOF;
to.destroyed = this.destroyed;
return to;
}
};
var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
var sha3_256 = /* @__PURE__ */ genKeccak(
6,
136,
32,
/* @__PURE__ */ oidNist(8)
);
var sha3_512 = /* @__PURE__ */ genKeccak(
6,
72,
64,
/* @__PURE__ */ oidNist(10)
);
var genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts2 = {}) => new Keccak(blockLen, suffix, opts2.dkLen === void 0 ? outputLen : opts2.dkLen, true), info);
var shake128 = /* @__PURE__ */ genShake(31, 168, 16, /* @__PURE__ */ oidNist(11));
var shake256 = /* @__PURE__ */ genShake(31, 136, 32, /* @__PURE__ */ oidNist(12));
// node_modules/@noble/post-quantum/utils.js
var abytesDoc = abytes;
var randomBytes3 = randomBytes;
function equalBytes(a, b) {
if (a.length !== b.length)
return false;
let diff = 0;
for (let i = 0; i < a.length; i++)
diff |= a[i] ^ b[i];
return diff === 0;
}
function copyBytes2(bytes) {
return Uint8Array.from(abytes(bytes));
}
function validateOpts(opts2) {
if (Object.prototype.toString.call(opts2) !== "[object Object]")
throw new TypeError("expected valid options object");
}
function validateVerOpts(opts2) {
validateOpts(opts2);
if (opts2.context !== void 0)
abytes(opts2.context, void 0, "opts.context");
}
function validateSigOpts2(opts2) {
validateVerOpts(opts2);
if (opts2.extraEntropy !== false && opts2.extraEntropy !== void 0)
abytes(opts2.extraEntropy, void 0, "opts.extraEntropy");
}
function splitCoder(label, ...lengths) {
const getLength = (c) => typeof c === "number" ? c : c.bytesLen;
const bytesLen = lengths.reduce((sum, a) => sum + getLength(a), 0);
return {
bytesLen,
encode: (bufs) => {
const res = new Uint8Array(bytesLen);
for (let i = 0, pos = 0; i < lengths.length; i++) {
const c = lengths[i];
const l = getLength(c);
const b = typeof c === "number" ? bufs[i] : c.encode(bufs[i]);
abytes(b, l, label);
res.set(b, pos);
if (typeof c !== "number")
b.fill(0);
pos += l;
}
return res;
},
decode: (buf) => {
abytes(buf, bytesLen, label);
const res = [];
for (const c of lengths) {
const l = getLength(c);
const b = buf.subarray(0, l);
res.push(typeof c === "number" ? b : c.decode(b));
buf = buf.subarray(l);
}
return res;
}
};
}
function vecCoder(c, vecLen) {
const coder = c;
const bytesLen = vecLen * coder.bytesLen;
return {
bytesLen,
encode: (u) => {
if (u.length !== vecLen)
throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);
const res = new Uint8Array(bytesLen);
for (let i = 0, pos = 0; i < u.length; i++) {
const b = coder.encode(u[i]);
res.set(b, pos);
b.fill(0);
pos += b.length;
}
return res;
},
decode: (a) => {
abytes(a, bytesLen);
const r = [];
for (let i = 0; i < a.length; i += coder.bytesLen)
r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));
return r;
}
};
}
function cleanBytes(...list) {
for (const t of list) {
if (Array.isArray(t))
for (const b of t)
b.fill(0);
else
t.fill(0);
}
}
function getMask(bits) {
if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
throw new RangeError(`expected bits in [0..32], got ${bits}`);
return bits === 32 ? 4294967295 : ~(-1 << bits) >>> 0;
}
var EMPTY = /* @__PURE__ */ Uint8Array.of();
function getMessage(msg, ctx = EMPTY) {
abytes(msg);
abytes(ctx);
if (ctx.length > 255)
throw new RangeError("context should be 255 bytes or less");
return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);
}
var oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2]);
function checkHash(hash, requiredStrength = 0) {
if (!hash.oid || !equalBytes(hash.oid.subarray(0, 10), oidNistP))
throw new Error("hash.oid is invalid: expected NIST hash");
const collisionResistance = hash.outputLen * 8 / 2;
if (requiredStrength > collisionResistance) {
throw new Error("Pre-hash security strength too low: " + collisionResistance + ", required: " + requiredStrength);
}
}
function getMessagePrehash(hash, msg, ctx = EMPTY) {
abytes(msg);
abytes(ctx);
if (ctx.length > 255)
throw new RangeError("context should be 255 bytes or less");
const hashed = hash(msg);
return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid, hashed);
}
// node_modules/@noble/post-quantum/_crystals.js
var genCrystals = (opts2) => {
const { newPoly: newPoly2, N: N3, Q: Q3, F: F3, ROOT_OF_UNITY: ROOT_OF_UNITY3, brvBits, isKyber } = opts2;
const mod2 = (a, modulo = Q3) => {
const result = a % modulo | 0;
return (result >= 0 ? result | 0 : modulo + result | 0) | 0;
};
const smod = (a, modulo = Q3) => {
const r = mod2(a, modulo) | 0;
return (r > modulo >> 1 ? r - modulo | 0 : r) | 0;
};
function getZettas() {
const out = newPoly2(N3);
for (let i = 0; i < N3; i++) {
const b = reverseBits(i, brvBits);
const p = BigInt(ROOT_OF_UNITY3) ** BigInt(b) % BigInt(Q3);
out[i] = Number(p) | 0;
}
return out;
}
const nttZetas = getZettas();
const field = {
add: (a, b) => mod2((a | 0) + (b | 0)) | 0,
sub: (a, b) => mod2((a | 0) - (b | 0)) | 0,
mul: (a, b) => mod2((a | 0) * (b | 0)) | 0,
inv: (_a) => {
throw new Error("not implemented");
}
};
const nttOpts = {
N: N3,
roots: nttZetas,
invertButterflies: true,
skipStages: isKyber ? 1 : 0,
brp: false
};
const dif = FFTCore(field, { dit: false, ...nttOpts });
const dit = FFTCore(field, { dit: true, ...nttOpts });
const NTT = {
encode: (r) => {
return dif(r);
},
decode: (r) => {
dit(r);
for (let i = 0; i < r.length; i++)
r[i] = mod2(F3 * r[i]);
return r;
}
};
const bitsCoder = (d, c) => {
const mask = getMask(d);
const bytesLen = d * (N3 / 8);
return {
bytesLen,
encode: (poly_) => {
const poly = poly_;
const r = new Uint8Array(bytesLen);
for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {
buf |= (c.encode(poly[i]) & mask) << bufLen;
bufLen += d;
for (; bufLen >= 8; bufLen -= 8, buf >>= 8)
r[pos++] = buf & getMask(bufLen);
}
return r;
},
decode: (bytes) => {
const r = newPoly2(N3);
for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {
buf |= bytes[i] << bufLen;
bufLen += 8;
for (; bufLen >= d; bufLen -= d, buf >>= d)
r[pos++] = c.decode(buf & mask);
}
return r;
}
};
};
return {
mod: mod2,
smod,
nttZetas,
NTT: {
encode: (r) => NTT.encode(r),
decode: (r) => NTT.decode(r)
},
bitsCoder
};
};
var createXofShake = (shake) => (seed, blockLen) => {
if (!blockLen)
blockLen = shake.blockLen;
const _seed = new Uint8Array(seed.length + 2);
_seed.set(seed);
const seedLen = seed.length;
const buf = new Uint8Array(blockLen);
let h = shake.create({});
let calls = 0;
let xofs = 0;
return {
stats: () => ({ calls, xofs }),
get: (x, y) => {
_seed[seedLen + 0] = x;
_seed[seedLen + 1] = y;
h.destroy();
h = shake.create({}).update(_seed);
calls++;
return () => {
xofs++;
return h.xofInto(buf);
};
},
clean: () => {
h.destroy();
cleanBytes(buf, _seed);
}
};
};
var XOF128 = /* @__PURE__ */ createXofShake(shake128);
var XOF256 = /* @__PURE__ */ createXofShake(shake256);
// node_modules/@noble/post-quantum/ml-dsa.js
function validateInternalOpts(opts2) {
validateOpts(opts2);
if (opts2.externalMu !== void 0)
abool(opts2.externalMu, "opts.externalMu");
}
var N = 256;
var Q = 8380417;
var ROOT_OF_UNITY = 1753;
var F = 8347681;
var D = 13;
var GAMMA2_1 = Math.floor((Q - 1) / 88) | 0;
var GAMMA2_2 = Math.floor((Q - 1) / 32) | 0;
var PARAMS = /* @__PURE__ */ (() => Object.freeze({
2: Object.freeze({
K: 4,
L: 4,
D,
GAMMA1: 2 ** 17,
GAMMA2: GAMMA2_1,
TAU: 39,
ETA: 2,
OMEGA: 80
}),
3: Object.freeze({
K: 6,
L: 5,
D,
GAMMA1: 2 ** 19,
GAMMA2: GAMMA2_2,
TAU: 49,
ETA: 4,
OMEGA: 55
}),
5: Object.freeze({
K: 8,
L: 7,
D,
GAMMA1: 2 ** 19,
GAMMA2: GAMMA2_2,
TAU: 60,
ETA: 2,
OMEGA: 75
})
}))();
var newPoly = (n) => new Int32Array(n);
var crystals = /* @__PURE__ */ genCrystals({
N,
Q,
F,
ROOT_OF_UNITY,
newPoly,
isKyber: false,
brvBits: 8
});
var id = (n) => n;
var polyCoder = (d, compress2 = id, verify = id) => crystals.bitsCoder(d, {
encode: (i) => compress2(verify(i)),
decode: (i) => verify(compress2(i))
});
var polyAdd = (a_, b_) => {
const a = a_;
const b = b_;
for (let i = 0; i < a.length; i++)
a[i] = crystals.mod(a[i] + b[i]);
return a;
};
var polySub = (a_, b_) => {
const a = a_;
const b = b_;
for (let i = 0; i < a.length; i++)
a[i] = crystals.mod(a[i] - b[i]);
return a;
};
var polyShiftl = (p_) => {
const p = p_;
for (let i = 0; i < N; i++)
p[i] <<= D;
return p;
};
var polyChknorm = (p_, B) => {
const p = p_;
for (let i = 0; i < N; i++)
if (Math.abs(crystals.smod(p[i])) >= B)
return true;
return false;
};
var MultiplyNTTs = (a_, b_) => {
const a = a_;
const b = b_;
const c = newPoly(N);
for (let i = 0; i < a.length; i++)
c[i] = crystals.mod(a[i] * b[i]);
return c;
};
function RejNTTPoly(xof_) {
const xof = xof_;
const r = newPoly(N);
for (let j = 0; j < N; ) {
const b = xof();
if (b.length % 3)
throw new Error("RejNTTPoly: unaligned block");
for (let i = 0; j < N && i <= b.length - 3; i += 3) {
const t = (b[i + 0] | b[i + 1] << 8 | b[i + 2] << 16) & 8388607;
if (t < Q)
r[j++] = t;
}
}
return r;
}
function getDilithium(opts_) {
const opts2 = opts_;
const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts2;
const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128: XOF1282, XOF256: XOF2562, securityLevel } = opts2;
if (![2, 4].includes(ETA))
throw new Error("Wrong ETA");
if (![1 << 17, 1 << 19].includes(GAMMA1))
throw new Error("Wrong GAMMA1");
if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2))
throw new Error("Wrong GAMMA2");
const BETA = TAU * ETA;
const decompose = (r) => {
const rPlus = crystals.mod(r);
const r0 = crystals.smod(rPlus, 2 * GAMMA2) | 0;
if (rPlus - r0 === Q - 1)
return { r1: 0 | 0, r0: r0 - 1 | 0 };
const r1 = Math.floor((rPlus - r0) / (2 * GAMMA2)) | 0;
return { r1, r0 };
};
const HighBits = (r) => decompose(r).r1;
const LowBits = (r) => decompose(r).r0;
const MakeHint = (z, r) => {
const res0 = z <= GAMMA2 || z > Q - GAMMA2 || z === Q - GAMMA2 && r === 0 ? 0 : 1;
return res0;
};
const UseHint = (h, r) => {
const m = Math.floor((Q - 1) / (2 * GAMMA2));
const { r1, r0 } = decompose(r);
if (h === 1)
return r0 > 0 ? crystals.mod(r1 + 1, m) | 0 : crystals.mod(r1 - 1, m) | 0;
return r1 | 0;
};
const Power2Round = (r) => {
const rPlus = crystals.mod(r);
const r0 = crystals.smod(rPlus, 2 ** D) | 0;
return { r1: Math.floor((rPlus - r0) / 2 ** D) | 0, r0 };
};
const hintCoder = {
bytesLen: OMEGA + K,
encode: (h_) => {
const h = h_;
if (h === false)
throw new Error("hint.encode: hint is false");
const res = new Uint8Array(OMEGA + K);
for (let i = 0, k = 0; i < K; i++) {
for (let j = 0; j < N; j++)
if (h[i][j] !== 0)
res[k++] = j;
res[OMEGA + i] = k;
}
return res;
},
decode: (buf) => {
const h = [];
let k = 0;
for (let i = 0; i < K; i++) {
const hi = newPoly(N);
if (buf[OMEGA + i] < k || buf[OMEGA + i] > OMEGA)
return false;
for (let j = k; j < buf[OMEGA + i]; j++) {
if (j > k && buf[j] <= buf[j - 1])
return false;
hi[buf[j]] = 1;
}
k = buf[OMEGA + i];
h.push(hi);
}
for (let j = k; j < OMEGA; j++)
if (buf[j] !== 0)
return false;
return h;
}
};
const ETACoder = polyCoder(ETA === 2 ? 3 : 4, (i) => ETA - i, (i) => {
if (!(-ETA <= i && i <= ETA))
throw new Error(`malformed key s1/s3 ${i} outside of ETA range [${-ETA}, ${ETA}]`);
return i;
});
const T0Coder = polyCoder(13, (i) => (1 << D - 1) - i);
const T1Coder = polyCoder(10);
const ZCoder = polyCoder(GAMMA1 === 1 << 17 ? 18 : 20, (i) => crystals.smod(GAMMA1 - i));
const W1Coder = polyCoder(GAMMA2 === GAMMA2_1 ? 6 : 4);
const W1Vec = vecCoder(W1Coder, K);
const publicCoder = splitCoder("publicKey", 32, vecCoder(T1Coder, K));
const secretCoder = splitCoder("secretKey", 32, 32, TR_BYTES, vecCoder(ETACoder, L), vecCoder(ETACoder, K), vecCoder(T0Coder, K));
const sigCoder = splitCoder("signature", C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder);
const CoefFromHalfByte = ETA === 2 ? (n) => n < 15 ? 2 - n % 5 : false : (n) => n < 9 ? 4 - n : false;
function RejBoundedPoly(xof_) {
const xof = xof_;
const r = newPoly(N);
for (let j = 0; j < N; ) {
const b = xof();
for (let i = 0; j < N && i < b.length; i += 1) {
const d1 = CoefFromHalfByte(b[i] & 15);
const d2 = CoefFromHalfByte(b[i] >> 4 & 15);
if (d1 !== false)
r[j++] = d1;
if (j < N && d2 !== false)
r[j++] = d2;
}
}
return r;
}
const SampleInBall = (seed) => {
const pre = newPoly(N);
const s = shake256.create({}).update(seed);
const buf = new Uint8Array(shake256.blockLen);
s.xofInto(buf);
const masks = buf.slice(0, 8);
for (let i = N - TAU, pos = 8, maskPos = 0, maskBit = 0; i < N; i++) {
let b = i + 1;
for (; b > i; ) {
b = buf[pos++];
if (pos < shake256.blockLen)
continue;
s.xofInto(buf);
pos = 0;
}
pre[i] = pre[b];
pre[b] = 1 - ((masks[maskPos] >> maskBit++ & 1) << 1);
if (maskBit >= 8) {
maskPos++;
maskBit = 0;
}
}
return pre;
};
const polyPowerRound = (p_) => {
const p = p_;
const res0 = newPoly(N);
const res1 = newPoly(N);
for (let i = 0; i < p.length; i++) {
const { r0, r1 } = Power2Round(p[i]);
res0[i] = r0;
res1[i] = r1;
}
return { r0: res0, r1: res1 };
};
const polyUseHint = (u_, h_) => {
const u = u_;
const h = h_;
for (let i = 0; i < N; i++)
u[i] = UseHint(h[i], u[i]);
return u;
};
const polyMakeHint = (a_, b_) => {
const a = a_;
const b = b_;
const v = newPoly(N);
let cnt = 0;
for (let i = 0; i < N; i++) {
const h = MakeHint(a[i], b[i]);
v[i] = h;
cnt += h;
}
return { v, cnt };
};
const signRandBytes = 32;
const seedCoder = splitCoder("seed", 32, 64, 32);
const internal = Object.freeze({
info: Object.freeze({ type: "internal-ml-dsa" }),
lengths: Object.freeze({
secretKey: secretCoder.bytesLen,
publicKey: publicCoder.bytesLen,
seed: 32,
signature: sigCoder.bytesLen,
signRand: signRandBytes
}),
keygen: (seed) => {
const seedDst = new Uint8Array(32 + 2);
const randSeed = seed === void 0;
if (randSeed)
seed = randomBytes3(32);
abytesDoc(seed, 32, "seed");
seedDst.set(seed);
if (randSeed)
cleanBytes(seed);
seedDst[32] = K;
seedDst[33] = L;
const [rho, rhoPrime, K_] = seedCoder.decode(shake256(seedDst, { dkLen: seedCoder.bytesLen }));
const xofPrime = XOF2562(rhoPrime);
const s1 = [];
for (let i = 0; i < L; i++)
s1.push(RejBoundedPoly(xofPrime.get(i & 255, i >> 8 & 255)));
const s2 = [];
for (let i = L; i < L + K; i++)
s2.push(RejBoundedPoly(xofPrime.get(i & 255, i >> 8 & 255)));
const s1Hat = s1.map((i) => crystals.NTT.encode(i.slice()));
const t0 = [];
const t1 = [];
const xof = XOF1282(rho);
const t = newPoly(N);
for (let i = 0; i < K; i++) {
cleanBytes(t);
for (let j = 0; j < L; j++) {
const aij = RejNTTPoly(xof.get(j, i));
polyAdd(t, MultiplyNTTs(aij, s1Hat[j]));
}
crystals.NTT.decode(t);
const { r0, r1 } = polyPowerRound(polyAdd(t, s2[i]));
t0.push(r0);
t1.push(r1);
}
const publicKey = publicCoder.encode([rho, t1]);
const tr = shake256(publicKey, { dkLen: TR_BYTES });
const secretKey = secretCoder.encode([rho, K_, tr, s1, s2, t0]);
xof.clean();
xofPrime.clean();
cleanBytes(rho, rhoPrime, K_, s1, s2, s1Hat, t, t0, t1, tr, seedDst);
return {
publicKey,
secretKey
};
},
getPublicKey: (secretKey) => {
const [rho, _K, _tr, s1, s2, _t0] = secretCoder.decode(secretKey);
const xof = XOF1282(rho);
const s1Hat = s1.map((p) => crystals.NTT.encode(p.slice()));
const t1 = [];
const tmp = newPoly(N);
for (let i = 0; i < K; i++) {
tmp.fill(0);
for (let j = 0; j < L; j++) {
const aij = RejNTTPoly(xof.get(j, i));
polyAdd(tmp, MultiplyNTTs(aij, s1Hat[j]));
}
crystals.NTT.decode(tmp);
polyAdd(tmp, s2[i]);
const { r1 } = polyPowerRound(tmp);
t1.push(r1);
}
xof.clean();
cleanBytes(tmp, s1Hat, _t0, s1, s2);
return publicCoder.encode([rho, t1]);
},
// NOTE: random is optional.
sign: (msg, secretKey, opts3 = {}) => {
validateSigOpts2(opts3);
validateInternalOpts(opts3);
let { extraEntropy: random, externalMu = false } = opts3;
const [rho, _K, tr, s1, s2, t0] = secretCoder.decode(secretKey);
const A = [];
const xof = XOF1282(rho);
for (let i = 0; i < K; i++) {
const pv = [];
for (let j = 0; j < L; j++)
pv.push(RejNTTPoly(xof.get(j, i)));
A.push(pv);
}
xof.clean();
for (let i = 0; i < L; i++)
crystals.NTT.encode(s1[i]);
for (let i = 0; i < K; i++) {
crystals.NTT.encode(s2[i]);
crystals.NTT.encode(t0[i]);
}
const mu = externalMu ? msg : (
// 6: µ ← H(tr||M, 512)
// ▷ Compute message representative µ
shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest()
);
const rnd = random === false ? new Uint8Array(32) : random === void 0 ? randomBytes3(signRandBytes) : random;
abytesDoc(rnd, 32, "extraEntropy");
const rhoprime = shake256.create({ dkLen: CRH_BYTES }).update(_K).update(rnd).update(mu).digest();
abytesDoc(rhoprime, CRH_BYTES);
const x256 = XOF2562(rhoprime, ZCoder.bytesLen);
main_loop: for (let kappa = 0; ; ) {
const y = [];
for (let i = 0; i < L; i++, kappa++)
y.push(ZCoder.decode(x256.get(kappa & 255, kappa >> 8)()));
const z = y.map((i) => crystals.NTT.encode(i.slice()));
const w = [];
for (let i = 0; i < K; i++) {
const wi = newPoly(N);
for (let j = 0; j < L; j++)
polyAdd(wi, MultiplyNTTs(A[i][j], z[j]));
crystals.NTT.decode(wi);
w.push(wi);
}
const w1 = w.map((j) => j.map(HighBits));
const cTilde = shake256.create({ dkLen: C_TILDE_BYTES }).update(mu).update(W1Vec.encode(w1)).digest();
const cHat = crystals.NTT.encode(SampleInBall(cTilde));
const cs1 = s1.map((i) => MultiplyNTTs(i, cHat));
for (let i = 0; i < L; i++) {
polyAdd(crystals.NTT.decode(cs1[i]), y[i]);
if (polyChknorm(cs1[i], GAMMA1 - BETA))
continue main_loop;
}
let cnt = 0;
const h = [];
for (let i = 0; i < K; i++) {
const cs2 = crystals.NTT.decode(MultiplyNTTs(s2[i], cHat));
const r0 = polySub(w[i], cs2).map(LowBits);
if (polyChknorm(r0, GAMMA2 - BETA))
continue main_loop;
const ct0 = crystals.NTT.decode(MultiplyNTTs(t0[i], cHat));
if (polyChknorm(ct0, GAMMA2))
continue main_loop;
polyAdd(r0, ct0);
const hint = polyMakeHint(r0, w1[i]);
h.push(hint.v);
cnt += hint.cnt;
}
if (cnt > OMEGA)
continue;
x256.clean();
const res = sigCoder.encode([cTilde, cs1, h]);
cleanBytes(cTilde, cs1, h, cHat, w1, w, z, y, rhoprime, s1, s2, t0, ...A);
if (!externalMu)
cleanBytes(mu);
return res;
}
throw new Error("Unreachable code path reached, report this error");
},
verify: (sig, msg, publicKey, opts3 = {}) => {
validateInternalOpts(opts3);
const { externalMu = false } = opts3;
const [rho, t1] = publicCoder.decode(publicKey);
const tr = shake256(publicKey, { dkLen: TR_BYTES });
if (sig.length !== sigCoder.bytesLen)
return false;
const [cTilde, z, h] = sigCoder.decode(sig);
if (h === false)
return false;
for (let i = 0; i < L; i++)
if (polyChknorm(z[i], GAMMA1 - BETA))
return false;
const mu = externalMu ? msg : (
// 7: µ ← H(tr||M, 512)
shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest()
);
const c = crystals.NTT.encode(SampleInBall(cTilde));
const zNtt = z.map((i) => i.slice());
for (let i = 0; i < L; i++)
crystals.NTT.encode(zNtt[i]);
const wTick1 = [];
const xof = XOF1282(rho);
for (let i = 0; i < K; i++) {
const ct12d = MultiplyNTTs(crystals.NTT.encode(polyShiftl(t1[i])), c);
const Az = newPoly(N);
for (let j = 0; j < L; j++) {
const aij = RejNTTPoly(xof.get(j, i));
polyAdd(Az, MultiplyNTTs(aij, zNtt[j]));
}
const wApprox = crystals.NTT.decode(polySub(Az, ct12d));
wTick1.push(polyUseHint(wApprox, h[i]));
}
xof.clean();
const c2 = shake256.create({ dkLen: C_TILDE_BYTES }).update(mu).update(W1Vec.encode(wTick1)).digest();
for (const t of h) {
const sum = t.reduce((acc, i) => acc + i, 0);
if (!(sum <= OMEGA))
return false;
}
for (const t of z)
if (polyChknorm(t, GAMMA1 - BETA))
return false;
return equalBytes(cTilde, c2);
}
});
return Object.freeze({
info: Object.freeze({ type: "ml-dsa" }),
internal,
securityLevel,
keygen: internal.keygen,
lengths: internal.lengths,
getPublicKey: internal.getPublicKey,
sign: (msg, secretKey, opts3 = {}) => {
validateSigOpts2(opts3);
const M = getMessage(msg, opts3.context);
const res = internal.sign(M, secretKey, opts3);
cleanBytes(M);
return res;
},
verify: (sig, msg, publicKey, opts3 = {}) => {
validateVerOpts(opts3);
return internal.verify(sig, getMessage(msg, opts3.context), publicKey);
},
prehash: (hash) => {
checkHash(hash, securityLevel);
return Object.freeze({
info: Object.freeze({ type: "hashml-dsa" }),
securityLevel,
lengths: internal.lengths,
keygen: internal.keygen,
getPublicKey: internal.getPublicKey,
sign: (msg, secretKey, opts3 = {}) => {
validateSigOpts2(opts3);
const M = getMessagePrehash(hash, msg, opts3.context);
const res = internal.sign(M, secretKey, opts3);
cleanBytes(M);
return res;
},
verify: (sig, msg, publicKey, opts3 = {}) => {
validateVerOpts(opts3);
return internal.verify(sig, getMessagePrehash(hash, msg, opts3.context), publicKey);
}
});
}
});
}
var ml_dsa65 = /* @__PURE__ */ (() => getDilithium({
...PARAMS[3],
CRH_BYTES: 64,
TR_BYTES: 64,
C_TILDE_BYTES: 48,
XOF128,
XOF256,
securityLevel: 192
}))();
// node_modules/@noble/post-quantum/slh-dsa.js
var PARAMS2 = /* @__PURE__ */ (() => Object.freeze({
"128f": Object.freeze({ W: 16, N: 16, H: 66, D: 22, K: 33, A: 6, securityLevel: 128 }),
"128s": Object.freeze({ W: 16, N: 16, H: 63, D: 7, K: 14, A: 12, securityLevel: 128 }),
"192f": Object.freeze({ W: 16, N: 24, H: 66, D: 22, K: 33, A: 8, securityLevel: 192 }),
"192s": Object.freeze({ W: 16, N: 24, H: 63, D: 7, K: 17, A: 14, securityLevel: 192 }),
"256f": Object.freeze({ W: 16, N: 32, H: 68, D: 17, K: 35, A: 9, securityLevel: 256 }),
"256s": Object.freeze({ W: 16, N: 32, H: 64, D: 8, K: 22, A: 14, securityLevel: 256 })
}))();
var AddressType = {
WOTS: 0,
WOTSPK: 1,
HASHTREE: 2,
FORSTREE: 3,
FORSPK: 4,
WOTSPRF: 5,
FORSPRF: 6
};
function hexToNumber2(hex) {
if (typeof hex !== "string")
throw new Error("hex string expected, got " + typeof hex);
return BigInt(hex === "" ? "0" : "0x" + hex);
}
function bytesToNumberBE2(bytes) {
return hexToNumber2(bytesToHex(bytes));
}
function numberToBytesBE2(n, len) {
return hexToBytes(n.toString(16).padStart(len * 2, "0"));
}
var base2b = (outLen, b) => {
const mask = getMask(b);
return (bytes) => {
const baseB = new Uint32Array(outLen);
for (let out = 0, pos = 0, bits = 0, total = 0; out < outLen; out++) {
while (bits < b) {
total = total << 8 | bytes[pos++];
bits += 8;
}
bits -= b;
baseB[out] = total >>> bits & mask;
}
return baseB;
};
};
function getMaskBig(bits) {
return (1n << BigInt(bits)) - 1n;
}
function gen(opts2, hashOpts_) {
const hashOpts = hashOpts_;
const { N: N3, W, H, D: D2, K, A, securityLevel } = opts2;
const getContext = hashOpts.getContext(opts2);
if (W !== 16)
throw new Error("Unsupported Winternitz parameter");
const WOTS_LOGW = 4;
const WOTS_LEN1 = Math.floor(8 * N3 / WOTS_LOGW);
const WOTS_LEN2 = N3 <= 8 ? 2 : N3 <= 136 ? 3 : 4;
const TREE_HEIGHT = Math.floor(H / D2);
const WOTS_LEN = WOTS_LEN1 + WOTS_LEN2;
let ADDR_BYTES = 22;
let OFFSET_LAYER = 0;
let OFFSET_TREE = 1;
let OFFSET_TYPE = 9;
let OFFSET_KP_ADDR2 = 12;
let OFFSET_KP_ADDR1 = 13;
let OFFSET_CHAIN_ADDR = 17;
let OFFSET_TREE_INDEX = 18;
let OFFSET_HASH_ADDR = 21;
if (!hashOpts.isCompressed) {
ADDR_BYTES = 32;
OFFSET_LAYER += 3;
OFFSET_TREE += 7;
OFFSET_TYPE += 10;
OFFSET_KP_ADDR2 += 10;
OFFSET_KP_ADDR1 += 10;
OFFSET_CHAIN_ADDR += 10;
OFFSET_TREE_INDEX += 10;
OFFSET_HASH_ADDR += 10;
}
const setAddr = (opts3, addr = new Uint8Array(ADDR_BYTES)) => {
const { type, height, tree, layer, index, chain: chain2, hash, keypair } = opts3;
const { subtreeAddr, keypairAddr } = opts3;
const v = createView(addr);
if (height !== void 0)
addr[OFFSET_CHAIN_ADDR] = height;
if (layer !== void 0)
addr[OFFSET_LAYER] = layer;
if (type !== void 0)
addr[OFFSET_TYPE] = type;
if (chain2 !== void 0)
addr[OFFSET_CHAIN_ADDR] = chain2;
if (hash !== void 0)
addr[OFFSET_HASH_ADDR] = hash;
if (index !== void 0)
v.setUint32(OFFSET_TREE_INDEX, index, false);
if (subtreeAddr)
addr.set(subtreeAddr.subarray(0, OFFSET_TREE + 8));
if (tree !== void 0)
v.setBigUint64(OFFSET_TREE, tree, false);
if (keypair !== void 0) {
addr[OFFSET_KP_ADDR1] = keypair;
if (TREE_HEIGHT > 8)
addr[OFFSET_KP_ADDR2] = keypair >>> 8;
}
if (keypairAddr) {
addr.set(keypairAddr.subarray(0, OFFSET_TREE + 8));
addr[OFFSET_KP_ADDR1] = keypairAddr[OFFSET_KP_ADDR1];
if (TREE_HEIGHT > 8)
addr[OFFSET_KP_ADDR2] = keypairAddr[OFFSET_KP_ADDR2];
}
return addr;
};
const chainCoder = base2b(WOTS_LEN2, WOTS_LOGW);
const chainLengths = (msg) => {
const W1 = base2b(WOTS_LEN1, WOTS_LOGW)(msg);
let csum = 0;
for (let i = 0; i < W1.length; i++)
csum += W - 1 - W1[i];
csum <<= (8 - WOTS_LEN2 * WOTS_LOGW % 8) % 8;
const W2 = chainCoder(numberToBytesBE2(csum, Math.ceil(WOTS_LEN2 * WOTS_LOGW / 8)));
const lengths = new Uint32Array(WOTS_LEN);
lengths.set(W1);
lengths.set(W2, W1.length);
return lengths;
};
const messageToIndices = base2b(K, A);
const TREE_BITS = TREE_HEIGHT * (D2 - 1);
const LEAF_BITS = TREE_HEIGHT;
const hashMsgCoder = splitCoder("hashedMessage", Math.ceil(A * K / 8), Math.ceil(TREE_BITS / 8), Math.ceil(TREE_HEIGHT / 8));
const hashMessage = (R, pkSeed, msg, context) => {
const rawContext = context;
const digest = rawContext.Hmsg(R, pkSeed, msg, hashMsgCoder.bytesLen);
const [md, tmpIdxTree, tmpIdxLeaf] = hashMsgCoder.decode(digest);
const tree = bytesToNumberBE2(tmpIdxTree) & getMaskBig(TREE_BITS);
const leafIdx = Number(bytesToNumberBE2(tmpIdxLeaf)) & getMask(LEAF_BITS);
return { tree, leafIdx, md };
};
const treehash = (height, fn) => function treehash_i(context, leafIdx, idxOffset, treeAddr, info) {
const rawContext = context;
const leafFn = fn;
const maxIdx = (1 << height) - 1;
const stack = new Uint8Array(height * N3);
const authPath = new Uint8Array(height * N3);
for (let idx = 0; ; idx++) {
const current = new Uint8Array(2 * N3);
const cur0 = current.subarray(0, N3);
const cur1 = current.subarray(N3);
const addrOffset = idx + idxOffset;
cur1.set(leafFn(leafIdx, addrOffset, rawContext, info));
let h = 0;
for (let i = idx, o = idxOffset, l = leafIdx; ; h++, i >>>= 1, l >>>= 1, o >>>= 1) {
if (h === height)
return { root: cur1, authPath };
if ((i ^ l) === 1)
authPath.subarray(h * N3).set(cur1);
if ((i & 1) === 0 && idx < maxIdx)
break;
setAddr({ height: h + 1, index: (i >> 1) + (o >> 1) }, treeAddr);
cur0.set(stack.subarray(h * N3).subarray(0, N3));
cur1.set(rawContext.thashN(2, current, treeAddr));
}
stack.subarray(h * N3).set(cur1);
}
throw new Error("Unreachable code path reached, report this error");
};
const wotsTreehash = treehash(TREE_HEIGHT, (leafIdx, addrOffset, context, info) => {
const rawContext = context;
const wotsPk = new Uint8Array(WOTS_LEN * N3);
const wotsKmask = addrOffset === leafIdx ? 0 : ~0 >>> 0;
setAddr({ keypair: addrOffset }, info.leafAddr);
setAddr({ keypair: addrOffset }, info.pkAddr);
for (let i = 0; i < WOTS_LEN; i++) {
const wotsK = info.wotsSteps[i] | wotsKmask;
const pk = wotsPk.subarray(i * N3, (i + 1) * N3);
setAddr({ chain: i, hash: 0, type: AddressType.WOTSPRF }, info.leafAddr);
pk.set(rawContext.PRFaddr(info.leafAddr));
setAddr({ type: AddressType.WOTS }, info.leafAddr);
for (let k = 0; ; k++) {
if (k === wotsK)
info.wotsSig.subarray(i * N3).set(pk);
if (k === W - 1)
break;
setAddr({ hash: k }, info.leafAddr);
pk.set(rawContext.thash1(pk, info.leafAddr));
}
}
return rawContext.thashN(WOTS_LEN, wotsPk, info.pkAddr);
});
const forsTreehash = treehash(A, (_, addrOffset, context, forsLeafAddr) => {
const rawContext = context;
setAddr({ type: AddressType.FORSPRF, index: addrOffset }, forsLeafAddr);
const prf = rawContext.PRFaddr(forsLeafAddr);
setAddr({ type: AddressType.FORSTREE }, forsLeafAddr);
return rawContext.thash1(prf, forsLeafAddr);
});
const merkleSign = (context, wotsAddr, treeAddr, leafIdx, prevRoot = new Uint8Array(N3)) => {
setAddr({ type: AddressType.HASHTREE }, treeAddr);
const info = {
wotsSig: new Uint8Array(wotsCoder.bytesLen),
wotsSteps: chainLengths(prevRoot),
leafAddr: setAddr({ subtreeAddr: wotsAddr }),
pkAddr: setAddr({ type: AddressType.WOTSPK, subtreeAddr: wotsAddr })
};
const { root, authPath } = wotsTreehash(context, leafIdx, 0, treeAddr, info);
return {
root,
sigWots: info.wotsSig.subarray(0, WOTS_LEN * N3),
sigAuth: authPath
};
};
const computeRoot = (leaf, leafIdx, idxOffset, authPath, treeHeight, context, addr) => {
const rawContext = context;
const buffer = new Uint8Array(2 * N3);
const b0 = buffer.subarray(0, N3);
const b1 = buffer.subarray(N3, 2 * N3);
if ((leafIdx & 1) !== 0) {
b1.set(leaf.subarray(0, N3));
b0.set(authPath.subarray(0, N3));
} else {
b0.set(leaf.subarray(0, N3));
b1.set(authPath.subarray(0, N3));
}
leafIdx >>>= 1;
idxOffset >>>= 1;
for (let i = 0; i < treeHeight - 1; i++, leafIdx >>= 1, idxOffset >>= 1) {
setAddr({ height: i + 1, index: leafIdx + idxOffset }, addr);
const a = authPath.subarray((i + 1) * N3, (i + 2) * N3);
if ((leafIdx & 1) !== 0) {
b1.set(rawContext.thashN(2, buffer, addr));
b0.set(a);
} else {
buffer.set(rawContext.thashN(2, buffer, addr));
b1.set(a);
}
}
setAddr({ height: treeHeight, index: leafIdx + idxOffset }, addr);
return rawContext.thashN(2, buffer, addr);
};
const seedCoder = splitCoder("seed", N3, N3, N3);
const publicCoder = splitCoder("publicKey", N3, N3);
const secretCoder = splitCoder("secretKey", N3, N3, publicCoder.bytesLen);
const forsCoder = vecCoder(splitCoder("fors", N3, N3 * A), K);
const wotsCoder = vecCoder(splitCoder("wots", WOTS_LEN * N3, TREE_HEIGHT * N3), D2);
const sigCoder = splitCoder("signature", N3, forsCoder, wotsCoder);
const internal = Object.freeze({
info: Object.freeze({ type: "internal-slh-dsa" }),
lengths: Object.freeze({
publicKey: publicCoder.bytesLen,
secretKey: secretCoder.bytesLen,
signature: sigCoder.bytesLen,
seed: seedCoder.bytesLen,
signRand: N3
}),
keygen(seed) {
if (seed !== void 0)
abytesDoc(seed, seedCoder.bytesLen, "seed");
seed = seed === void 0 ? randomBytes3(seedCoder.bytesLen) : copyBytes2(seed);
const [secretSeed, secretPRF, publicSeed] = seedCoder.decode(seed);
const context = getContext(publicSeed, secretSeed);
const topTreeAddr = setAddr({ layer: D2 - 1 });
const wotsAddr = setAddr({ layer: D2 - 1 });
const { root } = merkleSign(context, wotsAddr, topTreeAddr, ~0 >>> 0);
const publicKey = publicCoder.encode([publicSeed, root]);
const secretKey = secretCoder.encode([secretSeed, secretPRF, publicKey]);
context.clean();
cleanBytes(secretSeed, secretPRF, root, wotsAddr, topTreeAddr);
return {
publicKey,
secretKey
};
},
getPublicKey: (secretKey) => {
const [_skSeed, _skPRF, pk] = secretCoder.decode(secretKey);
return Uint8Array.from(pk);
},
sign: (msg, sk, opts3 = {}) => {
validateSigOpts2(opts3);
let { extraEntropy: random } = opts3;
const [skSeed, skPRF, pk] = secretCoder.decode(sk);
const [pkSeed, _] = publicCoder.decode(pk);
if (random === false)
random = copyBytes2(pkSeed);
else if (random === void 0)
random = randomBytes3(N3);
else
random = copyBytes2(random);
abytesDoc(random, N3);
const context = getContext(pkSeed, skSeed);
const R = context.PRFmsg(skPRF, random, msg);
let { tree, leafIdx, md } = hashMessage(R, pk, msg, context);
const wotsAddr = setAddr({
type: AddressType.WOTS,
tree,
keypair: leafIdx
});
const roots = [];
const forsLeaf = setAddr({ keypairAddr: wotsAddr });
const forsTreeAddr = setAddr({ keypairAddr: wotsAddr });
const indices = messageToIndices(md);
const fors = [];
for (let i = 0; i < indices.length; i++) {
const idxOffset = i << A;
setAddr({
type: AddressType.FORSPRF,
height: 0,
index: indices[i] + idxOffset
}, forsTreeAddr);
const prf = context.PRFaddr(forsTreeAddr);
setAddr({ type: AddressType.FORSTREE }, forsTreeAddr);
const { root: root2, authPath } = forsTreehash(context, indices[i], idxOffset, forsTreeAddr, forsLeaf);
roots.push(root2);
fors.push([prf, authPath]);
}
const forsPkAddr = setAddr({
type: AddressType.FORSPK,
keypairAddr: wotsAddr
});
const root = context.thashN(K, concatBytes(...roots), forsPkAddr);
const treeAddr = setAddr({ type: AddressType.HASHTREE });
const wots = [];
for (let i = 0; i < D2; i++, tree >>= BigInt(TREE_HEIGHT)) {
setAddr({ tree, layer: i }, treeAddr);
setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr);
const { sigWots, sigAuth, root: r } = merkleSign(context, wotsAddr, treeAddr, leafIdx, root);
root.set(r);
cleanBytes(r);
wots.push([sigWots, sigAuth]);
leafIdx = Number(tree & getMaskBig(TREE_HEIGHT));
}
context.clean();
const SIG = sigCoder.encode([R, fors, wots]);
cleanBytes(R, random, treeAddr, wotsAddr, forsLeaf, forsTreeAddr, indices, roots);
return SIG;
},
verify: (sig, msg, publicKey) => {
const [pkSeed, pubRoot] = publicCoder.decode(publicKey);
const [random, forsVec, wotsVec] = sigCoder.decode(sig);
const pk = publicKey;
if (sig.length !== sigCoder.bytesLen)
return false;
const context = getContext(pkSeed);
let { tree, leafIdx, md } = hashMessage(random, pk, msg, context);
const wotsAddr = setAddr({
type: AddressType.WOTS,
tree,
keypair: leafIdx
});
const roots = [];
const forsTreeAddr = setAddr({
type: AddressType.FORSTREE,
keypairAddr: wotsAddr
});
const indices = messageToIndices(md);
for (let i = 0; i < forsVec.length; i++) {
const [prf, authPath] = forsVec[i];
const idxOffset = i << A;
setAddr({ height: 0, index: indices[i] + idxOffset }, forsTreeAddr);
const leaf = context.thash1(prf, forsTreeAddr);
roots.push(computeRoot(leaf, indices[i], idxOffset, authPath, A, context, forsTreeAddr));
}
const forsPkAddr = setAddr({
type: AddressType.FORSPK,
keypairAddr: wotsAddr
});
let root = context.thashN(K, concatBytes(...roots), forsPkAddr);
const treeAddr = setAddr({ type: AddressType.HASHTREE });
const wotsPkAddr = setAddr({ type: AddressType.WOTSPK });
const wotsPk = new Uint8Array(WOTS_LEN * N3);
for (let i = 0; i < wotsVec.length; i++, tree >>= BigInt(TREE_HEIGHT)) {
const [wots, sigAuth] = wotsVec[i];
setAddr({ tree, layer: i }, treeAddr);
setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr);
setAddr({ keypairAddr: wotsAddr }, wotsPkAddr);
const lengths = chainLengths(root);
for (let i2 = 0; i2 < WOTS_LEN; i2++) {
setAddr({ chain: i2 }, wotsAddr);
const steps = W - 1 - lengths[i2];
const start = lengths[i2];
const out = wotsPk.subarray(i2 * N3);
out.set(wots.subarray(i2 * N3, (i2 + 1) * N3));
for (let j = start; j < start + steps && j < W; j++) {
setAddr({ hash: j }, wotsAddr);
out.set(context.thash1(out, wotsAddr));
}
}
const leaf = context.thashN(WOTS_LEN, wotsPk, wotsPkAddr);
root = computeRoot(leaf, leafIdx, 0, sigAuth, TREE_HEIGHT, context, treeAddr);
leafIdx = Number(tree & getMaskBig(TREE_HEIGHT));
}
return equalBytes(root, pubRoot);
}
});
return Object.freeze({
info: Object.freeze({ type: "slh-dsa" }),
internal,
securityLevel,
lengths: internal.lengths,
keygen: internal.keygen,
getPublicKey: internal.getPublicKey,
sign: (msg, secretKey, opts3 = {}) => {
validateSigOpts2(opts3);
const M = getMessage(msg, opts3.context);
const res = internal.sign(M, secretKey, opts3);
cleanBytes(M);
return res;
},
verify: (sig, msg, publicKey, opts3 = {}) => {
validateVerOpts(opts3);
return internal.verify(sig, getMessage(msg, opts3.context), publicKey);
},
prehash: (hash) => {
checkHash(hash, securityLevel);
const rawHash = hash;
return Object.freeze({
info: Object.freeze({ type: "hashslh-dsa" }),
lengths: internal.lengths,
keygen: internal.keygen,
getPublicKey: internal.getPublicKey,
sign: (msg, secretKey, opts3 = {}) => {
validateSigOpts2(opts3);
const M = getMessagePrehash(rawHash, msg, opts3.context);
const res = internal.sign(M, secretKey, opts3);
cleanBytes(M);
return res;
},
verify: (sig, msg, publicKey, opts3 = {}) => {
validateVerOpts(opts3);
return internal.verify(sig, getMessagePrehash(rawHash, msg, opts3.context), publicKey);
}
});
}
});
}
var genSha = (h0, h1) => (opts2) => (pub_seed, sk_seed) => {
const { N: N3 } = opts2;
const stats = { prf: 0, thash: 0, hmsg: 0, gen_message_random: 0, mgf1: 0 };
const counterB = new Uint8Array(4);
const counterV = createView(counterB);
const h0ps = h0.create().update(pub_seed).update(new Uint8Array(h0.blockLen - N3));
const h1ps = h1.create().update(pub_seed).update(new Uint8Array(h1.blockLen - N3));
const h0tmp = h0ps.clone();
const h1tmp = h1ps.clone();
function mgf1(seed, length, hash) {
stats.mgf1++;
const out = new Uint8Array(Math.ceil(length / hash.outputLen) * hash.outputLen);
if (length > 2 ** 32)
throw new Error("mask too long");
for (let counter = 0, o = out; o.length; counter++) {
counterV.setUint32(0, counter, false);
hash.create().update(seed).update(counterB).digestInto(o);
o = o.subarray(hash.outputLen);
}
cleanBytes(out.subarray(length));
return out.subarray(0, length);
}
const thash = (_, h, hTmp) => (blocks, input, addr) => {
stats.thash++;
const d = h._cloneInto(hTmp).update(addr).update(input.subarray(0, blocks * N3)).digest();
return d.subarray(0, N3);
};
return {
PRFaddr: (addr) => {
if (!sk_seed)
throw new Error("No sk seed");
stats.prf++;
const res = h0ps._cloneInto(h0tmp).update(addr).update(sk_seed).digest().subarray(0, N3);
return res;
},
PRFmsg: (skPRF, random, msg) => {
stats.gen_message_random++;
return hmac.create(h1, skPRF).update(random).update(msg).digest().subarray(0, N3);
},
Hmsg: (R, pk, m, outLen) => {
stats.hmsg++;
const seed = concatBytes(R.subarray(0, N3), pk.subarray(0, N3), h1.create().update(R.subarray(0, N3)).update(pk).update(m).digest());
return mgf1(seed, outLen, h1);
},
thash1: thash(h0, h0ps, h0tmp).bind(null, 1),
thashN: thash(h1, h1ps, h1tmp),
clean: () => {
h0ps.destroy();
h1ps.destroy();
h0tmp.destroy();
h1tmp.destroy();
}
};
};
var SHA256_SIMPLE = /* @__PURE__ */ (() => ({
isCompressed: true,
getContext: genSha(sha256, sha256)
}))();
var slh_dsa_sha2_128s = /* @__PURE__ */ (() => gen(PARAMS2["128s"], SHA256_SIMPLE))();
// node_modules/@noble/post-quantum/ml-kem.js
var N2 = 256;
var Q2 = 3329;
var F2 = 3303;
var ROOT_OF_UNITY2 = 17;
var crystals2 = /* @__PURE__ */ genCrystals({
N: N2,
Q: Q2,
F: F2,
ROOT_OF_UNITY: ROOT_OF_UNITY2,
newPoly: (n) => new Uint16Array(n),
brvBits: 7,
isKyber: true
});
var PARAMS3 = /* @__PURE__ */ (() => Object.freeze({
512: Object.freeze({ N: N2, Q: Q2, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),
768: Object.freeze({ N: N2, Q: Q2, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),
1024: Object.freeze({ N: N2, Q: Q2, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 })
}))();
var compress = (d) => {
if (d >= 12)
return { encode: (i) => i, decode: (i) => i >= Q2 ? i - Q2 : i };
const a = 2 ** (d - 1);
return {
// This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).
encode: (i) => ((i << d) + Q2 / 2) / Q2,
// const decompress = (i: number) => round((Q / 2 ** d) * i);
decode: (i) => i * Q2 + a >>> d
};
};
var byteCoder = (d) => crystals2.bitsCoder(d, d === 12 ? { encode: (i) => i, decode: (i) => i >= Q2 ? i - Q2 : i } : { encode: (i) => i, decode: (i) => i });
var polyCoder2 = (d) => d === 12 ? byteCoder(12) : crystals2.bitsCoder(d, compress(d));
function polyAdd2(a_, b_) {
const a = a_;
const b = b_;
for (let i = 0; i < N2; i++)
a[i] = crystals2.mod(a[i] + b[i]);
}
function polySub2(a_, b_) {
const a = a_;
const b = b_;
for (let i = 0; i < N2; i++)
a[i] = crystals2.mod(a[i] - b[i]);
}
function BaseCaseMultiply(a0, a1, b0, b1, zeta) {
const c0 = crystals2.mod(a1 * b1 * zeta + a0 * b0);
const c1 = crystals2.mod(a0 * b1 + a1 * b0);
return { c0, c1 };
}
function MultiplyNTTs2(f_, g_) {
const f = f_;
const g = g_;
for (let i = 0; i < N2 / 2; i++) {
let z = crystals2.nttZetas[64 + (i >> 1)];
if (i & 1)
z = -z;
const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);
f[2 * i + 0] = c0;
f[2 * i + 1] = c1;
}
return f;
}
function SampleNTT(xof_) {
const xof = xof_;
const r = new Uint16Array(N2);
for (let j = 0; j < N2; ) {
const b = xof();
if (b.length % 3)
throw new Error("SampleNTT: unaligned block");
for (let i = 0; j < N2 && i + 3 <= b.length; i += 3) {
const d1 = (b[i + 0] >> 0 | b[i + 1] << 8) & 4095;
const d2 = (b[i + 1] >> 4 | b[i + 2] << 4) & 4095;
if (d1 < Q2)
r[j++] = d1;
if (j < N2 && d2 < Q2)
r[j++] = d2;
}
}
return r;
}
var sampleCBDBytes = (buf, eta) => {
const r = new Uint16Array(N2);
const b32 = u32(buf);
swap32IfBE(b32);
let len = 0;
for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {
let b = b32[i];
for (let j = 0; j < 32; j++) {
bb += b & 1;
b >>= 1;
len += 1;
if (len === eta) {
t0 = bb;
bb = 0;
} else if (len === 2 * eta) {
r[p++] = crystals2.mod(t0 - bb);
bb = 0;
len = 0;
}
}
}
swap32IfBE(b32);
if (len)
throw new Error(`sampleCBD: leftover bits: ${len}`);
return r;
};
function sampleCBD(PRF_, seed, nonce, eta) {
const PRF = PRF_;
return sampleCBDBytes(PRF(eta * N2 / 4, seed, nonce), eta);
}
var genKPKE = (opts_) => {
const opts2 = opts_;
const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts2;
const poly1 = polyCoder2(1);
const polyV = polyCoder2(dv);
const polyU = polyCoder2(du);
const publicCoder = splitCoder("publicKey", vecCoder(polyCoder2(12), K), 32);
const secretCoder = vecCoder(polyCoder2(12), K);
const cipherCoder = splitCoder("ciphertext", vecCoder(polyU, K), polyV);
const seedCoder = splitCoder("seed", 32, 32);
return {
secretCoder,
lengths: {
secretKey: secretCoder.bytesLen,
publicKey: publicCoder.bytesLen,
cipherText: cipherCoder.bytesLen
},
keygen: (seed) => {
abytesDoc(seed, 32, "seed");
const seedDst = new Uint8Array(33);
seedDst.set(seed);
seedDst[32] = K;
const seedHash = HASH512(seedDst);
const [rho, sigma] = seedCoder.decode(seedHash);
const sHat = [];
const tHat = [];
for (let i = 0; i < K; i++)
sHat.push(crystals2.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));
const x = XOF(rho);
for (let i = 0; i < K; i++) {
const e = crystals2.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));
for (let j = 0; j < K; j++) {
const aji = SampleNTT(x.get(j, i));
polyAdd2(e, MultiplyNTTs2(aji, sHat[j]));
}
tHat.push(e);
}
x.clean();
const res = {
publicKey: publicCoder.encode([tHat, rho]),
secretKey: secretCoder.encode(sHat)
};
cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);
return res;
},
encrypt: (publicKey, msg, seed) => {
const [tHat, rho] = publicCoder.decode(publicKey);
const rHat = [];
for (let i = 0; i < K; i++)
rHat.push(crystals2.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));
const x = XOF(rho);
const tmp2 = new Uint16Array(N2);
const u = [];
for (let i = 0; i < K; i++) {
const e1 = sampleCBD(PRF, seed, K + i, ETA2);
const tmp = new Uint16Array(N2);
for (let j = 0; j < K; j++) {
const aij = SampleNTT(x.get(i, j));
polyAdd2(tmp, MultiplyNTTs2(aij, rHat[j]));
}
polyAdd2(e1, crystals2.NTT.decode(tmp));
u.push(e1);
polyAdd2(tmp2, MultiplyNTTs2(tHat[i], rHat[i]));
cleanBytes(tmp);
}
x.clean();
const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);
polyAdd2(e2, crystals2.NTT.decode(tmp2));
const v = poly1.decode(msg);
polyAdd2(v, e2);
cleanBytes(tHat, rHat, tmp2, e2);
return cipherCoder.encode([u, v]);
},
decrypt: (cipherText, privateKey) => {
const [u, v] = cipherCoder.decode(cipherText);
const sk = secretCoder.decode(privateKey);
const tmp = new Uint16Array(N2);
for (let i = 0; i < K; i++)
polyAdd2(tmp, MultiplyNTTs2(sk[i], crystals2.NTT.encode(u[i])));
polySub2(v, crystals2.NTT.decode(tmp));
cleanBytes(tmp, sk, u);
return poly1.encode(v);
}
};
};
function createKyber(opts2) {
const rawOpts = opts2;
const KPKE = genKPKE(rawOpts);
const { HASH256, HASH512, KDF } = rawOpts;
const { secretCoder: KPKESecretCoder, lengths } = KPKE;
const secretCoder = splitCoder("secretKey", lengths.secretKey, lengths.publicKey, 32, 32);
const msgLen = 32;
const seedLen = 64;
const kemLengths = Object.freeze({
...lengths,
seed: 64,
msg: msgLen,
msgRand: msgLen,
secretKey: secretCoder.bytesLen
});
return Object.freeze({
info: Object.freeze({ type: "ml-kem" }),
lengths: kemLengths,
keygen: (seed = randomBytes3(seedLen)) => {
abytesDoc(seed, seedLen, "seed");
const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));
const publicKeyHash = HASH256(publicKey);
const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);
cleanBytes(sk, publicKeyHash);
return {
publicKey,
secretKey
};
},
getPublicKey: (secretKey) => {
const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);
return Uint8Array.from(publicKey);
},
encapsulate: (publicKey, msg = randomBytes3(msgLen)) => {
abytesDoc(publicKey, lengths.publicKey, "publicKey");
abytesDoc(msg, msgLen, "message");
const eke = publicKey.subarray(0, 384 * opts2.K);
const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes2(eke)));
if (!equalBytes(ek, eke)) {
cleanBytes(ek);
throw new Error("ML-KEM.encapsulate: wrong publicKey modulus");
}
cleanBytes(ek);
const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();
const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
cleanBytes(kr.subarray(32));
return {
cipherText,
sharedSecret: kr.subarray(0, 32)
};
},
decapsulate: (cipherText, secretKey) => {
abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
abytesDoc(cipherText, lengths.cipherText, "cipherText");
const k768 = secretCoder.bytesLen - 96;
const start = k768 + 32;
const test = HASH256(secretKey.subarray(k768 / 2, start));
if (!equalBytes(test, secretKey.subarray(start, start + 32)))
throw new Error("invalid secretKey: hash check failed");
const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);
const msg = KPKE.decrypt(cipherText, sk);
const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
const Khat = kr.subarray(0, 32);
const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
const isValid = equalBytes(cipherText, cipherText2);
const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);
return isValid ? Khat : Kbar;
}
});
}
function shakePRF(dkLen, key, nonce) {
return shake256.create({ dkLen }).update(key).update(new Uint8Array([nonce])).digest();
}
var opts = /* @__PURE__ */ (() => ({
HASH256: sha3_256,
HASH512: sha3_512,
KDF: shake256,
XOF: XOF128,
PRF: shakePRF
}))();
var mk = (params) => createKyber({
...opts,
...params
});
var ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS3[768]))();
// www/js/pq-crypto.mjs
function generateSeedPhrase() {
return generateMnemonic(wordlist, 128);
}
function mnemonicToSeed(mnemonic, passphrase = "") {
if (!validateMnemonic(mnemonic, wordlist)) {
throw new Error("Invalid mnemonic");
}
return mnemonicToSeedSync(mnemonic, passphrase);
}
function isValidMnemonic(mnemonic) {
return validateMnemonic(mnemonic, wordlist);
}
function deriveSecp256k1FromSeed(seed, accountIndex = 0) {
const hdKey = HDKey.fromMasterSeed(seed);
const path = `m/44'/1237'/${accountIndex}'/0/0`;
const child = hdKey.derive(path);
if (!child.privateKey) {
throw new Error("Failed to derive private key");
}
return {
privateKey: child.privateKey,
publicKey: child.publicKey
};
}
function derivePQSeed(bip39Seed, label, length) {
const info = new TextEncoder().encode(label);
return hkdf(sha512, bip39Seed, void 0, info, length);
}
function derivePQKeysFromSeed(bip39Seed) {
const mlDsaSeed = derivePQSeed(bip39Seed, "nostr-pq-ml-dsa-65", 32);
const mlDsa = ml_dsa65.keygen(mlDsaSeed);
const slhDsaSeed = derivePQSeed(bip39Seed, "nostr-pq-slh-dsa-128s", 48);
const slhDsa = slh_dsa_sha2_128s.keygen(slhDsaSeed);
const mlKemSeed = derivePQSeed(bip39Seed, "nostr-pq-ml-kem-768", 64);
const mlKem = ml_kem768.keygen(mlKemSeed);
return { mlDsa, slhDsa, mlKem };
}
function signWithMLDSA(message, secretKey) {
return ml_dsa65.sign(message, secretKey);
}
function verifyMLDSA(signature, message, publicKey) {
return ml_dsa65.verify(signature, message, publicKey);
}
function signWithSLHDSA(message, secretKey) {
return slh_dsa_sha2_128s.sign(message, secretKey);
}
function verifySLHDSA(signature, message, publicKey) {
return slh_dsa_sha2_128s.verify(signature, message, publicKey);
}
function bytesToBase64(bytes) {
let binary = "";
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
function base64ToBytes(base64) {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
function bytesToHex3(bytes) {
return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
}
function hexToBytes3(hex) {
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
}
return bytes;
}
function buildNIPQRContent(npub, successorNpub, pqKeys) {
let statement;
if (successorNpub) {
statement = `Identity ${npub} is migrating to successor ${successorNpub}. All PQ keys listed below are derived from the same BIP39 seed as ${successorNpub}. This link is established pre-quantum.`;
} else {
statement = `Identity ${npub} is linked to the following PQ keys, all derived from the same BIP39 seed. This link is established pre-quantum.`;
}
const statementBytes = new TextEncoder().encode(statement);
const mlDsaSig = signWithMLDSA(statementBytes, pqKeys.mlDsa.secretKey);
const slhDsaSig = signWithSLHDSA(statementBytes, pqKeys.slhDsa.secretKey);
const content = {
statement,
pq_keys: [
{
algorithm: "ml-dsa-65",
public_key: bytesToBase64(pqKeys.mlDsa.publicKey),
signature: bytesToBase64(mlDsaSig)
},
{
algorithm: "slh-dsa-128s",
public_key: bytesToBase64(pqKeys.slhDsa.publicKey),
signature: bytesToBase64(slhDsaSig)
},
{
algorithm: "ml-kem-768",
public_key: bytesToBase64(pqKeys.mlKem.publicKey),
note: "KEM key for encryption; ownership asserted by secp256k1 signature over this content"
}
]
};
if (successorNpub) {
content.successor_pubkey = successorNpub;
}
return { statement, content, statementBytes };
}
function verifyNIPQRContent(content) {
const results = [];
for (const keyEntry of content.pq_keys) {
if (keyEntry.algorithm === "ml-kem-768") {
results.push({ algorithm: keyEntry.algorithm, valid: true, note: "KEM (no signature to verify)" });
continue;
}
const pubKey = base64ToBytes(keyEntry.public_key);
const sig = base64ToBytes(keyEntry.signature);
const msg = new TextEncoder().encode(content.statement);
let valid = false;
if (keyEntry.algorithm === "ml-dsa-65") {
valid = verifyMLDSA(sig, msg, pubKey);
} else if (keyEntry.algorithm === "slh-dsa-128s") {
valid = verifySLHDSA(sig, msg, pubKey);
}
results.push({ algorithm: keyEntry.algorithm, valid });
}
return {
valid: results.every((r) => r.valid),
results
};
}
var PQ_KEY_INFO = {
"ml-dsa-65": {
name: "ML-DSA-65 (Dilithium)",
publicKeySize: 1952,
signatureSize: 3309,
fips: "FIPS 204",
type: "signature"
},
"slh-dsa-128s": {
name: "SLH-DSA-128s (SPHINCS+)",
publicKeySize: 32,
signatureSize: 7856,
fips: "FIPS 205",
type: "signature"
},
"ml-kem-768": {
name: "ML-KEM-768 (Kyber)",
publicKeySize: 1184,
ciphertextSize: 1088,
fips: "FIPS 203",
type: "kem"
}
};
export {
PQ_KEY_INFO,
base64ToBytes,
buildNIPQRContent,
bytesToBase64,
bytesToHex3 as bytesToHex,
derivePQKeysFromSeed,
deriveSecp256k1FromSeed,
generateSeedPhrase,
hexToBytes3 as hexToBytes,
isValidMnemonic,
mnemonicToSeed,
signWithMLDSA,
signWithSLHDSA,
verifyMLDSA,
verifyNIPQRContent,
verifySLHDSA
};
/*! Bundled license information:
@scure/base/index.js:
(*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@scure/bip39/index.js:
(*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *)
@noble/curves/utils.js:
@noble/curves/abstract/modular.js:
@noble/curves/abstract/curve.js:
@noble/curves/abstract/weierstrass.js:
@noble/curves/secp256k1.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@scure/bip32/index.js:
(*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *)
@noble/post-quantum/utils.js:
@noble/post-quantum/_crystals.js:
@noble/post-quantum/ml-dsa.js:
@noble/post-quantum/slh-dsa.js:
@noble/post-quantum/ml-kem.js:
(*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) *)
*/
//# sourceMappingURL=pq-crypto.bundle.js.map