From d19dab891669a09214645b6903c971d2ba3feed1 Mon Sep 17 00:00:00 2001 From: matcha Date: Mon, 5 Oct 2026 04:41:41 +0000 Subject: [PATCH] Bundle Inscriboor signing worker --- extension/background.js | 13421 ++++++++++++++++++++++++++++++++++++++ package-lock.json | 506 ++ 2 files changed, 13927 insertions(+) create mode 100644 extension/background.js create mode 100644 package-lock.json diff --git a/extension/background.js b/extension/background.js new file mode 100644 index 0000000..e11ad95 --- /dev/null +++ b/extension/background.js @@ -0,0 +1,13421 @@ +// node_modules/@cmdcode/tapscript/dist/module.mjs +function number$3(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +function bool$3(b) { + if (typeof b !== "boolean") + throw new Error(`Expected boolean, not ${b}`); +} +function bytes$3(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new TypeError("Expected Uint8Array"); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +function hash$4(hash2) { + if (typeof hash2 !== "function" || typeof hash2.create !== "function") + throw new Error("Hash should be wrapped by utils.wrapConstructor"); + number$3(hash2.outputLen); + number$3(hash2.blockLen); +} +function exists$3(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function output$3(out, instance) { + bytes$3(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +var assert$1$2 = { + number: number$3, + bool: bool$3, + bytes: bytes$3, + hash: hash$4, + exists: exists$3, + output: output$3 +}; +var assert$2$1 = assert$1$2; +var createView$3 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +var rotr$3 = (word, shift) => word << 32 - shift | word >>> shift; +var isLE$3 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; +if (!isLE$3) + throw new Error("Non little-endian hardware is not supported"); +Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0")); +function utf8ToBytes$4(str) { + if (typeof str !== "string") { + throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`); + } + return new TextEncoder().encode(str); +} +function toBytes$5(data) { + if (typeof data === "string") + data = utf8ToBytes$4(data); + if (!(data instanceof Uint8Array)) + throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`); + return data; +} +var Hash$3 = class Hash { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +}; +function wrapConstructor$3(hashConstructor) { + const hashC = (message) => hashConstructor().update(toBytes$5(message)).digest(); + const tmp = hashConstructor(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashConstructor(); + return hashC; +} +function setBigUint64$3(view, byteOffset, value, isLE2) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE2); + const _32n2 = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n2 & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE2 ? 4 : 0; + const l = isLE2 ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE2); + view.setUint32(byteOffset + l, wl, isLE2); +} +var SHA2$3 = class SHA2 extends Hash$3 { + constructor(blockLen, outputLen, padOffset, isLE2) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE2; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView$3(this.buffer); + } + update(data) { + assert$2$1.exists(this); + const { view, buffer: buffer2, blockLen } = this; + data = toBytes$5(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView$3(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer2.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) { + assert$2$1.exists(this); + assert$2$1.output(out, this); + this.finished = true; + const { buffer: buffer2, view, blockLen, isLE: isLE2 } = this; + let { pos } = this; + buffer2[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) + buffer2[i] = 0; + setBigUint64$3(view, blockLen - 8, BigInt(this.length * 8), isLE2); + this.process(view, 0); + const oview = createView$3(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE2); + } + digest() { + const { buffer: buffer2, outputLen } = this; + this.digestInto(buffer2); + const res = buffer2.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer2); + return to; + } +}; +var Chi$3 = (a, b, c) => a & b ^ ~a & c; +var Maj$3 = (a, b, c) => a & b ^ a & c ^ b & c; +var SHA256_K$3 = new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +var IV$3 = new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); +var SHA256_W$3 = new Uint32Array(64); +var SHA256$3 = class SHA256 extends SHA2$3 { + constructor() { + super(64, 32, 8, false); + this.A = IV$3[0] | 0; + this.B = IV$3[1] | 0; + this.C = IV$3[2] | 0; + this.D = IV$3[3] | 0; + this.E = IV$3[4] | 0; + this.F = IV$3[5] | 0; + this.G = IV$3[6] | 0; + this.H = IV$3[7] | 0; + } + get() { + const { A, B, C, D, E, F, G: G2, H } = this; + return [A, B, C, D, E, F, G2, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G2, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G2 | 0; + this.H = H | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W$3[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W$3[i - 15]; + const W2 = SHA256_W$3[i - 2]; + const s0 = rotr$3(W15, 7) ^ rotr$3(W15, 18) ^ W15 >>> 3; + const s1 = rotr$3(W2, 17) ^ rotr$3(W2, 19) ^ W2 >>> 10; + SHA256_W$3[i] = s1 + SHA256_W$3[i - 7] + s0 + SHA256_W$3[i - 16] | 0; + } + let { A, B, C, D, E, F, G: G2, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr$3(E, 6) ^ rotr$3(E, 11) ^ rotr$3(E, 25); + const T1 = H + sigma1 + Chi$3(E, F, G2) + SHA256_K$3[i] + SHA256_W$3[i] | 0; + const sigma0 = rotr$3(A, 2) ^ rotr$3(A, 13) ^ rotr$3(A, 22); + const T2 = sigma0 + Maj$3(A, B, C) | 0; + H = G2; + G2 = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G2 = G2 + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G2, H); + } + roundClean() { + SHA256_W$3.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +}; +var SHA224$3 = class SHA224 extends SHA256$3 { + constructor() { + super(); + this.A = 3238371032 | 0; + this.B = 914150663 | 0; + this.C = 812702999 | 0; + this.D = 4144912697 | 0; + this.E = 4290775857 | 0; + this.F = 1750603025 | 0; + this.G = 1694076839 | 0; + this.H = 3204075428 | 0; + this.outputLen = 28; + } +}; +var sha256$4 = wrapConstructor$3(() => new SHA256$3()); +wrapConstructor$3(() => new SHA224$3()); +function within_size$1(data, size2) { + if (data.length > size2) { + throw new TypeError(`Data is larger than array size: ${data.length} > ${size2}`); + } +} +function is_hex$1(hex) { + if (hex.match(/[^a-fA-f0-9]/) !== null) { + throw new TypeError("Invalid characters in hex string: " + hex); + } + if (hex.length % 2 !== 0) { + throw new Error(`Length of hex string is invalid: ${hex.length}`); + } +} +function is_safe_num$1(num2) { + if (num2 > Number.MAX_SAFE_INTEGER) { + throw new TypeError("Number exceeds safe bounds!"); + } +} +var { getRandomValues: getRandomValues$1 } = crypto ?? globalThis.crypto ?? window.crypto; +function random$2(size2 = 32) { + if (typeof getRandomValues$1 === "function") { + return crypto.getRandomValues(new Uint8Array(size2)); + } + throw new Error("Crypto module missing getRandomValues!"); +} +function set_buffer$1(data, size2, endian = "be") { + if (size2 === void 0) + size2 = data.length; + within_size$1(data, size2); + const buffer2 = new Uint8Array(size2).fill(0); + const offset = endian === "be" ? 0 : size2 - data.length; + buffer2.set(data, offset); + return buffer2; +} +function join_array$1(arr) { + let i, offset = 0; + const size2 = arr.reduce((len, arr2) => len + arr2.length, 0); + const buff = new Uint8Array(size2); + for (i = 0; i < arr.length; i++) { + const a = arr[i]; + buff.set(a, offset); + offset += a.length; + } + return buff; +} +var ec$2$1 = new TextEncoder(); +var ALPHABETS$1 = [ + { + name: "base58", + charset: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + } +]; +function getAlphabet$1(name) { + for (const alpha of ALPHABETS$1) { + if (alpha.name === name) { + return alpha.charset; + } + } + throw TypeError("Charset does not exist: " + name); +} +function encode$1$2(data, charset, padding = false) { + if (typeof data === "string") + data = ec$2$1.encode(data); + const alphabet = getAlphabet$1(charset); + const len = alphabet.length; + const d = []; + let s = "", i, j = 0, c, n; + for (i = 0; i < data.length; i++) { + j = 0; + c = data[i]; + s += c > 0 || (s.length ^ i) > 0 ? "" : "1"; + while (j in d || c > 0) { + n = d[j]; + n = n > 0 ? n * 256 + c : c; + c = n / len | 0; + d[j] = n % len; + j++; + } + } + while (j-- > 0) { + s += alphabet[d[j]]; + } + return padding && s.length % 4 > 0 ? s + "=".repeat(4 - s.length % 4) : s; +} +function decode$1$2(encoded, charset) { + const alphabet = getAlphabet$1(charset); + const len = alphabet.length, d = [], b = []; + encoded = encoded.replace("=", ""); + let i, j = 0, c, n; + for (i = 0; i < encoded.length; i++) { + j = 0; + c = alphabet.indexOf(encoded[i]); + if (c < 0) { + throw new Error(`Character range out of bounds: ${c}`); + } + if (!(c > 0 || (b.length ^ i) > 0)) + b.push(0); + while (j in d || c > 0) { + n = d[j]; + n = n > 0 ? n * len + c : c; + c = n >> 8; + d[j] = n % 256; + j++; + } + } + while (j-- > 0) { + b.push(d[j]); + } + return new Uint8Array(b); +} +function hash256$2(data) { + return sha256$4(sha256$4(data)); +} +function addChecksum$1(data) { + const sum = hash256$2(data); + return join_array$1([data, sum.slice(0, 4)]); +} +function checkTheSum$1(data) { + const ret = data.slice(0, -4); + const chk = data.slice(-4); + const sum = hash256$2(ret).slice(0, 4); + if (sum.toString() !== chk.toString()) { + throw new Error("Invalid checksum!"); + } + return ret; +} +var BaseX$1 = { + encode: encode$1$2, + decode: decode$1$2 +}; +var Base58C$1 = { + encode: (data) => { + const withSum = addChecksum$1(data); + return BaseX$1.encode(withSum, "base58"); + }, + decode: (data) => { + const decoded = BaseX$1.decode(data, "base58"); + return checkTheSum$1(decoded); + } +}; +var CHARSET$1 = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; +var GENERATOR$1 = [996825010, 642813549, 513874426, 1027748829, 705979059]; +var ENCODINGS$1 = [ + { version: 0, name: "bech32", const: 1 }, + { version: 1, name: "bech32m", const: 734539939 } +]; +function polymod$1(values) { + let chk = 1; + for (let p = 0; p < values.length; ++p) { + const top = chk >> 25; + chk = (chk & 33554431) << 5 ^ values[p]; + for (let i = 0; i < 5; ++i) { + if ((top >> i & 1) !== 0) { + chk ^= GENERATOR$1[i]; + } + } + } + return chk; +} +function hrpExpand$1(hrp) { + const ret = []; + let p; + for (p = 0; p < hrp.length; ++p) { + ret.push(hrp.charCodeAt(p) >> 5); + } + ret.push(0); + for (p = 0; p < hrp.length; ++p) { + ret.push(hrp.charCodeAt(p) & 31); + } + return ret; +} +function verifyChecksum$1(hrp, data, enc) { + const combined = hrpExpand$1(hrp).concat(data); + return polymod$1(combined) === enc.const; +} +function createChecksum$1(hrp, data, enc) { + const values = hrpExpand$1(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]); + const mod3 = polymod$1(values) ^ enc.const; + const ret = []; + for (let p = 0; p < 6; ++p) { + ret.push(mod3 >> 5 * (5 - p) & 31); + } + return ret; +} +function convertBits$1(data, fromBits, toBits, pad = true) { + const ret = []; + let acc = 0; + let bits = 0; + const maxVal = (1 << toBits) - 1; + const maxAcc = (1 << fromBits + toBits - 1) - 1; + for (const val of data) { + if (val < 0 || val >> fromBits > 0) { + throw new Error("Failed to perform base conversion. Invalid value: " + String(val)); + } + acc = (acc << fromBits | val) & maxAcc; + bits += fromBits; + while (bits >= toBits) { + bits -= toBits; + ret.push(acc >> bits & maxVal); + } + } + if (pad) { + if (bits > 0) { + ret.push(acc << toBits - bits & maxVal); + } + } else if (bits >= fromBits || (acc << toBits - bits & maxVal) > 0) { + throw new Error("Failed to perform base conversion. Invalid Size!"); + } + return ret; +} +function encode$6(hrp, data, enc) { + const combined = data.concat(createChecksum$1(hrp, data, enc)); + let ret = hrp + "1"; + for (let p = 0; p < combined.length; ++p) { + ret += CHARSET$1.charAt(combined[p]); + } + return ret; +} +function decode$6(bechstr) { + if (!checkBounds$1(bechstr)) { + throw new Error("Encoded string goes out of bounds!"); + } + bechstr = bechstr.toLowerCase(); + if (!checkSeparatorPos$1(bechstr)) { + throw new Error("Encoded string has invalid separator!"); + } + const data = []; + const pos = bechstr.lastIndexOf("1"); + const hrp = bechstr.substring(0, pos); + for (let p = pos + 1; p < bechstr.length; ++p) { + const d = CHARSET$1.indexOf(bechstr.charAt(p)); + if (d === -1) { + throw new Error("Character idx out of bounds: " + String(p)); + } + data.push(d); + } + const enc = ENCODINGS$1.find((e) => e.version === data[0]) ?? ENCODINGS$1[0]; + if (!verifyChecksum$1(hrp, data, enc)) { + throw new Error("Checksum verification failed!"); + } + return [hrp, data.slice(0, data.length - 6)]; +} +function checkBounds$1(bechstr) { + let p; + let char; + let hasLower = false; + let hasUpper = false; + for (p = 0; p < bechstr.length; ++p) { + char = bechstr.charCodeAt(p); + if (char < 33 || char > 126) { + return false; + } + if (char >= 97 && char <= 122) { + hasLower = true; + } + if (char >= 65 && char <= 90) { + hasUpper = true; + } + } + if (hasLower && hasUpper) + return false; + return true; +} +function checkSeparatorPos$1(bechstr) { + const pos = bechstr.lastIndexOf("1"); + return !(pos < 1 || pos + 7 > bechstr.length || bechstr.length > 90); +} +function b32encode$1(data, hrp = "bc", version = 0) { + const dat = [version, ...convertBits$1([...data], 8, 5)]; + const enc = ENCODINGS$1.find((e) => e.version === version) ?? ENCODINGS$1[0]; + const str = encode$6(hrp, dat, enc); + b32decode$1(str); + return str; +} +function b32decode$1(str) { + str = str.toLowerCase(); + const hrp = str.split("1", 1)[0]; + const [hrpgot, data] = decode$6(str); + const decoded = convertBits$1(data.slice(1), 5, 8, false); + const length = decoded.length; + switch (true) { + case hrp !== hrpgot: + throw new Error("Returned hrp string is invalid."); + case (decoded === null || length < 2 || length > 40): + throw new Error("Decoded string is invalid or out of spec."); + case data[0] > 16: + throw new Error("Returned version bit is out of range."); + default: + return Uint8Array.from(decoded); + } +} +function getVersion$2(str) { + str = str.toLowerCase(); + const [_, data] = decode$6(str); + return data[0]; +} +var Bech32$1 = { + encode: b32encode$1, + decode: b32decode$1, + version: getVersion$2 +}; +var BASE64_MAP$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var B64URL_MAP$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; +var ec$1$1 = new TextEncoder(); +function b64encode$1(input, urlSafe = false, padding = true) { + if (typeof input === "string") + input = ec$1$1.encode(input); + const map = urlSafe ? B64URL_MAP$1 : BASE64_MAP$1; + let output2 = ""; + let bits = 0; + let buffer2 = 0; + for (let i = 0; i < input.length; i++) { + buffer2 = buffer2 << 8 | input[i]; + bits += 8; + while (bits >= 6) { + bits -= 6; + output2 += map[buffer2 >> bits & 63]; + } + } + if (bits > 0) { + buffer2 <<= 6 - bits; + output2 += map[buffer2 & 63]; + while (bits < 6) { + output2 += padding ? "=" : ""; + bits += 2; + } + } + return output2; +} +function b64decode$1(input, urlSafe = false) { + const map = urlSafe || input.includes("-") || input.includes("_") ? B64URL_MAP$1.split("") : BASE64_MAP$1.split(""); + input = input.replace(/=+$/, ""); + const chars = input.split(""); + let bits = 0; + let value = 0; + const bytes2 = []; + for (let i = 0; i < chars.length; i++) { + const c = chars[i]; + const index = map.indexOf(c); + if (index === -1) { + throw new Error("Invalid character: " + c); + } + bits += 6; + value <<= 6; + value |= index; + if (bits >= 8) { + bits -= 8; + bytes2.push(value >>> bits & 255); + } + } + return new Uint8Array(bytes2); +} +var Base64$1 = { + encode: b64encode$1, + decode: b64decode$1 +}; +var B64URL$1 = { + encode: (data) => b64encode$1(data, true, false), + decode: (data) => b64decode$1(data, true) +}; +var _0n = BigInt(0); +var _255n$1 = BigInt(255); +var _256n$1 = BigInt(256); +function big_size$1(big) { + if (big <= 0xffn) + return 1; + if (big <= 0xffffn) + return 2; + if (big <= 0xffffffffn) + return 4; + if (big <= 0xffffffffffffffffn) + return 8; + if (big <= 0xffffffffffffffffffffffffffffffffn) + return 16; + if (big <= 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn) { + return 32; + } + throw new TypeError("Must specify a fixed buffer size for bigints greater than 32 bytes."); +} +function bigToBytes$1(big, size2, endian = "be") { + if (size2 === void 0) + size2 = big_size$1(big); + const use_le = endian === "le"; + const buffer2 = new ArrayBuffer(size2); + const dataView = new DataView(buffer2); + let offset = use_le ? 0 : size2 - 1; + while (big > _0n) { + const byte = big & _255n$1; + const num2 = Number(byte); + if (use_le) { + dataView.setUint8(offset++, num2); + } else { + dataView.setUint8(offset--, num2); + } + big = (big - byte) / _256n$1; + } + return new Uint8Array(buffer2); +} +function bytesToBig$1(bytes2) { + let num2 = BigInt(0); + for (let i = bytes2.length - 1; i >= 0; i--) { + num2 = num2 * _256n$1 + BigInt(bytes2[i]); + } + return BigInt(num2); +} +function binToBytes$1(binary) { + const bins = binary.split("").map(Number); + if (bins.length % 8 !== 0) { + throw new Error(`Binary array is invalid length: ${binary.length}`); + } + const bytes2 = new Uint8Array(bins.length / 8); + for (let i = 0, ct = 0; i < bins.length; i += 8, ct++) { + let byte = 0; + for (let j = 0; j < 8; j++) { + byte |= bins[i + j] << 7 - j; + } + bytes2[ct] = byte; + } + return bytes2; +} +function bytesToBin$1(bytes2) { + const bin = new Array(bytes2.length * 8); + let count = 0; + for (const num2 of bytes2) { + if (num2 > 255) { + throw new Error(`Invalid byte value: ${num2}. Byte values must be between 0 and 255.`); + } + for (let i = 7; i >= 0; i--, count++) { + bin[count] = num2 >> i & 1; + } + } + return bin.join(""); +} +function num_size$1(num2) { + if (num2 <= 255) + return 1; + if (num2 <= 65535) + return 2; + if (num2 <= 4294967295) + return 4; + throw new TypeError("Numbers larger than 4 bytes must specify a fixed size!"); +} +function numToBytes$1(num2, size2, endian = "be") { + if (size2 === void 0) + size2 = num_size$1(num2); + const use_le = endian === "le"; + const buffer2 = new ArrayBuffer(size2); + const dataView = new DataView(buffer2); + let offset = use_le ? 0 : size2 - 1; + while (num2 > 0) { + const byte = num2 & 255; + if (use_le) { + dataView.setUint8(offset++, num2); + } else { + dataView.setUint8(offset--, num2); + } + num2 = (num2 - byte) / 256; + } + return new Uint8Array(buffer2); +} +function bytesToNum$1(bytes2) { + let num2 = 0; + for (let i = bytes2.length - 1; i >= 0; i--) { + num2 = num2 * 256 + bytes2[i]; + is_safe_num$1(num2); + } + return num2; +} +var ec$3 = new TextEncoder(); +var dc$1 = new TextDecoder(); +function strToBytes$1(str) { + return ec$3.encode(str); +} +function bytesToStr$1(bytes2) { + return dc$1.decode(bytes2); +} +function hex_size$1(hexstr2, size2) { + is_hex$1(hexstr2); + const len = hexstr2.length / 2; + if (size2 === void 0) + size2 = len; + if (len > size2) { + throw new TypeError(`Hex string is larger than array size: ${len} > ${size2}`); + } + return size2; +} +function hexToBytes$2(hexstr2, size2, endian = "le") { + size2 = hex_size$1(hexstr2, size2); + const use_le = endian === "le"; + const buffer2 = new ArrayBuffer(size2); + const dataView = new DataView(buffer2); + let offset = use_le ? 0 : size2 - 1; + for (let i = 0; i < hexstr2.length; i += 2) { + const char = hexstr2.substring(i, i + 2); + const num2 = parseInt(char, 16); + if (use_le) { + dataView.setUint8(offset++, num2); + } else { + dataView.setUint8(offset--, num2); + } + } + return new Uint8Array(buffer2); +} +function bytesToHex$2(bytes2) { + let chars = ""; + for (let i = 0; i < bytes2.length; i++) { + chars += bytes2[i].toString(16).padStart(2, "0"); + } + return chars; +} +function jsonToBytes$1(obj) { + const str = JSON.stringify(obj, (_, v) => { + return typeof v === "bigint" ? `${v}n` : v; + }); + return strToBytes$1(str); +} +function buffer$1(data, size2, endian) { + if (data instanceof ArrayBuffer) { + return new Uint8Array(data); + } + if (data instanceof Uint8Array) { + return set_buffer$1(data, size2, endian); + } + if (typeof data === "string") { + return hexToBytes$2(data, size2, endian); + } + if (typeof data === "bigint") { + return bigToBytes$1(data, size2, endian); + } + if (typeof data === "number") { + return numToBytes$1(data, size2, endian); + } + if (typeof data === "boolean") { + return Uint8Array.of(data ? 1 : 0); + } + throw TypeError("Unsupported format:" + String(typeof data)); +} +var Buff$1 = class Buff extends Uint8Array { + static { + this.num = numToBuff$1; + } + static { + this.big = bigToBuff$1; + } + static { + this.bin = binToBuff$1; + } + static { + this.raw = rawToBuff$1; + } + static { + this.str = strToBuff$1; + } + static { + this.hex = hexToBuff$1; + } + static { + this.bytes = bytesToBuff$1; + } + static { + this.json = jsonToBuff$1; + } + static { + this.base64 = base64ToBuff$1; + } + static { + this.b64url = b64urlToBuff$1; + } + static { + this.bech32 = bech32ToBuff$1; + } + static { + this.b58chk = b58chkToBuff$1; + } + static { + this.encode = strToBytes$1; + } + static { + this.decode = bytesToStr$1; + } + static random(size2 = 32) { + const rand = random$2(size2); + return new Buff(rand, size2); + } + constructor(data, size2, endian) { + const buffer$1$1 = buffer$1(data, size2, endian); + super(buffer$1$1); + } + get arr() { + return [...this]; + } + get num() { + return this.toNum(); + } + get big() { + return this.toBig(); + } + get str() { + return this.toStr(); + } + get hex() { + return this.toHex(); + } + get raw() { + return new Uint8Array(this); + } + get bin() { + return this.toBin(); + } + get b58chk() { + return this.tob58chk(); + } + get base64() { + return this.toBase64(); + } + get b64url() { + return this.toB64url(); + } + get digest() { + return this.toHash(); + } + get id() { + return this.toHash().hex; + } + get stream() { + return new Stream$1(this); + } + toNum(endian = "be") { + const bytes2 = endian === "be" ? this.reverse() : this; + return bytesToNum$1(bytes2); + } + toBin() { + return bytesToBin$1(this); + } + toBig(endian = "be") { + const bytes2 = endian === "be" ? this.reverse() : this; + return bytesToBig$1(bytes2); + } + toHash() { + const digest = sha256$4(this); + return new Buff(digest); + } + toJson() { + const str = bytesToStr$1(this); + return JSON.parse(str); + } + toBech32(hrp, version = 0) { + return Bech32$1.encode(this, hrp, version); + } + toStr() { + return bytesToStr$1(this); + } + toHex() { + return bytesToHex$2(this); + } + toBytes() { + return new Uint8Array(this); + } + tob58chk() { + return Base58C$1.encode(this); + } + toBase64() { + return Base64$1.encode(this); + } + toB64url() { + return B64URL$1.encode(this); + } + prepend(data) { + return Buff.join([Buff.bytes(data), this]); + } + append(data) { + return Buff.join([this, Buff.bytes(data)]); + } + slice(start, end) { + const arr = new Uint8Array(this).slice(start, end); + return new Buff(arr); + } + subarray(begin, end) { + const arr = new Uint8Array(this).subarray(begin, end); + return new Buff(arr); + } + reverse() { + const arr = new Uint8Array(this).reverse(); + return new Buff(arr); + } + write(bytes2, offset) { + const b = Buff.bytes(bytes2); + this.set(b, offset); + } + prefixSize(endian) { + const size2 = Buff.varInt(this.length, endian); + return Buff.join([size2, this]); + } + static from(data) { + return new Buff(Uint8Array.from(data)); + } + static of(...args) { + return new Buff(Uint8Array.of(...args)); + } + static join(arr) { + const bytes2 = arr.map((e) => Buff.bytes(e)); + const joined = join_array$1(bytes2); + return new Buff(joined); + } + static varInt(num2, endian) { + if (num2 < 253) { + return Buff.num(num2, 1); + } else if (num2 < 65536) { + return Buff.of(253, ...Buff.num(num2, 2, endian)); + } else if (num2 < 4294967296) { + return Buff.of(254, ...Buff.num(num2, 4, endian)); + } else if (BigInt(num2) < 0x10000000000000000n) { + return Buff.of(255, ...Buff.num(num2, 8, endian)); + } else { + throw new Error(`Value is too large: ${num2}`); + } + } +}; +function numToBuff$1(number2, size2, endian) { + return new Buff$1(number2, size2, endian); +} +function binToBuff$1(data, size2, endian) { + return new Buff$1(binToBytes$1(data), size2, endian); +} +function bigToBuff$1(bigint, size2, endian) { + return new Buff$1(bigint, size2, endian); +} +function rawToBuff$1(data, size2, endian) { + return new Buff$1(data, size2, endian); +} +function strToBuff$1(data, size2, endian) { + return new Buff$1(strToBytes$1(data), size2, endian); +} +function hexToBuff$1(data, size2, endian) { + return new Buff$1(data, size2, endian); +} +function bytesToBuff$1(data, size2, endian) { + return new Buff$1(data, size2, endian); +} +function jsonToBuff$1(data) { + return new Buff$1(jsonToBytes$1(data)); +} +function base64ToBuff$1(data) { + return new Buff$1(Base64$1.decode(data)); +} +function b64urlToBuff$1(data) { + return new Buff$1(B64URL$1.decode(data)); +} +function bech32ToBuff$1(data) { + return new Buff$1(Bech32$1.decode(data)); +} +function b58chkToBuff$1(data) { + return new Buff$1(Base58C$1.decode(data)); +} +var Stream$1 = class Stream { + constructor(data) { + this.data = Buff$1.bytes(data); + this.size = this.data.length; + } + peek(size2) { + if (size2 > this.size) { + throw new Error(`Size greater than stream: ${size2} > ${this.size}`); + } + return new Buff$1(this.data.slice(0, size2)); + } + read(size2) { + size2 = size2 ?? this.readSize(); + const chunk = this.peek(size2); + this.data = this.data.slice(size2); + this.size = this.data.length; + return chunk; + } + readSize(endian) { + const num2 = this.read(1).num; + switch (true) { + case (num2 >= 0 && num2 < 253): + return num2; + case num2 === 253: + return this.read(2).toNum(endian); + case num2 === 254: + return this.read(4).toNum(endian); + case num2 === 255: + return this.read(8).toNum(endian); + default: + throw new Error(`Varint is out of range: ${num2}`); + } + } +}; +function checkSize(input, size2) { + const bytes2 = Buff$1.bytes(input); + if (bytes2.length !== size2) { + throw new Error(`Invalid input size: ${bytes2.hex} !== ${size2}`); + } +} +function safeThrow(errorMsg, shouldThrow) { + if (shouldThrow) { + throw new Error(errorMsg); + } else { + return false; + } +} +function hashTag(tag, ...data) { + const htag = Buff$1.str(tag).digest.raw; + const buff = data.map((e) => Buff$1.bytes(e)); + return Buff$1.join([htag, htag, Buff$1.join(buff)]).digest; +} +var OPCODE_MAP = { + OP_0: 0, + OP_PUSHDATA1: 76, + OP_PUSHDATA2: 77, + OP_PUSHDATA4: 78, + OP_1NEGATE: 79, + OP_SUCCESS80: 80, + OP_1: 81, + OP_2: 82, + OP_3: 83, + OP_4: 84, + OP_5: 85, + OP_6: 86, + OP_7: 87, + OP_8: 88, + OP_9: 89, + OP_10: 90, + OP_11: 91, + OP_12: 92, + OP_13: 93, + OP_14: 94, + OP_15: 95, + OP_16: 96, + OP_NOP: 97, + OP_SUCCESS98: 98, + OP_IF: 99, + OP_NOTIF: 100, + OP_ELSE: 103, + OP_ENDIF: 104, + OP_VERIFY: 105, + OP_RETURN: 106, + OP_TOALTSTACK: 107, + OP_FROMALTSTACK: 108, + OP_2DROP: 109, + OP_2DUP: 110, + OP_3DUP: 111, + OP_2OVER: 112, + OP_2ROT: 113, + OP_2SWAP: 114, + OP_IFDUP: 115, + OP_DEPTH: 116, + OP_DROP: 117, + OP_DUP: 118, + OP_NIP: 119, + OP_OVER: 120, + OP_PICK: 121, + OP_ROLL: 122, + OP_ROT: 123, + OP_SWAP: 124, + OP_TUCK: 125, + OP_SUCCESS126: 126, + OP_SUCCESS127: 127, + OP_SUCCESS128: 128, + OP_SUCCESS129: 129, + OP_SIZE: 130, + OP_SUCCESS131: 131, + OP_SUCCESS132: 132, + OP_SUCCESS133: 133, + OP_SUCCESS134: 134, + OP_EQUAL: 135, + OP_EQUALVERIFY: 136, + OP_SUCCESS137: 137, + OP_SUCCESS138: 138, + OP_1ADD: 139, + OP_1SUB: 140, + OP_SUCCESS141: 141, + OP_SUCCESS142: 142, + OP_NEGATE: 143, + OP_ABS: 144, + OP_NOT: 145, + OP_0NOTEQUAL: 146, + OP_ADD: 147, + OP_SUB: 148, + OP_SUCCESS149: 149, + OP_SUCCESS150: 150, + OP_SUCCESS151: 151, + OP_SUCCESS152: 152, + OP_SUCCESS153: 153, + OP_BOOLAND: 154, + OP_BOOLOR: 155, + OP_NUMEQUAL: 156, + OP_NUMEQUALVERIFY: 157, + OP_NUMNOTEQUAL: 158, + OP_LESSTHAN: 159, + OP_GREATERTHAN: 160, + OP_LESSTHANOREQUAL: 161, + OP_GREATERTHANOREQUAL: 162, + OP_MIN: 163, + OP_MAX: 164, + OP_WITHIN: 165, + OP_RIPEMD160: 166, + OP_SHA1: 167, + OP_SHA256: 168, + OP_HASH160: 169, + OP_HASH256: 170, + OP_CODESEPARATOR: 171, + OP_CHECKSIG: 172, + OP_CHECKSIGVERIFY: 173, + OP_CHECKMULTISIG: 174, + OP_CHECKMULTISIGVERIFY: 175, + OP_NOP1: 176, + OP_CHECKLOCKTIMEVERIFY: 177, + OP_CHECKSEQUENCEVERIFY: 178, + OP_NOP4: 179, + OP_NOP5: 180, + OP_NOP6: 181, + OP_NOP7: 182, + OP_NOP8: 183, + OP_NOP9: 184, + OP_NOP10: 185, + OP_CHECKSIGADD: 186, + OP_SUCCESS187: 187, + OP_SUCCESS188: 188, + OP_SUCCESS189: 189, + OP_SUCCESS190: 190, + OP_SUCCESS191: 191, + OP_SUCCESS192: 192, + OP_SUCCESS193: 193, + OP_SUCCESS194: 194, + OP_SUCCESS195: 195, + OP_SUCCESS196: 196, + OP_SUCCESS197: 197, + OP_SUCCESS198: 198, + OP_SUCCESS199: 199, + OP_SUCCESS200: 200, + OP_SUCCESS201: 201, + OP_SUCCESS202: 202, + OP_SUCCESS203: 203, + OP_SUCCESS204: 204, + OP_SUCCESS205: 205, + OP_SUCCESS206: 206, + OP_SUCCESS207: 207, + OP_SUCCESS208: 208, + OP_SUCCESS209: 209, + OP_SUCCESS210: 210, + OP_SUCCESS211: 211, + OP_SUCCESS212: 212, + OP_SUCCESS213: 213, + OP_SUCCESS214: 214, + OP_SUCCESS215: 215, + OP_SUCCESS216: 216, + OP_SUCCESS217: 217, + OP_SUCCESS218: 218, + OP_SUCCESS219: 219, + OP_SUCCESS220: 220, + OP_SUCCESS221: 221, + OP_SUCCESS222: 222, + OP_SUCCESS223: 223, + OP_SUCCESS224: 224, + OP_SUCCESS225: 225, + OP_SUCCESS226: 226, + OP_SUCCESS227: 227, + OP_SUCCESS228: 228, + OP_SUCCESS229: 229, + OP_SUCCESS230: 230, + OP_SUCCESS231: 231, + OP_SUCCESS232: 232, + OP_SUCCESS233: 233, + OP_SUCCESS234: 234, + OP_SUCCESS235: 235, + OP_SUCCESS236: 236, + OP_SUCCESS237: 237, + OP_SUCCESS238: 238, + OP_SUCCESS239: 239, + OP_SUCCESS240: 240, + OP_SUCCESS241: 241, + OP_SUCCESS242: 242, + OP_SUCCESS243: 243, + OP_SUCCESS244: 244, + OP_SUCCESS245: 245, + OP_SUCCESS246: 246, + OP_SUCCESS247: 247, + OP_SUCCESS248: 248, + OP_SUCCESS249: 249, + OP_SUCCESS250: 250, + OP_SUCCESS251: 251, + OP_SUCCESS252: 252, + OP_SUCCESS253: 253, + OP_SUCCESS254: 254 +}; +function getOpLabel(num2) { + if (num2 > 186 && num2 < 255) { + return "OP_SUCCESS" + String(num2); + } + for (const [k, v] of Object.entries(OPCODE_MAP)) { + if (v === num2) + return k; + } + throw new Error("OPCODE not found:" + String(num2)); +} +function getOpCode(string) { + for (const [k, v] of Object.entries(OPCODE_MAP)) { + if (k === string) + return Number(v); + } + throw new Error("OPCODE not found:" + string); +} +function getWordType(word) { + switch (true) { + case word === 0: + return "opcode"; + case (word >= 1 && word <= 75): + return "varint"; + case word === 76: + return "pushdata1"; + case word === 77: + return "pushdata2"; + case word === 78: + return "pushdata4"; + case word <= 254: + return "opcode"; + default: + throw new Error(`Invalid word range: ${word}`); + } +} +function isValidWord(word) { + const MIN_RANGE = 75; + const MAX_RANGE = 254; + const DISABLED_OPCODES = []; + switch (true) { + case typeof word !== "number": + return false; + case word === 0: + return true; + case DISABLED_OPCODES.includes(word): + return false; + case (MIN_RANGE < word && word < MAX_RANGE): + return true; + default: + return false; + } +} +function isHex(value) { + return typeof value === "string" && value.length % 2 === 0 && /[0-9a-fA-F]/.test(value); +} +function isBytes$1(value) { + return isHex(value) || value instanceof Uint8Array; +} +var MAX_WORD_SIZE = 520; +function encodeScript(script2 = [], varint = true) { + let buff = Buff$1.num(0); + if (Array.isArray(script2)) { + buff = Buff$1.raw(encodeWords(script2)); + } + if (isHex(script2)) { + buff = Buff$1.hex(script2); + } + if (script2 instanceof Uint8Array) { + buff = Buff$1.raw(script2); + } + if (varint) { + buff = buff.prefixSize("le"); + } + return buff; +} +function encodeWords(wordArray) { + const words = []; + for (const word of wordArray) { + words.push(encodeWord(word)); + } + return words.length > 0 ? Buff$1.join(words) : new Uint8Array(); +} +function encodeWord(word) { + let buff = new Uint8Array(); + if (typeof word === "string") { + if (word.startsWith("OP_")) { + return Buff$1.num(getOpCode(word), 1); + } else if (isHex(word)) { + buff = Buff$1.hex(word); + } else { + buff = Buff$1.str(word); + } + } else { + buff = Buff$1.bytes(word); + } + if (buff.length === 1) { + if (buff[0] !== 0 && buff[0] <= 16) { + buff[0] += 80; + return buff; + } else if (buff[0] > 128 && buff[0] <= 255) { + buff = new Uint8Array([buff[0], 0]); + } + return Buff$1.join([encodeSize(buff.length), buff]); + } else if (buff.length > MAX_WORD_SIZE) { + const words = splitWord(buff); + return encodeWords(words); + } else { + return Buff$1.join([encodeSize(buff.length), buff]); + } +} +function encodeSize(size2) { + const OP_DATAPUSH1 = Buff$1.num(76, 1); + const OP_DATAPUSH2 = Buff$1.num(77, 1); + switch (true) { + case size2 <= 75: + return Buff$1.num(size2); + case (size2 > 75 && size2 < 256): + return Buff$1.join([OP_DATAPUSH1, Buff$1.num(size2, 1, "le")]); + case (size2 >= 256 && size2 <= MAX_WORD_SIZE): + return Buff$1.join([OP_DATAPUSH2, Buff$1.num(size2, 2, "le")]); + default: + throw new Error("Invalid word size:" + size2.toString()); + } +} +function splitWord(word) { + const words = []; + const buff = new Stream$1(word); + while (buff.size > MAX_WORD_SIZE) { + words.push(buff.read(MAX_WORD_SIZE)); + } + words.push(buff.read(buff.size)); + return words; +} +function decodeScript(script2, varint = false) { + let buff = Buff$1.bytes(script2); + if (varint) { + const stream = buff.stream; + const len = stream.readSize("le"); + buff = buff.slice(1); + if (buff.length !== len) { + throw new Error(`Varint does not match stream size: ${len} !== ${buff.length}`); + } + } + return decodeWords(buff); +} +function decodeWords(words) { + const stream = new Stream$1(words); + const stack = []; + const stackSize = stream.size; + let word; + let wordType; + let wordSize; + let count = 0; + while (count < stackSize) { + word = stream.read(1).num; + wordType = getWordType(word); + count++; + switch (wordType) { + case "varint": + stack.push(stream.read(word).hex); + count += word; + break; + case "pushdata1": + wordSize = stream.read(1).reverse().num; + stack.push(stream.read(wordSize).hex); + count += wordSize + 1; + break; + case "pushdata2": + wordSize = stream.read(2).reverse().num; + stack.push(stream.read(wordSize).hex); + count += wordSize + 2; + break; + case "pushdata4": + wordSize = stream.read(4).reverse().num; + stack.push(stream.read(wordSize).hex); + count += wordSize + 4; + break; + case "opcode": + if (!isValidWord(word)) { + throw new Error(`Invalid OPCODE: ${word}`); + } + stack.push(getOpLabel(word)); + break; + default: + throw new Error(`Word type undefined: ${word}`); + } + } + return stack; +} +function toAsm(script2, varint) { + if (Array.isArray(script2)) { + script2 = encodeScript(script2, varint); + } + if (script2 instanceof Uint8Array || isHex(script2)) { + return decodeScript(script2, varint); + } + throw new Error("Invalid format: " + String(typeof script2)); +} +function toBytes$4(script2, varint) { + if (script2 instanceof Uint8Array || isHex(script2)) { + script2 = decodeScript(script2, varint); + } + if (Array.isArray(script2)) { + return encodeScript(script2, varint); + } + throw new Error("Invalid format: " + String(typeof script2)); +} +function toParam(script2) { + if (!Array.isArray(script2)) { + return Buff$1.bytes(script2); + } + throw new Error("Invalid format: " + String(typeof script2)); +} +var FmtScript = { + toAsm, + toBytes: toBytes$4, + toParam +}; +var Script = { + encode: encodeScript, + decode: decodeScript, + fmt: FmtScript +}; +function number$2(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +function bool$2(b) { + if (typeof b !== "boolean") + throw new Error(`Expected boolean, not ${b}`); +} +function bytes$2(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new TypeError("Expected Uint8Array"); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +function hash$3(hash2) { + if (typeof hash2 !== "function" || typeof hash2.create !== "function") + throw new Error("Hash should be wrapped by utils.wrapConstructor"); + number$2(hash2.outputLen); + number$2(hash2.blockLen); +} +function exists$2(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function output$2(out, instance) { + bytes$2(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +var assert$3 = { + number: number$2, + bool: bool$2, + bytes: bytes$2, + hash: hash$3, + exists: exists$2, + output: output$2 +}; +var assert$4 = assert$3; +var crypto$1 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; +var createView$2 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +var rotr$2 = (word, shift) => word << 32 - shift | word >>> shift; +var isLE$2 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; +if (!isLE$2) + throw new Error("Non little-endian hardware is not supported"); +Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0")); +function utf8ToBytes$3(str) { + if (typeof str !== "string") { + throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`); + } + return new TextEncoder().encode(str); +} +function toBytes$2(data) { + if (typeof data === "string") + data = utf8ToBytes$3(data); + if (!(data instanceof Uint8Array)) + throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`); + return data; +} +function concatBytes$1(...arrays) { + if (!arrays.every((a) => a instanceof Uint8Array)) + throw new Error("Uint8Array list expected"); + if (arrays.length === 1) + return arrays[0]; + const length = arrays.reduce((a, arr) => a + arr.length, 0); + const result = new Uint8Array(length); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const arr = arrays[i]; + result.set(arr, pad); + pad += arr.length; + } + return result; +} +var Hash$2 = class Hash2 { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +}; +function wrapConstructor$2(hashConstructor) { + const hashC = (message) => hashConstructor().update(toBytes$2(message)).digest(); + const tmp = hashConstructor(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashConstructor(); + return hashC; +} +function randomBytes(bytesLength = 32) { + if (crypto$1 && typeof crypto$1.getRandomValues === "function") { + return crypto$1.getRandomValues(new Uint8Array(bytesLength)); + } + throw new Error("crypto.getRandomValues must be defined"); +} +function setBigUint64$2(view, byteOffset, value, isLE2) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE2); + const _32n2 = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n2 & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE2 ? 4 : 0; + const l = isLE2 ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE2); + view.setUint32(byteOffset + l, wl, isLE2); +} +var SHA2$2 = class SHA22 extends Hash$2 { + constructor(blockLen, outputLen, padOffset, isLE2) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE2; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView$2(this.buffer); + } + update(data) { + assert$4.exists(this); + const { view, buffer: buffer2, blockLen } = this; + data = toBytes$2(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView$2(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer2.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) { + assert$4.exists(this); + assert$4.output(out, this); + this.finished = true; + const { buffer: buffer2, view, blockLen, isLE: isLE2 } = this; + let { pos } = this; + buffer2[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) + buffer2[i] = 0; + setBigUint64$2(view, blockLen - 8, BigInt(this.length * 8), isLE2); + this.process(view, 0); + const oview = createView$2(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE2); + } + digest() { + const { buffer: buffer2, outputLen } = this; + this.digestInto(buffer2); + const res = buffer2.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer2); + return to; + } +}; +var Chi$2 = (a, b, c) => a & b ^ ~a & c; +var Maj$2 = (a, b, c) => a & b ^ a & c ^ b & c; +var SHA256_K$2 = new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +var IV$2 = new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); +var SHA256_W$2 = new Uint32Array(64); +var SHA256$2 = class SHA2562 extends SHA2$2 { + constructor() { + super(64, 32, 8, false); + this.A = IV$2[0] | 0; + this.B = IV$2[1] | 0; + this.C = IV$2[2] | 0; + this.D = IV$2[3] | 0; + this.E = IV$2[4] | 0; + this.F = IV$2[5] | 0; + this.G = IV$2[6] | 0; + this.H = IV$2[7] | 0; + } + get() { + const { A, B, C, D, E, F, G: G2, H } = this; + return [A, B, C, D, E, F, G2, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G2, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G2 | 0; + this.H = H | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W$2[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W$2[i - 15]; + const W2 = SHA256_W$2[i - 2]; + const s0 = rotr$2(W15, 7) ^ rotr$2(W15, 18) ^ W15 >>> 3; + const s1 = rotr$2(W2, 17) ^ rotr$2(W2, 19) ^ W2 >>> 10; + SHA256_W$2[i] = s1 + SHA256_W$2[i - 7] + s0 + SHA256_W$2[i - 16] | 0; + } + let { A, B, C, D, E, F, G: G2, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr$2(E, 6) ^ rotr$2(E, 11) ^ rotr$2(E, 25); + const T1 = H + sigma1 + Chi$2(E, F, G2) + SHA256_K$2[i] + SHA256_W$2[i] | 0; + const sigma0 = rotr$2(A, 2) ^ rotr$2(A, 13) ^ rotr$2(A, 22); + const T2 = sigma0 + Maj$2(A, B, C) | 0; + H = G2; + G2 = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G2 = G2 + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G2, H); + } + roundClean() { + SHA256_W$2.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +}; +var SHA224$2 = class SHA2242 extends SHA256$2 { + constructor() { + super(); + this.A = 3238371032 | 0; + this.B = 914150663 | 0; + this.C = 812702999 | 0; + this.D = 4144912697 | 0; + this.E = 4290775857 | 0; + this.F = 1750603025 | 0; + this.G = 1694076839 | 0; + this.H = 3204075428 | 0; + this.outputLen = 28; + } +}; +var sha256$3 = wrapConstructor$2(() => new SHA256$2()); +wrapConstructor$2(() => new SHA224$2()); +var _0n$8 = BigInt(0); +var _1n$5 = BigInt(1); +var _2n$4 = BigInt(2); +var u8a$1 = (a) => a instanceof Uint8Array; +var hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0")); +function bytesToHex$1(bytes2) { + if (!u8a$1(bytes2)) + throw new Error("Uint8Array expected"); + let hex = ""; + for (let i = 0; i < bytes2.length; i++) { + hex += hexes[bytes2[i]]; + } + return hex; +} +function numberToHexUnpadded(num2) { + const hex = num2.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +function hexToNumber(hex) { + if (typeof hex !== "string") + throw new Error("hex string expected, got " + typeof hex); + return BigInt(hex === "" ? "0" : `0x${hex}`); +} +function hexToBytes$1(hex) { + if (typeof hex !== "string") + throw new Error("hex string expected, got " + typeof hex); + if (hex.length % 2) + throw new Error("hex string is invalid: unpadded " + hex.length); + const array = new Uint8Array(hex.length / 2); + for (let i = 0; i < array.length; i++) { + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(byte) || byte < 0) + throw new Error("invalid byte sequence"); + array[i] = byte; + } + return array; +} +function bytesToNumberBE(bytes2) { + return hexToNumber(bytesToHex$1(bytes2)); +} +function bytesToNumberLE(bytes2) { + if (!u8a$1(bytes2)) + throw new Error("Uint8Array expected"); + return hexToNumber(bytesToHex$1(Uint8Array.from(bytes2).reverse())); +} +var numberToBytesBE = (n, len) => hexToBytes$1(n.toString(16).padStart(len * 2, "0")); +var numberToBytesLE = (n, len) => numberToBytesBE(n, len).reverse(); +var numberToVarBytesBE = (n) => hexToBytes$1(numberToHexUnpadded(n)); +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === "string") { + try { + res = hexToBytes$1(hex); + } catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); + } + } else if (u8a$1(hex)) { + res = Uint8Array.from(hex); + } else { + throw new Error(`${title} must be hex string or Uint8Array`); + } + const len = res.length; + if (typeof expectedLength === "number" && len !== expectedLength) + throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; +} +function concatBytes(...arrs) { + const r = new Uint8Array(arrs.reduce((sum, a) => sum + a.length, 0)); + let pad = 0; + arrs.forEach((a) => { + if (!u8a$1(a)) + throw new Error("Uint8Array expected"); + r.set(a, pad); + pad += a.length; + }); + return r; +} +function equalBytes(b1, b2) { + if (b1.length !== b2.length) + return false; + for (let i = 0; i < b1.length; i++) + if (b1[i] !== b2[i]) + return false; + return true; +} +function utf8ToBytes$2(str) { + if (typeof str !== "string") { + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + } + return new TextEncoder().encode(str); +} +function bitLen(n) { + let len; + for (len = 0; n > 0n; n >>= _1n$5, len += 1) + ; + return len; +} +var bitGet = (n, pos) => n >> BigInt(pos) & 1n; +var bitSet = (n, pos, value) => n | (value ? _1n$5 : _0n$8) << BigInt(pos); +var bitMask = (n) => (_2n$4 << BigInt(n - 1)) - _1n$5; +var u8n = (data) => new Uint8Array(data); +var u8fr = (arr) => Uint8Array.from(arr); +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== "number" || hashLen < 2) + throw new Error("hashLen must be a number"); + if (typeof qByteLen !== "number" || qByteLen < 2) + throw new Error("qByteLen must be a number"); + if (typeof hmacFn !== "function") + throw new Error("hmacFn must be a function"); + let v = u8n(hashLen); + let k = u8n(hashLen); + let i = 0; + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); + const reseed = (seed = u8n()) => { + k = h(u8fr([0]), seed); + v = h(); + if (seed.length === 0) + return; + k = h(u8fr([1]), seed); + v = h(); + }; + const gen = () => { + if (i++ >= 1e3) + throw new Error("drbg: tried 1000 values"); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); + let res = void 0; + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +var validatorFns = { + bigint: (val) => typeof val === "bigint", + function: (val) => typeof val === "function", + boolean: (val) => typeof val === "boolean", + string: (val) => typeof val === "string", + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) +}; +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== "function") + throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === void 0) + return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +var ut = /* @__PURE__ */ Object.freeze({ + __proto__: null, + bitGet, + bitLen, + bitMask, + bitSet, + bytesToHex: bytesToHex$1, + bytesToNumberBE, + bytesToNumberLE, + concatBytes, + createHmacDrbg, + ensureBytes, + equalBytes, + hexToBytes: hexToBytes$1, + hexToNumber, + numberToBytesBE, + numberToBytesLE, + numberToHexUnpadded, + numberToVarBytesBE, + utf8ToBytes: utf8ToBytes$2, + validateObject +}); +var _0n$7 = BigInt(0); +var _1n$4 = BigInt(1); +var _2n$3 = BigInt(2); +var _3n$2 = BigInt(3); +var _4n$2 = BigInt(4); +var _5n = BigInt(5); +var _8n = BigInt(8); +BigInt(9); +BigInt(16); +function mod(a, b) { + const result = a % b; + return result >= _0n$7 ? result : b + result; +} +function pow(num2, power, modulo) { + if (modulo <= _0n$7 || power < _0n$7) + throw new Error("Expected power/modulo > 0"); + if (modulo === _1n$4) + return _0n$7; + let res = _1n$4; + while (power > _0n$7) { + if (power & _1n$4) + res = res * num2 % modulo; + num2 = num2 * num2 % modulo; + power >>= _1n$4; + } + return res; +} +function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n$7) { + res *= res; + res %= modulo; + } + return res; +} +function invert(number2, modulo) { + if (number2 === _0n$7 || modulo <= _0n$7) { + throw new Error(`invert: expected positive integers, got n=${number2} mod=${modulo}`); + } + let a = mod(number2, modulo); + let b = modulo; + let x = _0n$7, u = _1n$4; + while (a !== _0n$7) { + const q = b / a; + const r = b % a; + const m = x - u * q; + b = a, a = r, x = u, u = m; + } + const gcd = b; + if (gcd !== _1n$4) + throw new Error("invert: does not exist"); + return mod(x, modulo); +} +function tonelliShanks(P2) { + const legendreC = (P2 - _1n$4) / _2n$3; + let Q, S, Z; + for (Q = P2 - _1n$4, S = 0; Q % _2n$3 === _0n$7; Q /= _2n$3, S++) + ; + for (Z = _2n$3; Z < P2 && pow(Z, legendreC, P2) !== P2 - _1n$4; Z++) + ; + if (S === 1) { + const p1div4 = (P2 + _1n$4) / _4n$2; + return function tonelliFast(Fp2, n) { + const root = Fp2.pow(n, p1div4); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + const Q1div2 = (Q + _1n$4) / _2n$3; + return function tonelliSlow(Fp2, n) { + if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE)) + throw new Error("Cannot find square root"); + let r = S; + let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q); + let x = Fp2.pow(n, Q1div2); + let b = Fp2.pow(n, Q); + while (!Fp2.eql(b, Fp2.ONE)) { + if (Fp2.eql(b, Fp2.ZERO)) + return Fp2.ZERO; + let m = 1; + for (let t2 = Fp2.sqr(b); m < r; m++) { + if (Fp2.eql(t2, Fp2.ONE)) + break; + t2 = Fp2.sqr(t2); + } + const ge2 = Fp2.pow(g, _1n$4 << BigInt(r - m - 1)); + g = Fp2.sqr(ge2); + x = Fp2.mul(x, ge2); + b = Fp2.mul(b, g); + r = m; + } + return x; + }; +} +function FpSqrt(P2) { + if (P2 % _4n$2 === _3n$2) { + const p1div4 = (P2 + _1n$4) / _4n$2; + return function sqrt3mod42(Fp2, n) { + const root = Fp2.pow(n, p1div4); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + if (P2 % _8n === _5n) { + const c1 = (P2 - _5n) / _8n; + return function sqrt5mod82(Fp2, n) { + const n2 = Fp2.mul(n, _2n$3); + const v = Fp2.pow(n2, c1); + const nv = Fp2.mul(n, v); + const i = Fp2.mul(Fp2.mul(nv, _2n$3), v); + const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; + }; + } + return tonelliShanks(P2); +} +var FIELD_FIELDS = [ + "create", + "isValid", + "is0", + "neg", + "inv", + "sqrt", + "sqr", + "eql", + "add", + "sub", + "mul", + "pow", + "div", + "addN", + "subN", + "mulN", + "sqrN" +]; +function validateField(field) { + const initial = { + ORDER: "bigint", + MASK: "bigint", + BYTES: "isSafeInteger", + BITS: "isSafeInteger" + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = "function"; + return map; + }, initial); + return validateObject(field, opts); +} +function FpPow(f2, num2, power) { + if (power < _0n$7) + throw new Error("Expected power > 0"); + if (power === _0n$7) + return f2.ONE; + if (power === _1n$4) + return num2; + let p = f2.ONE; + let d = num2; + while (power > _0n$7) { + if (power & _1n$4) + p = f2.mul(p, d); + d = f2.sqr(d); + power >>= _1n$4; + } + return p; +} +function FpInvertBatch(f2, nums) { + const tmp = new Array(nums.length); + const lastMultiplied = nums.reduce((acc, num2, i) => { + if (f2.is0(num2)) + return acc; + tmp[i] = acc; + return f2.mul(acc, num2); + }, f2.ONE); + const inverted = f2.inv(lastMultiplied); + nums.reduceRight((acc, num2, i) => { + if (f2.is0(num2)) + return acc; + tmp[i] = f2.mul(acc, tmp[i]); + return f2.mul(acc, num2); + }, inverted); + return tmp; +} +function nLength(n, nBitLength) { + const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +function Field$1(ORDER, bitLen3, isLE2 = false, redef = {}) { + if (ORDER <= _0n$7) + throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen3); + if (BYTES > 2048) + throw new Error("Field lengths over 2048 bytes are not supported"); + const sqrtP = FpSqrt(ORDER); + const f2 = Object.freeze({ + ORDER, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n$7, + ONE: _1n$4, + create: (num2) => mod(num2, ORDER), + isValid: (num2) => { + if (typeof num2 !== "bigint") + throw new Error(`Invalid field element: expected bigint, got ${typeof num2}`); + return _0n$7 <= num2 && num2 < ORDER; + }, + is0: (num2) => num2 === _0n$7, + isOdd: (num2) => (num2 & _1n$4) === _1n$4, + neg: (num2) => mod(-num2, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num2) => mod(num2 * num2, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num2, power) => FpPow(f2, num2, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num2) => num2 * num2, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num2) => invert(num2, ORDER), + sqrt: redef.sqrt || ((n) => sqrtP(f2, n)), + invertBatch: (lst) => FpInvertBatch(f2, lst), + // TODO: do we really need constant cmov? + // We don't have const-time bigints anyway, so probably will be not very useful + cmov: (a, b, c) => c ? b : a, + toBytes: (num2) => isLE2 ? numberToBytesLE(num2, BYTES) : numberToBytesBE(num2, BYTES), + fromBytes: (bytes2) => { + if (bytes2.length !== BYTES) + throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes2.length}`); + return isLE2 ? bytesToNumberLE(bytes2) : bytesToNumberBE(bytes2); + } + }); + return Object.freeze(f2); +} +function hashToPrivateScalar(hash2, groupOrder, isLE2 = false) { + hash2 = ensureBytes("privateHash", hash2); + const hashLen = hash2.length; + const minLen = nLength(groupOrder).nByteLength + 8; + if (minLen < 24 || hashLen < minLen || hashLen > 1024) + throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`); + const num2 = isLE2 ? bytesToNumberLE(hash2) : bytesToNumberBE(hash2); + return mod(num2, groupOrder - _1n$4) + _1n$4; +} +var _0n$6 = BigInt(0); +var _1n$3 = BigInt(1); +function wNAF(c, bits) { + const constTimeNegate = (condition, item) => { + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W) => { + const windows = Math.ceil(bits / W) + 1; + const windowSize = 2 ** (W - 1); + return { windows, windowSize }; + }; + return { + constTimeNegate, + // non-const time multiplication ladder + unsafeLadder(elm, n) { + let p = c.ZERO; + let d = elm; + while (n > _0n$6) { + if (n & _1n$3) + p = p.add(d); + d = d.double(); + n >>= _1n$3; + } + return p; + }, + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for (let window2 = 0; window2 < windows; window2++) { + base = p; + points.push(base); + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * @param W window size + * @param precomputes precomputed tables + * @param n scalar (we don't check here, but should be less than curve order) + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f2 = c.BASE; + const mask = BigInt(2 ** W - 1); + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window2 = 0; window2 < windows; window2++) { + const offset = window2 * windowSize; + let wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n$3; + } + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; + const cond1 = window2 % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + f2 = f2.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + return { p, f: f2 }; + }, + wNAFCached(P2, precomputesMap, n, transform) { + const W = P2._WINDOW_SIZE || 1; + let comp = precomputesMap.get(P2); + if (!comp) { + comp = this.precomputeWindow(P2, W); + if (W !== 1) { + precomputesMap.set(P2, transform(comp)); + } + } + return this.wNAF(W, comp, n); + } + }; +} +function validateBasic(curve2) { + validateField(curve2.Fp); + validateObject(curve2, { + n: "bigint", + h: "bigint", + Gx: "field", + Gy: "field" + }, { + nBitLength: "isSafeInteger", + nByteLength: "isSafeInteger" + }); + return Object.freeze({ + ...nLength(curve2.n, curve2.nBitLength), + ...curve2, + ...{ p: curve2.Fp.ORDER } + }); +} +function validatePointOpts(curve2) { + const opts = validateBasic(curve2); + validateObject(opts, { + a: "field", + b: "field" + }, { + allowedPrivateKeyLengths: "array", + wrapPrivateKey: "boolean", + isTorsionFree: "function", + clearCofactor: "function", + allowInfinityPoint: "boolean", + fromBytes: "function", + toBytes: "function" + }); + const { endo, Fp: Fp2, a } = opts; + if (endo) { + if (!Fp2.eql(a, Fp2.ZERO)) { + throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); + } + if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { + throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); + } + } + return Object.freeze({ ...opts }); +} +var { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +var DER = { + // asn.1 DER encoding utils + Err: class DERErr extends Error { + constructor(m = "") { + super(m); + } + }, + _parseInt(data) { + const { Err: E } = DER; + if (data.length < 2 || data[0] !== 2) + throw new E("Invalid signature integer tag"); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) + throw new E("Invalid signature integer: wrong length"); + if (res[0] === 0 && res[1] <= 127) + throw new E("Invalid signature integer: trailing length"); + return { d: b2n(res), l: data.subarray(len + 2) }; + }, + toSig(hex) { + const { Err: E } = DER; + const data = typeof hex === "string" ? h2b(hex) : hex; + if (!(data instanceof Uint8Array)) + throw new Error("ui8a expected"); + let l = data.length; + if (l < 2 || data[0] != 48) + throw new E("Invalid signature tag"); + if (data[1] !== l - 2) + throw new E("Invalid signature: incorrect length"); + const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); + if (rBytesLeft.length) + throw new E("Invalid signature: left bytes after parsing"); + return { r, s }; + }, + hexFromSig(sig) { + const slice = (s2) => Number.parseInt(s2[0], 16) >= 8 ? "00" + s2 : s2; + const h = (num2) => { + const hex = num2.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + } +}; +var _0n$5 = BigInt(0); +var _1n$2 = BigInt(1); +var _2n$2 = BigInt(2); +var _3n$1 = BigInt(3); +var _4n$1 = BigInt(4); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp: Fp2 } = CURVE; + const toBytes3 = CURVE.toBytes || ((c, point, isCompressed) => { + const a = point.toAffine(); + return concatBytes(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || ((bytes2) => { + const tail = bytes2.subarray(1); + const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x, y }; + }); + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp2.sqr(x); + const x3 = Fp2.mul(x2, x); + return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b); + } + function isWithinCurveOrder(num2) { + return typeof num2 === "bigint" && _0n$5 < num2 && num2 < CURVE.n; + } + function assertGE(num2) { + if (!isWithinCurveOrder(num2)) + throw new Error("Expected valid bigint: 0 < bigint < curve.n"); + } + function normPrivateKeyToScalar(key2) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key2 !== "bigint") { + if (key2 instanceof Uint8Array) + key2 = bytesToHex$1(key2); + if (typeof key2 !== "string" || !lengths.includes(key2.length)) + throw new Error("Invalid key"); + key2 = key2.padStart(nByteLength * 2, "0"); + } + let num2; + try { + num2 = typeof key2 === "bigint" ? key2 : bytesToNumberBE(ensureBytes("private key", key2, nByteLength)); + } catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key2}`); + } + if (wrapPrivateKey) + num2 = mod(num2, n); + assertGE(num2); + return num2; + } + const pointPrecomputes2 = /* @__PURE__ */ new Map(); + function assertPrjPoint(other) { + if (!(other instanceof Point2)) + throw new Error("ProjectivePoint expected"); + } + class Point2 { + constructor(px, py, pz) { + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp2.isValid(px)) + throw new Error("x required"); + if (py == null || !Fp2.isValid(py)) + throw new Error("y required"); + if (pz == null || !Fp2.isValid(pz)) + throw new Error("z required"); + } + // Does not validate if the point is on-curve. + // Use fromHex instead, or call assertValidity() later. + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp2.isValid(x) || !Fp2.isValid(y)) + throw new Error("invalid affine point"); + if (p instanceof Point2) + throw new Error("projective point not allowed"); + const is0 = (i) => Fp2.eql(i, Fp2.ZERO); + if (is0(x) && is0(y)) + return Point2.ZERO; + return new Point2(x, y, Fp2.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + */ + static normalizeZ(points) { + const toInv = Fp2.invertBatch(points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point2.fromAffine); + } + /** + * Converts hash string or Uint8Array to Point. + * @param hex short/long ECDSA hex + */ + static fromHex(hex) { + const P2 = Point2.fromAffine(fromBytes(ensureBytes("pointHex", hex))); + P2.assertValidity(); + return P2; + } + // Multiplies generator point by privateKey. + static fromPrivateKey(privateKey) { + return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + // "Private method", don't use it directly + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes2.delete(this); + } + // A point on curve is valid if it conforms to equation. + assertValidity() { + if (this.is0()) { + if (CURVE.allowInfinityPoint) + return; + throw new Error("bad point: ZERO"); + } + const { x, y } = this.toAffine(); + if (!Fp2.isValid(x) || !Fp2.isValid(y)) + throw new Error("bad point: x or y not FE"); + const left = Fp2.sqr(y); + const right = weierstrassEquation(x); + if (!Fp2.eql(left, right)) + throw new Error("bad point: equation left != right"); + if (!this.isTorsionFree()) + throw new Error("bad point: not in prime-order subgroup"); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp2.isOdd) + return !Fp2.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + /** + * Compare one point to another. + */ + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); + const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); + return U1 && U2; + } + /** + * Flips point to one corresponding to (x, -y) in Affine coordinates. + */ + negate() { + return new Point2(this.px, Fp2.neg(this.py), this.pz); + } + // 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 = Fp2.mul(b, _3n$1); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + let t0 = Fp2.mul(X1, X1); + let t1 = Fp2.mul(Y1, Y1); + let t2 = Fp2.mul(Z1, Z1); + let t3 = Fp2.mul(X1, Y1); + t3 = Fp2.add(t3, t3); + Z3 = Fp2.mul(X1, Z1); + Z3 = Fp2.add(Z3, Z3); + X3 = Fp2.mul(a, Z3); + Y3 = Fp2.mul(b3, t2); + Y3 = Fp2.add(X3, Y3); + X3 = Fp2.sub(t1, Y3); + Y3 = Fp2.add(t1, Y3); + Y3 = Fp2.mul(X3, Y3); + X3 = Fp2.mul(t3, X3); + Z3 = Fp2.mul(b3, Z3); + t2 = Fp2.mul(a, t2); + t3 = Fp2.sub(t0, t2); + t3 = Fp2.mul(a, t3); + t3 = Fp2.add(t3, Z3); + Z3 = Fp2.add(t0, t0); + t0 = Fp2.add(Z3, t0); + t0 = Fp2.add(t0, t2); + t0 = Fp2.mul(t0, t3); + Y3 = Fp2.add(Y3, t0); + t2 = Fp2.mul(Y1, Z1); + t2 = Fp2.add(t2, t2); + t0 = Fp2.mul(t2, t3); + X3 = Fp2.sub(X3, t0); + Z3 = Fp2.mul(t2, t1); + Z3 = Fp2.add(Z3, Z3); + Z3 = Fp2.add(Z3, Z3); + return new Point2(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) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + const a = CURVE.a; + const b3 = Fp2.mul(CURVE.b, _3n$1); + let t0 = Fp2.mul(X1, X2); + let t1 = Fp2.mul(Y1, Y2); + let t2 = Fp2.mul(Z1, Z2); + let t3 = Fp2.add(X1, Y1); + let t4 = Fp2.add(X2, Y2); + t3 = Fp2.mul(t3, t4); + t4 = Fp2.add(t0, t1); + t3 = Fp2.sub(t3, t4); + t4 = Fp2.add(X1, Z1); + let t5 = Fp2.add(X2, Z2); + t4 = Fp2.mul(t4, t5); + t5 = Fp2.add(t0, t2); + t4 = Fp2.sub(t4, t5); + t5 = Fp2.add(Y1, Z1); + X3 = Fp2.add(Y2, Z2); + t5 = Fp2.mul(t5, X3); + X3 = Fp2.add(t1, t2); + t5 = Fp2.sub(t5, X3); + Z3 = Fp2.mul(a, t4); + X3 = Fp2.mul(b3, t2); + Z3 = Fp2.add(X3, Z3); + X3 = Fp2.sub(t1, Z3); + Z3 = Fp2.add(t1, Z3); + Y3 = Fp2.mul(X3, Z3); + t1 = Fp2.add(t0, t0); + t1 = Fp2.add(t1, t0); + t2 = Fp2.mul(a, t2); + t4 = Fp2.mul(b3, t4); + t1 = Fp2.add(t1, t2); + t2 = Fp2.sub(t0, t2); + t2 = Fp2.mul(a, t2); + t4 = Fp2.add(t4, t2); + t0 = Fp2.mul(t1, t4); + Y3 = Fp2.add(Y3, t0); + t0 = Fp2.mul(t5, t4); + X3 = Fp2.mul(t3, X3); + X3 = Fp2.sub(X3, t0); + t0 = Fp2.mul(t3, t1); + Z3 = Fp2.mul(t5, Z3); + Z3 = Fp2.add(Z3, t0); + return new Point2(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point2.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes2, n, (comp) => { + const toInv = Fp2.invertBatch(comp.map((p) => p.pz)); + return comp.map((p, i) => p.toAffine(toInv[i])).map(Point2.fromAffine); + }); + } + /** + * 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 private key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(n) { + const I = Point2.ZERO; + if (n === _0n$5) + return I; + assertGE(n); + if (n === _1n$2) + return this; + const { endo } = CURVE; + if (!endo) + return wnaf.unsafeLadder(this, n); + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n$5 || k2 > _0n$5) { + if (k1 & _1n$2) + k1p = k1p.add(d); + if (k2 & _1n$2) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n$2; + k2 >>= _1n$2; + } + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + /** + * 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) { + assertGE(scalar); + let n = scalar; + let point, fake; + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + const { p, f: f2 } = this.wNAF(n); + point = p; + fake = f2; + } + return Point2.normalizeZ([point, fake])[0]; + } + /** + * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. + * Not using Strauss-Shamir trick: precomputation tables are faster. + * The trick could be useful if both P and Q are not G (not in our case). + * @returns non-zero affine point + */ + multiplyAndAddUnsafe(Q, a, b) { + const G2 = Point2.BASE; + const mul = (P2, a2) => a2 === _0n$5 || a2 === _1n$2 || !P2.equals(G2) ? P2.multiplyUnsafe(a2) : P2.multiply(a2); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? void 0 : sum; + } + // Converts Projective point to affine (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + // (x, y, z) ∋ (x=x/z, y=y/z) + toAffine(iz) { + const { px: x, py: y, pz: z2 } = this; + const is0 = this.is0(); + if (iz == null) + iz = is0 ? Fp2.ONE : Fp2.inv(z2); + const ax = Fp2.mul(x, iz); + const ay = Fp2.mul(y, iz); + const zz = Fp2.mul(z2, iz); + if (is0) + return { x: Fp2.ZERO, y: Fp2.ZERO }; + if (!Fp2.eql(zz, Fp2.ONE)) + throw new Error("invZ was invalid"); + return { x: ax, y: ay }; + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n$2) + return true; + if (isTorsionFree) + return isTorsionFree(Point2, this); + throw new Error("isTorsionFree() has not been declared for the elliptic curve"); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n$2) + return this; + if (clearCofactor) + return clearCofactor(Point2, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes3(Point2, this, isCompressed); + } + toHex(isCompressed = true) { + return bytesToHex$1(this.toRawBytes(isCompressed)); + } + } + Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp2.ONE); + Point2.ZERO = new Point2(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + return { + CURVE, + ProjectivePoint: Point2, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder + }; +} +function validateOpts(curve2) { + const opts = validateBasic(curve2); + validateObject(opts, { + hash: "hash", + hmac: "function", + randomBytes: "function" + }, { + bits2int: "function", + bits2int_modN: "function", + lowS: "boolean" + }); + return Object.freeze({ lowS: true, ...opts }); +} +function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp: Fp2, n: CURVE_ORDER2 } = CURVE; + const compressedLen = Fp2.BYTES + 1; + const uncompressedLen = 2 * Fp2.BYTES + 1; + function isValidFieldElement(num2) { + return _0n$5 < num2 && num2 < Fp2.ORDER; + } + function modN2(a) { + return mod(a, CURVE_ORDER2); + } + function invN(a) { + return invert(a, CURVE_ORDER2); + } + const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ + ...CURVE, + toBytes(c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp2.toBytes(a.x); + const cat = concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x); + } else { + return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y)); + } + }, + fromBytes(bytes2) { + const len = bytes2.length; + const head = bytes2[0]; + const tail = bytes2.subarray(1); + if (len === compressedLen && (head === 2 || head === 3)) { + const x = bytesToNumberBE(tail); + if (!isValidFieldElement(x)) + throw new Error("Point is not on curve"); + const y2 = weierstrassEquation(x); + let y = Fp2.sqrt(y2); + const isYOdd = (y & _1n$2) === _1n$2; + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp2.neg(y); + return { x, y }; + } else if (len === uncompressedLen && head === 4) { + const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); + const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); + return { x, y }; + } else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + } + }); + const numToNByteStr = (num2) => bytesToHex$1(numberToBytesBE(num2, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number2) { + const HALF = CURVE_ORDER2 >> _1n$2; + return number2 > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN2(-s) : s; + } + const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); + class Signature { + constructor(r, s, recovery) { + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + // pair (bytes of r, bytes of s) + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes("compactSignature", hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + // DER encoded ECDSA signature + // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes("DER", hex)); + return new Signature(r, s); + } + assertValidity() { + if (!isWithinCurveOrder(this.r)) + throw new Error("r must be 0 < r < CURVE.n"); + if (!isWithinCurveOrder(this.s)) + throw new Error("s must be 0 < s < CURVE.n"); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes("msgHash", msgHash)); + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error("recovery id invalid"); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp2.ORDER) + throw new Error("recovery id 2 or 3 invalid"); + const prefix = (rec & 1) === 0 ? "02" : "03"; + const R = Point2.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); + const u1 = modN2(-h * ir); + const u2 = modN2(s * ir); + const Q = Point2.BASE.multiplyAndAddUnsafe(R, u1, u2); + if (!Q) + throw new Error("point at infinify"); + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this; + } + // DER-encoded + toDERRawBytes() { + return hexToBytes$1(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ r: this.r, s: this.s }); + } + // padded bytes of r, then padded bytes of s + toCompactRawBytes() { + return hexToBytes$1(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; + } + }, + normPrivateKeyToScalar, + /** + * Produces cryptographically secure private key from random of size (nBitLength+64) + * as per FIPS 186 B.4.1 with modulo bias being neglible. + */ + randomPrivateKey: () => { + const rand = CURVE.randomBytes(Fp2.BYTES + 8); + const num2 = hashToPrivateScalar(rand, CURVE_ORDER2); + return numberToBytesBE(num2, CURVE.nByteLength); + }, + /** + * Creates precompute table for an arbitrary EC point. Makes point "cached". + * Allows to massively speed-up `point.multiply(scalar)`. + * @returns cached point + * @example + * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); + * fast.multiply(privKey); // much faster ECDH now + */ + precompute(windowSize = 8, point = Point2.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + } + }; + function getPublicKey2(privateKey, isCompressed = true) { + return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + function isProbPub(item) { + const arr = item instanceof Uint8Array; + const str = typeof item === "string"; + const len = (arr || str) && item.length; + if (arr) + return len === compressedLen || len === uncompressedLen; + if (str) + return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point2) + return true; + return false; + } + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) + throw new Error("first arg must be private key"); + if (!isProbPub(publicB)) + throw new Error("second arg must be public key"); + const b = Point2.fromHex(publicB); + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + const bits2int = CURVE.bits2int || function(bytes2) { + const num2 = bytesToNumberBE(bytes2); + const delta = bytes2.length * 8 - CURVE.nBitLength; + return delta > 0 ? num2 >> BigInt(delta) : num2; + }; + const bits2int_modN = CURVE.bits2int_modN || function(bytes2) { + return modN2(bits2int(bytes2)); + }; + const ORDER_MASK = bitMask(CURVE.nBitLength); + function int2octets(num2) { + if (typeof num2 !== "bigint") + throw new Error("bigint expected"); + if (!(_0n$5 <= num2 && num2 < ORDER_MASK)) + throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + return numberToBytesBE(num2, CURVE.nByteLength); + } + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (["recovered", "canonical"].some((k) => k in opts)) + throw new Error("sign() legacy options not supported"); + const { hash: hash2, randomBytes: randomBytes3 } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; + if (lowS == null) + lowS = true; + msgHash = ensureBytes("msgHash", msgHash); + if (prehash) + msgHash = ensureBytes("prehashed msgHash", hash2(msgHash)); + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); + const seedArgs = [int2octets(d), int2octets(h1int)]; + if (ent != null) { + const e = ent === true ? randomBytes3(Fp2.BYTES) : ent; + seedArgs.push(ensureBytes("extraEntropy", e, Fp2.BYTES)); + } + const seed = concatBytes(...seedArgs); + const m = h1int; + function k2sig(kBytes) { + const k = bits2int(kBytes); + if (!isWithinCurveOrder(k)) + return; + const ik = invN(k); + const q = Point2.BASE.multiply(k).toAffine(); + const r = modN2(q.x); + if (r === _0n$5) + return; + const s = modN2(ik * modN2(m + r * d)); + if (s === _0n$5) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$2); + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); + recovery ^= 1; + } + return new Signature(r, normS, recovery); + } + return { seed, k2sig }; + } + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + function sign2(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); + const drbg = createHmacDrbg(CURVE.hash.outputLen, CURVE.nByteLength, CURVE.hmac); + return drbg(seed, k2sig); + } + Point2.BASE._setWindowSize(8); + function verify2(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes("msgHash", msgHash); + publicKey = ensureBytes("publicKey", publicKey); + if ("strict" in opts) + throw new Error("options.strict was renamed to lowS"); + const { lowS, prehash } = opts; + let _sig = void 0; + let P2; + try { + if (typeof sg === "string" || sg instanceof Uint8Array) { + try { + _sig = Signature.fromDER(sg); + } catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + _sig = Signature.fromCompact(sg); + } + } else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") { + const { r: r2, s: s2 } = sg; + _sig = new Signature(r2, s2); + } else { + throw new Error("PARSE"); + } + P2 = Point2.fromHex(publicKey); + } catch (error) { + if (error.message === "PARSE") + throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); + const is = invN(s); + const u1 = modN2(h * is); + const u2 = modN2(r * is); + const R = Point2.BASE.multiplyAndAddUnsafe(P2, u1, u2)?.toAffine(); + if (!R) + return false; + const v = modN2(R.x); + return v === r; + } + return { + CURVE, + getPublicKey: getPublicKey2, + getSharedSecret, + sign: sign2, + verify: verify2, + ProjectivePoint: Point2, + Signature, + utils + }; +} +function SWUFpSqrtRatio(Fp2, Z) { + const q = Fp2.ORDER; + let l = _0n$5; + for (let o = q - _1n$2; o % _2n$2 === _0n$5; o /= _2n$2) + l += _1n$2; + const c1 = l; + const c2 = (q - _1n$2) / _2n$2 ** c1; + const c3 = (c2 - _1n$2) / _2n$2; + const c4 = _2n$2 ** c1 - _1n$2; + const c5 = _2n$2 ** (c1 - _1n$2); + const c6 = Fp2.pow(Z, c2); + const c7 = Fp2.pow(Z, (c2 + _1n$2) / _2n$2); + let sqrtRatio = (u, v) => { + let tv1 = c6; + let tv2 = Fp2.pow(v, c4); + let tv3 = Fp2.sqr(tv2); + tv3 = Fp2.mul(tv3, v); + let tv5 = Fp2.mul(u, tv3); + tv5 = Fp2.pow(tv5, c3); + tv5 = Fp2.mul(tv5, tv2); + tv2 = Fp2.mul(tv5, v); + tv3 = Fp2.mul(tv5, u); + let tv4 = Fp2.mul(tv3, tv2); + tv5 = Fp2.pow(tv4, c5); + let isQR = Fp2.eql(tv5, Fp2.ONE); + tv2 = Fp2.mul(tv3, c7); + tv5 = Fp2.mul(tv4, tv1); + tv3 = Fp2.cmov(tv2, tv3, isQR); + tv4 = Fp2.cmov(tv5, tv4, isQR); + for (let i = c1; i > 1; i--) { + let tv52 = _2n$2 ** (i - _2n$2); + let tvv5 = Fp2.pow(tv4, tv52); + const e1 = Fp2.eql(tvv5, Fp2.ONE); + tv2 = Fp2.mul(tv3, tv1); + tv1 = Fp2.mul(tv1, tv1); + tvv5 = Fp2.mul(tv4, tv1); + tv3 = Fp2.cmov(tv2, tv3, e1); + tv4 = Fp2.cmov(tvv5, tv4, e1); + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp2.ORDER % _4n$1 === _3n$1) { + const c12 = (Fp2.ORDER - _3n$1) / _4n$1; + const c22 = Fp2.sqrt(Fp2.neg(Z)); + sqrtRatio = (u, v) => { + let tv1 = Fp2.sqr(v); + const tv2 = Fp2.mul(u, v); + tv1 = Fp2.mul(tv1, tv2); + let y1 = Fp2.pow(tv1, c12); + y1 = Fp2.mul(y1, tv2); + const y2 = Fp2.mul(y1, c22); + const tv3 = Fp2.mul(Fp2.sqr(y1), v); + const isQR = Fp2.eql(tv3, u); + let y = Fp2.cmov(y2, y1, isQR); + return { isValid: isQR, value: y }; + }; + } + return sqrtRatio; +} +function mapToCurveSimpleSWU(Fp2, opts) { + validateField(Fp2); + if (!Fp2.isValid(opts.A) || !Fp2.isValid(opts.B) || !Fp2.isValid(opts.Z)) + throw new Error("mapToCurveSimpleSWU: invalid opts"); + const sqrtRatio = SWUFpSqrtRatio(Fp2, opts.Z); + if (!Fp2.isOdd) + throw new Error("Fp.isOdd is not implemented!"); + return (u) => { + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp2.sqr(u); + tv1 = Fp2.mul(tv1, opts.Z); + tv2 = Fp2.sqr(tv1); + tv2 = Fp2.add(tv2, tv1); + tv3 = Fp2.add(tv2, Fp2.ONE); + tv3 = Fp2.mul(tv3, opts.B); + tv4 = Fp2.cmov(opts.Z, Fp2.neg(tv2), !Fp2.eql(tv2, Fp2.ZERO)); + tv4 = Fp2.mul(tv4, opts.A); + tv2 = Fp2.sqr(tv3); + tv6 = Fp2.sqr(tv4); + tv5 = Fp2.mul(tv6, opts.A); + tv2 = Fp2.add(tv2, tv5); + tv2 = Fp2.mul(tv2, tv3); + tv6 = Fp2.mul(tv6, tv4); + tv5 = Fp2.mul(tv6, opts.B); + tv2 = Fp2.add(tv2, tv5); + x = Fp2.mul(tv1, tv3); + const { isValid: isValid2, value } = sqrtRatio(tv2, tv6); + y = Fp2.mul(tv1, u); + y = Fp2.mul(y, value); + x = Fp2.cmov(x, tv3, isValid2); + y = Fp2.cmov(y, value, isValid2); + const e1 = Fp2.isOdd(u) === Fp2.isOdd(y); + y = Fp2.cmov(Fp2.neg(y), y, e1); + x = Fp2.div(x, tv4); + return { x, y }; + }; +} +function validateDST(dst) { + if (dst instanceof Uint8Array) + return dst; + if (typeof dst === "string") + return utf8ToBytes$2(dst); + throw new Error("DST must be Uint8Array or string"); +} +var os2ip = bytesToNumberBE; +function i2osp(value, length) { + if (value < 0 || value >= 1 << 8 * length) { + throw new Error(`bad I2OSP call: value=${value} length=${length}`); + } + const res = Array.from({ length }).fill(0); + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 255; + value >>>= 8; + } + return new Uint8Array(res); +} +function strxor(a, b) { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +function isBytes(item) { + if (!(item instanceof Uint8Array)) + throw new Error("Uint8Array expected"); +} +function isNum(item) { + if (!Number.isSafeInteger(item)) + throw new Error("number expected"); +} +function expand_message_xmd(msg, DST, lenInBytes, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + if (DST.length > 255) + DST = H(concatBytes(utf8ToBytes$2("H2C-OVERSIZE-DST-"), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (ell > 255) + throw new Error("Invalid xmd length"); + const DST_prime = concatBytes(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); + const b = new Array(ell); + const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1; i <= ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H(concatBytes(...args)); + } + const pseudo_random_bytes = concatBytes(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} +function expand_message_xof(msg, DST, lenInBytes, k, H) { + isBytes(msg); + isBytes(DST); + isNum(lenInBytes); + if (DST.length > 255) { + const dkLen = Math.ceil(2 * k / 8); + DST = H.create({ dkLen }).update(utf8ToBytes$2("H2C-OVERSIZE-DST-")).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error("expand_message_xof: invalid lenInBytes"); + return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest(); +} +function hash_to_field(msg, count, options) { + validateObject(options, { + DST: "string", + p: "bigint", + m: "isSafeInteger", + k: "isSafeInteger", + hash: "hash" + }); + const { p, k, m, hash: hash2, expand, DST: _DST } = options; + isBytes(msg); + isNum(count); + const DST = validateDST(_DST); + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); + const len_in_bytes = count * m * L; + let prb; + if (expand === "xmd") { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash2); + } else if (expand === "xof") { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash2); + } else if (expand === void 0) { + prb = msg; + } else { + throw new Error('expand must be "xmd", "xof" or undefined'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = mod(os2ip(tv), p); + } + u[i] = e; + } + return u; +} +function isogenyMap(field, map) { + const COEFF = map.map((i) => Array.from(i).reverse()); + return (x, y) => { + const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); + x = field.div(xNum, xDen); + y = field.mul(y, field.div(yNum, yDen)); + return { x, y }; + }; +} +function createHasher(Point2, mapToCurve, def) { + if (typeof mapToCurve !== "function") + throw new Error("mapToCurve() must be defined"); + return { + // Encodes byte string to elliptic curve + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); + const u0 = Point2.fromAffine(mapToCurve(u[0])); + const u1 = Point2.fromAffine(mapToCurve(u[1])); + const P2 = u0.add(u1).clearCofactor(); + P2.assertValidity(); + return P2; + }, + // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3 + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); + const P2 = Point2.fromAffine(mapToCurve(u[0])).clearCofactor(); + P2.assertValidity(); + return P2; + } + }; +} +var HMAC$1 = class HMAC extends Hash$2 { + constructor(hash2, _key) { + super(); + this.finished = false; + this.destroyed = false; + assert$4.hash(hash2); + const key2 = toBytes$2(_key); + this.iHash = hash2.create(); + if (typeof this.iHash.update !== "function") + throw new TypeError("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(key2.length > blockLen ? hash2.create().update(key2).digest() : key2); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54; + this.iHash.update(pad); + this.oHash = hash2.create(); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54 ^ 92; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + assert$4.exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + assert$4.exists(this); + assert$4.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +}; +var hmac$2 = (hash2, key2, message) => new HMAC$1(hash2, key2).update(message).digest(); +hmac$2.create = (hash2, key2) => new HMAC$1(hash2, key2); +function getHash(hash2) { + return { + hash: hash2, + hmac: (key2, ...msgs) => hmac$2(hash2, key2, concatBytes$1(...msgs)), + randomBytes + }; +} +function createCurve(curveDef, defHash) { + const create = (hash2) => weierstrass({ ...curveDef, ...getHash(hash2) }); + return Object.freeze({ ...create(defHash), create }); +} +var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); +var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +var _1n$1 = BigInt(1); +var _2n$1 = BigInt(2); +var divNearest = (a, b) => (a + b / _2n$1) / b; +function sqrtMod(y) { + const P2 = secp256k1P; + const _3n4 = 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 % P2; + const b3 = b2 * b2 * y % P2; + const b6 = pow2(b3, _3n4, P2) * b3 % P2; + const b9 = pow2(b6, _3n4, P2) * b3 % P2; + const b11 = pow2(b9, _2n$1, P2) * b2 % P2; + const b22 = pow2(b11, _11n, P2) * b11 % P2; + const b44 = pow2(b22, _22n, P2) * b22 % P2; + const b88 = pow2(b44, _44n, P2) * b44 % P2; + const b176 = pow2(b88, _88n, P2) * b88 % P2; + const b220 = pow2(b176, _44n, P2) * b44 % P2; + const b223 = pow2(b220, _3n4, P2) * b3 % P2; + const t1 = pow2(b223, _23n, P2) * b22 % P2; + const t2 = pow2(t1, _6n, P2) * b2 % P2; + const root = pow2(t2, _2n$1, P2); + if (!Fp.eql(Fp.sqr(root), y)) + throw new Error("Cannot find square root"); + return root; +} +var Fp = Field$1(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); +var secp256k1 = createCurve({ + a: BigInt(0), + b: BigInt(7), + Fp, + n: secp256k1N, + // Base point (x, y) aka generator point + Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), + Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), + h: BigInt(1), + lowS: true, + /** + * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 + */ + endo: { + beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); + const b1 = -_1n$1 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); + const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); + const b2 = a1; + const POW_2_128 = BigInt("0x100000000000000000000000000000000"); + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error("splitScalar: Endomorphism failed, k=" + k); + } + return { k1neg, k1, k2neg, k2 }; + } + } +}, sha256$3); +var _0n$4 = BigInt(0); +var fe = (x) => typeof x === "bigint" && _0n$4 < x && x < secp256k1P; +var ge = (x) => typeof x === "bigint" && _0n$4 < x && x < secp256k1N; +var TAGGED_HASH_PREFIXES = {}; +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === void 0) { + const tagH = sha256$3(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256$3(concatBytes(tagP, ...messages)); +} +var pointToBytes = (point) => point.toRawBytes(true).slice(1); +var numTo32b = (n) => numberToBytesBE(n, 32); +var modP$1 = (x) => mod(x, secp256k1P); +var modN$1 = (x) => mod(x, secp256k1N); +var Point$2 = secp256k1.ProjectivePoint; +var GmulAdd = (Q, a, b) => Point$2.BASE.multiplyAndAddUnsafe(Q, a, b); +function schnorrGetExtPubKey(priv) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); + let p = Point$2.fromPrivateKey(d_); + const scalar = p.hasEvenY() ? d_ : modN$1(-d_); + return { scalar, bytes: pointToBytes(p) }; +} +function lift_x(x) { + if (!fe(x)) + throw new Error("bad x: need 0 < x < p"); + const xx = modP$1(x * x); + const c = modP$1(xx * x + BigInt(7)); + let y = sqrtMod(c); + if (y % _2n$1 !== _0n$4) + y = modP$1(-y); + const p = new Point$2(x, y, _1n$1); + p.assertValidity(); + return p; +} +function challenge(...args) { + return modN$1(bytesToNumberBE(taggedHash("BIP0340/challenge", ...args))); +} +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; +} +function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { + const m = ensureBytes("message", message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); + const a = ensureBytes("auxRand", auxRand, 32); + const t = numTo32b(d ^ bytesToNumberBE(taggedHash("BIP0340/aux", a))); + const rand = taggedHash("BIP0340/nonce", t, px, m); + const k_ = modN$1(bytesToNumberBE(rand)); + if (k_ === _0n$4) + throw new Error("sign failed: k is zero"); + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); + const e = challenge(rx, px, m); + const sig = new Uint8Array(64); + sig.set(rx, 0); + sig.set(numTo32b(modN$1(k + e * d)), 32); + if (!schnorrVerify(sig, m, px)) + throw new Error("sign: Invalid signature produced"); + return sig; +} +function schnorrVerify(signature, message, publicKey) { + const sig = ensureBytes("signature", signature, 64); + const m = ensureBytes("message", message); + const pub = ensureBytes("publicKey", publicKey, 32); + try { + const P2 = lift_x(bytesToNumberBE(pub)); + const r = bytesToNumberBE(sig.subarray(0, 32)); + if (!fe(r)) + return false; + const s = bytesToNumberBE(sig.subarray(32, 64)); + if (!ge(s)) + return false; + const e = challenge(numTo32b(r), pointToBytes(P2), m); + const R = GmulAdd(P2, s, modN$1(-e)); + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; + return true; + } catch (error) { + return false; + } +} +var schnorr = { + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod + } +}; +var isoMap = isogenyMap(Fp, [ + // xNum + [ + "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7", + "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581", + "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262", + "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c" + ], + // xDen + [ + "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b", + "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14", + "0x0000000000000000000000000000000000000000000000000000000000000001" + // LAST 1 + ], + // yNum + [ + "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c", + "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3", + "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931", + "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84" + ], + // yDen + [ + "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b", + "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573", + "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f", + "0x0000000000000000000000000000000000000000000000000000000000000001" + // LAST 1 + ] +].map((i) => i.map((j) => BigInt(j)))); +var mapSWU = mapToCurveSimpleSWU(Fp, { + A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"), + B: BigInt("1771"), + Z: Fp.create(BigInt("-11")) +}); +createHasher(secp256k1.ProjectivePoint, (scalars) => { + const { x, y } = mapSWU(Fp.create(scalars[0])); + return isoMap(x, y); +}, { + DST: "secp256k1_XMD:SHA-256_SSWU_RO_", + encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_", + p: Fp.ORDER, + m: 1, + k: 128, + expand: "xmd", + hash: sha256$3 +}); +function number$1(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +function bool$1(b) { + if (typeof b !== "boolean") + throw new Error(`Expected boolean, not ${b}`); +} +function bytes$1(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new TypeError("Expected Uint8Array"); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +function hash$2(hash2) { + if (typeof hash2 !== "function" || typeof hash2.create !== "function") + throw new Error("Hash should be wrapped by utils.wrapConstructor"); + number$1(hash2.outputLen); + number$1(hash2.blockLen); +} +function exists$1(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function output$1(out, instance) { + bytes$1(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +var assert$1$1 = { + number: number$1, + bool: bool$1, + bytes: bytes$1, + hash: hash$2, + exists: exists$1, + output: output$1 +}; +var assert$2 = assert$1$1; +var createView$1 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +var rotr$1 = (word, shift) => word << 32 - shift | word >>> shift; +var isLE$1 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; +if (!isLE$1) + throw new Error("Non little-endian hardware is not supported"); +Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0")); +function utf8ToBytes$1(str) { + if (typeof str !== "string") { + throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`); + } + return new TextEncoder().encode(str); +} +function toBytes$1(data) { + if (typeof data === "string") + data = utf8ToBytes$1(data); + if (!(data instanceof Uint8Array)) + throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`); + return data; +} +var Hash$1 = class Hash3 { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +}; +function wrapConstructor$1(hashConstructor) { + const hashC = (message) => hashConstructor().update(toBytes$1(message)).digest(); + const tmp = hashConstructor(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashConstructor(); + return hashC; +} +function setBigUint64$1(view, byteOffset, value, isLE2) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE2); + const _32n2 = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n2 & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE2 ? 4 : 0; + const l = isLE2 ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE2); + view.setUint32(byteOffset + l, wl, isLE2); +} +var SHA2$1 = class SHA23 extends Hash$1 { + constructor(blockLen, outputLen, padOffset, isLE2) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE2; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView$1(this.buffer); + } + update(data) { + assert$2.exists(this); + const { view, buffer: buffer2, blockLen } = this; + data = toBytes$1(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView$1(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer2.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) { + assert$2.exists(this); + assert$2.output(out, this); + this.finished = true; + const { buffer: buffer2, view, blockLen, isLE: isLE2 } = this; + let { pos } = this; + buffer2[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) + buffer2[i] = 0; + setBigUint64$1(view, blockLen - 8, BigInt(this.length * 8), isLE2); + this.process(view, 0); + const oview = createView$1(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE2); + } + digest() { + const { buffer: buffer2, outputLen } = this; + this.digestInto(buffer2); + const res = buffer2.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer2); + return to; + } +}; +var Chi$1 = (a, b, c) => a & b ^ ~a & c; +var Maj$1 = (a, b, c) => a & b ^ a & c ^ b & c; +var SHA256_K$1 = new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +var IV$1 = new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); +var SHA256_W$1 = new Uint32Array(64); +var SHA256$1 = class SHA2563 extends SHA2$1 { + constructor() { + super(64, 32, 8, false); + this.A = IV$1[0] | 0; + this.B = IV$1[1] | 0; + this.C = IV$1[2] | 0; + this.D = IV$1[3] | 0; + this.E = IV$1[4] | 0; + this.F = IV$1[5] | 0; + this.G = IV$1[6] | 0; + this.H = IV$1[7] | 0; + } + get() { + const { A, B, C, D, E, F, G: G2, H } = this; + return [A, B, C, D, E, F, G2, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G2, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G2 | 0; + this.H = H | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W$1[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W$1[i - 15]; + const W2 = SHA256_W$1[i - 2]; + const s0 = rotr$1(W15, 7) ^ rotr$1(W15, 18) ^ W15 >>> 3; + const s1 = rotr$1(W2, 17) ^ rotr$1(W2, 19) ^ W2 >>> 10; + SHA256_W$1[i] = s1 + SHA256_W$1[i - 7] + s0 + SHA256_W$1[i - 16] | 0; + } + let { A, B, C, D, E, F, G: G2, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr$1(E, 6) ^ rotr$1(E, 11) ^ rotr$1(E, 25); + const T1 = H + sigma1 + Chi$1(E, F, G2) + SHA256_K$1[i] + SHA256_W$1[i] | 0; + const sigma0 = rotr$1(A, 2) ^ rotr$1(A, 13) ^ rotr$1(A, 22); + const T2 = sigma0 + Maj$1(A, B, C) | 0; + H = G2; + G2 = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G2 = G2 + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G2, H); + } + roundClean() { + SHA256_W$1.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +}; +var SHA224$1 = class SHA2243 extends SHA256$1 { + constructor() { + super(); + this.A = 3238371032 | 0; + this.B = 914150663 | 0; + this.C = 812702999 | 0; + this.D = 4144912697 | 0; + this.E = 4290775857 | 0; + this.F = 1750603025 | 0; + this.G = 1694076839 | 0; + this.H = 3204075428 | 0; + this.outputLen = 28; + } +}; +var sha256$2 = wrapConstructor$1(() => new SHA256$1()); +wrapConstructor$1(() => new SHA224$1()); +function within_size(data, size2) { + if (data.length > size2) { + throw new TypeError(`Data is larger than array size: ${data.length} > ${size2}`); + } +} +function is_hex(hex) { + if (hex.match(/[^a-fA-f0-9]/) !== null) { + throw new TypeError("Invalid characters in hex string: " + hex); + } + if (hex.length % 2 !== 0) { + throw new Error(`Length of hex string is invalid: ${hex.length}`); + } +} +function is_safe_num(num2) { + if (num2 > Number.MAX_SAFE_INTEGER) { + throw new TypeError("Number exceeds safe bounds!"); + } +} +var { getRandomValues } = crypto ?? globalThis.crypto ?? window.crypto; +function random$1(size2 = 32) { + if (typeof getRandomValues === "function") { + return crypto.getRandomValues(new Uint8Array(size2)); + } + throw new Error("Crypto module missing getRandomValues!"); +} +function set_buffer(data, size2, endian = "be") { + if (size2 === void 0) + size2 = data.length; + within_size(data, size2); + const buffer2 = new Uint8Array(size2).fill(0); + const offset = endian === "be" ? 0 : size2 - data.length; + buffer2.set(data, offset); + return buffer2; +} +function join_array(arr) { + let i, offset = 0; + const size2 = arr.reduce((len, arr2) => len + arr2.length, 0); + const buff = new Uint8Array(size2); + for (i = 0; i < arr.length; i++) { + const a = arr[i]; + buff.set(a, offset); + offset += a.length; + } + return buff; +} +var ec$2 = new TextEncoder(); +var ALPHABETS = [ + { + name: "base58", + charset: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + } +]; +function getAlphabet(name) { + for (const alpha of ALPHABETS) { + if (alpha.name === name) { + return alpha.charset; + } + } + throw TypeError("Charset does not exist: " + name); +} +function encode$1$1(data, charset, padding = false) { + if (typeof data === "string") + data = ec$2.encode(data); + const alphabet = getAlphabet(charset); + const len = alphabet.length; + const d = []; + let s = "", i, j = 0, c, n; + for (i = 0; i < data.length; i++) { + j = 0; + c = data[i]; + s += c > 0 || (s.length ^ i) > 0 ? "" : "1"; + while (j in d || c > 0) { + n = d[j]; + n = n > 0 ? n * 256 + c : c; + c = n / len | 0; + d[j] = n % len; + j++; + } + } + while (j-- > 0) { + s += alphabet[d[j]]; + } + return padding && s.length % 4 > 0 ? s + "=".repeat(4 - s.length % 4) : s; +} +function decode$1$1(encoded, charset) { + const alphabet = getAlphabet(charset); + const len = alphabet.length, d = [], b = []; + encoded = encoded.replace("=", ""); + let i, j = 0, c, n; + for (i = 0; i < encoded.length; i++) { + j = 0; + c = alphabet.indexOf(encoded[i]); + if (c < 0) { + throw new Error(`Character range out of bounds: ${c}`); + } + if (!(c > 0 || (b.length ^ i) > 0)) + b.push(0); + while (j in d || c > 0) { + n = d[j]; + n = n > 0 ? n * len + c : c; + c = n >> 8; + d[j] = n % 256; + j++; + } + } + while (j-- > 0) { + b.push(d[j]); + } + return new Uint8Array(b); +} +function hash256$1(data) { + return sha256$2(sha256$2(data)); +} +function addChecksum(data) { + const sum = hash256$1(data); + return join_array([data, sum.slice(0, 4)]); +} +function checkTheSum(data) { + const ret = data.slice(0, -4); + const chk = data.slice(-4); + const sum = hash256$1(ret).slice(0, 4); + if (sum.toString() !== chk.toString()) { + throw new Error("Invalid checksum!"); + } + return ret; +} +var BaseX = { + encode: encode$1$1, + decode: decode$1$1 +}; +var Base58C = { + encode: (data) => { + const withSum = addChecksum(data); + return BaseX.encode(withSum, "base58"); + }, + decode: (data) => { + const decoded = BaseX.decode(data, "base58"); + return checkTheSum(decoded); + } +}; +var CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; +var GENERATOR = [996825010, 642813549, 513874426, 1027748829, 705979059]; +var ENCODINGS = [ + { version: 0, name: "bech32", const: 1 }, + { version: 1, name: "bech32m", const: 734539939 } +]; +function polymod(values) { + let chk = 1; + for (let p = 0; p < values.length; ++p) { + const top = chk >> 25; + chk = (chk & 33554431) << 5 ^ values[p]; + for (let i = 0; i < 5; ++i) { + if ((top >> i & 1) !== 0) { + chk ^= GENERATOR[i]; + } + } + } + return chk; +} +function hrpExpand(hrp) { + const ret = []; + let p; + for (p = 0; p < hrp.length; ++p) { + ret.push(hrp.charCodeAt(p) >> 5); + } + ret.push(0); + for (p = 0; p < hrp.length; ++p) { + ret.push(hrp.charCodeAt(p) & 31); + } + return ret; +} +function verifyChecksum(hrp, data, enc) { + const combined = hrpExpand(hrp).concat(data); + return polymod(combined) === enc.const; +} +function createChecksum(hrp, data, enc) { + const values = hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]); + const mod3 = polymod(values) ^ enc.const; + const ret = []; + for (let p = 0; p < 6; ++p) { + ret.push(mod3 >> 5 * (5 - p) & 31); + } + return ret; +} +function convertBits(data, fromBits, toBits, pad = true) { + const ret = []; + let acc = 0; + let bits = 0; + const maxVal = (1 << toBits) - 1; + const maxAcc = (1 << fromBits + toBits - 1) - 1; + for (const val of data) { + if (val < 0 || val >> fromBits > 0) { + throw new Error("Failed to perform base conversion. Invalid value: " + String(val)); + } + acc = (acc << fromBits | val) & maxAcc; + bits += fromBits; + while (bits >= toBits) { + bits -= toBits; + ret.push(acc >> bits & maxVal); + } + } + if (pad) { + if (bits > 0) { + ret.push(acc << toBits - bits & maxVal); + } + } else if (bits >= fromBits || (acc << toBits - bits & maxVal) > 0) { + throw new Error("Failed to perform base conversion. Invalid Size!"); + } + return ret; +} +function encode$5(hrp, data, enc) { + const combined = data.concat(createChecksum(hrp, data, enc)); + let ret = hrp + "1"; + for (let p = 0; p < combined.length; ++p) { + ret += CHARSET.charAt(combined[p]); + } + return ret; +} +function decode$5(bechstr) { + if (!checkBounds(bechstr)) { + throw new Error("Encoded string goes out of bounds!"); + } + bechstr = bechstr.toLowerCase(); + if (!checkSeparatorPos(bechstr)) { + throw new Error("Encoded string has invalid separator!"); + } + const data = []; + const pos = bechstr.lastIndexOf("1"); + const hrp = bechstr.substring(0, pos); + for (let p = pos + 1; p < bechstr.length; ++p) { + const d = CHARSET.indexOf(bechstr.charAt(p)); + if (d === -1) { + throw new Error("Character idx out of bounds: " + String(p)); + } + data.push(d); + } + const enc = ENCODINGS.find((e) => e.version === data[0]) ?? ENCODINGS[0]; + if (!verifyChecksum(hrp, data, enc)) { + throw new Error("Checksum verification failed!"); + } + return [hrp, data.slice(0, data.length - 6)]; +} +function checkBounds(bechstr) { + let p; + let char; + let hasLower = false; + let hasUpper = false; + for (p = 0; p < bechstr.length; ++p) { + char = bechstr.charCodeAt(p); + if (char < 33 || char > 126) { + return false; + } + if (char >= 97 && char <= 122) { + hasLower = true; + } + if (char >= 65 && char <= 90) { + hasUpper = true; + } + } + if (hasLower && hasUpper) + return false; + return true; +} +function checkSeparatorPos(bechstr) { + const pos = bechstr.lastIndexOf("1"); + return !(pos < 1 || pos + 7 > bechstr.length || bechstr.length > 90); +} +function b32encode(data, hrp = "bc", version = 0) { + const dat = [version, ...convertBits([...data], 8, 5)]; + const enc = ENCODINGS.find((e) => e.version === version) ?? ENCODINGS[0]; + const str = encode$5(hrp, dat, enc); + b32decode(str); + return str; +} +function b32decode(str) { + str = str.toLowerCase(); + const hrp = str.split("1", 1)[0]; + const [hrpgot, data] = decode$5(str); + const decoded = convertBits(data.slice(1), 5, 8, false); + const length = decoded.length; + switch (true) { + case hrp !== hrpgot: + throw new Error("Returned hrp string is invalid."); + case (decoded === null || length < 2 || length > 40): + throw new Error("Decoded string is invalid or out of spec."); + case data[0] > 16: + throw new Error("Returned version bit is out of range."); + default: + return Uint8Array.from(decoded); + } +} +function getVersion$1(str) { + str = str.toLowerCase(); + const [_, data] = decode$5(str); + return data[0]; +} +var Bech32 = { + encode: b32encode, + decode: b32decode, + version: getVersion$1 +}; +var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var B64URL_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; +var ec$1 = new TextEncoder(); +function b64encode(input, urlSafe = false, padding = true) { + if (typeof input === "string") + input = ec$1.encode(input); + const map = urlSafe ? B64URL_MAP : BASE64_MAP; + let output2 = ""; + let bits = 0; + let buffer2 = 0; + for (let i = 0; i < input.length; i++) { + buffer2 = buffer2 << 8 | input[i]; + bits += 8; + while (bits >= 6) { + bits -= 6; + output2 += map[buffer2 >> bits & 63]; + } + } + if (bits > 0) { + buffer2 <<= 6 - bits; + output2 += map[buffer2 & 63]; + while (bits < 6) { + output2 += padding ? "=" : ""; + bits += 2; + } + } + return output2; +} +function b64decode(input, urlSafe = false) { + const map = urlSafe || input.includes("-") || input.includes("_") ? B64URL_MAP.split("") : BASE64_MAP.split(""); + input = input.replace(/=+$/, ""); + const chars = input.split(""); + let bits = 0; + let value = 0; + const bytes2 = []; + for (let i = 0; i < chars.length; i++) { + const c = chars[i]; + const index = map.indexOf(c); + if (index === -1) { + throw new Error("Invalid character: " + c); + } + bits += 6; + value <<= 6; + value |= index; + if (bits >= 8) { + bits -= 8; + bytes2.push(value >>> bits & 255); + } + } + return new Uint8Array(bytes2); +} +var Base64 = { + encode: b64encode, + decode: b64decode +}; +var B64URL = { + encode: (data) => b64encode(data, true, false), + decode: (data) => b64decode(data, true) +}; +var _0n$3 = BigInt(0); +var _255n = BigInt(255); +var _256n = BigInt(256); +function big_size(big) { + if (big <= 0xffn) + return 1; + if (big <= 0xffffn) + return 2; + if (big <= 0xffffffffn) + return 4; + if (big <= 0xffffffffffffffffn) + return 8; + if (big <= 0xffffffffffffffffffffffffffffffffn) + return 16; + if (big <= 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn) { + return 32; + } + throw new TypeError("Must specify a fixed buffer size for bigints greater than 32 bytes."); +} +function bigToBytes(big, size2, endian = "be") { + if (size2 === void 0) + size2 = big_size(big); + const use_le = endian === "le"; + const buffer2 = new ArrayBuffer(size2); + const dataView = new DataView(buffer2); + let offset = use_le ? 0 : size2 - 1; + while (big > _0n$3) { + const byte = big & _255n; + const num2 = Number(byte); + if (use_le) { + dataView.setUint8(offset++, num2); + } else { + dataView.setUint8(offset--, num2); + } + big = (big - byte) / _256n; + } + return new Uint8Array(buffer2); +} +function bytesToBig(bytes2) { + let num2 = BigInt(0); + for (let i = bytes2.length - 1; i >= 0; i--) { + num2 = num2 * _256n + BigInt(bytes2[i]); + } + return BigInt(num2); +} +function binToBytes(binary) { + const bins = binary.split("").map(Number); + if (bins.length % 8 !== 0) { + throw new Error(`Binary array is invalid length: ${binary.length}`); + } + const bytes2 = new Uint8Array(bins.length / 8); + for (let i = 0, ct = 0; i < bins.length; i += 8, ct++) { + let byte = 0; + for (let j = 0; j < 8; j++) { + byte |= bins[i + j] << 7 - j; + } + bytes2[ct] = byte; + } + return bytes2; +} +function bytesToBin(bytes2) { + const bin = new Array(bytes2.length * 8); + let count = 0; + for (const num2 of bytes2) { + if (num2 > 255) { + throw new Error(`Invalid byte value: ${num2}. Byte values must be between 0 and 255.`); + } + for (let i = 7; i >= 0; i--, count++) { + bin[count] = num2 >> i & 1; + } + } + return bin.join(""); +} +function num_size(num2) { + if (num2 <= 255) + return 1; + if (num2 <= 65535) + return 2; + if (num2 <= 4294967295) + return 4; + throw new TypeError("Numbers larger than 4 bytes must specify a fixed size!"); +} +function numToBytes(num2, size2, endian = "be") { + if (size2 === void 0) + size2 = num_size(num2); + const use_le = endian === "le"; + const buffer2 = new ArrayBuffer(size2); + const dataView = new DataView(buffer2); + let offset = use_le ? 0 : size2 - 1; + while (num2 > 0) { + const byte = num2 & 255; + if (use_le) { + dataView.setUint8(offset++, num2); + } else { + dataView.setUint8(offset--, num2); + } + num2 = (num2 - byte) / 256; + } + return new Uint8Array(buffer2); +} +function bytesToNum(bytes2) { + let num2 = 0; + for (let i = bytes2.length - 1; i >= 0; i--) { + num2 = num2 * 256 + bytes2[i]; + is_safe_num(num2); + } + return num2; +} +var ec = new TextEncoder(); +var dc = new TextDecoder(); +function strToBytes(str) { + return ec.encode(str); +} +function bytesToStr(bytes2) { + return dc.decode(bytes2); +} +function hex_size(hexstr2, size2) { + is_hex(hexstr2); + const len = hexstr2.length / 2; + if (size2 === void 0) + size2 = len; + if (len > size2) { + throw new TypeError(`Hex string is larger than array size: ${len} > ${size2}`); + } + return size2; +} +function hexToBytes(hexstr2, size2, endian = "le") { + size2 = hex_size(hexstr2, size2); + const use_le = endian === "le"; + const buffer2 = new ArrayBuffer(size2); + const dataView = new DataView(buffer2); + let offset = use_le ? 0 : size2 - 1; + for (let i = 0; i < hexstr2.length; i += 2) { + const char = hexstr2.substring(i, i + 2); + const num2 = parseInt(char, 16); + if (use_le) { + dataView.setUint8(offset++, num2); + } else { + dataView.setUint8(offset--, num2); + } + } + return new Uint8Array(buffer2); +} +function bytesToHex(bytes2) { + let chars = ""; + for (let i = 0; i < bytes2.length; i++) { + chars += bytes2[i].toString(16).padStart(2, "0"); + } + return chars; +} +function jsonToBytes(obj) { + const str = JSON.stringify(obj, (_, v) => { + return typeof v === "bigint" ? `${v}n` : v; + }); + return strToBytes(str); +} +function buffer(data, size2, endian) { + if (data instanceof ArrayBuffer) { + return new Uint8Array(data); + } + if (data instanceof Uint8Array) { + return set_buffer(data, size2, endian); + } + if (typeof data === "string") { + return hexToBytes(data, size2, endian); + } + if (typeof data === "bigint") { + return bigToBytes(data, size2, endian); + } + if (typeof data === "number") { + return numToBytes(data, size2, endian); + } + if (typeof data === "boolean") { + return Uint8Array.of(data ? 1 : 0); + } + throw TypeError("Unsupported format:" + String(typeof data)); +} +var Buff2 = class _Buff extends Uint8Array { + static { + this.num = numToBuff; + } + static { + this.big = bigToBuff; + } + static { + this.bin = binToBuff; + } + static { + this.raw = rawToBuff; + } + static { + this.str = strToBuff; + } + static { + this.hex = hexToBuff; + } + static { + this.bytes = bytesToBuff; + } + static { + this.json = jsonToBuff; + } + static { + this.base64 = base64ToBuff; + } + static { + this.b64url = b64urlToBuff; + } + static { + this.bech32 = bech32ToBuff; + } + static { + this.b58chk = b58chkToBuff; + } + static { + this.encode = strToBytes; + } + static { + this.decode = bytesToStr; + } + static random(size2 = 32) { + const rand = random$1(size2); + return new _Buff(rand, size2); + } + constructor(data, size2, endian) { + const buffer$12 = buffer(data, size2, endian); + super(buffer$12); + } + get arr() { + return [...this]; + } + get num() { + return this.toNum(); + } + get big() { + return this.toBig(); + } + get str() { + return this.toStr(); + } + get hex() { + return this.toHex(); + } + get raw() { + return new Uint8Array(this); + } + get bin() { + return this.toBin(); + } + get b58chk() { + return this.tob58chk(); + } + get base64() { + return this.toBase64(); + } + get b64url() { + return this.toB64url(); + } + get digest() { + return this.toHash(); + } + get id() { + return this.toHash().hex; + } + get stream() { + return new Stream2(this); + } + toNum(endian = "be") { + const bytes2 = endian === "be" ? this.reverse() : this; + return bytesToNum(bytes2); + } + toBin() { + return bytesToBin(this); + } + toBig(endian = "be") { + const bytes2 = endian === "be" ? this.reverse() : this; + return bytesToBig(bytes2); + } + toHash() { + const digest = sha256$2(this); + return new _Buff(digest); + } + toJson() { + const str = bytesToStr(this); + return JSON.parse(str); + } + toBech32(hrp, version = 0) { + return Bech32.encode(this, hrp, version); + } + toStr() { + return bytesToStr(this); + } + toHex() { + return bytesToHex(this); + } + toBytes() { + return new Uint8Array(this); + } + tob58chk() { + return Base58C.encode(this); + } + toBase64() { + return Base64.encode(this); + } + toB64url() { + return B64URL.encode(this); + } + prepend(data) { + return _Buff.join([_Buff.bytes(data), this]); + } + append(data) { + return _Buff.join([this, _Buff.bytes(data)]); + } + slice(start, end) { + const arr = new Uint8Array(this).slice(start, end); + return new _Buff(arr); + } + subarray(begin, end) { + const arr = new Uint8Array(this).subarray(begin, end); + return new _Buff(arr); + } + reverse() { + const arr = new Uint8Array(this).reverse(); + return new _Buff(arr); + } + write(bytes2, offset) { + const b = _Buff.bytes(bytes2); + this.set(b, offset); + } + prefixSize(endian) { + const size2 = _Buff.varInt(this.length, endian); + return _Buff.join([size2, this]); + } + static from(data) { + return new _Buff(Uint8Array.from(data)); + } + static of(...args) { + return new _Buff(Uint8Array.of(...args)); + } + static join(arr) { + const bytes2 = arr.map((e) => _Buff.bytes(e)); + const joined = join_array(bytes2); + return new _Buff(joined); + } + static varInt(num2, endian) { + if (num2 < 253) { + return _Buff.num(num2, 1); + } else if (num2 < 65536) { + return _Buff.of(253, ..._Buff.num(num2, 2, endian)); + } else if (num2 < 4294967296) { + return _Buff.of(254, ..._Buff.num(num2, 4, endian)); + } else if (BigInt(num2) < 0x10000000000000000n) { + return _Buff.of(255, ..._Buff.num(num2, 8, endian)); + } else { + throw new Error(`Value is too large: ${num2}`); + } + } +}; +function numToBuff(number2, size2, endian) { + return new Buff2(number2, size2, endian); +} +function binToBuff(data, size2, endian) { + return new Buff2(binToBytes(data), size2, endian); +} +function bigToBuff(bigint, size2, endian) { + return new Buff2(bigint, size2, endian); +} +function rawToBuff(data, size2, endian) { + return new Buff2(data, size2, endian); +} +function strToBuff(data, size2, endian) { + return new Buff2(strToBytes(data), size2, endian); +} +function hexToBuff(data, size2, endian) { + return new Buff2(data, size2, endian); +} +function bytesToBuff(data, size2, endian) { + return new Buff2(data, size2, endian); +} +function jsonToBuff(data) { + return new Buff2(jsonToBytes(data)); +} +function base64ToBuff(data) { + return new Buff2(Base64.decode(data)); +} +function b64urlToBuff(data) { + return new Buff2(B64URL.decode(data)); +} +function bech32ToBuff(data) { + return new Buff2(Bech32.decode(data)); +} +function b58chkToBuff(data) { + return new Buff2(Base58C.decode(data)); +} +var Stream2 = class { + constructor(data) { + this.data = Buff2.bytes(data); + this.size = this.data.length; + } + peek(size2) { + if (size2 > this.size) { + throw new Error(`Size greater than stream: ${size2} > ${this.size}`); + } + return new Buff2(this.data.slice(0, size2)); + } + read(size2) { + size2 = size2 ?? this.readSize(); + const chunk = this.peek(size2); + this.data = this.data.slice(size2); + this.size = this.data.length; + return chunk; + } + readSize(endian) { + const num2 = this.read(1).num; + switch (true) { + case (num2 >= 0 && num2 < 253): + return num2; + case num2 === 253: + return this.read(2).toNum(endian); + case num2 === 254: + return this.read(4).toNum(endian); + case num2 === 255: + return this.read(8).toNum(endian); + default: + throw new Error(`Varint is out of range: ${num2}`); + } + } +}; +var curve = secp256k1.CURVE; +var N$1 = curve.n; +var P$1 = curve.p; +var G = { x: curve.Gx, y: curve.Gy }; +var _0n$2 = BigInt(0); +var _1n = BigInt(1); +var _2n = BigInt(2); +var _3n = BigInt(3); +var _4n = BigInt(4); +var CONST = { N: N$1, P: P$1, G, _0n: _0n$2, _1n, _2n, _3n, _4n }; +var ecc = Field$1(N$1, 32, true); +var modN = (x) => mod(x, N$1); +function fail(error, throws = false) { + if (throws) { + throw new Error(error); + } else { + return false; + } +} +function random(size2) { + return Buff2.random(size2); +} +function mod_bytes(bytes2) { + const b = Buff2.bytes(bytes2).big; + return Buff2.big(modN(b), 32); +} +var utl = /* @__PURE__ */ Object.freeze({ + __proto__: null, + fail, + mod_bytes, + random +}); +var { N, P, _0n: _0n$1 } = CONST; +function size(input, size2, throws) { + const bytes2 = Buff2.bytes(input); + if (bytes2.length !== size2) { + return fail(`Invalid byte size: ${bytes2.hex} !== ${size2}`, throws); + } + return true; +} +function in_field(x, throws) { + if (!(typeof x === "bigint" && _0n$1 < x && x < N)) { + fail("x value is not in the field!", throws); + } + return true; +} +var NoblePoint = secp256k1.ProjectivePoint; +var Field = class _Field extends Uint8Array { + static { + this.N = secp256k1.CURVE.n; + } + static mod(x) { + return new _Field(x); + } + static is_valid(value, throws) { + const big = Buff2.bytes(value, 32).big; + return in_field(big, throws); + } + constructor(x) { + let b = normalizeField(x); + b = modN(b); + _Field.is_valid(b, true); + super(Buff2.big(b, 32), 32); + } + get buff() { + return new Buff2(this); + } + get raw() { + return this.buff.raw; + } + get big() { + return this.buff.big; + } + get hex() { + return this.buff.hex; + } + get point() { + return this.generate(); + } + get hasOddY() { + return this.point.hasOddY; + } + get negated() { + return this.hasOddY ? this.negate() : this; + } + gt(value) { + const x = new _Field(value); + return x.big > this.big; + } + lt(value) { + const x = new _Field(value); + return x.big < this.big; + } + eq(value) { + const x = new _Field(value); + return x.big === this.big; + } + ne(value) { + const x = new _Field(value); + return x.big !== this.big; + } + add(value) { + const x = _Field.mod(value); + const a = ecc.add(this.big, x.big); + return new _Field(a); + } + sub(value) { + const x = _Field.mod(value); + const a = ecc.sub(this.big, x.big); + return new _Field(a); + } + mul(value) { + const x = _Field.mod(value); + const a = ecc.mul(this.big, x.big); + return new _Field(a); + } + pow(value) { + const x = _Field.mod(value); + const a = ecc.pow(this.big, x.big); + return new _Field(a); + } + div(value) { + const x = _Field.mod(value); + const a = ecc.div(this.big, x.big); + return new _Field(a); + } + negate() { + return new _Field(_Field.N - this.big); + } + generate() { + const base = secp256k1.ProjectivePoint.BASE; + const point = base.multiply(this.big); + return Point.import(point); + } +}; +var Point = class _Point { + static { + this.P = CONST.P; + } + static { + this.G = CONST.G; + } + static { + this.base = secp256k1.ProjectivePoint.BASE; + } + static from_x(bytes2) { + let cp = normalizePoint(bytes2); + if (cp.length === 32) { + cp = cp.prepend(2); + } + size(cp, 33); + const point = NoblePoint.fromHex(cp.hex); + point.assertValidity(); + return new _Point(point.x, point.y); + } + static generate(value) { + const field = Field.mod(value); + const point = _Point.base.multiply(field.big); + return _Point.import(point); + } + static import(point) { + const p = point instanceof _Point ? { x: point.x.big, y: point.y.big } : { x: point.x, y: point.y }; + return new _Point(p.x, p.y); + } + constructor(x, y) { + this._p = new NoblePoint(x, y, 1n); + this.p.assertValidity(); + } + get p() { + return this._p; + } + get x() { + return Buff2.big(this.p.x, 32); + } + get y() { + return Buff2.big(this.p.y, 32); + } + get buff() { + return Buff2.raw(this.p.toRawBytes(true)); + } + get raw() { + return this.buff.raw; + } + get hex() { + return this.buff.hex; + } + get hasEvenY() { + return this.p.hasEvenY(); + } + get hasOddY() { + return !this.p.hasEvenY(); + } + eq(value) { + const p = value instanceof _Point ? value : _Point.from_x(value); + return this.x.big === p.x.big && this.y.big === p.y.big; + } + add(x) { + return x instanceof _Point ? _Point.import(this.p.add(x.p)) : _Point.import(this.p.add(_Point.generate(x).p)); + } + sub(x) { + return x instanceof _Point ? _Point.import(this.p.subtract(x.p)) : _Point.import(this.p.subtract(_Point.generate(x).p)); + } + mul(value) { + return value instanceof _Point ? _Point.import(this.p.multiply(value.x.big)) : _Point.import(this.p.multiply(Field.mod(value).big)); + } + negate() { + return _Point.import(this.p.negate()); + } +}; +function normalizeField(value) { + if (value instanceof Field) { + return value.big; + } + if (value instanceof Point) { + return value.x.big; + } + if (value instanceof Uint8Array) { + return Buff2.raw(value).big; + } + if (typeof value === "string") { + return Buff2.hex(value).big; + } + if (typeof value === "number") { + return Buff2.num(value).big; + } + if (typeof value === "bigint") { + return BigInt(value); + } + throw TypeError("Invalid input type:" + typeof value); +} +function normalizePoint(value) { + if (value instanceof Field) { + return value.point.buff; + } + if (value instanceof Point) { + return value.buff; + } + if (value instanceof Uint8Array || typeof value === "string") { + return Buff2.bytes(value); + } + if (typeof value === "number" || typeof value === "bigint") { + return Buff2.bytes(value, 32); + } + throw new TypeError(`Unknown type: ${typeof value}`); +} +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error(`Wrong positive integer: ${n}`); +} +function bool(b) { + if (typeof b !== "boolean") + throw new Error(`Expected boolean, not ${b}`); +} +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) + throw new Error("Expected Uint8Array"); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +function hash$1(hash2) { + if (typeof hash2 !== "function" || typeof hash2.create !== "function") + throw new Error("Hash should be wrapped by utils.wrapConstructor"); + number(hash2.outputLen); + number(hash2.blockLen); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); + } +} +var assert = { + number, + bool, + bytes, + hash: hash$1, + exists, + output +}; +var assert$1 = assert; +var u8a = (a) => a instanceof Uint8Array; +var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +var rotr = (word, shift) => word << 32 - shift | word >>> shift; +var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; +if (!isLE) + throw new Error("Non little-endian hardware is not supported"); +Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0")); +function utf8ToBytes(str) { + if (typeof str !== "string") + throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array(new TextEncoder().encode(str)); +} +function toBytes$3(data) { + if (typeof data === "string") + data = utf8ToBytes(data); + if (!u8a(data)) + throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +var Hash4 = class { + // Safe version that clones internal state + clone() { + return this._cloneInto(); + } +}; +function wrapConstructor(hashCons) { + const hashC = (msg) => hashCons().update(toBytes$3(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function setBigUint64(view, byteOffset, value, isLE2) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE2); + const _32n2 = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n2 & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE2 ? 4 : 0; + const l = isLE2 ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE2); + view.setUint32(byteOffset + l, wl, isLE2); +} +var SHA24 = class extends Hash4 { + constructor(blockLen, outputLen, padOffset, isLE2) { + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE2; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + assert$1.exists(this); + const { view, buffer: buffer2, blockLen } = this; + data = toBytes$3(data); + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer2.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) { + assert$1.exists(this); + assert$1.output(out, this); + this.finished = true; + const { buffer: buffer2, view, blockLen, isLE: isLE2 } = this; + let { pos } = this; + buffer2[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) + buffer2[i] = 0; + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE2); + } + digest() { + const { buffer: buffer2, outputLen } = this; + this.digestInto(buffer2); + const res = buffer2.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) + to.buffer.set(buffer2); + return to; + } +}; +var Chi = (a, b, c) => a & b ^ ~a & c; +var Maj = (a, b, c) => a & b ^ a & c ^ b & c; +var SHA256_K = new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +var IV = new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); +var SHA256_W = new Uint32Array(64); +var SHA2564 = class extends SHA24 { + constructor() { + super(64, 32, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G: G2, H } = this; + return [A, B, C, D, E, F, G2, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G2, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G2 | 0; + this.H = H | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; + } + let { A, B, C, D, E, F, G: G2, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = H + sigma1 + Chi(E, F, G2) + 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 = G2; + G2 = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G2 = G2 + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G2, H); + } + roundClean() { + SHA256_W.fill(0); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); + } +}; +var SHA2244 = class extends SHA2564 { + constructor() { + super(); + this.A = 3238371032 | 0; + this.B = 914150663 | 0; + this.C = 812702999 | 0; + this.D = 4144912697 | 0; + this.E = 4290775857 | 0; + this.F = 1750603025 | 0; + this.G = 1694076839 | 0; + this.H = 3204075428 | 0; + this.outputLen = 28; + } +}; +var sha256$1 = wrapConstructor(() => new SHA2564()); +wrapConstructor(() => new SHA2244()); +var U32_MASK64 = BigInt(2 ** 32 - 1); +var _32n = BigInt(32); +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; + return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le = false) { + let Ah = new Uint32Array(lst.length); + let Al = new Uint32Array(lst.length); + for (let i = 0; i < lst.length; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +var toBig = (h, l) => BigInt(h >>> 0) << _32n | BigInt(l >>> 0); +var shrSH = (h, l, s) => h >>> s; +var shrSL = (h, l, s) => h << 32 - s | l >>> s; +var rotrSH = (h, l, s) => h >>> s | l << 32 - s; +var rotrSL = (h, l, s) => h << 32 - s | l >>> s; +var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32; +var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s; +var rotr32H = (h, l) => l; +var rotr32L = (h, l) => h; +var rotlSH = (h, l, s) => h << s | l >>> 32 - s; +var rotlSL = (h, l, s) => l << s | h >>> 32 - s; +var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; +var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 }; +} +var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0; +var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0; +var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0; +var u64 = { + fromBig, + split, + toBig, + shrSH, + shrSL, + rotrSH, + rotrSL, + rotrBH, + rotrBL, + rotr32H, + rotr32L, + rotlSH, + rotlSL, + rotlBH, + rotlBL, + add, + add3L, + add3H, + add4L, + add4H, + add5H, + add5L +}; +var u64$1 = u64; +var [SHA512_Kh, SHA512_Kl] = u64$1.split([ + "0x428a2f98d728ae22", + "0x7137449123ef65cd", + "0xb5c0fbcfec4d3b2f", + "0xe9b5dba58189dbbc", + "0x3956c25bf348b538", + "0x59f111f1b605d019", + "0x923f82a4af194f9b", + "0xab1c5ed5da6d8118", + "0xd807aa98a3030242", + "0x12835b0145706fbe", + "0x243185be4ee4b28c", + "0x550c7dc3d5ffb4e2", + "0x72be5d74f27b896f", + "0x80deb1fe3b1696b1", + "0x9bdc06a725c71235", + "0xc19bf174cf692694", + "0xe49b69c19ef14ad2", + "0xefbe4786384f25e3", + "0x0fc19dc68b8cd5b5", + "0x240ca1cc77ac9c65", + "0x2de92c6f592b0275", + "0x4a7484aa6ea6e483", + "0x5cb0a9dcbd41fbd4", + "0x76f988da831153b5", + "0x983e5152ee66dfab", + "0xa831c66d2db43210", + "0xb00327c898fb213f", + "0xbf597fc7beef0ee4", + "0xc6e00bf33da88fc2", + "0xd5a79147930aa725", + "0x06ca6351e003826f", + "0x142929670a0e6e70", + "0x27b70a8546d22ffc", + "0x2e1b21385c26c926", + "0x4d2c6dfc5ac42aed", + "0x53380d139d95b3df", + "0x650a73548baf63de", + "0x766a0abb3c77b2a8", + "0x81c2c92e47edaee6", + "0x92722c851482353b", + "0xa2bfe8a14cf10364", + "0xa81a664bbc423001", + "0xc24b8b70d0f89791", + "0xc76c51a30654be30", + "0xd192e819d6ef5218", + "0xd69906245565a910", + "0xf40e35855771202a", + "0x106aa07032bbd1b8", + "0x19a4c116b8d2d0c8", + "0x1e376c085141ab53", + "0x2748774cdf8eeb99", + "0x34b0bcb5e19b48a8", + "0x391c0cb3c5c95a63", + "0x4ed8aa4ae3418acb", + "0x5b9cca4f7763e373", + "0x682e6ff3d6b2b8a3", + "0x748f82ee5defb2fc", + "0x78a5636f43172f60", + "0x84c87814a1f0ab72", + "0x8cc702081a6439ec", + "0x90befffa23631e28", + "0xa4506cebde82bde9", + "0xbef9a3f7b2c67915", + "0xc67178f2e372532b", + "0xca273eceea26619c", + "0xd186b8c721c0c207", + "0xeada7dd6cde0eb1e", + "0xf57d4f7fee6ed178", + "0x06f067aa72176fba", + "0x0a637dc5a2c898a6", + "0x113f9804bef90dae", + "0x1b710b35131c471b", + "0x28db77f523047d84", + "0x32caab7b40c72493", + "0x3c9ebe0a15c9bebc", + "0x431d67c49c100d4c", + "0x4cc5d4becb3e42b6", + "0x597f299cfc657e2a", + "0x5fcb6fab3ad6faec", + "0x6c44198c4a475817" +].map((n) => BigInt(n))); +var SHA512_W_H = new Uint32Array(80); +var SHA512_W_L = new Uint32Array(80); +var SHA512 = class extends SHA24 { + constructor() { + super(128, 64, 16, false); + this.Ah = 1779033703 | 0; + this.Al = 4089235720 | 0; + this.Bh = 3144134277 | 0; + this.Bl = 2227873595 | 0; + this.Ch = 1013904242 | 0; + this.Cl = 4271175723 | 0; + this.Dh = 2773480762 | 0; + this.Dl = 1595750129 | 0; + this.Eh = 1359893119 | 0; + this.El = 2917565137 | 0; + this.Fh = 2600822924 | 0; + this.Fl = 725511199 | 0; + this.Gh = 528734635 | 0; + this.Gl = 4215389547 | 0; + this.Hh = 1541459225 | 0; + this.Hl = 327033209 | 0; + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32(offset += 4); + } + for (let i = 16; i < 80; i++) { + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64$1.rotrSH(W15h, W15l, 1) ^ u64$1.rotrSH(W15h, W15l, 8) ^ u64$1.shrSH(W15h, W15l, 7); + const s0l = u64$1.rotrSL(W15h, W15l, 1) ^ u64$1.rotrSL(W15h, W15l, 8) ^ u64$1.shrSL(W15h, W15l, 7); + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64$1.rotrSH(W2h, W2l, 19) ^ u64$1.rotrBH(W2h, W2l, 61) ^ u64$1.shrSH(W2h, W2l, 6); + const s1l = u64$1.rotrSL(W2h, W2l, 19) ^ u64$1.rotrBL(W2h, W2l, 61) ^ u64$1.shrSL(W2h, W2l, 6); + const SUMl = u64$1.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64$1.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + for (let i = 0; i < 80; i++) { + const sigma1h = u64$1.rotrSH(Eh, El, 14) ^ u64$1.rotrSH(Eh, El, 18) ^ u64$1.rotrBH(Eh, El, 41); + const sigma1l = u64$1.rotrSL(Eh, El, 14) ^ u64$1.rotrSL(Eh, El, 18) ^ u64$1.rotrBL(Eh, El, 41); + const CHIh = Eh & Fh ^ ~Eh & Gh; + const CHIl = El & Fl ^ ~El & Gl; + const T1ll = u64$1.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64$1.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + const sigma0h = u64$1.rotrSH(Ah, Al, 28) ^ u64$1.rotrBH(Ah, Al, 34) ^ u64$1.rotrBH(Ah, Al, 39); + const sigma0l = u64$1.rotrSL(Ah, Al, 28) ^ u64$1.rotrBL(Ah, Al, 34) ^ u64$1.rotrBL(Ah, Al, 39); + const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; + const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64$1.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64$1.add3L(T1l, sigma0l, MAJl); + Ah = u64$1.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + ({ h: Ah, l: Al } = u64$1.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64$1.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64$1.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64$1.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64$1.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64$1.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64$1.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64$1.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); + } + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +}; +var SHA512_224 = class extends SHA512 { + constructor() { + super(); + this.Ah = 2352822216 | 0; + this.Al = 424955298 | 0; + this.Bh = 1944164710 | 0; + this.Bl = 2312950998 | 0; + this.Ch = 502970286 | 0; + this.Cl = 855612546 | 0; + this.Dh = 1738396948 | 0; + this.Dl = 1479516111 | 0; + this.Eh = 258812777 | 0; + this.El = 2077511080 | 0; + this.Fh = 2011393907 | 0; + this.Fl = 79989058 | 0; + this.Gh = 1067287976 | 0; + this.Gl = 1780299464 | 0; + this.Hh = 286451373 | 0; + this.Hl = 2446758561 | 0; + this.outputLen = 28; + } +}; +var SHA512_256 = class extends SHA512 { + constructor() { + super(); + this.Ah = 573645204 | 0; + this.Al = 4230739756 | 0; + this.Bh = 2673172387 | 0; + this.Bl = 3360449730 | 0; + this.Ch = 596883563 | 0; + this.Cl = 1867755857 | 0; + this.Dh = 2520282905 | 0; + this.Dl = 1497426621 | 0; + this.Eh = 2519219938 | 0; + this.El = 2827943907 | 0; + this.Fh = 3193839141 | 0; + this.Fl = 1401305490 | 0; + this.Gh = 721525244 | 0; + this.Gl = 746961066 | 0; + this.Hh = 246885852 | 0; + this.Hl = 2177182882 | 0; + this.outputLen = 32; + } +}; +var SHA384 = class extends SHA512 { + constructor() { + super(); + this.Ah = 3418070365 | 0; + this.Al = 3238371032 | 0; + this.Bh = 1654270250 | 0; + this.Bl = 914150663 | 0; + this.Ch = 2438529370 | 0; + this.Cl = 812702999 | 0; + this.Dh = 355462360 | 0; + this.Dl = 4144912697 | 0; + this.Eh = 1731405415 | 0; + this.El = 4290775857 | 0; + this.Fh = 2394180231 | 0; + this.Fl = 1750603025 | 0; + this.Gh = 3675008525 | 0; + this.Gl = 1694076839 | 0; + this.Hh = 1203062813 | 0; + this.Hl = 3204075428 | 0; + this.outputLen = 48; + } +}; +var sha512$1 = wrapConstructor(() => new SHA512()); +wrapConstructor(() => new SHA512_224()); +wrapConstructor(() => new SHA512_256()); +wrapConstructor(() => new SHA384()); +var Rho = new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); +var Id = Uint8Array.from({ length: 16 }, (_, i) => i); +var Pi = Id.map((i) => (9 * i + 5) % 16); +var idxL = [Id]; +var idxR = [Pi]; +for (let i = 0; i < 4; i++) + for (let j of [idxL, idxR]) + j.push(j[i].map((k) => Rho[k])); +var shifts = [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5] +].map((i) => new Uint8Array(i)); +var shiftsL = idxL.map((idx, i) => idx.map((j) => shifts[i][j])); +var shiftsR = idxR.map((idx, i) => idx.map((j) => shifts[i][j])); +var Kl = new Uint32Array([0, 1518500249, 1859775393, 2400959708, 2840853838]); +var Kr = new Uint32Array([1352829926, 1548603684, 1836072691, 2053994217, 0]); +var rotl = (word, shift) => word << shift | word >>> 32 - shift; +function f(group, x, y, z2) { + if (group === 0) + return x ^ y ^ z2; + else if (group === 1) + return x & y | ~x & z2; + else if (group === 2) + return (x | ~y) ^ z2; + else if (group === 3) + return x & z2 | y & ~z2; + else + return x ^ (y | ~z2); +} +var BUF = new Uint32Array(16); +var RIPEMD160 = class extends SHA24 { + constructor() { + super(64, 20, 8, true); + this.h0 = 1732584193 | 0; + this.h1 = 4023233417 | 0; + this.h2 = 2562383102 | 0; + this.h3 = 271733878 | 0; + this.h4 = 3285377520 | 0; + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF[i] = view.getUint32(offset, true); + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; + const rl = idxL[group], rr = idxR[group]; + const sl = shiftsL[group], sr = shiftsR[group]; + for (let i = 0; i < 16; i++) { + const tl = rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; + } + for (let i = 0; i < 16; i++) { + const tr = rotl(ar + f(rGroup, br, cr, dr) + BUF[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() { + BUF.fill(0); + } + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); + } +}; +var ripemd160 = wrapConstructor(() => new RIPEMD160()); +var HMAC2 = class extends Hash4 { + constructor(hash2, _key) { + super(); + this.finished = false; + this.destroyed = false; + assert$1.hash(hash2); + const key2 = toBytes$3(_key); + this.iHash = hash2.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + pad.set(key2.length > blockLen ? hash2.create().update(key2).digest() : key2); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54; + this.iHash.update(pad); + this.oHash = hash2.create(); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54 ^ 92; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + assert$1.exists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + assert$1.exists(this); + assert$1.bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +}; +var hmac$1 = (hash2, key2, message) => new HMAC2(hash2, key2).update(message).digest(); +hmac$1.create = (hash2, key2) => new HMAC2(hash2, key2); +function sha256(msg) { + const b = Buff2.bytes(msg); + return Buff2.raw(sha256$1(b)); +} +function hash256(msg) { + const b = Buff2.bytes(msg); + return Buff2.raw(sha256$1(sha256$1(b))); +} +function hash160(msg) { + const b = Buff2.bytes(msg); + return Buff2.raw(ripemd160(sha256$1(b))); +} +function hmac512(key2, msg) { + const k = Buff2.bytes(key2); + const b = Buff2.bytes(msg); + return Buff2.raw(hmac$1(sha512$1, k, b)); +} +function hashtag(tag) { + const hash2 = Buff2.str(tag).digest; + return Buff2.join([hash2, hash2]); +} +function genSecretKey(size2 = 32) { + return getSecretKey(random(size2)); +} +function getSecretKey(secret) { + return Field.mod(secret).buff; +} +function getPublicKey(seckey, xonly = false) { + const p = Field.mod(seckey).point; + return xonly ? p.x : p.buff; +} +function getSharedKey(seckey, pubkey) { + const P2 = Point.from_x(pubkey); + const sp = Field.mod(seckey); + const sh = P2.mul(sp); + return sh.buff; +} +function getSharedCode(self_sec, peer_pub, tag = "ecdh/code") { + const hash2 = hashtag(tag); + const sec = getSecretKey(self_sec); + const pub = getPublicKey(sec); + const peer = Buff2.bytes(peer_pub); + const link = getSharedKey(sec, peer); + const keys = [pub.hex, peer.hex]; + keys.sort(); + return hmac512(link, Buff2.join([hash2, ...keys])); +} +function is_even_pub(pubkey) { + const pub = Buff2.bytes(pubkey); + switch (true) { + case pub.length === 32: + return true; + case (pub.length === 33 && pub[0] === 2): + return true; + case (pub.length === 33 && pub[0] === 3): + return false; + default: + throw new TypeError(`Invalid public key: ${pub.hex}`); + } +} +function xonly_pub(pubkey) { + const key2 = Buff2.bytes(pubkey); + switch (key2.length) { + case 32: + return key2; + case 33: + return key2.slice(1, 33); + default: + throw new Error(`Invalid key length: ${key2.length}`); + } +} +var key = /* @__PURE__ */ Object.freeze({ + __proto__: null, + genSecretKey, + getPublicKey, + getSecretKey, + getSharedCode, + getSharedKey, + is_even_pub, + xonly_pub +}); +({ + aux: Buff2.random(32), + throws: false, + xonly: true +}); +var noble = { secp: secp256k1, schnorr }; +var util$1 = { ...key, ...utl }; +function hash160pkh(pubkey) { + const bytes2 = Buff$1.bytes(pubkey); + checkSize(bytes2, 33); + return hash160(bytes2); +} +function hash160sh(script2) { + const bytes2 = Script.fmt.toBytes(script2, false); + return hash160(bytes2); +} +function sha256sh(script2) { + const bytes2 = Script.fmt.toBytes(script2, false); + return sha256(bytes2); +} +function check$4(address, network = "main") { + const prefixes = network === "main" ? ["1"] : ["m", "n"]; + for (const prefix of prefixes) { + if (address.startsWith(prefix)) { + return true; + } + } + return false; +} +function encode$4(input, network = "main") { + const bytes2 = Buff$1.bytes(input); + const prefix = network === "main" ? Buff$1.num(0) : Buff$1.num(111); + checkSize(input, 20); + return bytes2.prepend(prefix).tob58chk(); +} +function decode$4(address, network = "main") { + if (!check$4(address, network)) { + throw new TypeError("Invalid p2pkh address!"); + } + return Buff$1.b58chk(address).slice(1); +} +function scriptPubKey$4(input) { + const bytes2 = Buff$1.bytes(input); + checkSize(bytes2, 20); + return ["OP_DUP", "OP_HASH160", bytes2.hex, "OP_EQUALVERIFY", "OP_CHECKSIG"]; +} +function fromPubKey$2(pubkey, network) { + const pkh = hash160pkh(pubkey); + return encode$4(pkh, network); +} +var P2PKH = { check: check$4, encode: encode$4, decode: decode$4, hash: hash160pkh, scriptPubKey: scriptPubKey$4, fromPubKey: fromPubKey$2 }; +function check$3(address, network = "main") { + const prefixes = network === "main" ? ["3"] : ["2"]; + for (const prefix of prefixes) { + if (address.startsWith(prefix)) { + return true; + } + } + return false; +} +function encode$3(input, network = "main") { + const prefix = network === "main" ? Buff$1.num(5) : Buff$1.num(196); + const bytes2 = Buff$1.bytes(input); + checkSize(bytes2, 20); + return bytes2.prepend(prefix).tob58chk(); +} +function decode$3(address, network = "main") { + if (!check$3(address, network)) { + throw new TypeError(`Invalid p2sh address for network ${network}:` + address); + } + return Buff$1.b58chk(address).slice(1); +} +function scriptPubKey$3(input) { + const bytes2 = Buff$1.bytes(input); + return ["OP_HASH160", bytes2.hex, "OP_EQUAL"]; +} +function fromScript$1(script2, network) { + const scriptHash = hash160sh(script2); + return encode$3(scriptHash, network); +} +var P2SH = { check: check$3, encode: encode$3, decode: decode$3, hash: hash160sh, scriptPubKey: scriptPubKey$3, fromScript: fromScript$1 }; +var BECH32_PREFIXES = { + main: "bc", + testnet: "tb", + signet: "tb", + regtest: "bcrt" +}; +var VALID_PREFIXES$2 = ["bc1q", "tb1q", "bcrt1q"]; +function check$2(address) { + for (const prefix of VALID_PREFIXES$2) { + if (address.startsWith(prefix)) { + return true; + } + } + return false; +} +function encode$2(input, network = "main") { + const prefix = BECH32_PREFIXES[network]; + const bytes2 = Buff$1.bytes(input); + checkSize(bytes2, 20); + return bytes2.toBech32(prefix, 0); +} +function decode$2(address) { + if (!check$2(address)) { + throw new TypeError("Invalid segwit address!"); + } + return Buff$1.bech32(address); +} +function scriptPubKey$2(input) { + const bytes2 = Buff$1.bytes(input); + checkSize(bytes2, 20); + return ["OP_0", bytes2.hex]; +} +function fromPubKey$1(pubkey, network) { + const pkh = hash160pkh(pubkey); + return encode$2(pkh, network); +} +var P2WPKH = { check: check$2, encode: encode$2, decode: decode$2, hash: hash160pkh, scriptPubKey: scriptPubKey$2, fromPubKey: fromPubKey$1 }; +var VALID_PREFIXES$1 = ["bc1q", "tb1q", "bcrt1q"]; +function check$1(address) { + for (const prefix of VALID_PREFIXES$1) { + if (address.startsWith(prefix)) { + return true; + } + } + return false; +} +function encode$1(input, network = "main") { + const prefix = BECH32_PREFIXES[network]; + const bytes2 = Buff$1.bytes(input); + checkSize(bytes2, 32); + return bytes2.toBech32(prefix, 0); +} +function decode$1(address) { + if (!check$1(address)) { + throw new TypeError("Invalid segwit address!"); + } + return Buff$1.bech32(address); +} +function scriptPubKey$1(input) { + const bytes2 = Buff$1.bytes(input); + checkSize(bytes2, 32); + return ["OP_0", bytes2.hex]; +} +function fromScript(script2, network) { + const sh = sha256sh(script2); + return encode$1(sh, network); +} +var P2WSH = { check: check$1, encode: encode$1, decode: decode$1, hash: sha256sh, scriptPubKey: scriptPubKey$1, fromScript }; +function xOnlyPub(key2) { + const bytes2 = Buff$1.bytes(key2); + return bytes2.length > 32 ? bytes2.slice(1, 33) : bytes2; +} +var VALID_PREFIXES = ["bc1p", "tb1p", "bcrt1p"]; +function check(address) { + for (const prefix of VALID_PREFIXES) { + if (address.startsWith(prefix)) { + return true; + } + } + return false; +} +function encode(input, network = "main") { + const prefix = BECH32_PREFIXES[network]; + const bytes2 = Buff$1.bytes(input); + checkSize(bytes2, 32); + return bytes2.toBech32(prefix, 1); +} +function decode(address) { + if (!check(address)) { + throw new TypeError("Invalid taproot address!"); + } + return Buff$1.bech32(address); +} +function scriptPubKey(input) { + const bytes2 = Buff$1.bytes(input); + checkSize(bytes2, 32); + return ["OP_1", bytes2.hex]; +} +function fromPubKey(pubkey, network) { + const bytes2 = xOnlyPub(pubkey); + return encode(bytes2, network); +} +var P2TR = { check, encode, decode, scriptPubKey, fromPubKey }; +var DEFAULT_TX = { + version: 2, + vin: [], + vout: [], + locktime: 0 +}; +var DEFAULT_VIN = { + scriptSig: [], + sequence: 4294967293, + witness: [] +}; +var DEFAULT_VOUT = { + value: 0n, + scriptPubKey: [] +}; +function createTx(template) { + const tx = { ...DEFAULT_TX, ...template }; + tx.vin = tx.vin.map((txin) => { + return { ...DEFAULT_VIN, ...txin }; + }); + tx.vout = tx.vout.map((txout) => { + return { ...DEFAULT_VOUT, ...txout }; + }); + return tx; +} +function encodeTx(txdata, omitWitness) { + const { version, vin, vout, locktime } = createTx(txdata); + const useWitness = omitWitness !== true && checkForWitness(vin); + const raw = [encodeVersion(version)]; + if (useWitness) { + raw.push(Buff$1.hex("0001")); + } + raw.push(encodeInputs(vin)); + raw.push(encodeOutputs(vout)); + for (const txin of vin) { + if (useWitness) { + raw.push(encodeWitness(txin.witness)); + } + } + raw.push(encodeLocktime(locktime)); + return Buff$1.join(raw); +} +function checkForWitness(vin) { + for (const txin of vin) { + const { witness: witness2 } = txin; + if (typeof witness2 === "string" || witness2 instanceof Uint8Array || Array.isArray(witness2) && witness2.length > 0) { + return true; + } + } + return false; +} +function encodeVersion(num2) { + return Buff$1.num(num2, 4).reverse(); +} +function encodeTxid(txid) { + return Buff$1.hex(txid, 32).reverse(); +} +function encodePrevOut(vout) { + return Buff$1.num(vout, 4).reverse(); +} +function encodeSequence(sequence) { + if (typeof sequence === "string") { + return Buff$1.hex(sequence, 4).reverse(); + } + if (typeof sequence === "number") { + return Buff$1.num(sequence, 4).reverse(); + } + throw new Error("Unrecognized format: " + String(sequence)); +} +function encodeInputs(arr) { + const raw = [Buff$1.varInt(arr.length, "le")]; + for (const vin of arr) { + const { txid, vout, scriptSig, sequence } = vin; + raw.push(encodeTxid(txid)); + raw.push(encodePrevOut(vout)); + raw.push(encodeScript(scriptSig, true)); + raw.push(encodeSequence(sequence)); + } + return Buff$1.join(raw); +} +function encodeValue(value) { + if (typeof value === "number") { + if (value % 1 !== 0) { + throw new Error("Value must be an integer:" + String(value)); + } + return Buff$1.num(value, 8).reverse(); + } + return Buff$1.big(value, 8).reverse(); +} +function encodeOutputs(arr) { + const raw = [Buff$1.varInt(arr.length, "le")]; + for (const vout of arr) { + raw.push(encodeOutput(vout)); + } + return Buff$1.join(raw); +} +function encodeOutput(vout) { + const { value, scriptPubKey: scriptPubKey2 } = vout; + const raw = []; + raw.push(encodeValue(value)); + raw.push(encodeScript(scriptPubKey2, true)); + return Buff$1.join(raw); +} +function encodeWitness(data = []) { + const buffer2 = []; + if (Array.isArray(data)) { + const count = Buff$1.varInt(data.length); + buffer2.push(count); + for (const entry of data) { + buffer2.push(encodeData(entry)); + } + return Buff$1.join(buffer2); + } else { + return Buff$1.bytes(data); + } +} +function encodeData(data) { + return !isEmpty(data) ? encodeScript(data, true) : new Buff$1(0); +} +function isEmpty(data) { + if (Array.isArray(data)) { + return data.length === 0; + } + if (typeof data === "string") { + if (data === "") + return true; + } + const bytes2 = Buff$1.bytes(data); + return bytes2.length === 1 && bytes2[0] === 0; +} +function encodeLocktime(locktime) { + if (typeof locktime === "string") { + return Buff$1.hex(locktime, 4); + } + if (typeof locktime === "number") { + return Buff$1.num(locktime, 4).reverse(); + } + throw new Error("Unrecognized format: " + String(locktime)); +} +function decodeTx(bytes2) { + if (typeof bytes2 === "string") { + bytes2 = Buff$1.hex(bytes2).raw; + } + const stream = new Stream$1(bytes2); + const version = readVersion(stream); + const hasWitness = checkWitnessFlag(stream); + const vin = readInputs(stream); + const vout = readOutputs(stream); + if (hasWitness) { + for (const txin of vin) { + txin.witness = readWitness$1(stream); + } + } + const locktime = readLocktime(stream); + return { version, vin, vout, locktime }; +} +function readVersion(stream) { + return stream.read(4).reverse().toNum(); +} +function checkWitnessFlag(stream) { + const [marker, flag] = [...stream.peek(2)]; + if (marker === 0) { + stream.read(2); + if (flag === 1) { + return true; + } else { + throw new Error(`Invalid witness flag: ${flag}`); + } + } + return false; +} +function readInputs(stream) { + const inputs = []; + const vinCount = stream.readSize("le"); + for (let i = 0; i < vinCount; i++) { + inputs.push(readInput(stream)); + } + return inputs; +} +function readInput(stream) { + const txin = { + txid: stream.read(32).reverse().toHex(), + vout: stream.read(4).reverse().toNum(), + scriptSig: readScript(stream, true), + sequence: stream.read(4).reverse().toHex(), + witness: [] + }; + return txin; +} +function readOutputs(stream) { + const outputs = []; + const outcount = stream.readSize("le"); + for (let i = 0; i < outcount; i++) { + outputs.push(readOutput(stream)); + } + return outputs; +} +function readOutput(stream) { + const txout = { + value: stream.read(8).reverse().big, + scriptPubKey: readScript(stream, true) + }; + return txout; +} +function readWitness$1(stream) { + const stack = []; + const count = stream.readSize(); + for (let i = 0; i < count; i++) { + const word = readData(stream, true); + stack.push(word ?? ""); + } + return stack; +} +function readData(stream, varint) { + const size2 = varint === true ? stream.readSize("le") : stream.size; + return size2 > 0 ? stream.read(size2).hex : null; +} +function readScript(stream, varint) { + const data = readData(stream, varint); + return data !== null ? data : []; +} +function readLocktime(stream) { + return stream.read(4).reverse().toNum(); +} +function toJson(txdata) { + if (isBytes$1(txdata)) { + return decodeTx(txdata); + } + if (typeof txdata === "object" && !(txdata instanceof Uint8Array)) { + encodeTx(txdata); + return createTx(txdata); + } + throw new Error("Invalid format: " + String(typeof txdata)); +} +function toBytes(txdata) { + if (isBytes$1(txdata)) { + decodeTx(txdata); + return Buff$1.bytes(txdata); + } + if (typeof txdata === "object") { + return encodeTx(txdata); + } + throw new Error("Invalid format: " + String(typeof txdata)); +} +var TxFmt = { + toBytes, + toJson +}; +var OUTPUT_TYPES = [ + ["p2pkh", /^76a914(?\w{40})88ac$/], + ["p2sh", /^a914(?\w{40})87$/], + ["p2w-pkh", /^0014(?\w{40})$/], + ["p2w-sh", /^0020(?\w{64})$/], + ["p2tr", /^5120(?\w{64})$/] +]; +var LEAF_VERSIONS = [ + 192, + 194, + 196, + 198, + 200, + 202, + 204, + 206, + 208, + 210, + 212, + 214, + 216, + 218, + 220, + 222, + 224, + 226, + 228, + 230, + 232, + 234, + 236, + 238, + 240, + 242, + 244, + 246, + 248, + 250, + 252, + 254, + 102, + 126, + 128, + 132, + 150, + 152, + 186, + 188, + 190 +]; +function parseAnnex(data) { + let item = data.at(-1); + if (isHex(item)) { + item = Buff$1.hex(item); + } + if (data.length > 1 && item instanceof Uint8Array && item[0] === 80) { + data.pop(); + return Buff$1.raw(item); + } + return null; +} +function parseBlock(data) { + let item = data.at(-1); + if (isHex(item)) { + item = Buff$1.hex(item); + } + if (data.length > 1 && item instanceof Uint8Array && item.length > 32 && LEAF_VERSIONS.includes(item[0] & 254)) { + data.pop(); + return Buff$1.raw(item); + } + return null; +} +function parseWitScript(data) { + if (data.length > 1) { + const item = data.at(-1); + try { + const script2 = Script.fmt.toBytes(item); + data.pop(); + return script2; + } catch (err) { + return null; + } + } + return null; +} +function parseParams(data) { + const params = []; + for (const d of data) { + if (isHex(d) || d instanceof Uint8Array || typeof d === "number") { + params.push(Buff$1.bytes(d)); + } else { + throw new Error("unrecognized value: " + String(d)); + } + } + return params; +} +function readWitness(data = []) { + const items = [...data]; + const annex = parseAnnex(items); + const cblock = parseBlock(items); + const script2 = parseWitScript(items); + const params = parseParams(items); + return { annex, cblock, script: script2, params }; +} +function readScriptPubKey(script2) { + const hex = Script.fmt.toBytes(script2, false).hex; + for (const [keytype, pattern] of OUTPUT_TYPES) { + const type = keytype; + const { groups } = pattern.exec(hex) ?? {}; + const { hash: hash2 } = groups ?? {}; + if (isHex(hash2)) { + return { type, data: Buff$1.hex(hash2) }; + } + } + return { type: "raw", data: Buff$1.hex(hex) }; +} +function getTxid(txdata) { + const json = TxFmt.toJson(txdata); + const data = encodeTx(json, true); + return hash256(data).reverse().hex; +} +function getTxSize(txdata) { + const json = TxFmt.toJson(txdata); + const bsize = encodeTx(json, true).length; + const fsize = encodeTx(json, false).length; + const weight = bsize * 3 + fsize; + const remain = weight % 4 > 0 ? 1 : 0; + const vsize = Math.floor(weight / 4) + remain; + return { size: fsize, bsize, vsize, weight }; +} +var Tx = { + create: createTx, + encode: encodeTx, + decode: decodeTx, + fmt: TxFmt, + util: { + getTxSize, + getTxid, + readScriptPubKey, + readWitness + } +}; +var ADDRESS_TYPES = [ + ["1", "p2pkh", "main", 20, "base58"], + ["3", "p2sh", "main", 20, "base58"], + ["m", "p2pkh", "testnet", 20, "base58"], + ["n", "p2pkh", "testnet", 20, "base58"], + ["2", "p2sh", "testnet", 20, "base58"], + ["bc1q", "p2w-pkh", "main", 20, "bech32"], + ["tb1q", "p2w-pkh", "testnet", 20, "bech32"], + ["bcrt1q", "p2w-pkh", "regtest", 20, "bech32"], + ["bc1q", "p2w-sh", "main", 32, "bech32"], + ["tb1q", "p2w-sh", "testnet", 32, "bech32"], + ["bcrt1q", "p2w-sh", "regtest", 32, "bech32"], + ["bc1p", "p2tr", "main", 32, "bech32m"], + ["tb1p", "p2tr", "testnet", 32, "bech32m"], + ["bcrt1p", "p2tr", "regtest", 32, "bech32m"] +]; +function decodeFormat(address, format) { + switch (format) { + case "base58": + return Buff$1.b58chk(address).slice(1); + case "bech32": + return Buff$1.bech32(address); + case "bech32m": + return Buff$1.bech32(address); + default: + throw new Error("Invalid address format: " + format); + } +} +function getData(address) { + for (const row of ADDRESS_TYPES) { + const [prefix, _type, _network, size2, format] = row; + if (address.startsWith(prefix)) { + const bytes2 = decodeFormat(address, format); + if (bytes2.length === size2) + return row; + } + } + throw new Error("Invalid address: " + address); +} +function getTool(type) { + switch (type) { + case "p2pkh": + return P2PKH; + case "p2sh": + return P2SH; + case "p2w-pkh": + return P2WPKH; + case "p2w-sh": + return P2WSH; + case "p2tr": + return P2TR; + default: + throw new Error("Invalid address type: " + type); + } +} +function decodeAddress(address) { + const [prefix, type, network] = getData(address); + const tool = getTool(type); + const data = tool.decode(address, network); + const script2 = tool.scriptPubKey(data); + return { prefix, type, network, data, script: script2 }; +} +function fromScriptPubKey(script2, network) { + const { type, data } = Tx.util.readScriptPubKey(script2); + const tool = getTool(type); + return tool.encode(data, network); +} +function toScriptPubKey(address) { + const { script: script2 } = decodeAddress(address); + return Script.fmt.toAsm(script2, false); +} +var Address = { + p2pkh: P2PKH, + p2sh: P2SH, + p2wpkh: P2WPKH, + p2wsh: P2WSH, + p2tr: P2TR, + decode: decodeAddress, + fromScriptPubKey, + toScriptPubKey +}; +var VALID_HASH_TYPES$1 = [1, 2, 3]; +function hashTx$1(txdata, idx, config = {}) { + const { sigflag = 1 } = config; + const isAnypay = (sigflag & 128) === 128; + const flag = sigflag % 128; + if (!VALID_HASH_TYPES$1.includes(flag)) { + throw new Error("Invalid hash type: " + String(sigflag)); + } + const tx = Tx.fmt.toJson(txdata); + const { version, vin, vout, locktime } = tx; + const { txid, vout: prevIdx, prevout, sequence } = vin[idx]; + const { value } = prevout ?? {}; + if (value === void 0) { + throw new Error("Prevout value is empty!"); + } + let script2 = config.script; + if (script2 === void 0 && config.pubkey !== void 0) { + const pkhash = hash160(config.pubkey); + script2 = `76a914${pkhash.hex}88ac`; + } + if (script2 === void 0) { + throw new Error("No pubkey / script has been set!"); + } + if (Script.fmt.toAsm(script2).includes("OP_CODESEPARATOR")) { + throw new Error("This library does not currently support the use of OP_CODESEPARATOR in segwit scripts."); + } + const sighash = [ + encodeVersion(version), + hashPrevouts(vin, isAnypay), + hashSequence$1(vin, flag, isAnypay), + encodeTxid(txid), + encodePrevOut(prevIdx), + Script.encode(script2, true), + encodeValue(value), + encodeSequence(sequence), + hashOutputs$1(vout, idx, flag), + encodeLocktime(locktime), + Buff$1.num(sigflag, 4).reverse() + ]; + return hash256(Buff$1.join(sighash)); +} +function hashPrevouts(vin, isAnypay) { + if (isAnypay === true) { + return Buff$1.num(0, 32); + } + const stack = []; + for (const { txid, vout } of vin) { + stack.push(encodeTxid(txid)); + stack.push(encodePrevOut(vout)); + } + return hash256(Buff$1.join(stack)); +} +function hashSequence$1(vin, sigflag, isAnyPay) { + if (isAnyPay || sigflag !== 1) { + return Buff$1.num(0, 32); + } + const stack = []; + for (const { sequence } of vin) { + stack.push(encodeSequence(sequence)); + } + return hash256(Buff$1.join(stack)); +} +function hashOutputs$1(vout, idx, sigflag) { + const stack = []; + if (sigflag === 1) { + for (const { value, scriptPubKey: scriptPubKey2 } of vout) { + stack.push(encodeValue(value)); + stack.push(Script.encode(scriptPubKey2, true)); + } + return hash256(Buff$1.join(stack)); + } + if (sigflag === 3 && idx < vout.length) { + const { value, scriptPubKey: scriptPubKey2 } = vout[idx]; + stack.push(encodeValue(value)); + stack.push(Script.encode(scriptPubKey2, true)); + return hash256(Buff$1.join(stack)); + } + return Buff$1.num(0, 32); +} +function signTx$1(seckey, txdata, index, config = {}) { + const { sigflag = 1 } = config; + const hash2 = hashTx$1(txdata, index, config); + const sig = noble.secp.sign(hash2, seckey).toDERRawBytes(true); + return Buff$1.join([sig, sigflag]); +} +function verifyTx$1(txdata, index, config = {}) { + const tx = Tx.fmt.toJson(txdata); + const { throws = false } = config; + const { witness: witness2 = [] } = tx.vin[index]; + const witnessData = Tx.util.readWitness(witness2); + const { script: script2, params } = witnessData; + let pub = null; + if (params.length < 1) { + return safeThrow("Invalid witness data: " + String(witness2), throws); + } + if (config.script === void 0 && script2 !== null) { + config.script = script2; + } + if (config.pubkey !== void 0) { + pub = Buff$1.bytes(config.pubkey); + } else if (params.length > 1 && params[1].length === 33) { + pub = Buff$1.bytes(params[1]); + } else { + return safeThrow("No pubkey provided!", throws); + } + const rawsig = Script.fmt.toParam(params[0]); + const signature = rawsig.slice(0, -1); + const sigflag = rawsig.slice(-1)[0]; + const hash2 = hashTx$1(tx, index, { ...config, sigflag }); + if (!noble.secp.verify(signature, hash2, pub)) { + return safeThrow("Invalid signature!", throws); + } + return true; +} +var SWSigner = { + hash: hashTx$1, + sign: signTx$1, + verify: verifyTx$1 +}; +var VALID_HASH_TYPES = [0, 1, 2, 3, 129, 130, 131]; +function hashTx(template, index, config = {}) { + const { extension, sigflag = 0, extflag = 0, key_version = 0, separator_pos = 4294967295 } = config; + const txdata = Tx.fmt.toJson(template); + const { version, vin: input, vout: output2, locktime } = txdata; + if (index >= input.length) { + throw new Error("Index out of bounds: " + String(index)); + } + if (!VALID_HASH_TYPES.includes(sigflag)) { + throw new Error("Invalid hash type: " + String(sigflag)); + } + if (extflag < 0 || extflag > 127) { + throw new Error("Extention flag out of range: " + String(extflag)); + } + const { txid, vout, sequence, witness: witness2 = [] } = input[index]; + const isAnyPay = (sigflag & 128) === 128; + const annex = getAnnexData(witness2); + const annexBit = annex !== void 0 ? 1 : 0; + const extendBit = extension !== void 0 ? 1 : 0; + const spendType = (extflag + extendBit) * 2 + annexBit; + const hashtag2 = Buff$1.str("TapSighash").digest; + const preimage = [ + hashtag2, + hashtag2, + Buff$1.num(0, 1), + Buff$1.num(sigflag, 1), + encodeVersion(version), + encodeLocktime(locktime) + ]; + if (!isAnyPay) { + const prevouts = input.map((e) => getPrevout(e)); + preimage.push(hashOutpoints(input), hashAmounts(prevouts), hashScripts(prevouts), hashSequence(input)); + } + if ((sigflag & 3) < 2 || (sigflag & 3) > 3) { + preimage.push(hashOutputs(output2)); + } + preimage.push(Buff$1.num(spendType, 1)); + if (isAnyPay) { + const { value, scriptPubKey: scriptPubKey2 } = getPrevout(input[index]); + preimage.push(encodeTxid(txid), encodePrevOut(vout), encodeValue(value), Script.encode(scriptPubKey2, true), encodeSequence(sequence)); + } else { + preimage.push(Buff$1.num(index, 4).reverse()); + } + if (annex !== void 0) { + preimage.push(annex); + } + if ((sigflag & 3) === 3) { + preimage.push(hashOutput(output2[index])); + } + if (extension !== void 0) { + preimage.push(Buff$1.bytes(extension), Buff$1.num(key_version), Buff$1.num(separator_pos, 4, "le")); + } + return Buff$1.join(preimage).digest; +} +function hashOutpoints(vin) { + const stack = []; + for (const { txid, vout } of vin) { + stack.push(encodeTxid(txid)); + stack.push(encodePrevOut(vout)); + } + return Buff$1.join(stack).digest; +} +function hashSequence(vin) { + const stack = []; + for (const { sequence } of vin) { + stack.push(encodeSequence(sequence)); + } + return Buff$1.join(stack).digest; +} +function hashAmounts(prevouts) { + const stack = []; + for (const { value } of prevouts) { + stack.push(encodeValue(value)); + } + return Buff$1.join(stack).digest; +} +function hashScripts(prevouts) { + const stack = []; + for (const { scriptPubKey: scriptPubKey2 } of prevouts) { + stack.push(encodeScript(scriptPubKey2, true)); + } + return Buff$1.join(stack).digest; +} +function hashOutputs(vout) { + const stack = []; + for (const { value, scriptPubKey: scriptPubKey2 } of vout) { + stack.push(encodeValue(value)); + stack.push(Script.encode(scriptPubKey2, true)); + } + return Buff$1.join(stack).digest; +} +function hashOutput(vout) { + return Buff$1.join([ + encodeValue(vout.value), + Script.encode(vout.scriptPubKey, true) + ]).digest; +} +function getAnnexData(witness2) { + if (witness2 === void 0) + return; + if (witness2.length < 2) + return; + let annex = witness2.at(-1); + if (typeof annex === "string") { + annex = Buff$1.hex(annex); + } + if (annex instanceof Uint8Array && annex[0] === 80) { + return Buff$1.raw(annex).prefixSize("be").digest; + } + return void 0; +} +function getPrevout(vin) { + if (vin.prevout === void 0) { + throw new Error("Prevout data missing for input: " + String(vin.txid)); + } + return vin.prevout; +} +var FIELD_SIZE = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn; +var CURVE_ORDER = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n; +function signTx(seckey, txdata, index, config = {}) { + const { sigflag = 0 } = config; + const hash2 = hashTx(txdata, index, config); + const sig = sign(seckey, hash2); + return sigflag === 0 ? Buff$1.raw(sig) : Buff$1.join([sig, sigflag]); +} +function sign(secret, message, rand = Buff$1.random(32)) { + const m = Buff$1.bytes(message); + const dp = new Field(secret); + const P2 = dp.point; + const d = P2.hasEvenY ? dp.big : dp.negated.big; + const a = hashTag("BIP0340/aux", Buff$1.bytes(rand)); + const t = d ^ a.big; + const n = hashTag("BIP0340/nonce", t, P2.x.raw, m); + const kp = new Field(n); + const R = kp.point; + const k = R.hasEvenY ? kp.big : kp.negated.big; + const e = new Field(hashTag("BIP0340/challenge", R.x.raw, P2.x.raw, m)); + const s = new Field(k + e.big * d); + return Buff$1.join([R.x.raw, s.raw]); +} +function verify(signature, message, pubkey, shouldThrow = false) { + const P2 = Point.from_x(xOnlyPub(pubkey)); + const m = Buff$1.bytes(message); + const stream = Buff$1.bytes(signature).stream; + if (stream.size < 64) { + safeThrow("Signature length is too small: " + String(stream.size), shouldThrow); + } + const r = stream.read(32); + if (r.big > FIELD_SIZE) { + safeThrow("Signature r value greater than field size!", shouldThrow); + } + const s = stream.read(32); + if (s.big > CURVE_ORDER) { + safeThrow("Signature s value greater than curve order!", shouldThrow); + } + const e = new Field(hashTag("BIP0340/challenge", r.raw, P2.x.raw, m)); + const sG = new Field(s).point; + const eP = P2.mul(e.big); + const R = sG.sub(eP); + if (R.hasOddY) { + safeThrow("Signature R value has odd Y coordinate!", shouldThrow); + } + if (R.x.big === 0n) { + safeThrow("Signature R value is infinite!", shouldThrow); + } + return R.x.big === r.big; +} +var DEFAULT_VERSION$1 = 192; +function getTapTag(tag) { + const htag = Buff$1.str(tag).digest; + return Buff$1.join([htag, htag]); +} +function getTapLeaf(data, version = DEFAULT_VERSION$1) { + return Buff$1.join([ + getTapTag("TapLeaf"), + getVersion(version), + Buff$1.bytes(data) + ]).digest.hex; +} +function getTapBranch(leafA, leafB) { + if (leafB < leafA) { + [leafA, leafB] = [leafB, leafA]; + } + return Buff$1.join([ + getTapTag("TapBranch"), + Buff$1.hex(leafA).raw, + Buff$1.hex(leafB).raw + ]).digest.hex; +} +function getVersion(version = 192) { + return version & 254; +} +function getTapTweak(key2, data = new Uint8Array(), isPrivate = false) { + const pub = isPrivate ? new Field(key2).point.x.raw : xOnlyPub(key2); + return Buff$1.join([getTapTag("TapTweak"), pub, Buff$1.bytes(data)]).digest; +} +function getTweakedKey(intkey, data, isPrivate = false) { + if (data === void 0) + data = new Uint8Array(); + const k = Buff$1.bytes(intkey); + const t = getTapTweak(intkey, data, isPrivate); + if (isPrivate) { + return tweakSecKey(k, t); + } else { + return tweakPubKey(k, t); + } +} +function tweakSecKey(seckey, tweak) { + let sec = new Field(seckey); + if (sec.point.hasOddY) { + sec = sec.negate(); + } + return Buff$1.raw(sec.add(tweak).raw); +} +function tweakPubKey(pubkey, tweak) { + pubkey = xOnlyPub(pubkey); + const P2 = Point.from_x(pubkey); + const Q = P2.add(tweak); + return Buff$1.raw(Q.raw); +} +function getScriptOnlyPubkey() { + const G2 = Buff$1.hex("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"); + return Point.from_x(G2.digest).x; +} +var SCRIPT_PUBKEY = getScriptOnlyPubkey(); +function checkPath(tapkey, target, cblock, config = {}) { + const { isPrivate = false, throws = false } = config; + const { parity, paths, intkey } = readCtrlBlock(cblock); + const pub = isPrivate ? util$1.getPublicKey(tapkey, true) : xOnlyPub(tapkey); + const extkey = Buff$1.join([parity, pub]); + if (extkey.length !== 33) { + return safeThrow("Invalid tapkey: " + extkey.hex, throws); + } + let branch = Buff$1.bytes(target).hex; + for (const path of paths) { + branch = getTapBranch(branch, path); + } + const k = getTweakedKey(intkey, branch); + return Buff$1.raw(k).hex === Buff$1.raw(extkey).hex; +} +function readCtrlBlock(cblock) { + const buffer2 = new Stream$1(Buff$1.bytes(cblock)); + const cbyte = buffer2.read(1).num; + const intkey = buffer2.read(32); + const [version, parity] = cbyte % 2 === 0 ? [cbyte, 2] : [cbyte - 1, 3]; + const paths = []; + while (buffer2.size >= 32) { + paths.push(buffer2.read(32).hex); + } + if (buffer2.size !== 0) { + throw new Error("Non-empty buffer on control block: " + String(buffer2)); + } + return { intkey, paths, parity, version }; +} +function verifyTx(txdata, index, config = {}) { + const tx = Tx.fmt.toJson(txdata); + const { throws = false } = config; + const { prevout, witness: witness2 = [] } = tx.vin[index]; + const witnessData = Tx.util.readWitness(witness2); + const { cblock, script: script2, params } = witnessData; + let pub; + if (params.length < 1) { + return safeThrow("Invalid witness data: " + String(witness2), throws); + } + const { scriptPubKey: scriptPubKey2 } = prevout ?? {}; + if (scriptPubKey2 === void 0) { + return safeThrow("Prevout scriptPubKey is empty!", throws); + } + const { type, data: tapkey } = Tx.util.readScriptPubKey(scriptPubKey2); + if (type !== "p2tr") { + return safeThrow("Prevout script is not a valid taproot output:" + tapkey.hex, throws); + } + if (tapkey.length !== 32) { + return safeThrow("Invalid tapkey length: " + String(tapkey.length), throws); + } + if (cblock !== null && script2 !== null) { + const version = cblock[0] & 254; + const target = getTapLeaf(script2, version); + config.extension = target; + if (!checkPath(tapkey, target, cblock, { throws })) { + return safeThrow("cblock verification failed!", throws); + } + } + if (config.pubkey !== void 0) { + pub = Buff$1.bytes(config.pubkey); + } else if (params.length > 1 && params[1].length === 32) { + pub = Buff$1.bytes(params[1]); + } else { + pub = Buff$1.bytes(tapkey); + } + const rawsig = Script.fmt.toParam(params[0]); + const stream = new Stream$1(rawsig); + const signature = stream.read(64).raw; + if (stream.size === 1) { + config.sigflag = stream.read(1).num; + if (config.sigflag === 0) { + return safeThrow("0x00 is not a valid appended sigflag!", throws); + } + } + const hash2 = hashTx(tx, index, config); + if (!verify(signature, hash2, pub, throws)) { + return safeThrow("Invalid signature!", throws); + } + return true; +} +var TRSigner = { + hash: hashTx, + sign: signTx, + verify: verifyTx +}; +var Signer = { + segwit: SWSigner, + taproot: TRSigner +}; +var NO_LOCK = 1 << 31; +var LOCK_TYPE = 1 << 22; +var util; +(function(util2) { + util2.assertEqual = (val) => val; + function assertIs(_arg) { + } + util2.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util2.assertNever = assertNever; + util2.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util2.getValidEnumValues = (obj) => { + const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util2.objectValues(filtered); + }; + util2.objectValues = (obj) => { + return util2.objectKeys(obj).map(function(e) { + return obj[e]; + }); + }; + util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { + const keys = []; + for (const key2 in object) { + if (Object.prototype.hasOwnProperty.call(object, key2)) { + keys.push(key2); + } + } + return keys; + }; + util2.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return void 0; + }; + util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + } + util2.joinValues = joinValues; + util2.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (util = {})); +var objectUtil; +(function(objectUtil2) { + objectUtil2.mergeShapes = (first, second) => { + return { + ...first, + ...second + // second overwrites first + }; + }; +})(objectUtil || (objectUtil = {})); +var ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" +]); +var getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}; +var ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" +]); +var quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +var ZodError = class extends Error { + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + get errors() { + return this.issues; + } + format(_mapper) { + const mapper = _mapper || function(issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +}; +ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; +}; +var errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } else { + util.assertNever(issue.validation); + } + } else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue); + } + return { message }; +}; +var overrideErrorMap = errorMap; +function setErrorMap(map) { + overrideErrorMap = map; +} +function getErrorMap() { + return overrideErrorMap; +} +var makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + let errorMessage = ""; + const maps = errorMaps.filter((m) => !!m).slice().reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: issueData.message || errorMessage + }; +}; +var EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const issue = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap + // then global default map + ].filter((x) => !!x) + }); + ctx.common.issues.push(issue); +} +var ParseStatus = class _ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + syncPairs.push({ + key: await pair.key, + value: await pair.value + }); + } + return _ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key: key2, value } = pair; + if (key2.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key2.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (typeof value.value !== "undefined" || pair.alwaysSet) { + finalObject[key2.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } +}; +var INVALID = Object.freeze({ + status: "aborted" +}); +var DIRTY = (value) => ({ status: "dirty", value }); +var OK = (value) => ({ status: "valid", value }); +var isAborted = (x) => x.status === "aborted"; +var isDirty = (x) => x.status === "dirty"; +var isValid = (x) => x.status === "valid"; +var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; +var errorUtil; +(function(errorUtil2) { + errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; +})(errorUtil || (errorUtil = {})); +var ParseInputLazyPath = class { + constructor(parent, value, path, key2) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key2; + } + get path() { + if (!this._cachedPath.length) { + if (this._key instanceof Array) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } +}; +var handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + } + }; + } +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; + if (errorMap2 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap2) + return { errorMap: errorMap2, description }; + const customMap = (iss, ctx) => { + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + if (typeof ctx.data === "undefined") { + return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; + } + return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +var ZodType = class { + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + } + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + var _a; + const ctx = { + common: { + issues: [], + async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + async: true + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check2, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val); + } else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check2(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + refinement(check2, refinementData) { + return this._refinement((val, ctx) => { + if (!check2(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this, this._def); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } +}; +var cuidRegex = /^c[^\s-]{8,}$/i; +var cuid2Regex = /^[a-z][a-z0-9]*$/; +var ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/; +var uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; +var emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; +var emojiRegex = new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); +var ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; +var ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; +var datetimeRegex = (args) => { + if (args.precision) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); + } + } else if (args.precision === 0) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); + } + } else { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); + } + } +}; +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +var ZodString = class _ZodString extends ZodType { + constructor() { + super(...arguments); + this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message) + }); + this.nonempty = (message) => this.min(1, errorUtil.errToObj(message)); + this.trim = () => new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + this.toLowerCase = () => new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + this.toUpperCase = () => new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext( + ctx2, + { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx2.parsedType + } + // + ); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + if (input.data.length < check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check2.value, + type: "string", + inclusive: true, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "max") { + if (input.data.length > check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check2.value, + type: "string", + inclusive: true, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "length") { + const tooBig = input.data.length > check2.value; + const tooSmall = input.data.length < check2.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check2.value, + type: "string", + inclusive: true, + exact: true, + message: check2.message + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check2.value, + type: "string", + inclusive: true, + exact: true, + message: check2.message + }); + } + status.dirty(); + } + } else if (check2.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "emoji") { + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "url") { + try { + new URL(input.data); + } catch (_a) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "regex") { + check2.regex.lastIndex = 0; + const testResult = check2.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "trim") { + input.data = input.data.trim(); + } else if (check2.kind === "includes") { + if (!input.data.includes(check2.value, check2.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check2.value, position: check2.position }, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check2.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check2.kind === "startsWith") { + if (!input.data.startsWith(check2.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check2.value }, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "endsWith") { + if (!input.data.endsWith(check2.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check2.value }, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "datetime") { + const regex = datetimeRegex(check2); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "ip") { + if (!isValidIP(input.data, check2.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else { + util.assertNever(check2); + } + } + return { status: status.value, value: input.data }; + } + _addCheck(check2) { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, check2] + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + datetime(options) { + var _a; + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + message: options + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, + offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) + }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options === null || options === void 0 ? void 0 : options.position, + ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message) + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +}; +ZodString.create = (params) => { + var _a; + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params) + }); +}; +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / Math.pow(10, decCount); +} +var ZodNumber = class _ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx2.parsedType + }); + return INVALID; + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check2 of this._def.checks) { + if (check2.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "min") { + const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check2.value, + type: "number", + inclusive: check2.inclusive, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "max") { + const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check2.value, + type: "number", + inclusive: check2.inclusive, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check2.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check2.value, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check2.message + }); + status.dirty(); + } + } else { + util.assertNever(check2); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check2) { + return new _ZodNumber({ + ...this._def, + checks: [...this._def.checks, check2] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + } + get isFinite() { + let max = null, min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +}; +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params) + }); +}; +var ZodBigInt = class _ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + input.data = BigInt(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx2.parsedType + }); + return INVALID; + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check2.value, + inclusive: check2.inclusive, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "max") { + const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check2.value, + inclusive: check2.inclusive, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "multipleOf") { + if (input.data % check2.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check2.value, + message: check2.message + }); + status.dirty(); + } + } else { + util.assertNever(check2); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check2) { + return new _ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check2] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +}; +ZodBigInt.create = (params) => { + var _a; + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params) + }); +}; +var ZodBoolean = class extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params) + }); +}; +var ZodDate = class _ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx2.parsedType + }); + return INVALID; + } + if (isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_date + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + if (input.data.getTime() < check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check2.message, + inclusive: true, + exact: false, + minimum: check2.value, + type: "date" + }); + status.dirty(); + } + } else if (check2.kind === "max") { + if (input.data.getTime() > check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check2.message, + inclusive: true, + exact: false, + maximum: check2.value, + type: "date" + }); + status.dirty(); + } + } else { + util.assertNever(check2); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()) + }; + } + _addCheck(check2) { + return new _ZodDate({ + ...this._def, + checks: [...this._def.checks, check2] + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message) + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message) + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } +}; +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params) + }); +}; +var ZodSymbol = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params) + }); +}; +var ZodUndefined = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params) + }); +}; +var ZodNull = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params) + }); +}; +var ZodAny = class extends ZodType { + constructor() { + super(...arguments); + this._any = true; + } + _parse(input) { + return OK(input.data); + } +}; +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params) + }); +}; +var ZodUnknown = class extends ZodType { + constructor() { + super(...arguments); + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } +}; +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params) + }); +}; +var ZodNever = class extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }); + return INVALID; + } +}; +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params) + }); +}; +var ZodVoid = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params) + }); +}; +var ZodArray = class _ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result2) => { + return ParseStatus.mergeArray(status, result2); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new _ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) } + }); + } + max(maxLength, message) { + return new _ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) } + }); + } + length(len, message) { + return new _ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) } + }); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params) + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key2 in schema.shape) { + const fieldSchema = schema.shape[key2]; + newShape[key2] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element) + }); + } else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } else { + return schema; + } +} +var ZodObject = class _ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + return this._cached = { shape, keys }; + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx2.parsedType + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key2 in ctx.data) { + if (!shapeKeys.includes(key2)) { + extraKeys.push(key2); + } + } + } + const pairs = []; + for (const key2 of shapeKeys) { + const keyValidator = shape[key2]; + const value = ctx.data[key2]; + pairs.push({ + key: { status: "valid", value: key2 }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key2)), + alwaysSet: key2 in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key2 of extraKeys) { + pairs.push({ + key: { status: "valid", value: key2 }, + value: { status: "valid", value: ctx.data[key2] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") ; + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key2 of extraKeys) { + const value = ctx.data[key2]; + pairs.push({ + key: { status: "valid", value: key2 }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key2) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key2 in ctx.data + }); + } + } + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key2 = await pair.key; + syncPairs.push({ + key: key2, + value: await pair.value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + return new _ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { + errorMap: (issue, ctx) => { + var _a, _b, _c, _d; + const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new _ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new _ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new _ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new _ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind.ZodObject + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key2, schema) { + return this.augment({ [key2]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new _ZodObject({ + ...this._def, + catchall: index + }); + } + pick(mask) { + const shape = {}; + util.objectKeys(mask).forEach((key2) => { + if (mask[key2] && this.shape[key2]) { + shape[key2] = this.shape[key2]; + } + }); + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + const shape = {}; + util.objectKeys(this.shape).forEach((key2) => { + if (!mask[key2]) { + shape[key2] = this.shape[key2]; + } + }); + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + util.objectKeys(this.shape).forEach((key2) => { + const fieldSchema = this.shape[key2]; + if (mask && !mask[key2]) { + newShape[key2] = fieldSchema; + } else { + newShape[key2] = fieldSchema.optional(); + } + }); + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + const newShape = {}; + util.objectKeys(this.shape).forEach((key2) => { + if (mask && !mask[key2]) { + newShape[key2] = this.shape[key2]; + } else { + const fieldSchema = this.shape[key2]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key2] = newField; + } + }); + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } +}; +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +var ZodUnion = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = void 0; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues2) => new ZodError(issues2)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + } + get options() { + return this._def.options; + } +}; +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params) + }); +}; +var getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } else if (type instanceof ZodLiteral) { + return [type.value]; + } else if (type instanceof ZodEnum) { + return type.options; + } else if (type instanceof ZodNativeEnum) { + return Object.keys(type.enum); + } else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } else if (type instanceof ZodUndefined) { + return [void 0]; + } else if (type instanceof ZodNull) { + return [null]; + } else { + return null; + } +}; +var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + const optionsMap = /* @__PURE__ */ new Map(); + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new _ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); + } +}; +function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key2) => bKeys.indexOf(key2) !== -1); + const newObj = { ...a, ...b }; + for (const key2 of sharedKeys) { + const sharedValue = mergeValues(a[key2], b[key2]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key2] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } else { + return { valid: false }; + } +} +var ZodIntersection = class extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } + } +}; +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left, + right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params) + }); +}; +var ZodTuple = class _ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }).filter((x) => !!x); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new _ZodTuple({ + ...this._def, + rest + }); + } +}; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params) + }); +}; +var ZodRecord = class _ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key2 in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key2, ctx.path, key2)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key2], ctx.path, key2)) + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new _ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third) + }); + } + return new _ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second) + }); + } +}; +var ZodMap = class extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key2, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key2, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key2 = await pair.key; + const value = await pair.value; + if (key2.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key2.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key2.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = /* @__PURE__ */ new Map(); + for (const pair of pairs) { + const key2 = pair.key; + const value = pair.value; + if (key2.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key2.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key2.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } +}; +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params) + }); +}; +var ZodSet = class _ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements2) { + const parsedSet = /* @__PURE__ */ new Set(); + for (const element of elements2) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements2) => finalizeSet(elements2)); + } else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new _ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) } + }); + } + max(maxSize, message) { + return new _ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) } + }); + } + size(size2, message) { + return this.min(size2, message).max(size2, message); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params) + }); +}; +var ZodFunction = class _ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error + } + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + errorMap + ].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + return OK(async (...args) => { + const error = new ZodError([]); + const parsedArgs = await this._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await fn(...parsedArgs); + const parsedReturns = await this._def.returns._def.type.parseAsync(result, params).catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } else { + return OK((...args) => { + const parsedArgs = this._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = fn(...parsedArgs.data); + const parsedReturns = this._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new _ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) + }); + } + returns(returnType) { + return new _ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new _ZodFunction({ + args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params) + }); + } +}; +var ZodLazy = class extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +}; +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params) + }); +}; +var ZodLiteral = class extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +}; +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params) + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params) + }); +} +var ZodEnum = class _ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (this._def.values.indexOf(input.data) === -1) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values) { + return _ZodEnum.create(values); + } + exclude(values) { + return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); + } +}; +ZodEnum.create = createZodEnum; +var ZodNativeEnum = class extends ZodType { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (nativeEnumValues.indexOf(input.data) === -1) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } +}; +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params) + }); +}; +var ZodPromise = class extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } +}; +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params) + }); +}; +var ZodEffects = class extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data); + if (ctx.common.async) { + return Promise.resolve(processed).then((processed2) => { + return this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + }); + } else { + return this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + } + } + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) + return base; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return base; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); + }); + } + } + util.assertNever(effect); + } +}; +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params) + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params) + }); +}; +var ZodOptional = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(void 0); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params) + }); +}; +var ZodNullable = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params) + }); +}; +var ZodDefault = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } +}; +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params) + }); +}; +var ZodCatch = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + if (isAsync(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + } + removeCatch() { + return this._def.innerType; + } +}; +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params) + }); +}; +var ZodNaN = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } +}; +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params) + }); +}; +var BRAND = Symbol("zod_brand"); +var ZodBranded = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } +}; +var ZodPipeline = class _ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + } + static create(a, b) { + return new _ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline + }); + } +}; +var custom = (check2, params = {}, fatal) => { + if (check2) + return ZodAny.create().superRefine((data, ctx) => { + var _a, _b; + if (!check2(data)) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; + const p2 = typeof p === "string" ? { message: p } : p; + ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); + } + }); + return ZodAny.create(); +}; +var late = { + object: ZodObject.lazycreate +}; +var ZodFirstPartyTypeKind; +(function(ZodFirstPartyTypeKind2) { + ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +var instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}` +}) => custom((data) => data instanceof cls, params); +var stringType = ZodString.create; +var numberType = ZodNumber.create; +var nanType = ZodNaN.create; +var bigIntType = ZodBigInt.create; +var booleanType = ZodBoolean.create; +var dateType = ZodDate.create; +var symbolType = ZodSymbol.create; +var undefinedType = ZodUndefined.create; +var nullType = ZodNull.create; +var anyType = ZodAny.create; +var unknownType = ZodUnknown.create; +var neverType = ZodNever.create; +var voidType = ZodVoid.create; +var arrayType = ZodArray.create; +var objectType = ZodObject.create; +var strictObjectType = ZodObject.strictCreate; +var unionType = ZodUnion.create; +var discriminatedUnionType = ZodDiscriminatedUnion.create; +var intersectionType = ZodIntersection.create; +var tupleType = ZodTuple.create; +var recordType = ZodRecord.create; +var mapType = ZodMap.create; +var setType = ZodSet.create; +var functionType = ZodFunction.create; +var lazyType = ZodLazy.create; +var literalType = ZodLiteral.create; +var enumType = ZodEnum.create; +var nativeEnumType = ZodNativeEnum.create; +var promiseType = ZodPromise.create; +var effectsType = ZodEffects.create; +var optionalType = ZodOptional.create; +var nullableType = ZodNullable.create; +var preprocessType = ZodEffects.createWithPreprocess; +var pipelineType = ZodPipeline.create; +var ostring = () => stringType().optional(); +var onumber = () => numberType().optional(); +var oboolean = () => booleanType().optional(); +var coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })) +}; +var NEVER = INVALID; +var z = /* @__PURE__ */ Object.freeze({ + __proto__: null, + defaultErrorMap: errorMap, + setErrorMap, + getErrorMap, + makeIssue, + EMPTY_PATH, + addIssueToContext, + ParseStatus, + INVALID, + DIRTY, + OK, + isAborted, + isDirty, + isValid, + isAsync, + get util() { + return util; + }, + get objectUtil() { + return objectUtil; + }, + ZodParsedType, + getParsedType, + ZodType, + ZodString, + ZodNumber, + ZodBigInt, + ZodBoolean, + ZodDate, + ZodSymbol, + ZodUndefined, + ZodNull, + ZodAny, + ZodUnknown, + ZodNever, + ZodVoid, + ZodArray, + ZodObject, + ZodUnion, + ZodDiscriminatedUnion, + ZodIntersection, + ZodTuple, + ZodRecord, + ZodMap, + ZodSet, + ZodFunction, + ZodLazy, + ZodLiteral, + ZodEnum, + ZodNativeEnum, + ZodPromise, + ZodEffects, + ZodTransformer: ZodEffects, + ZodOptional, + ZodNullable, + ZodDefault, + ZodCatch, + ZodNaN, + BRAND, + ZodBranded, + ZodPipeline, + custom, + Schema: ZodType, + ZodSchema: ZodType, + late, + get ZodFirstPartyTypeKind() { + return ZodFirstPartyTypeKind; + }, + coerce, + any: anyType, + array: arrayType, + bigint: bigIntType, + boolean: booleanType, + date: dateType, + discriminatedUnion: discriminatedUnionType, + effect: effectsType, + "enum": enumType, + "function": functionType, + "instanceof": instanceOfType, + intersection: intersectionType, + lazy: lazyType, + literal: literalType, + map: mapType, + nan: nanType, + nativeEnum: nativeEnumType, + never: neverType, + "null": nullType, + nullable: nullableType, + number: numberType, + object: objectType, + oboolean, + onumber, + optional: optionalType, + ostring, + pipeline: pipelineType, + preprocess: preprocessType, + promise: promiseType, + record: recordType, + set: setType, + strictObject: strictObjectType, + string: stringType, + symbol: symbolType, + transformer: effectsType, + tuple: tupleType, + "undefined": undefinedType, + union: unionType, + unknown: unknownType, + "void": voidType, + NEVER, + ZodIssueCode, + quotelessJson, + ZodError +}); +var hexstr = z.string().regex(/^[a-fA-F0-9]$/); +var hash = z.string().regex(/^[a-fA-F0-9]{64}$/); +var uint32 = z.number().min(0).max(4294967295); +var uint64 = z.bigint(); +var byteArr = z.instanceof(Uint8Array); +var asmcode = z.union([hexstr, uint32, z.string(), byteArr]).array(); +var script = z.union([asmcode, hexstr, byteArr]); +var witness = z.array(script); +var TxOutput = z.object({ + value: z.union([uint32, uint64]), + scriptPubKey: script +}); +var TxInput = z.object({ + txid: hash, + vout: uint32, + scriptSig: script, + sequence: uint32, + prevout: TxOutput.optional(), + witness +}); +var TxData = z.object({ + version: uint32, + vin: z.array(TxInput), + vout: z.array(TxOutput), + locktime: uint32 +}); + +// node_modules/@noble/hashes/esm/crypto.js +var crypto2 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; + +// node_modules/@noble/hashes/esm/utils.js +function isBytes2(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; +} +function anumber(n) { + if (!Number.isSafeInteger(n) || n < 0) + throw new Error("positive integer expected, got " + n); +} +function abytes(b, ...lengths) { + if (!isBytes2(b)) + throw new Error("Uint8Array expected"); + if (lengths.length > 0 && !lengths.includes(b.length)) + throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length); +} +function ahash(h) { + if (typeof h !== "function" || typeof h.create !== "function") + throw new Error("Hash should be wrapped by utils.createHasher"); + anumber(h.outputLen); + anumber(h.blockLen); +} +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); + const min = instance.outputLen; + if (out.length < min) { + throw new Error("digestInto() expects output buffer of length at least " + min); + } +} +function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} +function createView2(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} +function rotr2(word, shift) { + return word << 32 - shift | word >>> shift; +} +var hasHexBuiltin = /* @__PURE__ */ (() => ( + // @ts-ignore + typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" +))(); +var hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); +function bytesToHex2(bytes2) { + abytes(bytes2); + if (hasHexBuiltin) + return bytes2.toHex(); + let hex = ""; + for (let i = 0; i < bytes2.length; i++) { + hex += hexes2[bytes2[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 hexToBytes2(hex) { + if (typeof hex !== "string") + throw new Error("hex string expected, got " + typeof hex); + if (hasHexBuiltin) + return Uint8Array.fromHex(hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error("hex string expected, got unpadded hex of length " + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === void 0 || n2 === void 0) { + const char = hex[hi] + hex[hi + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; + } + return array; +} +function utf8ToBytes2(str) { + if (typeof str !== "string") + throw new Error("string expected"); + return new Uint8Array(new TextEncoder().encode(str)); +} +function toBytes2(data) { + if (typeof data === "string") + data = utf8ToBytes2(data); + abytes(data); + return data; +} +function concatBytes2(...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; +} +var Hash5 = class { +}; +function createHasher2(hashCons) { + const hashC = (msg) => hashCons().update(toBytes2(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = () => hashCons(); + return hashC; +} +function randomBytes2(bytesLength = 32) { + if (crypto2 && typeof crypto2.getRandomValues === "function") { + return crypto2.getRandomValues(new Uint8Array(bytesLength)); + } + if (crypto2 && typeof crypto2.randomBytes === "function") { + return Uint8Array.from(crypto2.randomBytes(bytesLength)); + } + throw new Error("crypto.getRandomValues must be defined"); +} + +// node_modules/@noble/hashes/esm/_md.js +function setBigUint642(view, byteOffset, value, isLE2) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE2); + const _32n2 = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n2 & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE2 ? 4 : 0; + const l = isLE2 ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE2); + view.setUint32(byteOffset + l, wl, isLE2); +} +function Chi2(a, b, c) { + return a & b ^ ~a & c; +} +function Maj2(a, b, c) { + return a & b ^ a & c ^ b & c; +} +var HashMD = class extends Hash5 { + constructor(blockLen, outputLen, padOffset, isLE2) { + super(); + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE2; + this.buffer = new Uint8Array(blockLen); + this.view = createView2(this.buffer); + } + update(data) { + aexists(this); + data = toBytes2(data); + abytes(data); + const { view, buffer: buffer2, 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 = createView2(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer2.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: buffer2, view, blockLen, isLE: isLE2 } = this; + let { pos } = this; + buffer2[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++) + buffer2[i] = 0; + setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE2); + this.process(view, 0); + const oview = createView2(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE2); + } + digest() { + const { buffer: buffer2, outputLen } = this; + this.digestInto(buffer2); + const res = buffer2.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + if (length % blockLen) + to.buffer.set(buffer2); + return to; + } + clone() { + return this._cloneInto(); + } +}; +var SHA256_IV = /* @__PURE__ */ Uint32Array.from([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); + +// node_modules/@noble/hashes/esm/sha2.js +var SHA256_K2 = /* @__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_W2 = /* @__PURE__ */ new Uint32Array(64); +var SHA2565 = class extends HashMD { + constructor(outputLen = 32) { + super(64, outputLen, 8, false); + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; + } + get() { + const { A, B, C, D, E, F, G: G2, H } = this; + return [A, B, C, D, E, F, G2, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G2, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G2 | 0; + this.H = H | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W2[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W2[i - 15]; + const W2 = SHA256_W2[i - 2]; + const s0 = rotr2(W15, 7) ^ rotr2(W15, 18) ^ W15 >>> 3; + const s1 = rotr2(W2, 17) ^ rotr2(W2, 19) ^ W2 >>> 10; + SHA256_W2[i] = s1 + SHA256_W2[i - 7] + s0 + SHA256_W2[i - 16] | 0; + } + let { A, B, C, D, E, F, G: G2, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr2(E, 6) ^ rotr2(E, 11) ^ rotr2(E, 25); + const T1 = H + sigma1 + Chi2(E, F, G2) + SHA256_K2[i] + SHA256_W2[i] | 0; + const sigma0 = rotr2(A, 2) ^ rotr2(A, 13) ^ rotr2(A, 22); + const T2 = sigma0 + Maj2(A, B, C) | 0; + H = G2; + G2 = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G2 = G2 + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G2, H); + } + roundClean() { + clean(SHA256_W2); + } + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + clean(this.buffer); + } +}; +var sha2562 = /* @__PURE__ */ createHasher2(() => new SHA2565()); + +// node_modules/@noble/hashes/esm/hmac.js +var HMAC3 = class extends Hash5 { + constructor(hash2, _key) { + super(); + this.finished = false; + this.destroyed = false; + ahash(hash2); + const key2 = toBytes2(_key); + this.iHash = hash2.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + pad.set(key2.length > blockLen ? hash2.create().update(key2).digest() : key2); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54; + this.iHash.update(pad); + this.oHash = hash2.create(); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54 ^ 92; + this.oHash.update(pad); + clean(pad); + } + update(buf) { + aexists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + aexists(this); + abytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + clone() { + return this._cloneInto(); + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +}; +var hmac = (hash2, key2, message) => new HMAC3(hash2, key2).update(message).digest(); +hmac.create = (hash2, key2) => new HMAC3(hash2, key2); + +// node_modules/@noble/curves/esm/utils.js +var _0n2 = /* @__PURE__ */ BigInt(0); +var _1n2 = /* @__PURE__ */ BigInt(1); +function _abool2(value, title = "") { + if (typeof value !== "boolean") { + const prefix = title && `"${title}"`; + throw new Error(prefix + "expected boolean, got type=" + typeof value); + } + return value; +} +function _abytes2(value, length, title = "") { + const bytes2 = isBytes2(value); + const len = value?.length; + const needsLen = length !== void 0; + if (!bytes2 || needsLen && len !== length) { + const prefix = title && `"${title}" `; + const ofLen = needsLen ? ` of length ${length}` : ""; + const got = bytes2 ? `length=${len}` : `type=${typeof value}`; + throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got); + } + return value; +} +function numberToHexUnpadded2(num2) { + const hex = num2.toString(16); + return hex.length & 1 ? "0" + hex : hex; +} +function hexToNumber2(hex) { + if (typeof hex !== "string") + throw new Error("hex string expected, got " + typeof hex); + return hex === "" ? _0n2 : BigInt("0x" + hex); +} +function bytesToNumberBE2(bytes2) { + return hexToNumber2(bytesToHex2(bytes2)); +} +function bytesToNumberLE2(bytes2) { + abytes(bytes2); + return hexToNumber2(bytesToHex2(Uint8Array.from(bytes2).reverse())); +} +function numberToBytesBE2(n, len) { + return hexToBytes2(n.toString(16).padStart(len * 2, "0")); +} +function numberToBytesLE2(n, len) { + return numberToBytesBE2(n, len).reverse(); +} +function ensureBytes2(title, hex, expectedLength) { + let res; + if (typeof hex === "string") { + try { + res = hexToBytes2(hex); + } catch (e) { + throw new Error(title + " must be hex string or Uint8Array, cause: " + e); + } + } else if (isBytes2(hex)) { + res = Uint8Array.from(hex); + } else { + throw new Error(title + " must be hex string or Uint8Array"); + } + const len = res.length; + if (typeof expectedLength === "number" && len !== expectedLength) + throw new Error(title + " of length " + expectedLength + " expected, got " + len); + return res; +} +var isPosBig = (n) => typeof n === "bigint" && _0n2 <= n; +function inRange(n, min, max) { + return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; +} +function aInRange(title, n, min, max) { + if (!inRange(n, min, max)) + throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); +} +function bitLen2(n) { + let len; + for (len = 0; n > _0n2; n >>= _1n2, len += 1) + ; + return len; +} +var bitMask2 = (n) => (_1n2 << BigInt(n)) - _1n2; +function createHmacDrbg2(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== "number" || hashLen < 2) + throw new Error("hashLen must be a number"); + if (typeof qByteLen !== "number" || qByteLen < 2) + throw new Error("qByteLen must be a number"); + if (typeof hmacFn !== "function") + throw new Error("hmacFn must be a function"); + const u8n2 = (len) => new Uint8Array(len); + const u8of = (byte) => Uint8Array.of(byte); + let v = u8n2(hashLen); + let k = u8n2(hashLen); + let i = 0; + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); + const reseed = (seed = u8n2(0)) => { + k = h(u8of(0), seed); + v = h(); + if (seed.length === 0) + return; + k = h(u8of(1), seed); + v = h(); + }; + const gen = () => { + if (i++ >= 1e3) + throw new Error("drbg: tried 1000 values"); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes2(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); + let res = void 0; + while (!(res = pred(gen()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +function _validateObject(object, fields, optFields = {}) { + if (!object || typeof object !== "object") + throw new Error("expected valid options object"); + function checkField(fieldName, expectedType, isOpt) { + const val = object[fieldName]; + if (isOpt && val === void 0) + return; + const current = typeof val; + if (current !== expectedType || val === null) + throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`); + } + Object.entries(fields).forEach(([k, v]) => checkField(k, v, false)); + Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true)); +} +function memoized(fn) { + const map = /* @__PURE__ */ new WeakMap(); + return (arg, ...args) => { + const val = map.get(arg); + if (val !== void 0) + return val; + const computed = fn(arg, ...args); + map.set(arg, computed); + return computed; + }; +} + +// node_modules/@noble/curves/esm/abstract/modular.js +var _0n3 = BigInt(0); +var _1n3 = BigInt(1); +var _2n2 = /* @__PURE__ */ BigInt(2); +var _3n2 = /* @__PURE__ */ BigInt(3); +var _4n2 = /* @__PURE__ */ BigInt(4); +var _5n2 = /* @__PURE__ */ BigInt(5); +var _7n = /* @__PURE__ */ BigInt(7); +var _8n2 = /* @__PURE__ */ BigInt(8); +var _9n = /* @__PURE__ */ BigInt(9); +var _16n = /* @__PURE__ */ BigInt(16); +function mod2(a, b) { + const result = a % b; + return result >= _0n3 ? result : b + result; +} +function pow22(x, power, modulo) { + let res = x; + while (power-- > _0n3) { + res *= res; + res %= modulo; + } + return res; +} +function invert2(number2, modulo) { + if (number2 === _0n3) + throw new Error("invert: expected non-zero number"); + if (modulo <= _0n3) + throw new Error("invert: expected positive modulus, got " + modulo); + let a = mod2(number2, modulo); + let b = modulo; + let x = _0n3, y = _1n3, u = _1n3, v = _0n3; + while (a !== _0n3) { + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n3) + throw new Error("invert: does not exist"); + return mod2(x, modulo); +} +function assertIsSquare(Fp2, root, n) { + if (!Fp2.eql(Fp2.sqr(root), n)) + throw new Error("Cannot find square root"); +} +function sqrt3mod4(Fp2, n) { + const p1div4 = (Fp2.ORDER + _1n3) / _4n2; + const root = Fp2.pow(n, p1div4); + assertIsSquare(Fp2, root, n); + return root; +} +function sqrt5mod8(Fp2, n) { + const p5div8 = (Fp2.ORDER - _5n2) / _8n2; + const n2 = Fp2.mul(n, _2n2); + const v = Fp2.pow(n2, p5div8); + const nv = Fp2.mul(n, v); + const i = Fp2.mul(Fp2.mul(nv, _2n2), v); + const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); + assertIsSquare(Fp2, root, n); + return root; +} +function sqrt9mod16(P2) { + const Fp_ = Field2(P2); + const tn = tonelliShanks2(P2); + const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); + const c2 = tn(Fp_, c1); + const c3 = tn(Fp_, Fp_.neg(c1)); + const c4 = (P2 + _7n) / _16n; + return (Fp2, n) => { + let tv1 = Fp2.pow(n, c4); + let tv2 = Fp2.mul(tv1, c1); + const tv3 = Fp2.mul(tv1, c2); + const tv4 = Fp2.mul(tv1, c3); + const e1 = Fp2.eql(Fp2.sqr(tv2), n); + const e2 = Fp2.eql(Fp2.sqr(tv3), n); + tv1 = Fp2.cmov(tv1, tv2, e1); + tv2 = Fp2.cmov(tv4, tv3, e2); + const e3 = Fp2.eql(Fp2.sqr(tv2), n); + const root = Fp2.cmov(tv1, tv2, e3); + assertIsSquare(Fp2, root, n); + return root; + }; +} +function tonelliShanks2(P2) { + if (P2 < _3n2) + throw new Error("sqrt is not defined for small field"); + let Q = P2 - _1n3; + let S = 0; + while (Q % _2n2 === _0n3) { + Q /= _2n2; + S++; + } + let Z = _2n2; + const _Fp = Field2(P2); + 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, Q); + const Q1div2 = (Q + _1n3) / _2n2; + return function tonelliSlow(Fp2, n) { + if (Fp2.is0(n)) + return n; + if (FpLegendre(Fp2, n) !== 1) + throw new Error("Cannot find square root"); + let M = S; + let c = Fp2.mul(Fp2.ONE, cc); + let t = Fp2.pow(n, Q); + let R = Fp2.pow(n, Q1div2); + while (!Fp2.eql(t, Fp2.ONE)) { + if (Fp2.is0(t)) + return Fp2.ZERO; + let i = 1; + let t_tmp = Fp2.sqr(t); + while (!Fp2.eql(t_tmp, Fp2.ONE)) { + i++; + t_tmp = Fp2.sqr(t_tmp); + if (i === M) + throw new Error("Cannot find square root"); + } + const exponent = _1n3 << BigInt(M - i - 1); + const b = Fp2.pow(c, exponent); + M = i; + c = Fp2.sqr(b); + t = Fp2.mul(t, c); + R = Fp2.mul(R, b); + } + return R; + }; +} +function FpSqrt2(P2) { + if (P2 % _4n2 === _3n2) + return sqrt3mod4; + if (P2 % _8n2 === _5n2) + return sqrt5mod8; + if (P2 % _16n === _9n) + return sqrt9mod16(P2); + return tonelliShanks2(P2); +} +var FIELD_FIELDS2 = [ + "create", + "isValid", + "is0", + "neg", + "inv", + "sqrt", + "sqr", + "eql", + "add", + "sub", + "mul", + "pow", + "div", + "addN", + "subN", + "mulN", + "sqrN" +]; +function validateField2(field) { + const initial = { + ORDER: "bigint", + MASK: "bigint", + BYTES: "number", + BITS: "number" + }; + const opts = FIELD_FIELDS2.reduce((map, val) => { + map[val] = "function"; + return map; + }, initial); + _validateObject(field, opts); + return field; +} +function FpPow2(Fp2, num2, power) { + if (power < _0n3) + throw new Error("invalid exponent, negatives unsupported"); + if (power === _0n3) + return Fp2.ONE; + if (power === _1n3) + return num2; + let p = Fp2.ONE; + let d = num2; + while (power > _0n3) { + if (power & _1n3) + p = Fp2.mul(p, d); + d = Fp2.sqr(d); + power >>= _1n3; + } + return p; +} +function FpInvertBatch2(Fp2, nums, passZero = false) { + const inverted = new Array(nums.length).fill(passZero ? Fp2.ZERO : void 0); + const multipliedAcc = nums.reduce((acc, num2, i) => { + if (Fp2.is0(num2)) + return acc; + inverted[i] = acc; + return Fp2.mul(acc, num2); + }, Fp2.ONE); + const invertedAcc = Fp2.inv(multipliedAcc); + nums.reduceRight((acc, num2, i) => { + if (Fp2.is0(num2)) + return acc; + inverted[i] = Fp2.mul(acc, inverted[i]); + return Fp2.mul(acc, num2); + }, invertedAcc); + return inverted; +} +function FpLegendre(Fp2, n) { + const p1mod2 = (Fp2.ORDER - _1n3) / _2n2; + const powered = Fp2.pow(n, p1mod2); + const yes = Fp2.eql(powered, Fp2.ONE); + const zero = Fp2.eql(powered, Fp2.ZERO); + const no = Fp2.eql(powered, Fp2.neg(Fp2.ONE)); + if (!yes && !zero && !no) + throw new Error("invalid Legendre symbol result"); + return yes ? 1 : zero ? 0 : -1; +} +function nLength2(n, nBitLength) { + if (nBitLength !== void 0) + anumber(nBitLength); + const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +function Field2(ORDER, bitLenOrOpts, isLE2 = false, opts = {}) { + if (ORDER <= _0n3) + throw new Error("invalid field: expected ORDER > 0, got " + ORDER); + let _nbitLength = void 0; + let _sqrt = void 0; + let modFromBytes = false; + let allowedLengths = void 0; + if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) { + if (opts.sqrt || isLE2) + throw new Error("cannot specify opts in two arguments"); + const _opts = bitLenOrOpts; + if (_opts.BITS) + _nbitLength = _opts.BITS; + if (_opts.sqrt) + _sqrt = _opts.sqrt; + if (typeof _opts.isLE === "boolean") + isLE2 = _opts.isLE; + if (typeof _opts.modFromBytes === "boolean") + modFromBytes = _opts.modFromBytes; + allowedLengths = _opts.allowedLengths; + } else { + if (typeof bitLenOrOpts === "number") + _nbitLength = bitLenOrOpts; + if (opts.sqrt) + _sqrt = opts.sqrt; + } + const { nBitLength: BITS, nByteLength: BYTES } = nLength2(ORDER, _nbitLength); + if (BYTES > 2048) + throw new Error("invalid field: expected ORDER of <= 2048 bytes"); + let sqrtP; + const f2 = Object.freeze({ + ORDER, + isLE: isLE2, + BITS, + BYTES, + MASK: bitMask2(BITS), + ZERO: _0n3, + ONE: _1n3, + allowedLengths, + create: (num2) => mod2(num2, ORDER), + isValid: (num2) => { + if (typeof num2 !== "bigint") + throw new Error("invalid field element: expected bigint, got " + typeof num2); + return _0n3 <= num2 && num2 < ORDER; + }, + is0: (num2) => num2 === _0n3, + // is valid and invertible + isValidNot0: (num2) => !f2.is0(num2) && f2.isValid(num2), + isOdd: (num2) => (num2 & _1n3) === _1n3, + neg: (num2) => mod2(-num2, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num2) => mod2(num2 * num2, ORDER), + add: (lhs, rhs) => mod2(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod2(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod2(lhs * rhs, ORDER), + pow: (num2, power) => FpPow2(f2, num2, power), + div: (lhs, rhs) => mod2(lhs * invert2(rhs, ORDER), ORDER), + // Same as above, but doesn't normalize + sqrN: (num2) => num2 * num2, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num2) => invert2(num2, ORDER), + sqrt: _sqrt || ((n) => { + if (!sqrtP) + sqrtP = FpSqrt2(ORDER); + return sqrtP(f2, n); + }), + toBytes: (num2) => isLE2 ? numberToBytesLE2(num2, BYTES) : numberToBytesBE2(num2, BYTES), + fromBytes: (bytes2, skipValidation = true) => { + if (allowedLengths) { + if (!allowedLengths.includes(bytes2.length) || bytes2.length > BYTES) { + throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes2.length); + } + const padded = new Uint8Array(BYTES); + padded.set(bytes2, isLE2 ? 0 : padded.length - bytes2.length); + bytes2 = padded; + } + if (bytes2.length !== BYTES) + throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes2.length); + let scalar = isLE2 ? bytesToNumberLE2(bytes2) : bytesToNumberBE2(bytes2); + if (modFromBytes) + scalar = mod2(scalar, ORDER); + if (!skipValidation) { + if (!f2.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) => FpInvertBatch2(f2, lst), + // We can't move this out because Fp6, Fp12 implement it + // and it's unclear what to return in there. + cmov: (a, b, c) => c ? b : a + }); + return Object.freeze(f2); +} +function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== "bigint") + throw new Error("field order must be bigint"); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +function mapHashToField(key2, fieldOrder, isLE2 = false) { + const len = key2.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + if (len < 16 || len < minLen || len > 1024) + throw new Error("expected " + minLen + "-1024 bytes of input, got " + len); + const num2 = isLE2 ? bytesToNumberLE2(key2) : bytesToNumberBE2(key2); + const reduced = mod2(num2, fieldOrder - _1n3) + _1n3; + return isLE2 ? numberToBytesLE2(reduced, fieldLen) : numberToBytesBE2(reduced, fieldLen); +} + +// node_modules/@noble/curves/esm/abstract/curve.js +var _0n4 = BigInt(0); +var _1n4 = BigInt(1); +function negateCt(condition, item) { + const neg = item.negate(); + return condition ? neg : item; +} +function normalizeZ(c, points) { + const invertedZs = FpInvertBatch2(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 = bitMask2(W); + const shiftBy = BigInt(W); + return { windows, windowSize, mask, maxNumber, shiftBy }; +} +function calcOffsets(n, window2, wOpts) { + const { windowSize, mask, maxNumber, shiftBy } = wOpts; + let wbits = Number(n & mask); + let nextN = n >> shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + nextN += _1n4; + } + const offsetStart = window2 * windowSize; + const offset = offsetStart + Math.abs(wbits) - 1; + const isZero = wbits === 0; + const isNeg = wbits < 0; + const isNegF = window2 % 2 !== 0; + const offsetF = offsetStart; + return { nextN, offset, isZero, isNeg, isNegF, offsetF }; +} +function validateMSMPoints(points, c) { + if (!Array.isArray(points)) + throw new Error("array expected"); + points.forEach((p, i) => { + if (!(p instanceof c)) + throw new Error("invalid point at index " + i); + }); +} +function validateMSMScalars(scalars, field) { + if (!Array.isArray(scalars)) + throw new Error("array of scalars expected"); + scalars.forEach((s, i) => { + if (!field.isValid(s)) + throw new Error("invalid scalar at index " + i); + }); +} +var pointPrecomputes = /* @__PURE__ */ new WeakMap(); +var pointWindowSizes = /* @__PURE__ */ new WeakMap(); +function getW(P2) { + return pointWindowSizes.get(P2) || 1; +} +function assert0(n) { + if (n !== _0n4) + throw new Error("invalid wNAF"); +} +var wNAF2 = class { + // Parametrized with a given Point class (not individual point) + constructor(Point2, 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 > _0n4) { + if (n & _1n4) + p = p.add(d); + d = d.double(); + n >>= _1n4; + } + 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 window2 = 0; window2 < windows; window2++) { + 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 f2 = this.BASE; + const wo = calcWOpts(W, this.bits); + for (let window2 = 0; window2 < wo.windows; window2++) { + const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window2, wo); + n = nextN; + if (isZero) { + f2 = f2.add(negateCt(isNegF, precomputes[offsetF])); + } else { + p = p.add(negateCt(isNeg, precomputes[offset])); + } + } + assert0(n); + return { p, f: f2 }; + } + /** + * Implements ec unsafe (non const-time) 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 window2 = 0; window2 < wo.windows; window2++) { + if (n === _0n4) + break; + const { nextN, offset, isZero, isNeg } = calcOffsets(n, window2, 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(P2, W) { + validateW(W, this.bits); + pointWindowSizes.set(P2, W); + pointPrecomputes.delete(P2); + } + 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 > _0n4 || k2 > _0n4) { + if (k1 & _1n4) + p1 = p1.add(acc); + if (k2 & _1n4) + p2 = p2.add(acc); + acc = acc.double(); + k1 >>= _1n4; + k2 >>= _1n4; + } + return { p1, p2 }; +} +function pippenger(c, fieldN, points, scalars) { + validateMSMPoints(points, c); + validateMSMScalars(scalars, fieldN); + const plength = points.length; + const slength = scalars.length; + if (plength !== slength) + throw new Error("arrays of points and scalars must have equal length"); + const zero = c.ZERO; + const wbits = bitLen2(BigInt(plength)); + let windowSize = 1; + if (wbits > 12) + windowSize = wbits - 3; + else if (wbits > 4) + windowSize = wbits - 2; + else if (wbits > 0) + windowSize = 2; + const MASK = bitMask2(windowSize); + const buckets = new Array(Number(MASK) + 1).fill(zero); + const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize; + let sum = zero; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(zero); + for (let j = 0; j < slength; j++) { + const scalar = scalars[j]; + const wbits2 = Number(scalar >> BigInt(i) & MASK); + buckets[wbits2] = buckets[wbits2].add(points[j]); + } + let resI = zero; + for (let j = buckets.length - 1, sumI = zero; j > 0; j--) { + sumI = sumI.add(buckets[j]); + resI = resI.add(sumI); + } + sum = sum.add(resI); + if (i !== 0) + for (let j = 0; j < windowSize; j++) + sum = sum.double(); + } + return sum; +} +function createField(order, field, isLE2) { + if (field) { + if (field.ORDER !== order) + throw new Error("Field.ORDER must match order: Fp == p, Fn == n"); + validateField2(field); + return field; + } else { + return Field2(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 > _0n4)) + throw new Error(`CURVE.${p} must be positive bigint`); + } + const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE); + const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE); + const _b = type === "weierstrass" ? "b" : "d"; + const params = ["Gx", "Gy", "a", _b]; + for (const p of params) { + if (!Fp2.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: Fp2, Fn }; +} + +// node_modules/@noble/curves/esm/abstract/weierstrass.js +var divNearest2 = (num2, den) => (num2 + (num2 >= 0 ? den : -den) / _2n3) / den; +function _splitEndoScalar(k, basis, n) { + const [[a1, b1], [a2, b2]] = basis; + const c1 = divNearest2(b2 * k, n); + const c2 = divNearest2(-b1 * k, n); + let k1 = k - c1 * a1 - c2 * a2; + let k2 = -c1 * b1 - c2 * b2; + const k1neg = k1 < _0n5; + const k2neg = k2 < _0n5; + if (k1neg) + k1 = -k1; + if (k2neg) + k2 = -k2; + const MAX_NUM = bitMask2(Math.ceil(bitLen2(n) / 2)) + _1n5; + if (k1 < _0n5 || k1 >= MAX_NUM || k2 < _0n5 || k2 >= MAX_NUM) { + throw new Error("splitScalar (endomorphism): failed, k=" + 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(opts, def) { + const optsn = {}; + for (let optName of Object.keys(def)) { + optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName]; + } + _abool2(optsn.lowS, "lowS"); + _abool2(optsn.prehash, "prehash"); + if (optsn.format !== void 0) + validateSigFormat(optsn.format); + return optsn; +} +var DERErr2 = class extends Error { + constructor(m = "") { + super(m); + } +}; +var DER2 = { + // asn.1 DER encoding utils + Err: DERErr2, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag, data) => { + const { Err: E } = DER2; + if (tag < 0 || tag > 256) + throw new E("tlv.encode: wrong tag"); + if (data.length & 1) + throw new E("tlv.encode: unpadded data"); + const dataLen = data.length / 2; + const len = numberToHexUnpadded2(dataLen); + if (len.length / 2 & 128) + throw new E("tlv.encode: long form length too big"); + const lenLen = dataLen > 127 ? numberToHexUnpadded2(len.length / 2 | 128) : ""; + const t = numberToHexUnpadded2(tag); + return t + lenLen + len + data; + }, + // v - value, l - left bytes (unparsed) + decode(tag, data) { + const { Err: E } = DER2; + let pos = 0; + if (tag < 0 || tag > 256) + throw new E("tlv.encode: wrong tag"); + if (data.length < 2 || data[pos++] !== tag) + throw new E("tlv.decode: wrong tlv"); + const first = data[pos++]; + const isLong = !!(first & 128); + let length = 0; + if (!isLong) + length = first; + else { + const lenLen = first & 127; + if (!lenLen) + throw new E("tlv.decode(long): indefinite length not supported"); + if (lenLen > 4) + throw new E("tlv.decode(long): byte length is too big"); + const lengthBytes = data.subarray(pos, pos + lenLen); + if (lengthBytes.length !== lenLen) + throw new E("tlv.decode: length bytes not complete"); + if (lengthBytes[0] === 0) + throw new E("tlv.decode(long): zero leftmost byte"); + for (const b of lengthBytes) + length = length << 8 | b; + pos += lenLen; + if (length < 128) + throw new E("tlv.decode(long): not minimal encoding"); + } + const v = data.subarray(pos, pos + length); + if (v.length !== length) + throw new E("tlv.decode: wrong value length"); + return { v, l: data.subarray(pos + length) }; + } + }, + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + _int: { + encode(num2) { + const { Err: E } = DER2; + if (num2 < _0n5) + throw new E("integer: negative integers are not allowed"); + let hex = numberToHexUnpadded2(num2); + 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 } = DER2; + if (data[0] & 128) + throw new E("invalid signature integer: negative"); + if (data[0] === 0 && !(data[1] & 128)) + throw new E("invalid signature integer: unnecessary leading zero"); + return bytesToNumberBE2(data); + } + }, + toSig(hex) { + const { Err: E, _int: int, _tlv: tlv } = DER2; + const data = ensureBytes2("signature", hex); + 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 } = DER2; + 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); + } +}; +var _0n5 = BigInt(0); +var _1n5 = BigInt(1); +var _2n3 = BigInt(2); +var _3n3 = BigInt(3); +var _4n3 = BigInt(4); +function _normFnElement(Fn, key2) { + const { BYTES: expected } = Fn; + let num2; + if (typeof key2 === "bigint") { + num2 = key2; + } else { + let bytes2 = ensureBytes2("private key", key2); + try { + num2 = Fn.fromBytes(bytes2); + } catch (error) { + throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key2}`); + } + } + if (!Fn.isValidNot0(num2)) + throw new Error("invalid private key: out of range [1..N-1]"); + return num2; +} +function weierstrassN(params, extraOpts = {}) { + const validated = _createCurveFields("weierstrass", params, extraOpts); + const { Fp: Fp2, Fn } = validated; + let CURVE = validated.CURVE; + const { h: cofactor, n: CURVE_ORDER2 } = CURVE; + _validateObject(extraOpts, {}, { + allowInfinityPoint: "boolean", + clearCofactor: "function", + isTorsionFree: "function", + fromBytes: "function", + toBytes: "function", + endo: "object", + wrapPrivateKey: "boolean" + }); + const { endo } = extraOpts; + if (endo) { + if (!Fp2.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(Fp2, Fn); + function assertCompressionIsSupported() { + if (!Fp2.isOdd) + throw new Error("compression is not supported: Field does not have .isOdd()"); + } + function pointToBytes3(_c, point, isCompressed) { + const { x, y } = point.toAffine(); + const bx = Fp2.toBytes(x); + _abool2(isCompressed, "isCompressed"); + if (isCompressed) { + assertCompressionIsSupported(); + const hasEvenY = !Fp2.isOdd(y); + return concatBytes2(pprefix(hasEvenY), bx); + } else { + return concatBytes2(Uint8Array.of(4), bx, Fp2.toBytes(y)); + } + } + function pointFromBytes(bytes2) { + _abytes2(bytes2, void 0, "Point"); + const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; + const length = bytes2.length; + const head = bytes2[0]; + const tail = bytes2.subarray(1); + if (length === comp && (head === 2 || head === 3)) { + const x = Fp2.fromBytes(tail); + if (!Fp2.isValid(x)) + throw new Error("bad point: is not on curve, wrong x"); + const y2 = weierstrassEquation(x); + let y; + try { + y = Fp2.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 isYOdd = Fp2.isOdd(y); + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp2.neg(y); + return { x, y }; + } else if (length === uncomp && head === 4) { + const L = Fp2.BYTES; + const x = Fp2.fromBytes(tail.subarray(0, L)); + const y = Fp2.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 || pointToBytes3; + const decodePoint = extraOpts.fromBytes || pointFromBytes; + function weierstrassEquation(x) { + const x2 = Fp2.sqr(x); + const x3 = Fp2.mul(x2, x); + return Fp2.add(Fp2.add(x3, Fp2.mul(x, CURVE.a)), CURVE.b); + } + function isValidXY(x, y) { + const left = Fp2.sqr(y); + const right = weierstrassEquation(x); + return Fp2.eql(left, right); + } + if (!isValidXY(CURVE.Gx, CURVE.Gy)) + throw new Error("bad curve params: generator point"); + const _4a3 = Fp2.mul(Fp2.pow(CURVE.a, _3n3), _4n3); + const _27b2 = Fp2.mul(Fp2.sqr(CURVE.b), BigInt(27)); + if (Fp2.is0(Fp2.add(_4a3, _27b2))) + throw new Error("bad curve params: a or b"); + function acoord(title, n, banZero = false) { + if (!Fp2.isValid(n) || banZero && Fp2.is0(n)) + throw new Error(`bad point coordinate ${title}`); + return n; + } + function aprjpoint(other) { + if (!(other instanceof Point2)) + throw new Error("ProjectivePoint expected"); + } + function splitEndoScalarN(k) { + if (!endo || !endo.basises) + throw new Error("no endo"); + return _splitEndoScalar(k, endo.basises, Fn.ORDER); + } + const toAffineMemo = memoized((p, iz) => { + const { X, Y, Z } = p; + if (Fp2.eql(Z, Fp2.ONE)) + return { x: X, y: Y }; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? Fp2.ONE : Fp2.inv(Z); + const x = Fp2.mul(X, iz); + const y = Fp2.mul(Y, iz); + const zz = Fp2.mul(Z, iz); + if (is0) + return { x: Fp2.ZERO, y: Fp2.ZERO }; + if (!Fp2.eql(zz, Fp2.ONE)) + throw new Error("invZ was invalid"); + return { x, y }; + }); + const assertValidMemo = memoized((p) => { + if (p.is0()) { + if (extraOpts.allowInfinityPoint && !Fp2.is0(p.Y)) + return; + throw new Error("bad point: ZERO"); + } + const { x, y } = p.toAffine(); + if (!Fp2.isValid(x) || !Fp2.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"); + return true; + }); + function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) { + k2p = new Point2(Fp2.mul(k2p.X, endoBeta), k2p.Y, k2p.Z); + k1p = negateCt(k1neg, k1p); + k2p = negateCt(k2neg, k2p); + return k1p.add(k2p); + } + class Point2 { + /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ + constructor(X, Y, 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 || !Fp2.isValid(x) || !Fp2.isValid(y)) + throw new Error("invalid affine point"); + if (p instanceof Point2) + throw new Error("projective point not allowed"); + if (Fp2.is0(x) && Fp2.is0(y)) + return Point2.ZERO; + return new Point2(x, y, Fp2.ONE); + } + static fromBytes(bytes2) { + const P2 = Point2.fromAffine(decodePoint(_abytes2(bytes2, void 0, "point"))); + P2.assertValidity(); + return P2; + } + static fromHex(hex) { + return Point2.fromBytes(ensureBytes2("pointHex", 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(_3n3); + return this; + } + // TODO: return `this` + /** A point on curve is valid if it conforms to equation. */ + assertValidity() { + assertValidMemo(this); + } + hasEvenY() { + const { y } = this.toAffine(); + if (!Fp2.isOdd) + throw new Error("Field doesn't support isOdd"); + return !Fp2.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 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); + const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); + return U1 && U2; + } + /** Flips point to one corresponding to (x, -y) in Affine coordinates. */ + negate() { + return new Point2(this.X, Fp2.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 = Fp2.mul(b, _3n3); + const { X: X1, Y: Y1, Z: Z1 } = this; + let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + let t0 = Fp2.mul(X1, X1); + let t1 = Fp2.mul(Y1, Y1); + let t2 = Fp2.mul(Z1, Z1); + let t3 = Fp2.mul(X1, Y1); + t3 = Fp2.add(t3, t3); + Z3 = Fp2.mul(X1, Z1); + Z3 = Fp2.add(Z3, Z3); + X3 = Fp2.mul(a, Z3); + Y3 = Fp2.mul(b3, t2); + Y3 = Fp2.add(X3, Y3); + X3 = Fp2.sub(t1, Y3); + Y3 = Fp2.add(t1, Y3); + Y3 = Fp2.mul(X3, Y3); + X3 = Fp2.mul(t3, X3); + Z3 = Fp2.mul(b3, Z3); + t2 = Fp2.mul(a, t2); + t3 = Fp2.sub(t0, t2); + t3 = Fp2.mul(a, t3); + t3 = Fp2.add(t3, Z3); + Z3 = Fp2.add(t0, t0); + t0 = Fp2.add(Z3, t0); + t0 = Fp2.add(t0, t2); + t0 = Fp2.mul(t0, t3); + Y3 = Fp2.add(Y3, t0); + t2 = Fp2.mul(Y1, Z1); + t2 = Fp2.add(t2, t2); + t0 = Fp2.mul(t2, t3); + X3 = Fp2.sub(X3, t0); + Z3 = Fp2.mul(t2, t1); + Z3 = Fp2.add(Z3, Z3); + Z3 = Fp2.add(Z3, Z3); + return new Point2(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 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; + const a = CURVE.a; + const b3 = Fp2.mul(CURVE.b, _3n3); + let t0 = Fp2.mul(X1, X2); + let t1 = Fp2.mul(Y1, Y2); + let t2 = Fp2.mul(Z1, Z2); + let t3 = Fp2.add(X1, Y1); + let t4 = Fp2.add(X2, Y2); + t3 = Fp2.mul(t3, t4); + t4 = Fp2.add(t0, t1); + t3 = Fp2.sub(t3, t4); + t4 = Fp2.add(X1, Z1); + let t5 = Fp2.add(X2, Z2); + t4 = Fp2.mul(t4, t5); + t5 = Fp2.add(t0, t2); + t4 = Fp2.sub(t4, t5); + t5 = Fp2.add(Y1, Z1); + X3 = Fp2.add(Y2, Z2); + t5 = Fp2.mul(t5, X3); + X3 = Fp2.add(t1, t2); + t5 = Fp2.sub(t5, X3); + Z3 = Fp2.mul(a, t4); + X3 = Fp2.mul(b3, t2); + Z3 = Fp2.add(X3, Z3); + X3 = Fp2.sub(t1, Z3); + Z3 = Fp2.add(t1, Z3); + Y3 = Fp2.mul(X3, Z3); + t1 = Fp2.add(t0, t0); + t1 = Fp2.add(t1, t0); + t2 = Fp2.mul(a, t2); + t4 = Fp2.mul(b3, t4); + t1 = Fp2.add(t1, t2); + t2 = Fp2.sub(t0, t2); + t2 = Fp2.mul(a, t2); + t4 = Fp2.add(t4, t2); + t0 = Fp2.mul(t1, t4); + Y3 = Fp2.add(Y3, t0); + t0 = Fp2.mul(t5, t4); + X3 = Fp2.mul(t3, X3); + X3 = Fp2.sub(X3, t0); + t0 = Fp2.mul(t3, t1); + Z3 = Fp2.mul(t5, Z3); + Z3 = Fp2.add(Z3, t0); + return new Point2(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point2.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 (!Fn.isValidNot0(scalar)) + throw new Error("invalid scalar: out of range"); + let point, fake; + const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point2, 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: f2 } = mul(scalar); + point = p; + fake = f2; + } + return normalizeZ(Point2, [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(sc) { + const { endo: endo2 } = extraOpts; + const p = this; + if (!Fn.isValid(sc)) + throw new Error("invalid scalar: out of range"); + if (sc === _0n5 || p.is0()) + return Point2.ZERO; + if (sc === _1n5) + return p; + if (wnaf.hasCache(this)) + return this.multiply(sc); + if (endo2) { + const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc); + const { p1, p2 } = mulEndoUnsafe(Point2, p, k1, k2); + return finishEndo(endo2.beta, p1, p2, k1neg, k2neg); + } else { + return wnaf.unsafe(p, sc); + } + } + multiplyAndAddUnsafe(Q, a, b) { + const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b)); + return sum.is0() ? void 0 : sum; + } + /** + * Converts Projective point to affine (x, y) coordinates. + * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch + */ + toAffine(invertedZ) { + return toAffineMemo(this, invertedZ); + } + /** + * 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 === _1n5) + return true; + if (isTorsionFree) + return isTorsionFree(Point2, this); + return wnaf.unsafe(this, CURVE_ORDER2).is0(); + } + clearCofactor() { + const { clearCofactor } = extraOpts; + if (cofactor === _1n5) + return this; + if (clearCofactor) + return clearCofactor(Point2, this); + return this.multiplyUnsafe(cofactor); + } + isSmallOrder() { + return this.multiplyUnsafe(cofactor).is0(); + } + toBytes(isCompressed = true) { + _abool2(isCompressed, "isCompressed"); + this.assertValidity(); + return encodePoint(Point2, this, isCompressed); + } + toHex(isCompressed = true) { + return bytesToHex2(this.toBytes(isCompressed)); + } + toString() { + return ``; + } + // TODO: remove + get px() { + return this.X; + } + get py() { + return this.X; + } + get pz() { + return this.Z; + } + toRawBytes(isCompressed = true) { + return this.toBytes(isCompressed); + } + _setWindowSize(windowSize) { + this.precompute(windowSize); + } + static normalizeZ(points) { + return normalizeZ(Point2, points); + } + static msm(points, scalars) { + return pippenger(Point2, Fn, points, scalars); + } + static fromPrivateKey(privateKey) { + return Point2.BASE.multiply(_normFnElement(Fn, privateKey)); + } + } + Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp2.ONE); + Point2.ZERO = new Point2(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); + Point2.Fp = Fp2; + Point2.Fn = Fn; + const bits = Fn.BITS; + const wnaf = new wNAF2(Point2, extraOpts.endo ? Math.ceil(bits / 2) : bits); + Point2.BASE.precompute(8); + return Point2; +} +function pprefix(hasEvenY) { + return Uint8Array.of(hasEvenY ? 2 : 3); +} +function getWLengths(Fp2, Fn) { + return { + secretKey: Fn.BYTES, + publicKey: 1 + Fp2.BYTES, + publicKeyUncompressed: 1 + 2 * Fp2.BYTES, + publicKeyHasPrefix: true, + signature: 2 * Fn.BYTES + }; +} +function ecdh(Point2, ecdhOpts = {}) { + const { Fn } = Point2; + const randomBytes_ = ecdhOpts.randomBytes || randomBytes2; + const lengths = Object.assign(getWLengths(Point2.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) }); + function isValidSecretKey(secretKey) { + try { + return !!_normFnElement(Fn, secretKey); + } 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 = randomBytes_(lengths.seed)) { + return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn.ORDER); + } + function getPublicKey2(secretKey, isCompressed = true) { + return Point2.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed); + } + function keygen(seed) { + const secretKey = randomSecretKey(seed); + return { secretKey, publicKey: getPublicKey2(secretKey) }; + } + function isProbPub(item) { + if (typeof item === "bigint") + return false; + if (item instanceof Point2) + return true; + const { secretKey, publicKey, publicKeyUncompressed } = lengths; + if (Fn.allowedLengths || secretKey === publicKey) + return void 0; + const l = ensureBytes2("key", item).length; + return l === publicKey || l === publicKeyUncompressed; + } + 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 = _normFnElement(Fn, secretKeyA); + const b = Point2.fromHex(publicKeyB); + return b.multiply(s).toBytes(isCompressed); + } + const utils = { + isValidSecretKey, + isValidPublicKey, + randomSecretKey, + // TODO: remove + isValidPrivateKey: isValidSecretKey, + randomPrivateKey: randomSecretKey, + normPrivateKeyToScalar: (key2) => _normFnElement(Fn, key2), + precompute(windowSize = 8, point = Point2.BASE) { + return point.precompute(windowSize, false); + } + }; + return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point: Point2, utils, lengths }); +} +function ecdsa(Point2, hash2, ecdsaOpts = {}) { + ahash(hash2); + _validateObject(ecdsaOpts, {}, { + hmac: "function", + lowS: "boolean", + randomBytes: "function", + bits2int: "function", + bits2int_modN: "function" + }); + const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2; + const hmac2 = ecdsaOpts.hmac || ((key2, ...msgs) => hmac(hash2, key2, concatBytes2(...msgs))); + const { Fp: Fp2, Fn } = Point2; + const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn; + const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point2, ecdsaOpts); + const defaultSigOpts = { + prehash: false, + lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false, + format: void 0, + //'compact' as ECDSASigFormat, + extraEntropy: false + }; + const defaultSigOpts_format = "compact"; + function isBiggerThanHalfOrder(number2) { + const HALF = CURVE_ORDER2 >> _1n5; + return number2 > HALF; + } + function validateRS(title, num2) { + if (!Fn.isValidNot0(num2)) + throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`); + return num2; + } + function validateSigLength(bytes2, format) { + validateSigFormat(format); + const size2 = lengths.signature; + const sizer = format === "compact" ? size2 : format === "recovered" ? size2 + 1 : void 0; + return _abytes2(bytes2, sizer, `${format} signature`); + } + class Signature { + constructor(r, s, recovery) { + this.r = validateRS("r", r); + this.s = validateRS("s", s); + if (recovery != null) + this.recovery = recovery; + Object.freeze(this); + } + static fromBytes(bytes2, format = defaultSigOpts_format) { + validateSigLength(bytes2, format); + let recid; + if (format === "der") { + const { r: r2, s: s2 } = DER2.toSig(_abytes2(bytes2)); + return new Signature(r2, s2); + } + if (format === "recovered") { + recid = bytes2[0]; + format = "compact"; + bytes2 = bytes2.subarray(1); + } + const L = Fn.BYTES; + const r = bytes2.subarray(0, L); + const s = bytes2.subarray(L, L * 2); + return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid); + } + static fromHex(hex, format) { + return this.fromBytes(hexToBytes2(hex), format); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(messageHash) { + const FIELD_ORDER = Fp2.ORDER; + const { r, s, recovery: rec } = this; + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error("recovery id invalid"); + const hasCofactor = CURVE_ORDER2 * _2n3 < FIELD_ORDER; + if (hasCofactor && rec > 1) + throw new Error("recovery id is ambiguous for h>1 curve"); + const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER2 : r; + if (!Fp2.isValid(radj)) + throw new Error("recovery id 2 or 3 invalid"); + const x = Fp2.toBytes(radj); + const R = Point2.fromBytes(concatBytes2(pprefix((rec & 1) === 0), x)); + const ir = Fn.inv(radj); + const h = bits2int_modN(ensureBytes2("msgHash", messageHash)); + const u1 = Fn.create(-h * ir); + const u2 = Fn.create(s * ir); + const Q = Point2.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2)); + if (Q.is0()) + throw new Error("point at infinify"); + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + toBytes(format = defaultSigOpts_format) { + validateSigFormat(format); + if (format === "der") + return hexToBytes2(DER2.hexFromSig(this)); + const r = Fn.toBytes(this.r); + const s = Fn.toBytes(this.s); + if (format === "recovered") { + if (this.recovery == null) + throw new Error("recovery bit must be present"); + return concatBytes2(Uint8Array.of(this.recovery), r, s); + } + return concatBytes2(r, s); + } + toHex(format) { + return bytesToHex2(this.toBytes(format)); + } + // TODO: remove + assertValidity() { + } + static fromCompact(hex) { + return Signature.fromBytes(ensureBytes2("sig", hex), "compact"); + } + static fromDER(hex) { + return Signature.fromBytes(ensureBytes2("sig", hex), "der"); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this; + } + toDERRawBytes() { + return this.toBytes("der"); + } + toDERHex() { + return bytesToHex2(this.toBytes("der")); + } + toCompactRawBytes() { + return this.toBytes("compact"); + } + toCompactHex() { + return bytesToHex2(this.toBytes("compact")); + } + } + const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes2) { + if (bytes2.length > 8192) + throw new Error("input is too large"); + const num2 = bytesToNumberBE2(bytes2); + const delta = bytes2.length * 8 - fnBits; + return delta > 0 ? num2 >> BigInt(delta) : num2; + }; + const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes2) { + return Fn.create(bits2int(bytes2)); + }; + const ORDER_MASK = bitMask2(fnBits); + function int2octets(num2) { + aInRange("num < 2^" + fnBits, num2, _0n5, ORDER_MASK); + return Fn.toBytes(num2); + } + function validateMsgAndHash(message, prehash) { + _abytes2(message, void 0, "message"); + return prehash ? _abytes2(hash2(message), void 0, "prehashed message") : message; + } + function prepSig(message, privateKey, opts) { + if (["recovered", "canonical"].some((k) => k in opts)) + throw new Error("sign() legacy options not supported"); + const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts); + message = validateMsgAndHash(message, prehash); + const h1int = bits2int_modN(message); + const d = _normFnElement(Fn, privateKey); + const seedArgs = [int2octets(d), int2octets(h1int)]; + if (extraEntropy != null && extraEntropy !== false) { + const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy; + seedArgs.push(ensureBytes2("extraEntropy", e)); + } + const seed = concatBytes2(...seedArgs); + const m = h1int; + function k2sig(kBytes) { + const k = bits2int(kBytes); + if (!Fn.isValidNot0(k)) + return; + const ik = Fn.inv(k); + const q = Point2.BASE.multiply(k).toAffine(); + const r = Fn.create(q.x); + if (r === _0n5) + return; + const s = Fn.create(ik * Fn.create(m + r * d)); + if (s === _0n5) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n5); + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = Fn.neg(s); + recovery ^= 1; + } + return new Signature(r, normS, recovery); + } + return { seed, k2sig }; + } + function sign2(message, secretKey, opts = {}) { + message = ensureBytes2("message", message); + const { seed, k2sig } = prepSig(message, secretKey, opts); + const drbg = createHmacDrbg2(hash2.outputLen, Fn.BYTES, hmac2); + const sig = drbg(seed, k2sig); + return sig; + } + function tryParsingSig(sg) { + let sig = void 0; + const isHex2 = typeof sg === "string" || isBytes2(sg); + const isObj = !isHex2 && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint"; + if (!isHex2 && !isObj) + throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance"); + if (isObj) { + sig = new Signature(sg.r, sg.s); + } else if (isHex2) { + try { + sig = Signature.fromBytes(ensureBytes2("sig", sg), "der"); + } catch (derError) { + if (!(derError instanceof DER2.Err)) + throw derError; + } + if (!sig) { + try { + sig = Signature.fromBytes(ensureBytes2("sig", sg), "compact"); + } catch (error) { + return false; + } + } + } + if (!sig) + return false; + return sig; + } + function verify2(signature, message, publicKey, opts = {}) { + const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts); + publicKey = ensureBytes2("publicKey", publicKey); + message = validateMsgAndHash(ensureBytes2("message", message), prehash); + if ("strict" in opts) + throw new Error("options.strict was renamed to lowS"); + const sig = format === void 0 ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes2("sig", signature), format); + if (sig === false) + return false; + try { + const P2 = Point2.fromBytes(publicKey); + if (lowS && sig.hasHighS()) + return false; + const { r, s } = sig; + const h = bits2int_modN(message); + const is = Fn.inv(s); + const u1 = Fn.create(h * is); + const u2 = Fn.create(r * is); + const R = Point2.BASE.multiplyUnsafe(u1).add(P2.multiplyUnsafe(u2)); + if (R.is0()) + return false; + const v = Fn.create(R.x); + return v === r; + } catch (e) { + return false; + } + } + function recoverPublicKey(signature, message, opts = {}) { + const { prehash } = validateSigOpts(opts, defaultSigOpts); + message = validateMsgAndHash(message, prehash); + return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes(); + } + return Object.freeze({ + keygen, + getPublicKey: getPublicKey2, + getSharedSecret, + utils, + lengths, + Point: Point2, + sign: sign2, + verify: verify2, + recoverPublicKey, + Signature, + hash: hash2 + }); +} +function _weierstrass_legacy_opts_to_new(c) { + const CURVE = { + a: c.a, + b: c.b, + p: c.Fp.ORDER, + n: c.n, + h: c.h, + Gx: c.Gx, + Gy: c.Gy + }; + const Fp2 = c.Fp; + let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : void 0; + const Fn = Field2(CURVE.n, { + BITS: c.nBitLength, + allowedLengths, + modFromBytes: c.wrapPrivateKey + }); + const curveOpts = { + Fp: Fp2, + Fn, + allowInfinityPoint: c.allowInfinityPoint, + endo: c.endo, + isTorsionFree: c.isTorsionFree, + clearCofactor: c.clearCofactor, + fromBytes: c.fromBytes, + toBytes: c.toBytes + }; + return { CURVE, curveOpts }; +} +function _ecdsa_legacy_opts_to_new(c) { + const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c); + const ecdsaOpts = { + hmac: c.hmac, + randomBytes: c.randomBytes, + lowS: c.lowS, + bits2int: c.bits2int, + bits2int_modN: c.bits2int_modN + }; + return { CURVE, curveOpts, hash: c.hash, ecdsaOpts }; +} +function _ecdsa_new_output_to_legacy(c, _ecdsa) { + const Point2 = _ecdsa.Point; + return Object.assign({}, _ecdsa, { + ProjectivePoint: Point2, + CURVE: Object.assign({}, c, nLength2(Point2.Fn.ORDER, Point2.Fn.BITS)) + }); +} +function weierstrass2(c) { + const { CURVE, curveOpts, hash: hash2, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c); + const Point2 = weierstrassN(CURVE, curveOpts); + const signs = ecdsa(Point2, hash2, ecdsaOpts); + return _ecdsa_new_output_to_legacy(c, signs); +} + +// node_modules/@noble/curves/esm/_shortw_utils.js +function createCurve2(curveDef, defHash) { + const create = (hash2) => weierstrass2({ ...curveDef, hash: hash2 }); + return { ...create(defHash), create }; +} + +// node_modules/@noble/curves/esm/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 _0n6 = /* @__PURE__ */ BigInt(0); +var _1n6 = /* @__PURE__ */ BigInt(1); +var _2n4 = /* @__PURE__ */ BigInt(2); +function sqrtMod2(y) { + const P2 = secp256k1_CURVE.p; + const _3n4 = 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 % P2; + const b3 = b2 * b2 * y % P2; + const b6 = pow22(b3, _3n4, P2) * b3 % P2; + const b9 = pow22(b6, _3n4, P2) * b3 % P2; + const b11 = pow22(b9, _2n4, P2) * b2 % P2; + const b22 = pow22(b11, _11n, P2) * b11 % P2; + const b44 = pow22(b22, _22n, P2) * b22 % P2; + const b88 = pow22(b44, _44n, P2) * b44 % P2; + const b176 = pow22(b88, _88n, P2) * b88 % P2; + const b220 = pow22(b176, _44n, P2) * b44 % P2; + const b223 = pow22(b220, _3n4, P2) * b3 % P2; + const t1 = pow22(b223, _23n, P2) * b22 % P2; + const t2 = pow22(t1, _6n, P2) * b2 % P2; + const root = pow22(t2, _2n4, P2); + if (!Fpk1.eql(Fpk1.sqr(root), y)) + throw new Error("Cannot find square root"); + return root; +} +var Fpk1 = Field2(secp256k1_CURVE.p, { sqrt: sqrtMod2 }); +var secp256k12 = createCurve2({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha2562); +var TAGGED_HASH_PREFIXES2 = {}; +function taggedHash2(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES2[tag]; + if (tagP === void 0) { + const tagH = sha2562(utf8ToBytes2(tag)); + tagP = concatBytes2(tagH, tagH); + TAGGED_HASH_PREFIXES2[tag] = tagP; + } + return sha2562(concatBytes2(tagP, ...messages)); +} +var pointToBytes2 = (point) => point.toBytes(true).slice(1); +var Pointk1 = /* @__PURE__ */ (() => secp256k12.Point)(); +var hasEven = (y) => y % _2n4 === _0n6; +function schnorrGetExtPubKey2(priv) { + const { Fn, BASE } = Pointk1; + const d_ = _normFnElement(Fn, priv); + const p = BASE.multiply(d_); + const scalar = hasEven(p.y) ? d_ : Fn.neg(d_); + return { scalar, bytes: pointToBytes2(p) }; +} +function lift_x2(x) { + const Fp2 = Fpk1; + if (!Fp2.isValidNot0(x)) + throw new Error("invalid x: Fail if x \u2265 p"); + const xx = Fp2.create(x * x); + const c = Fp2.create(xx * x + BigInt(7)); + let y = Fp2.sqrt(c); + if (!hasEven(y)) + y = Fp2.neg(y); + const p = Pointk1.fromAffine({ x, y }); + p.assertValidity(); + return p; +} +var num = bytesToNumberBE2; +function challenge2(...args) { + return Pointk1.Fn.create(num(taggedHash2("BIP0340/challenge", ...args))); +} +function schnorrGetPublicKey2(secretKey) { + return schnorrGetExtPubKey2(secretKey).bytes; +} +function schnorrSign2(message, secretKey, auxRand = randomBytes2(32)) { + const { Fn } = Pointk1; + const m = ensureBytes2("message", message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey2(secretKey); + const a = ensureBytes2("auxRand", auxRand, 32); + const t = Fn.toBytes(d ^ num(taggedHash2("BIP0340/aux", a))); + const rand = taggedHash2("BIP0340/nonce", t, px, m); + const { bytes: rx, scalar: k } = schnorrGetExtPubKey2(rand); + const e = challenge2(rx, px, m); + const sig = new Uint8Array(64); + sig.set(rx, 0); + sig.set(Fn.toBytes(Fn.create(k + e * d)), 32); + if (!schnorrVerify2(sig, m, px)) + throw new Error("sign: Invalid signature produced"); + return sig; +} +function schnorrVerify2(signature, message, publicKey) { + const { Fn, BASE } = Pointk1; + const sig = ensureBytes2("signature", signature, 64); + const m = ensureBytes2("message", message); + const pub = ensureBytes2("publicKey", publicKey, 32); + try { + const P2 = lift_x2(num(pub)); + const r = num(sig.subarray(0, 32)); + if (!inRange(r, _1n6, secp256k1_CURVE.p)) + return false; + const s = num(sig.subarray(32, 64)); + if (!inRange(s, _1n6, secp256k1_CURVE.n)) + return false; + const e = challenge2(Fn.toBytes(r), pointToBytes2(P2), m); + const R = BASE.multiplyUnsafe(s).add(P2.multiplyUnsafe(Fn.neg(e))); + const { x, y } = R.toAffine(); + if (R.is0() || !hasEven(y) || x !== r) + return false; + return true; + } catch (error) { + return false; + } +} +var schnorr2 = /* @__PURE__ */ (() => { + const size2 = 32; + const seedLength = 48; + const randomSecretKey = (seed = randomBytes2(seedLength)) => { + return mapHashToField(seed, secp256k1_CURVE.n); + }; + secp256k12.utils.randomSecretKey; + function keygen(seed) { + const secretKey = randomSecretKey(seed); + return { secretKey, publicKey: schnorrGetPublicKey2(secretKey) }; + } + return { + keygen, + getPublicKey: schnorrGetPublicKey2, + sign: schnorrSign2, + verify: schnorrVerify2, + Point: Pointk1, + utils: { + randomSecretKey, + randomPrivateKey: randomSecretKey, + taggedHash: taggedHash2, + // TODO: remove + lift_x: lift_x2, + pointToBytes: pointToBytes2, + numberToBytesBE: numberToBytesBE2, + bytesToNumberBE: bytesToNumberBE2, + mod: mod2 + }, + lengths: { + secretKey: size2, + publicKey: size2, + publicKeyHasPrefix: false, + signature: size2 * 2, + seed: seedLength + } + }; +})(); + +// node_modules/@noble/curves/esm/abstract/utils.js +var bytesToHex3 = bytesToHex2; + +// src/background.js +var NETWORK = "super-testnet-local-v0"; +var KEY_STORAGE = "inscriboor:test-wallet:v1"; +var pending = /* @__PURE__ */ new Map(); +async function account() { + const saved = (await chrome.storage.local.get(KEY_STORAGE))[KEY_STORAGE]; + let secret = saved?.secret; + if (!secret || !/^[0-9a-f]{64}$/.test(secret) || !secp256k12.utils.isValidPrivateKey(secret)) { + secret = bytesToHex3(secp256k12.utils.randomPrivateKey()); + await chrome.storage.local.set({ [KEY_STORAGE]: { kind: "super-testnet-test-key", version: 1, network: NETWORK, secret } }); + } + const pubkey = bytesToHex3(schnorr2.getPublicKey(secret)); + return { secret, pubkey, address: Address.p2tr.fromPubKey(pubkey, "regtest"), network: NETWORK }; +} +function hydrate(hex, prevouts) { + const tx = Tx.decode(hex); + if (!Array.isArray(prevouts) || prevouts.length !== tx.vin.length) throw new Error("Prevout set does not match transaction inputs."); + tx.vin.forEach((input, i) => { + const prevout = prevouts[i]; + if (!Number.isSafeInteger(prevout?.value) || prevout.value < 0 || !Array.isArray(prevout?.scriptPubKey)) throw new Error("Invalid signing prevout."); + input.prevout = { value: prevout.value, scriptPubKey: prevout.scriptPubKey }; + }); + return tx; +} +function assertOwnKeyPath(me, tx, inputIndex) { + if (JSON.stringify(tx.vin[inputIndex]?.prevout?.scriptPubKey) !== JSON.stringify(["OP_1", me.pubkey])) { + throw new Error("Refusing key-path signature for an input not owned by Inscriboor."); + } +} +async function signInscription(params) { + const me = await account(); + if (params?.network !== NETWORK) throw new Error("Inscriboor is currently limited to Super Testnet local mode."); + const commit = hydrate(params.commit.hex, params.commit.prevouts); + const reveal = hydrate(params.reveal.hex, params.reveal.prevouts); + assertOwnKeyPath(me, commit, 0); + const revealInput = Number(params.reveal.scriptInput); + if (!Number.isInteger(revealInput) || revealInput < 0 || revealInput >= reveal.vin.length) throw new Error("Invalid reveal script input."); + if (typeof params.reveal.leaf !== "string" || !/^[0-9a-f]+$/.test(params.reveal.leaf)) throw new Error("Missing reveal leaf."); + const result = { + commit: Signer.taproot.sign(me.secret, commit, 0).hex, + revealScript: Signer.taproot.sign(me.secret, reveal, revealInput, { extension: params.reveal.leaf }).hex, + revealKey: null + }; + if (revealInput === 1) { + assertOwnKeyPath(me, reveal, 0); + result.revealKey = Signer.taproot.sign(me.secret, reveal, 0).hex; + } + return result; +} +function summary(params, origin) { + const intent = params?.intent ?? {}; + return { + origin, + network: params?.network, + contentType: intent.contentType ?? "unknown", + size: intent.size ?? 0, + metadata: !!intent.metadata, + metaprotocol: intent.metaprotocol || null, + parent: intent.parent || null, + delegate: intent.delegate || null, + pointer: intent.pointer ?? "automatic", + reinscribe: intent.reinscribe || null, + postage: intent.postage ?? 1e3, + fees: intent.fees ?? 1e3 + }; +} +function finish(id, error, result) { + const request = pending.get(id); + if (!request) return; + pending.delete(id); + clearTimeout(request.timer); + try { + request.port.postMessage({ id, ...error ? { error } : { result } }); + } catch { + } +} +async function openApproval(message, port) { + const local = /^http:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/.test(message.origin); + if (message.origin !== "https://supertestnet.lol" && !local) throw new Error("This Inscriboor build only accepts Super Testnet origins."); + const id = message.id; + const timer = setTimeout(() => finish(id, "Signing request expired."), 12e4); + pending.set(id, { port, params: message.params, origin: message.origin, timer }); + await chrome.windows.create({ url: chrome.runtime.getURL(`approval.html?id=${encodeURIComponent(id)}`), type: "popup", width: 420, height: 680, focused: true }); +} +chrome.runtime.onConnect.addListener((port) => { + if (port.name !== "inscriboor-provider") return; + port.onMessage.addListener(async (message) => { + try { + if (message.method === "bitcoin_getAccounts") { + const me = await account(); + port.postMessage({ id: message.id, result: [{ address: me.address, pubkey: me.pubkey, network: me.network }] }); + } else if (message.method === "bitcoin_getNetwork") { + port.postMessage({ id: message.id, result: NETWORK }); + } else if (message.method === "ord_signInscription") { + await openApproval(message, port); + } else { + port.postMessage({ id: message.id, error: `Unsupported Inscriboor method: ${message.method}` }); + } + } catch (error) { + port.postMessage({ id: message.id, error: error.message }); + } + }); + port.onDisconnect.addListener(() => { + for (const [id, request] of pending) if (request.port === port) finish(id, "Page disconnected before signing completed."); + }); +}); +chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => { + if (message?.type === "approval:get") { + const request = pending.get(message.id); + sendResponse(request ? { ok: true, summary: summary(request.params, request.origin) } : { ok: false, error: "Signing request no longer exists." }); + return; + } + if (message?.type === "approval:reject") { + finish(message.id, "User rejected signing request."); + sendResponse({ ok: true }); + return; + } + if (message?.type === "approval:approve") { + const request = pending.get(message.id); + if (!request) { + sendResponse({ ok: false, error: "Signing request no longer exists." }); + return; + } + signInscription(request.params).then((result) => { + finish(message.id, null, result); + sendResponse({ ok: true }); + }).catch((error) => { + finish(message.id, error.message); + sendResponse({ ok: false, error: error.message }); + }); + return true; + } +}); +/*! Bundled license information: + +@cmdcode/tapscript/dist/module.mjs: + (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@noble/hashes/esm/utils.js: + (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@noble/curves/esm/utils.js: +@noble/curves/esm/abstract/modular.js: +@noble/curves/esm/abstract/curve.js: +@noble/curves/esm/abstract/weierstrass.js: +@noble/curves/esm/_shortw_utils.js: +@noble/curves/esm/secp256k1.js: + (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) +*/ diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..d5ae30a --- /dev/null +++ b/package-lock.json @@ -0,0 +1,506 @@ +{ + "name": "inscriboor", + "version": "0.2.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "inscriboor", + "version": "0.2.0", + "dependencies": { + "@cmdcode/tapscript": "1.5.3", + "@noble/curves": "1.9.7" + }, + "devDependencies": { + "esbuild": "0.25.10" + } + }, + "node_modules/@cmdcode/tapscript": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/@cmdcode/tapscript/-/tapscript-1.5.3.tgz", + "integrity": "sha512-WCTtZsp5aXk7IKM9DpCSkDjx9eW9WrPxfmFPyfLcYnwEqnEvd+6iAjp8A5elkVfepMZ1e69OHO2qULYlH4TUWA==" + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.10.tgz", + "integrity": "sha512-0NFWnA+7l41irNuaSVlLfgNT12caWJVLzp5eAVhZ0z1qpxbockccEt3s+149rE64VUI3Ml2zt8Nv5JVc4QXTsw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.10.tgz", + "integrity": "sha512-dQAxF1dW1C3zpeCDc5KqIYuZ1tgAdRXNoZP7vkBIRtKZPYe2xVr/d3SkirklCHudW1B45tGiUlz2pUWDfbDD4w==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.10.tgz", + "integrity": "sha512-LSQa7eDahypv/VO6WKohZGPSJDq5OVOo3UoFR1E4t4Gj1W7zEQMUhI+lo81H+DtB+kP+tDgBp+M4oNCwp6kffg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.10.tgz", + "integrity": "sha512-MiC9CWdPrfhibcXwr39p9ha1x0lZJ9KaVfvzA0Wxwz9ETX4v5CHfF09bx935nHlhi+MxhA63dKRRQLiVgSUtEg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.10.tgz", + "integrity": "sha512-JC74bdXcQEpW9KkV326WpZZjLguSZ3DfS8wrrvPMHgQOIEIG/sPXEN/V8IssoJhbefLRcRqw6RQH2NnpdprtMA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.10.tgz", + "integrity": "sha512-tguWg1olF6DGqzws97pKZ8G2L7Ig1vjDmGTwcTuYHbuU6TTjJe5FXbgs5C1BBzHbJ2bo1m3WkQDbWO2PvamRcg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.10.tgz", + "integrity": "sha512-3ZioSQSg1HT2N05YxeJWYR+Libe3bREVSdWhEEgExWaDtyFbbXWb49QgPvFH8u03vUPX10JhJPcz7s9t9+boWg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.10.tgz", + "integrity": "sha512-LLgJfHJk014Aa4anGDbh8bmI5Lk+QidDmGzuC2D+vP7mv/GeSN+H39zOf7pN5N8p059FcOfs2bVlrRr4SK9WxA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.10.tgz", + "integrity": "sha512-oR31GtBTFYCqEBALI9r6WxoU/ZofZl962pouZRTEYECvNF/dtXKku8YXcJkhgK/beU+zedXfIzHijSRapJY3vg==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.10.tgz", + "integrity": "sha512-5luJWN6YKBsawd5f9i4+c+geYiVEw20FVW5x0v1kEMWNq8UctFjDiMATBxLvmmHA4bf7F6hTRaJgtghFr9iziQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.10.tgz", + "integrity": "sha512-NrSCx2Kim3EnnWgS4Txn0QGt0Xipoumb6z6sUtl5bOEZIVKhzfyp/Lyw4C1DIYvzeW/5mWYPBFJU3a/8Yr75DQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.10.tgz", + "integrity": "sha512-xoSphrd4AZda8+rUDDfD9J6FUMjrkTz8itpTITM4/xgerAZZcFW7Dv+sun7333IfKxGG8gAq+3NbfEMJfiY+Eg==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.10.tgz", + "integrity": "sha512-ab6eiuCwoMmYDyTnyptoKkVS3k8fy/1Uvq7Dj5czXI6DF2GqD2ToInBI0SHOp5/X1BdZ26RKc5+qjQNGRBelRA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.10.tgz", + "integrity": "sha512-NLinzzOgZQsGpsTkEbdJTCanwA5/wozN9dSgEl12haXJBzMTpssebuXR42bthOF3z7zXFWH1AmvWunUCkBE4EA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.10.tgz", + "integrity": "sha512-FE557XdZDrtX8NMIeA8LBJX3dC2M8VGXwfrQWU7LB5SLOajfJIxmSdyL/gU1m64Zs9CBKvm4UAuBp5aJ8OgnrA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.10.tgz", + "integrity": "sha512-3BBSbgzuB9ajLoVZk0mGu+EHlBwkusRmeNYdqmznmMc9zGASFjSsxgkNsqmXugpPk00gJ0JNKh/97nxmjctdew==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.10.tgz", + "integrity": "sha512-QSX81KhFoZGwenVyPoberggdW1nrQZSvfVDAIUXr3WqLRZGZqWk/P4T8p2SP+de2Sr5HPcvjhcJzEiulKgnxtA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.10.tgz", + "integrity": "sha512-AKQM3gfYfSW8XRk8DdMCzaLUFB15dTrZfnX8WXQoOUpUBQ+NaAFCP1kPS/ykbbGYz7rxn0WS48/81l9hFl3u4A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.10.tgz", + "integrity": "sha512-7RTytDPGU6fek/hWuN9qQpeGPBZFfB4zZgcz2VK2Z5VpdUxEI8JKYsg3JfO0n/Z1E/6l05n0unDCNc4HnhQGig==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.10.tgz", + "integrity": "sha512-5Se0VM9Wtq797YFn+dLimf2Zx6McttsH2olUBsDml+lm0GOCRVebRWUvDtkY4BWYv/3NgzS8b/UM3jQNh5hYyw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.10.tgz", + "integrity": "sha512-XkA4frq1TLj4bEMB+2HnI0+4RnjbuGZfet2gs/LNs5Hc7D89ZQBHQ0gL2ND6Lzu1+QVkjp3x1gIcPKzRNP8bXw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.10.tgz", + "integrity": "sha512-AVTSBhTX8Y/Fz6OmIVBip9tJzZEUcY8WLh7I59+upa5/GPhh2/aM6bvOMQySspnCCHvFi79kMtdJS1w0DXAeag==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.10.tgz", + "integrity": "sha512-fswk3XT0Uf2pGJmOpDB7yknqhVkJQkAQOcW/ccVOtfx05LkbWOaRAtn5SaqXypeKQra1QaEa841PgrSL9ubSPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.10.tgz", + "integrity": "sha512-ah+9b59KDTSfpaCg6VdJoOQvKjI33nTaQr4UluQwW7aEwZQsbMCfTmfEO4VyewOxx4RaDT/xCy9ra2GPWmO7Kw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.10.tgz", + "integrity": "sha512-QHPDbKkrGO8/cz9LKVnJU22HOi4pxZnZhhA2HYHez5Pz4JeffhDjf85E57Oyco163GnzNCVkZK0b/n4Y0UHcSw==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.10.tgz", + "integrity": "sha512-9KpxSVFCu0iK1owoez6aC/s/EdUQLDN3adTxGCqxMVhrPDj6bt5dbrHDXUuq+Bs2vATFBBrQS5vdQ/Ed2P+nbw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/esbuild": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.10.tgz", + "integrity": "sha512-9RiGKvCwaqxO2owP61uQ4BgNborAQskMR6QusfWzQqv7AZOg5oGehdY2pRJMTKuwxd1IDBP4rSbI5lHzU7SMsQ==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.10", + "@esbuild/android-arm": "0.25.10", + "@esbuild/android-arm64": "0.25.10", + "@esbuild/android-x64": "0.25.10", + "@esbuild/darwin-arm64": "0.25.10", + "@esbuild/darwin-x64": "0.25.10", + "@esbuild/freebsd-arm64": "0.25.10", + "@esbuild/freebsd-x64": "0.25.10", + "@esbuild/linux-arm": "0.25.10", + "@esbuild/linux-arm64": "0.25.10", + "@esbuild/linux-ia32": "0.25.10", + "@esbuild/linux-loong64": "0.25.10", + "@esbuild/linux-mips64el": "0.25.10", + "@esbuild/linux-ppc64": "0.25.10", + "@esbuild/linux-riscv64": "0.25.10", + "@esbuild/linux-s390x": "0.25.10", + "@esbuild/linux-x64": "0.25.10", + "@esbuild/netbsd-arm64": "0.25.10", + "@esbuild/netbsd-x64": "0.25.10", + "@esbuild/openbsd-arm64": "0.25.10", + "@esbuild/openbsd-x64": "0.25.10", + "@esbuild/openharmony-arm64": "0.25.10", + "@esbuild/sunos-x64": "0.25.10", + "@esbuild/win32-arm64": "0.25.10", + "@esbuild/win32-ia32": "0.25.10", + "@esbuild/win32-x64": "0.25.10" + } + } + } +}