@ckb-ccc/core 1.22.0 → 1.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"file":"barrel-DZkApbAR.js","names":["Chi","Maj","HashMD","createView","SHA256_IV","_0n","_1n","_2n","_7n","split","u32","createHasher","bytesFrom","hexFrom","Owner","Owner","OwnerMoved","hashCkb","CellInput","numLeToBytes","Transaction","numFrom","DEFAULT_CONFIRMED_BLOCK_TIME","DEFAULT_CONFIRMED_BLOCK_TIME","MapLru","numFrom","Cell","hexFrom","OutPoint","filterCell","ClientTransactionResponse","ClientBlockHeader","ClientBlock","ScriptInfo","numMax","DEFAULT_MIN_FEE_RATE","numFrom","DEFAULT_MAX_FEE_RATE","numMin","OutPoint","Cell","ClientIndexerSearchKey","CellDepInfo","CellDep","reduceAsync","Zero","Transaction","ErrorClientMaxFeeRateExceeded","hexFrom","ErrorClientWaitTransactionTimeout","sleep","jsonRpcTransportFromUri","abortSignalToPromise","ErrorClientResolveUnknown","OutPoint","ErrorClientVerification","ErrorClientDuplicatedTransaction","ErrorClientRBFRejected","ErrorClientBase","apply","numFrom","DEFAULT_MIN_FEE_RATE","JsonRpcTransformers","numToHex","hexFrom","Cell","WebSocket","MAINNET_SCRIPTS","WebSocket","TESTNET_SCRIPTS","Script","addressPayloadFromString","addressFromPayload","bytesConcat","bytesFrom","hashTypeToBytes","bech32m","ADDRESS_BECH32_LIMIT","isBytes","atitle","anumber","abytes","clean","copyBytes","copyBytes","checkOpts","kdfInputToBytes","createView","SHA256_K","SHA256_W","HashMD","rotr","Chi","Maj","SHA256_IV","sha256","rotl","checkOpts","sha256","u32","clean","asyncLoop","hexFrom","bytesConcat","randomBytes","bytesFrom","hexFrom","abytes","abytes_","anumber_","bytesToHex_","concatBytes_","hexToBytes_","isBytes","isBytes_","randomBytes_","_0n","_1n","_0n","_1n","_2n","_3n","_4n","gcd","_0n","_1n","_4n","isBytes","_0n","abytes","_2n","_0n","randomBytes","wcRandomBytes","abytes","isBytes","hmac","nobleHmac","sha256","abytes","randomBytes","HashMD","rotl","sha256","sha256n","basex","base58","bs58checkBase","numFrom","numLeToBytes","bytesConcat","bytesFrom","sha256","bs58check","hexFrom","bytesFrom","hexFrom","bytesConcat","hashCkb","hexFrom","verifySignature","hexFrom","bytesFrom","verifyMessage","bytesFrom","hexFrom","sha256","bytesFrom","Transaction","hexFrom","Transaction","bytesFrom","WitnessArgs","bytesConcat","numToBytes","hexFrom","Transaction","hexFrom","bytesFrom","hashCkbShort","Script","Transaction","hexFrom","bytesFrom","Transaction","WitnessArgs","Script","Entity","hashCkbShort","hexFrom","numFrom","bytesConcat","Since","bytesFrom","codec","numToBytes","apply","ScriptInfo","Script","Transaction","WitnessArgs","reduceAsync","hexFrom","Transaction","hashCkbShort","bs58check","hexFrom","Transaction","bytesFrom","WitnessArgs","bytesConcat","numToBytes","bytesFrom","hexFrom","bytesTo","bytesConcat","hexFrom","bytesFrom","Transaction","reduceAsync","WitnessArgs","bytesConcat","numToBytes","hexFrom","hexFrom","randomBytes","JsonRpcTransformers","SignerJsonRpcTransformers","OwnerUnique","sleep","abortSignalAny","SignerJsonRpcTransformers","JsonRpcTransformers","hexFrom","randomBytes","retry","waitForAvailability","sleep","hexFrom","bytesFrom","bytesConcat","hashCkb","Transaction","WitnessArgs","hexFrom","bytesFrom","hexFrom"],"sources":["../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha3.js","../src/hasher/hasherKeecak256.ts","../src/molecule/barrel.ts","../src/utils/owner/aggregated.ts","../src/utils/owner/refCount.ts","../src/utils/proxy.ts","../src/ckb/hash.ts","../src/client/cache/cache.ts","../src/client/cache/memory.ts","../src/client/client.ts","../src/jsonRpc/transports/fallback.ts","../src/jsonRpc/transports/transport.ts","../src/jsonRpc/requestor.ts","../src/client/jsonRpc/client.ts","../src/client/clientPublicMainnet.ts","../src/client/clientPublicTestnet.ts","../src/address/index.ts","../../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/utils.js","../../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/aes.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/hmac.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/pbkdf2.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha2.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/scrypt.js","../src/keystore/index.ts","../src/signer/btc/psbt.ts","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/utils.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/modular.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/curve.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/der.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/weierstrass.js","../../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/secp256k1.js","../../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/legacy.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js","../../../node_modules/.pnpm/base-x@5.0.1/node_modules/base-x/src/esm/index.js","../../../node_modules/.pnpm/bs58@6.0.0/node_modules/bs58/src/esm/index.js","../../../node_modules/.pnpm/bs58check@4.0.0/node_modules/bs58check/src/esm/base.js","../../../node_modules/.pnpm/bs58check@4.0.0/node_modules/bs58check/src/esm/index.js","../src/signer/btc/verify.ts","../src/signer/ckb/secp256k1Signing.ts","../src/signer/ckb/verifyJoyId.ts","../src/signer/doge/verify.ts","../src/signer/evm/verify.ts","../src/signer/nostr/verify.ts","../src/signer/signer/index.ts","../src/signer/btc/signerBtc.ts","../src/signer/btc/signerBtcPublicKeyReadonly.ts","../src/signer/ckb/signerCkbAlwaysSuccess.ts","../src/signer/ckb/signerCkbPublicKey.ts","../src/signer/ckb/signerCkbPrivateKey.ts","../src/signer/ckb/signerCkbScriptReadonly.ts","../src/signer/ckb/signerMultisigCkbReadonly.ts","../src/signer/ckb/signerMultisigCkbPrivateKey.ts","../src/signer/doge/signerDoge.ts","../src/signer/doge/signerDogeAddressReadonly.ts","../src/signer/doge/signerDogePrivateKey.ts","../src/signer/dummy/dummy.ts","../src/signer/dummy/alwaysError.ts","../src/signer/dummy/openLink.ts","../src/signer/evm/signerEvm.ts","../src/signer/evm/signerEvmAddressReadonly.ts","../src/signer/jsonRpc/network.ts","../src/signer/jsonRpc/handler.ts","../src/signer/jsonRpc/signer.ts","../src/signer/nostr/signerNostr.ts","../src/signer/nostr/signerNostrPublicKeyReadonly.ts","../src/signer/nostr/signerNostrPrivateKey.ts","../src/barrel.ts"],"sourcesContent":["/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n let processed = false;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n processed = true;\n continue;\n }\n // When the whole input is buffered in one go (common for short messages), passing `data`\n // directly avoids allocating a subarray view.\n buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n processed = true;\n }\n }\n this.length += data.length;\n // Shared schedule buffers only pick up input-derived words inside process(); if everything\n // was buffered without processing, there is nothing to zero.\n if (processed)\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message, then zero-pad the rest of the block\n buffer[pos++] = 0b10000000;\n buffer.fill(0, pos);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n buffer.fill(0);\n }\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n // integer below 2**53, so the split inside the helper stays exact).\n setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n this.process(view, 0);\n // The final block above is processed outside update(), so the shared message-schedule\n // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n this.roundClean();\n // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n const oview = out === buffer ? view : createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n const outLen = len / 4;\n const state = this.get();\n // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n if (len % 4 || outLen > state.length)\n throw new Error('invalid outputLen');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneIntoMeta(to) {\n const { buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (pos)\n to.buffer.set(buffer); // Avoid a hot modulo guard.\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf | FIPS-202},\n * {@link https://keccak.team/keccak.html | Website}, and\n * {@link https://crypto.stackexchange.com/q/15727 | the differences between\n * SHA-3 and Keccak}.\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { split } from \"./_u64.js\";\n// prettier-ignore\nimport { abool, abytes, aexists, anumber, aoutput, checkOpts, clean, createHasher, oidNist, swap32IfBE, u32 } from \"./utils.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\n// FIPS 202 Algorithm 5 rc(): when the outgoing bit is 1, the 8-bit LFSR xors\n// taps 0, 4, 5, and 6, which compresses to the feedback mask `0x71`.\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = []; // no pure annotation: var is always used\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\n// `split(..., true)` keeps the local little-endian lane-word layout used by\n// `state32`, so these `H` / `L` tables follow the file's first-word /\n// second-word lane slots rather than `_u64.ts`'s usual high/low naming.\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// 64-bit left rotates as u32 pairs. Inlined here (not imported from _u64) so V8 can\n// inline them into keccakP — the import path costs ~24% on sha3_256. SHA3 is the only\n// consumer of left-rotates; other hashes use right-rotates from _u64.\n// Valid for s in 1..31 (SH/SL) and 33..63 (BH/BL); keccak never rotates by 0/32/64.\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Reused Theta scratch buffer (column parities), same pattern as SHA256_W in sha2.\n// keccakP never calls user code, so the shared buffer cannot be observed mid-permutation.\nconst B = new Uint32Array(5 * 2);\n/**\n * `keccakf1600` internal permutation, additionally allows adjusting the round count.\n * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words\n * in this file's local little-endian lane-word order\n * @param rounds - number of rounds to execute\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If `rounds` is outside the supported `1..24` range. {@link Error}\n * @example\n * Permute a Keccak state with the default 24 rounds.\n * ```ts\n * keccakP(new Uint32Array(50));\n * ```\n */\nexport function keccakP(s, rounds = 24) {\n if (!(s instanceof Uint32Array))\n throw new TypeError('\"s\" expected Uint32Array(50), got type=' + typeof s);\n if (s.length !== 50)\n throw new RangeError('\"s\" expected Uint32Array(50), got length=' + s.length);\n anumber(rounds, 'rounds');\n // This implementation precomputes only the standard Keccak-f[1600] 24-round Iota table.\n if (rounds < 1 || rounds > 24)\n throw new Error('\"rounds\" expected integer 1..24');\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n // Same as:\n // for (let x = 0; x < 10; x++) B[x] = s[y + x];\n // for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n for (let y = 0; y < 50; y += 10) {\n const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];\n s[y] ^= ~s[y + 2] & s[y + 4];\n s[y + 1] ^= ~s[y + 3] & s[y + 5];\n s[y + 2] ^= ~s[y + 4] & s[y + 6];\n s[y + 3] ^= ~s[y + 5] & s[y + 7];\n s[y + 4] ^= ~s[y + 6] & s[y + 8];\n s[y + 5] ^= ~s[y + 7] & s[y + 9];\n s[y + 6] ^= ~s[y + 8] & b0;\n s[y + 7] ^= ~s[y + 9] & b1;\n s[y + 8] ^= ~b0 & b2;\n s[y + 9] ^= ~b1 & b3;\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n/**\n * Keccak sponge function.\n * @param blockLen - absorb/squeeze rate in bytes\n * @param suffix - domain separation suffix byte\n * @param outputLen - default digest length in bytes. This base sponge only\n * requires a non-negative integer; wrappers that need positive output\n * lengths must enforce that themselves.\n * @param enableXOF - whether XOF output is allowed\n * @param rounds - number of Keccak-f rounds\n * @example\n * Build a sponge state, absorb bytes, then finalize a digest.\n * ```ts\n * const hash = new Keccak(136, 0x06, 32);\n * hash.update(new Uint8Array([1, 2, 3]));\n * hash.digest();\n * ```\n */\nexport class Keccak {\n state;\n pos = 0;\n posOut = 0;\n finished = false;\n state32;\n destroyed = false;\n blockLen;\n suffix;\n outputLen;\n canXOF;\n enableXOF = false;\n rounds;\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n anumber(blockLen, 'blockLen');\n anumber(suffix, 'suffix');\n anumber(rounds, 'rounds');\n abool(enableXOF, 'enableXOF');\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.canXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen, 'outputLen');\n // Only keccak-f1600 is supported: 1600 bits (5x5 matrix of 64bit) === 200 bytes of state.\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('\"blockLen\" must be 1..199');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { blockLen, state, state32 } = this;\n const len = data.length;\n // Absorb full blocks with u32 XORs when both sides are 4-byte aligned.\n // XOR of same-position words equals XOR of same-position bytes, so this is endianness-safe.\n const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;\n const blockLen32 = blockLen / 4;\n const data32 = canUseU32 && len >= blockLen ? u32(data) : undefined;\n for (let pos = 0; pos < len;) {\n if (data32 !== undefined && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {\n for (let i = 0, o = pos / 4; i < blockLen32; i++)\n state32[i] ^= data32[o + i];\n pos += blockLen;\n // Subclasses (_KeccakPRG) read `this.pos` inside their `keccak()` override,\n // so it must reflect the fully-absorbed block before the permutation fires.\n this.pos = blockLen;\n this.keccak();\n continue;\n }\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // FIPS 202 appends the SHA3/SHAKE domain-separation suffix before pad10*1.\n // These byte values already include the first padding bit, while the\n // final `0x80` below supplies the closing `1` bit in the last rate byte.\n state[pos] ^= suffix;\n // If that combined suffix lands in the last rate byte and already sets\n // bit 7, absorb it first so the final pad10*1 bit can be xored into a\n // fresh block.\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Plain SHA3/Keccak usage with XOF is probably a mistake, but this base\n // class is also reused by SHAKE/cSHAKE/KMAC/TupleHash/ParallelHash/\n // TurboSHAKE/KangarooTwelve wrappers that intentionally enable XOF.\n if (!this.enableXOF)\n throw new Error('XOF is not enabled');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n // `aoutput(...)` allows oversized buffers; digestInto() must fill only the advertised digest.\n this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.outputLen);\n this.digestInto(out);\n return out;\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n // Reused destinations can come from a different rate/capacity variant, so clone must rewrite\n // the sponge geometry as well as the state words.\n to.blockLen = blockLen;\n to.state32.set(this.state32);\n // Sponge padding and XOF output are positional, so both offsets are part of the clone state.\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n // Clones must preserve the public capability bit too; `_KMAC` reuses this path and deep clone\n // tests compare instance fields directly, so leaving `canXOF` behind makes the clone lie.\n to.canXOF = this.canXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n/**\n * SHA3-224 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-224.\n * ```ts\n * sha3_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_224 = /* @__PURE__ */ genKeccak(0x06, 144, 28, \n/* @__PURE__ */ oidNist(0x07));\n/**\n * SHA3-256 hash function. Different from keccak-256.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-256.\n * ```ts\n * sha3_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32, \n/* @__PURE__ */ oidNist(0x08));\n/**\n * SHA3-384 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-384.\n * ```ts\n * sha3_384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48, \n/* @__PURE__ */ oidNist(0x09));\n/**\n * SHA3-512 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-512.\n * ```ts\n * sha3_512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64, \n/* @__PURE__ */ oidNist(0x0a));\n/**\n * Keccak-224 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-224.\n * ```ts\n * keccak_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/**\n * Keccak-256 hash function. Different from SHA3-256.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-256.\n * ```ts\n * keccak_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/**\n * Keccak-384 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-384.\n * ```ts\n * keccak_384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/**\n * Keccak-512 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-512.\n * ```ts\n * keccak_512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64);\nconst genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => {\n opts = checkOpts({}, opts);\n return new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true);\n}, info);\n/**\n * SHAKE128 XOF with 128-bit security and a 16-byte default output.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE128.\n * ```ts\n * shake128(new Uint8Array([97, 98, 99]), { dkLen: 32 });\n * ```\n */\nexport const shake128 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));\n/**\n * SHAKE256 XOF with 256-bit security and a 32-byte default output.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE256.\n * ```ts\n * shake256(new Uint8Array([97, 98, 99]), { dkLen: 64 });\n * ```\n */\nexport const shake256 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n/**\n * SHAKE128 XOF with 256-bit output (NIST version).\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE128 using a 32-byte default output.\n * ```ts\n * shake128_32(new Uint8Array([97, 98, 99]), { dkLen: 32 });\n * ```\n */\nexport const shake128_32 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));\n/**\n * SHAKE256 XOF with 512-bit output (NIST version).\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE256 using a 64-byte default output.\n * ```ts\n * shake256_64(new Uint8Array([97, 98, 99]), { dkLen: 64 });\n * ```\n */\nexport const shake256_64 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\n","import { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { BytesLike, bytesFrom } from \"../bytes/index.js\";\nimport { Hex, hexFrom } from \"../hex/index.js\";\nimport { Hasher } from \"./hasher.js\";\n\n/**\n * @public\n */\nexport class HasherKeecak256 implements Hasher {\n private readonly hasher: ReturnType<(typeof keccak_256)[\"create\"]>;\n\n /**\n * Creates an instance of Hasher.\n */\n\n constructor() {\n this.hasher = keccak_256.create();\n }\n\n /**\n * Updates the hash with the given data.\n *\n * @param data - The data to update the hash with.\n * @returns The current Hasher instance for chaining.\n *\n * @example\n * ```typescript\n * const hasher = new Hasher();\n * hasher.update(\"some data\").update(\"more data\");\n * const hash = hasher.digest();\n * ```\n */\n\n update(data: BytesLike): HasherKeecak256 {\n this.hasher.update(bytesFrom(data));\n return this;\n }\n\n /**\n * Finalizes the hash and returns the digest as a hexadecimal string.\n *\n * @returns The hexadecimal string representation of the hash.\n *\n * @example\n * ```typescript\n * const hasher = new Hasher();\n * hasher.update(\"some data\");\n * const hash = hasher.digest(); // Outputs something like \"0x...\"\n * ```\n */\n\n digest(): Hex {\n return hexFrom(this.hasher.digest());\n }\n}\n","export {\n /**\n * @deprecated Use ccc.Entity instead\n */\n Entity,\n /**\n * @deprecated Use ccc.codec instead\n */\n codec,\n} from \"../codec/entity.js\";\nexport * from \"./codec.js\";\nexport * from \"./predefined.js\";\n","import { Owner, OwnerMoved } from \"./owner.js\";\n\n// TypeScript has no existential type for heterogeneous Owner values.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Owners = readonly Owner<any>[];\n\ntype OwnerValues<T extends Owners> = {\n [K in keyof T]: T[K] extends Owner<infer U> ? U : never;\n};\n\n/**\n * An Owner that aggregates multiple ownership claims.\n *\n * Disposing it attempts to release every claim and aggregates any failures.\n *\n * @public\n */\nexport class OwnerAggregated<T extends readonly unknown[]> extends Owner<T> {\n private constructor(\n protected readonly value_: T,\n private readonly owners: readonly OwnerMoved<unknown>[],\n ) {\n super();\n }\n\n /** Moves multiple ownership claims into one Owner. */\n static from<const TOwners extends Owners>(\n owners: TOwners,\n ): OwnerAggregated<OwnerValues<TOwners>> {\n if (new Set(owners).size !== owners.length) {\n throw new Error(\"Cannot aggregate the same Owner more than once\");\n }\n\n // Validate every source before moving any of them.\n const values = owners.map(\n (owner): unknown => owner.value,\n ) as OwnerValues<TOwners>;\n const moved = owners.map((owner) => this.moveFrom(owner));\n return new OwnerAggregated(values, moved);\n }\n\n protected async release(): Promise<void> {\n const results = await Promise.allSettled(\n this.owners.map((owner) => owner.dispose()),\n );\n const errors: unknown[] = [];\n for (const result of results) {\n if (result.status === \"rejected\") {\n errors.push(result.reason as unknown);\n }\n }\n if (errors.length !== 0) {\n throw new AggregateError(errors, \"Failed to dispose aggregated Owners\");\n }\n }\n}\n","import { Owner, OwnerMoved } from \"./owner.js\";\n\ntype OwnerRefCountState<T> = {\n owner: OwnerMoved<T>;\n referenceCount: number;\n};\n\n/**\n * A reference-counted Owner for a shared value.\n *\n * The source ownership is disposed after the final OwnerRefCount is disposed.\n * Each clone owns one reference and can be disposed independently.\n *\n * @example\n * ```ts\n * const controller = new AbortController();\n * const first = OwnerRefCount.new(\n * controller,\n * (controller) => controller.abort(),\n * );\n * const second = first.clone();\n *\n * await first.dispose();\n * console.log(controller.signal.aborted); // false\n *\n * await second.dispose();\n * console.log(controller.signal.aborted); // true\n * ```\n *\n * @public\n */\nexport class OwnerRefCount<T> extends Owner<T> {\n private constructor(private readonly state: OwnerRefCountState<T>) {\n super();\n }\n\n protected get value_(): T {\n return this.state.owner.value;\n }\n\n /** Creates the first reference-counted Owner for a value. */\n static new<T>(\n value: T,\n disposer: (value: T) => PromiseLike<void> | void,\n ): OwnerRefCount<T> {\n return new OwnerRefCount({\n owner: new OwnerMoved(value, disposer),\n referenceCount: 1,\n });\n }\n\n /**\n * Moves an ownership claim into a new reference-counted Owner.\n *\n * @throws If the source Owner has already been moved or disposed.\n */\n static from<T>(owner: Owner<T>): OwnerRefCount<T> {\n return new OwnerRefCount({\n owner: this.moveFrom(owner),\n referenceCount: 1,\n });\n }\n\n /** Creates another Owner for the same shared value. */\n clone(): OwnerRefCount<T> {\n // Assert that this Owner is still active before adding a reference.\n void this.value;\n this.state.referenceCount += 1;\n return new OwnerRefCount(this.state);\n }\n\n protected release(): Promise<void> | void {\n this.state.referenceCount -= 1;\n if (this.state.referenceCount === 0) {\n return this.state.owner.dispose();\n }\n }\n}\n","import type { AbstractConstructor, Constructor } from \"./constructor.js\";\n\n/**\n * Utilities for creating composition wrappers.\n *\n * @example\n * ```ts\n * class Wrapper extends Proxy.Base(Client) {\n * static readonly [Proxy.localKeys] = [\"feeRate\"];\n * public feeRate = 1000;\n *\n * request(): void {\n * this[Proxy.inner].request();\n * }\n * }\n *\n * const wrapper = new Wrapper(client);\n * ```\n *\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace Proxy {\n /** The property key for accessing the immediately wrapped object. */\n export const inner = \"@ckb-ccc/core.Proxy.inner\";\n\n /**\n * The static metadata key for instance fields that belong to the wrapper.\n * Every wrapper instance field must be listed here. Prototype members are\n * detected automatically.\n */\n export const localKeys: unique symbol = Symbol.for(\n \"@ckb-ccc/core.Proxy.localKeys\",\n );\n\n /**\n * Creates a wrapper base that delegates non-local members to an inner instance.\n * Its constructor accepts the inner instance and does not invoke `BaseClass`.\n *\n * @remarks\n * Wrapping an abstract class may require suppressing TS2655 because its abstract\n * members are implemented by runtime delegation.\n *\n * @param BaseClass - The class represented by the wrapper.\n */\n export function Base<BaseClass extends AbstractConstructor<object>>(\n BaseClass: BaseClass,\n ): Omit<BaseClass, \"prototype\"> &\n Constructor<\n InstanceType<BaseClass> & {\n readonly [inner]: InstanceType<BaseClass>;\n },\n [InstanceType<BaseClass>]\n > {\n type T = InstanceType<BaseClass>;\n\n class ProxyClass {\n public readonly [inner]: T;\n\n constructor(innerValue: T) {\n this[inner] = innerValue;\n\n const allLocalKeys = new Set<PropertyKey>([inner]);\n const forwardedFunctions = new Map<\n PropertyKey,\n { value: unknown; wrapper: (...args: unknown[]) => unknown }\n >();\n\n // Members introduced between the concrete subclass and ProxyClass belong\n // to the wrapper. Stop before ProxyClass so members inherited from Base\n // continue to be forwarded to inner.\n for (\n let prototype: object | null = new.target.prototype;\n prototype !== null && prototype !== ProxyClass.prototype;\n prototype = Reflect.getPrototypeOf(prototype)\n ) {\n // Every member defined directly on this prototype belongs to the wrapper.\n for (const property of Reflect.ownKeys(prototype)) {\n allLocalKeys.add(property);\n }\n\n // Resolve the class that owns this prototype and merge the local keys\n // declared in its static metadata.\n const constructor = Object.getOwnPropertyDescriptor(\n prototype,\n \"constructor\",\n )?.value as unknown;\n\n try {\n const metadataKeys = Object.getOwnPropertyDescriptor(\n constructor,\n localKeys,\n )?.value as readonly PropertyKey[] | undefined;\n for (const property of metadataKeys ?? []) {\n allLocalKeys.add(property);\n }\n } catch {}\n }\n\n const isLocalProperty = (\n target: object,\n property: PropertyKey,\n ): boolean =>\n allLocalKeys.has(property) ||\n Reflect.getOwnPropertyDescriptor(target, property) !== undefined;\n\n return new globalThis.Proxy(this, {\n deleteProperty: (target, property) => {\n return Reflect.deleteProperty(\n isLocalProperty(target, property) ? target : innerValue,\n property,\n );\n },\n get: (target, property, receiver) => {\n const isLocal = isLocalProperty(target, property);\n const value = Reflect.get(\n isLocal ? target : innerValue,\n property,\n isLocal ? receiver : innerValue,\n ) as unknown;\n if (isLocal || typeof value !== \"function\") {\n return value;\n }\n\n let cached = forwardedFunctions.get(property);\n if (cached?.value !== value) {\n cached = {\n value,\n wrapper: (...args: unknown[]): unknown =>\n Reflect.apply(value, innerValue, args) as unknown,\n };\n forwardedFunctions.set(property, cached);\n }\n return cached.wrapper;\n },\n has: (target, property) => {\n return Reflect.has(\n isLocalProperty(target, property) ? target : innerValue,\n property,\n );\n },\n set: (target, property, value, receiver) => {\n const isLocal = isLocalProperty(target, property);\n return Reflect.set(\n isLocal ? target : innerValue,\n property,\n value,\n isLocal ? receiver : innerValue,\n );\n },\n });\n }\n }\n\n // Preserve the runtime instance and static inheritance relationships without\n // constructing a second BaseClass instance as the proxy target.\n const BasePrototype = (BaseClass as unknown as { prototype: object })\n .prototype;\n Object.setPrototypeOf(ProxyClass.prototype, BasePrototype);\n Object.setPrototypeOf(ProxyClass, BaseClass);\n\n return ProxyClass as unknown as Omit<BaseClass, \"prototype\"> &\n Constructor<T & { readonly [inner]: T }, [T]>;\n }\n}\n","import { hashCkb } from \"../hasher/hasherCkb.js\";\nimport { Hex } from \"../hex/index.js\";\nimport { NumLike, numLeToBytes } from \"../num/index.js\";\nimport { CellInput, CellInputLike } from \"./transaction.js\";\n\n/**\n * Computes the Type ID hash of the given data.\n * @public\n *\n * @param cellInputLike - The first cell input of the transaction.\n * @param outputIndex - The output index of the Type ID cell.\n * @returns The hexadecimal string representation of the hash.\n *\n * @example\n * ```typescript\n * const hash = hashTypeId(cellInput, outputIndex); // Outputs something like \"0x...\"\n * ```\n */\n\nexport function hashTypeId(\n cellInputLike: CellInputLike,\n outputIndex: NumLike,\n): Hex {\n return hashCkb(\n CellInput.from(cellInputLike).toBytes(),\n numLeToBytes(outputIndex, 8),\n );\n}\n","import {\n Cell,\n CellLike,\n OutPointLike,\n Transaction,\n TransactionLike,\n} from \"../../ckb/index.js\";\nimport { HexLike } from \"../../hex/index.js\";\nimport { numFrom, NumLike } from \"../../num/index.js\";\nimport { ClientCollectableSearchKeyLike } from \"../clientTypes.advanced.js\";\nimport {\n ClientBlock,\n ClientBlockHeader,\n ClientBlockHeaderLike,\n ClientBlockLike,\n ClientTransactionResponse,\n ClientTransactionResponseLike,\n} from \"../clientTypes.js\";\nimport { DEFAULT_CONFIRMED_BLOCK_TIME } from \"./memory.advanced.js\";\n\n/**\n * @public\n * The ClientCache class is mainly designed for chained transactions.\n * Consumed & Created cells are \"marked\" so they can be correctly handled when composing transactions.\n * It also act as cache for rpc requests to reduce cost, but this is optional.\n */\nexport abstract class ClientCache {\n abstract markUsableNoCache(\n ...cellLikes: (CellLike | CellLike[])[]\n ): Promise<void>;\n async markUsable(...cellLikes: (CellLike | CellLike[])[]): Promise<void> {\n await this.recordCells(...cellLikes);\n return this.markUsableNoCache(...cellLikes);\n }\n abstract markUnusable(\n ...outPointLike: (OutPointLike | OutPointLike[])[]\n ): Promise<void>;\n async markTransactions(\n ...transactionLike: (TransactionLike | TransactionLike[])[]\n ): Promise<void> {\n await Promise.all([\n this.recordTransactionResponses(\n transactionLike.flat().map((transaction) => ({\n transaction: transaction,\n status: \"sent\",\n })),\n ),\n ...transactionLike.flat().map((transactionLike) => {\n const tx = Transaction.from(transactionLike);\n const txHash = tx.hash();\n\n return Promise.all([\n ...tx.inputs.map((i) => this.markUnusable(i.previousOutput)),\n ...tx.outputs.map((o, i) =>\n this.markUsable({\n cellOutput: o,\n outputData: tx.outputsData[i],\n outPoint: {\n txHash,\n index: i,\n },\n }),\n ),\n ]);\n }),\n ]);\n }\n abstract clear(): Promise<void>;\n abstract findCells(\n filter: ClientCollectableSearchKeyLike,\n ): AsyncGenerator<Cell>;\n abstract isUnusable(outPointLike: OutPointLike): Promise<boolean>;\n\n // ======\n // Following methods are for requests caching and optional.\n // ======\n\n /**\n * Record known cells\n * Implement this method to enable cells query caching\n * @param _cells\n */\n async recordCells(..._cells: (CellLike | CellLike[])[]): Promise<void> {}\n /**\n * Get a known cell by out point\n * Implement this method to enable cells query caching\n * @param _outPoint\n */\n async getCell(_outPoint: OutPointLike): Promise<Cell | undefined> {\n return;\n }\n\n /**\n * Record known transaction responses.\n * Implement this method to enable transactions query caching\n * @param _transactions\n */\n async recordTransactionResponses(\n ..._transactions: (\n ClientTransactionResponseLike | ClientTransactionResponseLike[]\n )[]\n ): Promise<void> {}\n /**\n * Get a known transaction response by hash\n * Implement this method to enable transactions query caching\n * @param _txHash\n */\n async getTransactionResponse(\n _txHash: HexLike,\n ): Promise<ClientTransactionResponse | undefined> {\n return;\n }\n /**\n * Record known transactions.\n * @param transactions\n */\n async recordTransactions(\n ...transactions: (TransactionLike | TransactionLike[])[]\n ): Promise<void> {\n return this.recordTransactionResponses(\n transactions.flat().map((transaction) => ({\n transaction,\n status: \"unknown\",\n })),\n );\n }\n /**\n * Get a known transaction by hash\n * @param txHash\n */\n async getTransaction(txHash: HexLike): Promise<Transaction | undefined> {\n return (await this.getTransactionResponse(txHash))?.transaction;\n }\n\n /**\n * Record known block headers.\n * Implement this method to enable block headers query caching\n * @param _headers\n */\n async recordHeaders(\n ..._headers: (ClientBlockHeaderLike | ClientBlockHeaderLike[])[]\n ): Promise<void> {}\n /**\n * Get a known block header by hash\n * Implement this method to enable block headers query caching\n * @param _hash\n */\n async getHeaderByHash(\n _hash: HexLike,\n ): Promise<ClientBlockHeader | undefined> {\n return;\n }\n /**\n * Get a known block header by number\n * Implement this method to enable block headers query caching\n * @param _number\n */\n async getHeaderByNumber(\n _number: NumLike,\n ): Promise<ClientBlockHeader | undefined> {\n return;\n }\n\n /**\n * Record known blocks.\n * Implement this method to enable blocks query caching\n * @param _blocks\n */\n async recordBlocks(\n ..._blocks: (ClientBlockLike | ClientBlockLike[])[]\n ): Promise<void> {}\n /**\n * Get a known block header by hash\n * Implement this method to enable block headers query caching\n * @param _hash\n */\n async getBlockByHash(_hash: HexLike): Promise<ClientBlock | undefined> {\n return;\n }\n /**\n * Get a known block header by number\n * Implement this method to enable block headers query caching\n * @param _number\n */\n async getBlockByNumber(_number: NumLike): Promise<ClientBlock | undefined> {\n return;\n }\n\n /**\n * Checks if a block header is considered confirmed.\n * The default implementation compares the header's timestamp against the current time\n * and a configured confirmation time. Override this method for custom confirmation logic.\n * @param header\n */\n hasHeaderConfirmed(header: ClientBlockHeader): boolean {\n return (\n numFrom(Date.now()) - header.timestamp >= DEFAULT_CONFIRMED_BLOCK_TIME\n );\n }\n}\n","import { Cell, CellLike, OutPoint, OutPointLike } from \"../../ckb/index.js\";\nimport { hexFrom, HexLike } from \"../../hex/index.js\";\nimport { Num, numFrom, NumLike } from \"../../num/index.js\";\nimport { ClientCollectableSearchKeyLike } from \"../clientTypes.advanced.js\";\nimport {\n ClientBlock,\n ClientBlockHeader,\n ClientBlockHeaderLike,\n ClientBlockLike,\n ClientTransactionResponse,\n ClientTransactionResponseLike,\n} from \"../clientTypes.js\";\nimport { ClientCache } from \"./cache.js\";\nimport {\n CellRecord,\n DEFAULT_CONFIRMED_BLOCK_TIME,\n filterCell,\n MapLru,\n} from \"./memory.advanced.js\";\n\nexport class ClientCacheMemory extends ClientCache {\n /**\n * OutPoint => [isLive, Cell | OutPoint]\n */\n private readonly cells: MapLru<string, CellRecord>;\n\n /**\n * TX Hash => Transaction Response\n */\n private readonly knownTransactions: MapLru<string, ClientTransactionResponse>;\n\n /**\n * Block Number => Block Hash\n */\n private readonly knownBlockHashes: MapLru<Num, string>;\n\n /**\n * Block Hash => Block Header / Full Block\n */\n private readonly knownBlocks: MapLru<\n string,\n Pick<ClientBlock, \"header\"> | ClientBlock\n >;\n\n private readonly confirmedBlockTime;\n\n /**\n * @param maxCells - Maximum number of cells to store in the cache. Defaults to 512.\n * @param maxTxs - Maximum number of transactions to store in the cache. Defaults to 256.\n * @param maxBlocks - Maximum number of blocks to store in the cache. Defaults to 128.\n * @param confirmedBlockTimeLike - Time in milliseconds after which a block is considered confirmed.\n * Defaults to DEFAULT_CONFIRMED_BLOCK_TIME (50 blocks * 10s).\n */\n constructor(\n private readonly maxCells = 512,\n private readonly maxTxs = 256,\n private readonly maxBlocks = 128,\n confirmedBlockTimeLike: NumLike = DEFAULT_CONFIRMED_BLOCK_TIME,\n ) {\n super();\n\n this.cells = new MapLru<string, CellRecord>(this.maxCells);\n this.knownTransactions = new MapLru<string, ClientTransactionResponse>(\n this.maxTxs,\n );\n this.knownBlockHashes = new MapLru<Num, string>(this.maxBlocks);\n this.knownBlocks = new MapLru<\n string,\n Pick<ClientBlock, \"header\"> | ClientBlock\n >(this.maxBlocks);\n\n this.confirmedBlockTime = numFrom(confirmedBlockTimeLike);\n }\n\n async markUsableNoCache(\n ...cellLikes: (CellLike | CellLike[])[]\n ): Promise<void> {\n cellLikes.flat().forEach((cellLike) => {\n const cell = Cell.from(cellLike).clone();\n const outPointStr = hexFrom(cell.outPoint.toBytes());\n\n this.cells.set(outPointStr, [true, cell]);\n });\n }\n\n async markUnusable(\n ...outPointLikes: (OutPointLike | OutPointLike[])[]\n ): Promise<void> {\n outPointLikes.flat().forEach((outPointLike) => {\n const outPoint = OutPoint.from(outPointLike);\n const outPointStr = hexFrom(outPoint.toBytes());\n\n const existed = this.cells.get(outPointStr);\n if (existed) {\n existed[0] = false;\n return;\n }\n this.cells.set(outPointStr, [false, { outPoint }]);\n });\n }\n\n async clear(): Promise<void> {\n this.cells.clear();\n this.knownTransactions.clear();\n }\n\n async *findCells(\n keyLike: ClientCollectableSearchKeyLike,\n ): AsyncGenerator<Cell> {\n for (const [key, [isLive, cell]] of this.cells.entries()) {\n if (!isLive) {\n continue;\n }\n if (!filterCell(keyLike, cell)) {\n continue;\n }\n\n this.cells.get(key);\n yield cell.clone();\n }\n }\n\n async isUnusable(outPointLike: OutPointLike): Promise<boolean> {\n const outPoint = OutPoint.from(outPointLike);\n\n return !(this.cells.get(hexFrom(outPoint.toBytes()))?.[0] ?? true);\n }\n\n async recordCells(...cells: (CellLike | CellLike[])[]): Promise<void> {\n cells.flat().map((cellLike) => {\n const cell = Cell.from(cellLike);\n const outPointStr = hexFrom(cell.outPoint.toBytes());\n\n if (this.cells.get(outPointStr)) {\n return;\n }\n this.cells.set(outPointStr, [undefined, cell]);\n });\n }\n async getCell(outPointLike: OutPointLike): Promise<Cell | undefined> {\n const outPoint = OutPoint.from(outPointLike);\n\n const cell = this.cells.get(hexFrom(outPoint.toBytes()))?.[1];\n if (cell && cell.cellOutput && cell.outputData) {\n return Cell.from((cell as Cell).clone());\n }\n }\n\n async recordTransactionResponses(\n ...transactions: (\n ClientTransactionResponseLike | ClientTransactionResponseLike[]\n )[]\n ): Promise<void> {\n transactions.flat().map((txLike) => {\n const tx = ClientTransactionResponse.from(txLike);\n this.knownTransactions.set(tx.transaction.hash(), tx);\n });\n }\n async getTransactionResponse(\n txHashLike: HexLike,\n ): Promise<ClientTransactionResponse | undefined> {\n const txHash = hexFrom(txHashLike);\n return this.knownTransactions.get(txHash)?.clone();\n }\n\n async recordHeaders(\n ...headers: (ClientBlockHeaderLike | ClientBlockHeaderLike[])[]\n ): Promise<void> {\n headers.flat().map((headerLike) => {\n const header = ClientBlockHeader.from(headerLike);\n\n this.knownBlockHashes.set(header.number, header.hash);\n\n const existed = this.knownBlocks.get(header.hash);\n if (existed) {\n return;\n }\n this.knownBlocks.set(header.hash, { header });\n });\n }\n async getHeaderByHash(\n hashLike: HexLike,\n ): Promise<ClientBlockHeader | undefined> {\n const hash = hexFrom(hashLike);\n const block = this.knownBlocks.get(hash);\n if (block) {\n this.knownBlockHashes.get(block.header.number); // For LRU\n }\n return block?.header;\n }\n async getHeaderByNumber(\n numberLike: NumLike,\n ): Promise<ClientBlockHeader | undefined> {\n const number = numFrom(numberLike);\n\n const hash = this.knownBlockHashes.get(number);\n if (!hash) {\n return;\n }\n return this.getHeaderByHash(hash);\n }\n\n async recordBlocks(\n ...blocks: (ClientBlockLike | ClientBlockLike[])[]\n ): Promise<void> {\n blocks.flat().map((blockLike) => {\n const block = ClientBlock.from(blockLike);\n\n this.knownBlockHashes.set(block.header.number, block.header.hash);\n this.knownBlocks.set(block.header.hash, block);\n });\n }\n async getBlockByHash(hashLike: HexLike): Promise<ClientBlock | undefined> {\n const hash = hexFrom(hashLike);\n const block = this.knownBlocks.get(hash);\n if (block) {\n this.knownBlockHashes.get(block.header.number); // For LRU\n if (\"transactions\" in block) {\n return block;\n }\n }\n return;\n }\n async getBlockByNumber(\n numberLike: NumLike,\n ): Promise<ClientBlock | undefined> {\n const number = numFrom(numberLike);\n\n const hash = this.knownBlockHashes.get(number);\n if (!hash) {\n return;\n }\n return this.getBlockByHash(hash);\n }\n\n hasHeaderConfirmed(header: ClientBlockHeader): boolean {\n return numFrom(Date.now()) - header.timestamp >= this.confirmedBlockTime;\n }\n}\n","import {\n Cell,\n CellDep,\n OutPoint,\n OutPointLike,\n ScriptLike,\n Transaction,\n TransactionLike,\n} from \"../ckb/index.js\";\nimport { Zero } from \"../fixedPoint/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../hex/index.js\";\nimport { Num, NumLike, numFrom, numMax, numMin } from \"../num/index.js\";\nimport { reduceAsync, sleep } from \"../utils/index.js\";\nimport { ClientCache } from \"./cache/index.js\";\nimport { ClientCacheMemory } from \"./cache/memory.js\";\nimport {\n ClientCollectableSearchKeyLike,\n DEFAULT_MAX_FEE_RATE,\n DEFAULT_MIN_FEE_RATE,\n} from \"./clientTypes.advanced.js\";\nimport {\n CellDepInfo,\n CellDepInfoLike,\n ClientBlock,\n ClientBlockHeader,\n ClientFindCellsResponse,\n ClientFindTransactionsGroupedResponse,\n ClientFindTransactionsResponse,\n ClientIndexerSearchKey,\n ClientIndexerSearchKeyLike,\n ClientIndexerSearchKeyTransactionLike,\n ClientTransactionResponse,\n ErrorClientMaxFeeRateExceeded,\n ErrorClientWaitTransactionTimeout,\n OutputsValidator,\n ScriptInfo,\n type ScriptInfoLike,\n} from \"./clientTypes.js\";\nimport { KnownScript } from \"./knownScript.js\";\n\nexport type ClientConfig = {\n cache?: ClientCache;\n scripts?: Partial<Record<KnownScript, ScriptInfoLike>>;\n};\n\n/**\n * @public\n */\nexport abstract class Client {\n public cache: ClientCache;\n private readonly scripts: Partial<Record<KnownScript, ScriptInfoLike>>;\n\n constructor(config?: ClientConfig) {\n this.cache = config?.cache ?? new ClientCacheMemory();\n this.scripts = config?.scripts ?? {};\n }\n\n /**\n * The legacy primary URL associated with this Client.\n *\n * @deprecated A Client may use multiple endpoints or a Transport without a\n * URL, so this value does not reliably identify its connection.\n */\n abstract get url(): string;\n abstract get addressPrefix(): string;\n\n /**\n * Get the deployment info for a well-known CKB script.\n * Returns the cell deps and type script info needed to use the script.\n *\n * @param script - The KnownScript enum value.\n * @returns Script info including cellDeps and type hash.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n *\n * // Get xUDT script deployment info\n * const xudtInfo = await client.getKnownScript(ccc.KnownScript.XUdt);\n * console.log(`xUDT cellDeps:`, xudtInfo.cellDeps);\n *\n * // Build an xUDT type script\n * const xudtType = await ccc.Script.fromKnownScript(\n * client,\n * ccc.KnownScript.XUdt,\n * \"0xOWNER_LOCK_HASH...\",\n * );\n * ```\n */\n async getKnownScript(script: KnownScript): Promise<ScriptInfo> {\n const found = this.scripts[script];\n if (!found) {\n throw new Error(\n `No script information was found for ${script} on ${this.addressPrefix}`,\n );\n }\n return ScriptInfo.from(found);\n }\n\n abstract getFeeRateStatistics(\n blockRange?: NumLike,\n ): Promise<{ mean: Num; median: Num }>;\n /**\n * Get the recommended transaction fee rate based on recent blocks.\n * Returns the median fee rate, clamped between min and max fee rates.\n *\n * @param blockRange - Number of recent blocks to analyze.\n * @param options - Optional max fee rate cap.\n * @returns The recommended fee rate in Shannons per KB.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const feeRate = await client.getFeeRate();\n * console.log(`Current fee rate: ${feeRate} Shannons/KB`);\n * ```\n */\n async getFeeRate(\n blockRange?: NumLike,\n options?: { maxFeeRate?: NumLike },\n ): Promise<Num> {\n const feeRate = numMax(\n (await this.getFeeRateStatistics(blockRange)).median,\n DEFAULT_MIN_FEE_RATE,\n );\n\n const maxFeeRate = numFrom(options?.maxFeeRate ?? DEFAULT_MAX_FEE_RATE);\n if (maxFeeRate === Zero) {\n return feeRate;\n }\n\n return numMin(feeRate, maxFeeRate);\n }\n\n /**\n * Get the latest block number (tip) of the chain.\n *\n * @returns The current tip block number.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const tipBlockNumber = await client.getTip();\n * console.log(`Current block height: ${tipBlockNumber}`);\n * ```\n */\n abstract getTip(): Promise<Num>;\n\n /**\n * Get the header of the latest block.\n *\n * @param verbosity - Verbosity level (0 for hex, 1 for object).\n * @returns The tip block header.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const header = await client.getTipHeader();\n * console.log(`Block #${header.number}, hash: ${header.hash}`);\n * ```\n */\n abstract getTipHeader(verbosity?: number | null): Promise<ClientBlockHeader>;\n abstract getBlockByNumberNoCache(\n blockNumber: NumLike,\n verbosity?: number | null,\n withCycles?: boolean | null,\n ): Promise<ClientBlock | undefined>;\n abstract getBlockByHashNoCache(\n blockHash: HexLike,\n verbosity?: number | null,\n withCycles?: boolean | null,\n ): Promise<ClientBlock | undefined>;\n abstract getHeaderByNumberNoCache(\n blockNumber: NumLike,\n verbosity?: number | null,\n ): Promise<ClientBlockHeader | undefined>;\n abstract getHeaderByHashNoCache(\n blockHash: HexLike,\n verbosity?: number | null,\n ): Promise<ClientBlockHeader | undefined>;\n async getBlockByNumber(\n blockNumber: NumLike,\n verbosity?: number | null,\n withCycles?: boolean | null,\n ): Promise<ClientBlock | undefined> {\n const block = await this.cache.getBlockByNumber(blockNumber);\n if (block) {\n return block;\n }\n\n const res = await this.getBlockByNumberNoCache(\n blockNumber,\n verbosity,\n withCycles,\n );\n if (res && this.cache.hasHeaderConfirmed(res.header)) {\n await this.cache.recordBlocks(res);\n }\n return res;\n }\n async getBlockByHash(\n blockHash: HexLike,\n verbosity?: number | null,\n withCycles?: boolean | null,\n ): Promise<ClientBlock | undefined> {\n const block = await this.cache.getBlockByHash(blockHash);\n if (block) {\n return block;\n }\n\n const res = await this.getBlockByHashNoCache(\n blockHash,\n verbosity,\n withCycles,\n );\n if (res && this.cache.hasHeaderConfirmed(res.header)) {\n await this.cache.recordBlocks(res);\n }\n return res;\n }\n async getHeaderByNumber(\n blockNumber: NumLike,\n verbosity?: number | null,\n ): Promise<ClientBlockHeader | undefined> {\n const header = await this.cache.getHeaderByNumber(blockNumber);\n if (header) {\n return header;\n }\n\n const res = await this.getHeaderByNumberNoCache(blockNumber, verbosity);\n if (res && this.cache.hasHeaderConfirmed(res)) {\n await this.cache.recordHeaders(res);\n }\n return res;\n }\n async getHeaderByHash(\n blockHash: HexLike,\n verbosity?: number | null,\n ): Promise<ClientBlockHeader | undefined> {\n const header = await this.cache.getHeaderByHash(blockHash);\n if (header) {\n return header;\n }\n\n const res = await this.getHeaderByHashNoCache(blockHash, verbosity);\n if (res && this.cache.hasHeaderConfirmed(res)) {\n await this.cache.recordHeaders(res);\n }\n return res;\n }\n\n abstract estimateCycles(transaction: TransactionLike): Promise<Num>;\n abstract sendTransactionDry(\n transaction: TransactionLike,\n validator?: OutputsValidator,\n ): Promise<Num>;\n\n abstract sendTransactionNoCache(\n transaction: TransactionLike,\n validator?: OutputsValidator,\n ): Promise<Hex>;\n abstract getTransactionNoCache(\n txHash: HexLike,\n ): Promise<ClientTransactionResponse | undefined>;\n\n /**\n * Get a cell by its out point.\n * The cell will be cached if it is found.\n *\n * @param outPointLike - The out point of the cell to get.\n * @returns The cell if it exists, otherwise undefined.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const cell = await client.getCell({\n * txHash: \"0xTX_HASH...\",\n * index: 0,\n * });\n * if (cell) {\n * console.log(`Capacity: ${ccc.fixedPointToString(cell.cellOutput.capacity)} CKB`);\n * console.log(`Lock: ${cell.cellOutput.lock.codeHash}`);\n * console.log(`Data: ${cell.outputData}`);\n * }\n * ```\n */\n async getCell(outPointLike: OutPointLike): Promise<Cell | undefined> {\n const outPoint = OutPoint.from(outPointLike);\n const cached = await this.cache.getCell(outPoint);\n\n if (cached) {\n return cached;\n }\n\n const transaction = await this.getTransaction(outPoint.txHash);\n if (!transaction) {\n return;\n }\n const output = transaction.transaction.getOutput(outPoint.index);\n if (!output) {\n return;\n }\n\n const cell = Cell.from({\n ...output,\n outPoint,\n });\n await this.cache.recordCells(cell);\n return cell;\n }\n\n async getCellWithHeader(\n outPointLike: OutPointLike,\n ): Promise<{ cell: Cell; header?: ClientBlockHeader } | undefined> {\n const outPoint = OutPoint.from(outPointLike);\n\n const res = await this.getTransactionWithHeader(outPoint.txHash);\n if (!res) {\n return;\n }\n const { transaction, header } = res;\n\n const output = transaction.transaction.getOutput(outPoint.index);\n if (!output) {\n return;\n }\n\n const cell = Cell.from({\n ...output,\n outPoint,\n });\n await this.cache.recordCells(cell);\n return { cell, header };\n }\n\n abstract getCellLiveNoCache(\n outPointLike: OutPointLike,\n withData?: boolean | null,\n includeTxPool?: boolean | null,\n ): Promise<Cell | undefined>;\n /**\n * Get a live (unspent) cell by its out point.\n * Unlike getCell(), this verifies the cell is still live on-chain.\n *\n * @param outPointLike - The out point of the cell.\n * @param withData - Whether to include cell data.\n * @param includeTxPool - Whether to include cells in the transaction pool.\n * @returns The live cell, or undefined if spent or not found.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const cell = await client.getCellLive(\n * { txHash: \"0xTX_HASH...\", index: 0 },\n * true, // include data\n * true, // include tx pool\n * );\n * if (cell) {\n * console.log(\"Cell is still live!\");\n * } else {\n * console.log(\"Cell has been spent or does not exist.\");\n * }\n * ```\n */\n async getCellLive(\n outPointLike: OutPointLike,\n withData?: boolean | null,\n includeTxPool?: boolean | null,\n ): Promise<Cell | undefined> {\n const cell = await this.getCellLiveNoCache(\n outPointLike,\n withData,\n includeTxPool,\n );\n if (withData && cell) {\n await this.cache.recordCells(cell);\n }\n return cell;\n }\n\n abstract findCellsPagedNoCache(\n key: ClientIndexerSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<ClientFindCellsResponse>;\n /**\n * Find cells with pagination support.\n * Returns one page of results at a time with a cursor for the next page.\n *\n * @param key - The indexer search key.\n * @param order - Sort order (\"asc\" or \"desc\").\n * @param limit - Maximum cells per page.\n * @param after - Cursor from previous page for pagination.\n * @returns A page of cells with a cursor for the next page.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const { script: lock } = await ccc.Address.fromString(\"ckt1q...\", client);\n *\n * // Get first page of cells\n * const page1 = await client.findCellsPaged({\n * script: lock,\n * scriptType: \"lock\",\n * }, \"asc\", 20);\n * console.log(`Found ${page1.cells.length} cells`);\n *\n * // Get next page\n * if (page1.cells.length === 20) {\n * const page2 = await client.findCellsPaged(\n * { script: lock, scriptType: \"lock\" },\n * \"asc\", 20, page1.lastCursor,\n * );\n * }\n * ```\n */\n async findCellsPaged(\n key: ClientIndexerSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<ClientFindCellsResponse> {\n const res = await this.findCellsPagedNoCache(key, order, limit, after);\n if (key.withData !== false) {\n await this.cache.recordCells(res.cells);\n }\n return res;\n }\n\n async *findCellsOnChain(\n key: ClientIndexerSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<Cell> {\n let last: string | undefined = undefined;\n\n while (true) {\n const { cells, lastCursor } = await this.findCellsPaged(\n key,\n order,\n limit,\n last,\n );\n for (const cell of cells) {\n yield cell;\n }\n if (cells.length === 0 || cells.length < limit) {\n return;\n }\n last = lastCursor;\n }\n }\n\n /**\n * Find cells by search key designed for collectable cells.\n * The result also includes cached cells, the order param only works for cells fetched from RPC.\n *\n * @param keyLike - The search key.\n * @returns A async generator for yielding cells.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const { script: lock } = await ccc.Address.fromString(\"ckt1q...\", client);\n *\n * // Find all cells owned by a lock script\n * for await (const cell of client.findCells({\n * script: lock,\n * scriptType: \"lock\",\n * scriptSearchMode: \"exact\",\n * withData: true,\n * })) {\n * console.log(`Cell: ${cell.outPoint.txHash}:${cell.outPoint.index}`);\n * console.log(`Capacity: ${ccc.fixedPointToString(cell.cellOutput.capacity)} CKB`);\n * }\n * ```\n */\n async *findCells(\n keyLike: ClientCollectableSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<Cell> {\n const key = ClientIndexerSearchKey.from(keyLike);\n const foundedOutPoints = [];\n\n for await (const cell of this.cache.findCells(key)) {\n foundedOutPoints.push(cell.outPoint);\n yield cell;\n }\n\n for await (const cell of this.findCellsOnChain(key, order, limit)) {\n if (\n (await this.cache.isUnusable(cell.outPoint)) ||\n foundedOutPoints.some((founded) => founded.eq(cell.outPoint))\n ) {\n continue;\n }\n\n yield cell;\n }\n }\n\n /**\n * Find cells by lock script, optionally filtered by type script.\n *\n * @param lock - The lock script to search by.\n * @param type - Optional type script filter.\n * @param withData - Whether to include cell data (default: true).\n * @param order - Sort order by block number (\"asc\" or \"desc\").\n * @param limit - Page size for each RPC call (default: 10).\n * @returns An async generator yielding matching cells.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const { script: lock } = await ccc.Address.fromString(\"ckt1q...\", client);\n *\n * // Find all cells belonging to this address\n * for await (const cell of client.findCellsByLock(lock)) {\n * console.log(`${ccc.fixedPointToString(cell.cellOutput.capacity)} CKB`);\n * }\n *\n * // Find only xUDT cells belonging to this address\n * const xudtType = await ccc.Script.fromKnownScript(\n * client, ccc.KnownScript.XUdt, \"0xOWNER_LOCK_HASH...\",\n * );\n * for await (const cell of client.findCellsByLock(lock, xudtType)) {\n * console.log(`UDT cell found`);\n * }\n * ```\n */\n findCellsByLock(\n lock: ScriptLike,\n type?: ScriptLike | null,\n withData = true,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<Cell> {\n return this.findCells(\n {\n script: lock,\n scriptType: \"lock\",\n scriptSearchMode: \"exact\",\n filter: {\n script: type,\n },\n withData,\n },\n order,\n limit,\n );\n }\n\n /**\n * Find cells by type script.\n *\n * @param type - The type script to search by.\n * @param withData - Whether to include cell data (default: true).\n * @param order - Sort order by block number.\n * @param limit - Page size for each RPC call (default: 10).\n * @returns An async generator yielding matching cells.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * // Find all xUDT cells of a specific token\n * const xudtType = await ccc.Script.fromKnownScript(\n * client, ccc.KnownScript.XUdt, \"0xOWNER_LOCK_HASH...\",\n * );\n * for await (const cell of client.findCellsByType(xudtType)) {\n * console.log(`Token cell: ${cell.outPoint.txHash}:${cell.outPoint.index}`);\n * }\n * ```\n */\n findCellsByType(\n type: ScriptLike,\n withData = true,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<Cell> {\n return this.findCells(\n {\n script: type,\n scriptType: \"type\",\n scriptSearchMode: \"exact\",\n withData,\n },\n order,\n limit,\n );\n }\n\n async findSingletonCellByType(\n type: ScriptLike,\n withData = true,\n ): Promise<Cell | undefined> {\n for await (const cell of this.findCellsByType(\n type,\n withData,\n undefined,\n 1,\n )) {\n return cell;\n }\n }\n\n /**\n * Resolve cell dependency info into concrete CellDep objects.\n *\n * If a CellDepInfo specifies a type script, the live cell carrying it is looked up\n * on-chain and, when found, its outpoint is used instead of the configured one. When\n * the lookup finds nothing, the configured outpoint is used as written. A CellDepInfo\n * without a type script is always used as written.\n *\n * @param cellDepsInfoLike - One or more CellDepInfo or arrays of CellDepInfo.\n * @returns Resolved CellDep array ready to be added to a transaction.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const xudtInfo = await client.getKnownScript(ccc.KnownScript.XUdt);\n * const cellDeps = await client.getCellDeps(xudtInfo.cellDeps);\n * // cellDeps can be added to a transaction:\n * // tx.cellDeps.push(...cellDeps);\n * ```\n */\n async getCellDeps(\n ...cellDepsInfoLike: (CellDepInfoLike | CellDepInfoLike[])[]\n ): Promise<CellDep[]> {\n return Promise.all(\n cellDepsInfoLike.flat().map(async (infoLike) => {\n const { cellDep, type } = CellDepInfo.from(infoLike);\n if (type === undefined) {\n return cellDep;\n }\n const found = await this.findSingletonCellByType(type);\n if (!found) {\n return cellDep;\n }\n\n return CellDep.from({\n outPoint: found.outPoint,\n depType: cellDep.depType,\n });\n }),\n );\n }\n\n abstract findTransactionsPaged(\n key: Omit<ClientIndexerSearchKeyTransactionLike, \"groupByTransaction\"> & {\n groupByTransaction: true;\n },\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<ClientFindTransactionsGroupedResponse>;\n abstract findTransactionsPaged(\n key: Omit<ClientIndexerSearchKeyTransactionLike, \"groupByTransaction\"> & {\n groupByTransaction?: false | null;\n },\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<ClientFindTransactionsResponse>;\n abstract findTransactionsPaged(\n key: ClientIndexerSearchKeyTransactionLike,\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ): Promise<\n ClientFindTransactionsResponse | ClientFindTransactionsGroupedResponse\n >;\n\n findTransactions(\n key: Omit<ClientIndexerSearchKeyTransactionLike, \"groupByTransaction\"> & {\n groupByTransaction: true;\n },\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsGroupedResponse[\"transactions\"][0]>;\n findTransactions(\n key: Omit<ClientIndexerSearchKeyTransactionLike, \"groupByTransaction\"> & {\n groupByTransaction?: false | null;\n },\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsResponse[\"transactions\"][0]>;\n findTransactions(\n key: ClientIndexerSearchKeyTransactionLike,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n >;\n async *findTransactions(\n key: ClientIndexerSearchKeyTransactionLike,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n > {\n let last: string | undefined = undefined;\n\n while (true) {\n const {\n transactions,\n lastCursor,\n }:\n ClientFindTransactionsResponse | ClientFindTransactionsGroupedResponse =\n await this.findTransactionsPaged(key, order, limit, last);\n for (const tx of transactions) {\n yield tx;\n }\n if (transactions.length === 0 || transactions.length < limit) {\n return;\n }\n last = lastCursor;\n }\n }\n\n /**\n * Find transactions related to a lock script, optionally filtered by type script.\n *\n * @param lock - The lock script to search by.\n * @param type - Optional type script filter.\n * @param groupByTransaction - If true, group results by transaction.\n * @param order - Sort order by block number.\n * @param limit - Page size per RPC call.\n * @returns An async generator yielding transaction records.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const { script: lock } = await ccc.Address.fromString(\"ckt1q...\", client);\n *\n * // List all transactions related to an address (grouped)\n * for await (const txRecord of client.findTransactionsByLock(lock, null, true)) {\n * console.log(`TX: ${txRecord.txHash}, Block: ${txRecord.blockNumber}`);\n * }\n * ```\n */\n findTransactionsByLock(\n lock: ScriptLike,\n type: ScriptLike | undefined | null,\n groupByTransaction: true,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsGroupedResponse[\"transactions\"][0]>;\n findTransactionsByLock(\n lock: ScriptLike,\n type?: ScriptLike | null,\n groupByTransaction?: false | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsResponse[\"transactions\"][0]>;\n findTransactionsByLock(\n lock: ScriptLike,\n type?: ScriptLike | null,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n >;\n findTransactionsByLock(\n lock: ScriptLike,\n type?: ScriptLike | null,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n > {\n return this.findTransactions(\n {\n script: lock,\n scriptType: \"lock\",\n scriptSearchMode: \"exact\",\n filter: {\n script: type,\n },\n groupByTransaction,\n },\n order,\n limit,\n );\n }\n\n findTransactionsByType(\n type: ScriptLike,\n groupByTransaction: true,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsGroupedResponse[\"transactions\"][0]>;\n findTransactionsByType(\n type: ScriptLike,\n groupByTransaction?: false | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsResponse[\"transactions\"][0]>;\n findTransactionsByType(\n type: ScriptLike,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n >;\n findTransactionsByType(\n type: ScriptLike,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit = 10,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n > {\n return this.findTransactions(\n {\n script: type,\n scriptType: \"type\",\n scriptSearchMode: \"exact\",\n groupByTransaction,\n },\n order,\n limit,\n );\n }\n\n abstract getCellsCapacity(key: ClientIndexerSearchKeyLike): Promise<Num>;\n\n /**\n * Get the total CKB balance of a single lock script.\n * Only counts cells with no type script and no data (pure CKB capacity cells).\n *\n * @param lock - The lock script to query balance for.\n * @returns The total capacity in Shannons as a bigint.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const { script: lock } = await ccc.Address.fromString(\n * \"ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsq...\",\n * client,\n * );\n * const balance = await client.getBalanceSingle(lock);\n * console.log(`Balance: ${ccc.fixedPointToString(balance)} CKB`);\n * ```\n */\n async getBalanceSingle(lock: ScriptLike): Promise<Num> {\n return this.getCellsCapacity({\n script: lock,\n scriptType: \"lock\",\n scriptSearchMode: \"exact\",\n filter: {\n scriptLenRange: [0, 1],\n outputDataLenRange: [0, 1],\n },\n });\n }\n\n /**\n * Get the total CKB balance across multiple lock scripts.\n * Sums the balance from each lock script.\n *\n * @param locks - An array of lock scripts to query.\n * @returns The combined total capacity in Shannons as a bigint.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const signer = new ccc.SignerCkbPrivateKey(client, \"0x...\");\n * await signer.connect();\n *\n * const locks = await signer.getRecommendedAddressObj()\n * .then(({ script }) => [script]);\n * const totalBalance = await client.getBalance(locks);\n * console.log(`Total: ${ccc.fixedPointToString(totalBalance)} CKB`);\n * ```\n */\n async getBalance(locks: ScriptLike[]): Promise<Num> {\n return reduceAsync(\n locks,\n async (acc, lock) => acc + (await this.getBalanceSingle(lock)),\n Zero,\n );\n }\n\n /**\n * Send a signed transaction to the CKB network.\n * Validates the fee rate against the maximum before sending.\n *\n * @param transaction - The transaction to send.\n * @param validator - Optional outputs validator (\"passthrough\" or \"well_known_scripts_only\").\n * @param options - Optional configuration including maxFeeRate.\n * @returns The transaction hash.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const signer = new ccc.SignerCkbPrivateKey(client, \"0x...\");\n * await signer.connect();\n *\n * const tx = ccc.Transaction.from({\n * outputs: [{ capacity: ccc.fixedPointFrom(100), lock: receiverLock }],\n * });\n * await tx.completeInputsByCapacity(signer);\n * await tx.completeFeeBy(signer);\n *\n * // Usually you call signer.sendTransaction(tx) which signs then sends.\n * // client.sendTransaction expects an already-signed transaction.\n * const txHash = await client.sendTransaction(tx);\n * ```\n */\n async sendTransaction(\n transaction: TransactionLike,\n validator?: OutputsValidator,\n options?: { maxFeeRate?: NumLike },\n ): Promise<Hex> {\n const tx = Transaction.from(transaction);\n\n const maxFeeRate = numFrom(options?.maxFeeRate ?? DEFAULT_MAX_FEE_RATE);\n const feeRate = await tx.getFeeRate(this);\n if (maxFeeRate > Zero && feeRate > maxFeeRate) {\n throw new ErrorClientMaxFeeRateExceeded(maxFeeRate, feeRate);\n }\n\n const txHash = await this.sendTransactionNoCache(tx, validator);\n\n await this.cache.markTransactions(tx);\n return txHash;\n }\n\n /**\n * Get a transaction by its hash, including its status and block info.\n *\n * @param txHashLike - The transaction hash to look up.\n * @returns The transaction response with status, or undefined if not found.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * const txResponse = await client.getTransaction(\"0xTX_HASH...\");\n * if (txResponse) {\n * console.log(`Status: ${txResponse.status}`);\n * console.log(`Block: ${txResponse.blockNumber}`);\n * console.log(`Outputs: ${txResponse.transaction.outputs.length}`);\n * }\n * ```\n */\n async getTransaction(\n txHashLike: HexLike,\n ): Promise<ClientTransactionResponse | undefined> {\n const txHash = hexFrom(txHashLike);\n const res = await this.getTransactionNoCache(txHash);\n if (res) {\n await this.cache.recordTransactionResponses(res);\n return res;\n }\n\n return this.cache.getTransactionResponse(txHash);\n }\n\n /**\n * This method gets specified transaction with its block header (if existed).\n * This is mainly for caching because we need the header to test if we can safely trust the cached tx status.\n * @param txHashLike\n */\n async getTransactionWithHeader(\n txHashLike: HexLike,\n ): Promise<\n | { transaction: ClientTransactionResponse; header?: ClientBlockHeader }\n | undefined\n > {\n const txHash = hexFrom(txHashLike);\n const tx = await this.cache.getTransactionResponse(txHash);\n if (tx?.blockHash) {\n const header = await this.getHeaderByHash(tx.blockHash);\n if (header && this.cache.hasHeaderConfirmed(header)) {\n return {\n transaction: tx,\n header,\n };\n }\n }\n\n const res = await this.getTransactionNoCache(txHash);\n if (!res) {\n return;\n }\n\n await this.cache.recordTransactionResponses(res);\n return {\n transaction: res,\n header: res.blockHash\n ? await this.getHeaderByHash(res.blockHash)\n : undefined,\n };\n }\n\n /**\n * Wait for a transaction to be confirmed on-chain.\n * Polls the node until the transaction reaches the specified confirmation depth.\n *\n * @param txHash - The transaction hash to wait for.\n * @param confirmations - Number of block confirmations to wait for (default: 0 = committed).\n * @param timeout - Maximum wait time in milliseconds (default: 60000).\n * @param interval - Polling interval in milliseconds (default: 2000).\n * @returns The transaction response once confirmed, or throws on timeout.\n *\n * @example\n * ```typescript\n * import { ccc } from \"@ckb-ccc/core\";\n *\n * const clientOwner = ccc.ClientPublicTestnet.open();\n * const client = clientOwner.value;\n * // Call `await clientOwner.dispose()` when the client is no longer needed.\n * // Wait for transaction to be committed (0 confirmations)\n * const tx = await client.waitTransaction(\"0xTX_HASH...\");\n * console.log(`Confirmed in block: ${tx?.blockNumber}`);\n *\n * // Wait for 4 confirmations with 2 minute timeout\n * const confirmedTx = await client.waitTransaction(\n * \"0xTX_HASH...\",\n * 4, // confirmations\n * 120000, // timeout: 2 minutes\n * );\n * ```\n */\n async waitTransaction(\n txHash: HexLike,\n confirmations: number = 0,\n timeout: number = 60000,\n interval: number = 2000,\n ): Promise<ClientTransactionResponse | undefined> {\n const startTime = Date.now();\n let tx: ClientTransactionResponse | undefined;\n\n const getTx = async () => {\n const res = await this.getTransaction(txHash);\n if (\n !res ||\n res.blockNumber == null ||\n [\"sent\", \"pending\", \"proposed\"].includes(res.status)\n ) {\n return undefined;\n }\n\n tx = res;\n return res;\n };\n\n while (true) {\n if (!tx) {\n if (await getTx()) {\n continue;\n }\n } else if (confirmations === 0) {\n return tx;\n } else if (\n (await this.getTipHeader()).number - tx.blockNumber! >=\n confirmations\n ) {\n return tx;\n }\n\n if (Date.now() - startTime + interval >= timeout) {\n throw new ErrorClientWaitTransactionTimeout(timeout);\n }\n await sleep(interval);\n }\n }\n}\n","import {\n JsonRpcPayload,\n JsonRpcResponse,\n JsonRpcTransport,\n JsonRpcTransportRequestOptions,\n} from \"./transport.js\";\n\nexport class JsonRpcTransportFallback implements JsonRpcTransport {\n // Current transport index\n private i = 0;\n\n constructor(private readonly transports: JsonRpcTransport[]) {}\n\n async request(\n data: JsonRpcPayload,\n options?: JsonRpcTransportRequestOptions,\n ): Promise<JsonRpcResponse> {\n const startI = this.i;\n let lastErr: unknown = new Error(\n \"JsonRpcTransportFallback requires at least one transport\",\n );\n\n for (let tried = 0; tried < this.transports.length; tried += 1) {\n const i = (startI + tried) % this.transports.length;\n\n try {\n const res = await this.transports[i].request(data, options);\n\n this.i = i;\n return res;\n } catch (err) {\n lastErr = err;\n }\n }\n\n throw lastErr;\n }\n}\n","export type JsonRpcId = string | number;\n\nexport type JsonRpcPayload = {\n id: JsonRpcId;\n jsonrpc: \"2.0\";\n method: string;\n params: unknown[] | Record<string, unknown>;\n};\n\nexport type JsonRpcErrorLike<Data = unknown> = {\n code: number;\n message: string;\n data?: Data;\n};\n\nexport class JsonRpcError<Data = unknown> extends Error {\n readonly code: number;\n readonly data?: Data;\n\n constructor(error: JsonRpcErrorLike<Data>) {\n super(error.message);\n this.name = \"JsonRpcError\";\n this.code = error.code;\n this.data = error.data;\n }\n}\n\nexport type JsonRpcResponse<Result = unknown, ErrorData = unknown> = {\n id: JsonRpcId;\n jsonrpc: \"2.0\";\n} & (\n | { result: Result; error?: never }\n | { result?: never; error: JsonRpcErrorLike<ErrorData> }\n);\n\nexport type JsonRpcTransportRequestOptions = {\n /** Cancels this individual request without disposing the transport. */\n signal?: AbortSignal;\n /** Overrides the transport's default timeout for this request. */\n timeout?: number;\n};\n\nexport interface JsonRpcTransport {\n /**\n * Sends a JSON-RPC request to the server.\n *\n * @param payload - The JSON-RPC payload to send.\n * @returns The JSON-RPC response.\n */\n request(\n payload: JsonRpcPayload,\n options?: JsonRpcTransportRequestOptions,\n ): Promise<JsonRpcResponse>;\n}\n","import { abortSignalToPromise } from \"../utils/abortSignal.js\";\nimport { OwnerAggregated } from \"../utils/owner/aggregated.js\";\nimport { Owner } from \"../utils/owner/owner.js\";\nimport { jsonRpcTransportFromUri } from \"./transports/factory.js\";\nimport { JsonRpcTransportFallback } from \"./transports/fallback.js\";\nimport {\n JsonRpcError,\n JsonRpcPayload,\n JsonRpcResponse,\n JsonRpcTransport,\n JsonRpcTransportRequestOptions,\n} from \"./transports/index.js\";\n\nfunction openTransports(\n urls: readonly [string, ...string[]],\n config?: { timeout?: number },\n): Owner<JsonRpcTransportFallback> {\n const transportOwners = Array.from(new Set(urls), (url) =>\n jsonRpcTransportFromUri(url, config),\n );\n return OwnerAggregated.from(transportOwners).map(\n (transports) => new JsonRpcTransportFallback([...transports]),\n );\n}\n\n/**\n * Applies a transformation function to a value if the transformer is provided.\n *\n * @param value - The value to be transformed.\n * @param transformer - An optional transformation function.\n * @returns The transformed value if a transformer is provided, otherwise the original value.\n *\n * @example\n * ```typescript\n * const result = transform(5, (x) => x * 2); // Outputs 10\n * const resultWithoutTransformer = transform(5); // Outputs 5\n * ```\n */\nfunction transform(value: unknown, transformer?: (i: unknown) => unknown) {\n if (transformer) {\n return transformer(value);\n }\n return value;\n}\n\n/**\n * @deprecated Used only by the legacy positional constructor. Use the static\n * {@link RequestorJsonRpc.new} or {@link RequestorJsonRpc.open} methods.\n */\nexport type RequestorJsonRpcConfig = {\n fallbacks?: string[];\n timeout?: number;\n maxConcurrent?: number;\n transport?: JsonRpcTransport;\n};\n\nexport class RequestorJsonRpc {\n public readonly maxConcurrent?: number;\n private concurrent = 0;\n private readonly pending: (() => void)[] = [];\n\n public readonly transport: JsonRpcTransport;\n\n private id = 0;\n\n /**\n * Creates a Requestor using legacy positional arguments.\n *\n * @param url_ - The URL of the JSON-RPC server.\n * @param timeout - The timeout for requests in milliseconds\n * @deprecated Use {@link RequestorJsonRpc.new} with a borrowed Transport or\n * {@link RequestorJsonRpc.open} when creating Transports.\n */\n constructor(\n private readonly url_: string,\n config?: RequestorJsonRpcConfig,\n private readonly onError?: (err: unknown) => Promise<void> | void,\n ) {\n this.maxConcurrent = config?.maxConcurrent;\n if (config?.transport) {\n this.transport = config.transport;\n } else {\n this.transport = openTransports(\n [url_, ...(config?.fallbacks ?? [])],\n config,\n ).value;\n }\n }\n\n /** Creates a Requestor that borrows an existing Transport. */\n static new({\n transport,\n maxConcurrent,\n onError,\n }: {\n transport: JsonRpcTransport;\n maxConcurrent?: number;\n onError?: (err: unknown) => Promise<void> | void;\n }): RequestorJsonRpc {\n return new RequestorJsonRpc(\"\", { transport, maxConcurrent }, onError);\n }\n\n /** Opens a Requestor with ownership of its default transports. */\n static open({\n urls: [url, ...fallbacks],\n onError,\n ...config\n }: {\n urls: readonly [string, ...string[]];\n timeout?: number;\n maxConcurrent?: number;\n onError?: (err: unknown) => Promise<void> | void;\n }): Owner<RequestorJsonRpc> {\n const transportOwner = openTransports([url, ...fallbacks], config);\n return transportOwner.map((transport) =>\n RequestorJsonRpc.new({\n transport,\n ...config,\n onError,\n }),\n );\n }\n\n /**\n * Returns the URL of the JSON-RPC server.\n *\n * @returns The URL of the JSON-RPC server.\n * @deprecated URL belongs to Transport construction and is unavailable for\n * Requestors created with {@link RequestorJsonRpc.new}.\n */\n\n get url(): string {\n return this.url_;\n }\n\n /**\n * request a JSON-RPC method.\n *\n * @param rpcMethod - The JSON-RPC method.\n * @param params - Params for the method.\n * @param inTransformers - An array of input transformers.\n * @param outTransformer - An output transformer function.\n * @returns Method response.\n */\n async request(\n rpcMethod: string,\n params: unknown[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inTransformers?: (((_: any) => unknown) | undefined)[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n outTransformer?: (_: any) => unknown,\n options?: JsonRpcTransportRequestOptions,\n ): Promise<unknown> {\n const payload = this.buildPayload(\n rpcMethod,\n inTransformers\n ? await Promise.all(\n params\n .concat(\n Array.from(\n new Array(Math.max(inTransformers.length - params.length, 0)),\n ),\n )\n .map((v, i) => transform(v, inTransformers[i])),\n )\n : params,\n );\n\n try {\n return await transform(\n await this.requestPayload(payload, options),\n outTransformer,\n );\n } catch (err: unknown) {\n if (!this.onError) {\n throw err;\n }\n await this.onError(err);\n }\n }\n\n async requestPayload(\n payload: JsonRpcPayload,\n options?: JsonRpcTransportRequestOptions,\n ): Promise<unknown> {\n if (\n this.maxConcurrent !== undefined &&\n this.concurrent >= this.maxConcurrent\n ) {\n options?.signal?.throwIfAborted();\n let resolvePending: (() => void) | undefined;\n const pending = new Promise<void>((resolve) => {\n resolvePending = resolve;\n this.pending.push(resolve);\n });\n try {\n await (options?.signal\n ? Promise.race([pending, abortSignalToPromise(options.signal)])\n : pending);\n } catch (cause) {\n const index = resolvePending\n ? this.pending.indexOf(resolvePending)\n : -1;\n if (index !== -1) {\n this.pending.splice(index, 1);\n } else {\n this.pending.shift()?.();\n }\n throw cause;\n }\n }\n\n const res: JsonRpcResponse = await (async () => {\n this.concurrent += 1;\n try {\n return await this.transport.request(payload, options);\n } finally {\n this.concurrent -= 1;\n this.pending.shift()?.();\n }\n })();\n\n if (res.id !== payload.id) {\n throw new Error(`Id mismatched, got ${res.id}, expected ${payload.id}`);\n }\n if (res.error != null) {\n throw new JsonRpcError(res.error);\n }\n return res.result;\n }\n\n /**\n * Builds a JSON-RPC payload for the given method and parameters.\n *\n * @param method - The JSON-RPC method name.\n * @param req - The parameters for the JSON-RPC method.\n * @returns The JSON-RPC payload.\n */\n\n buildPayload(method: string, req: unknown[]): JsonRpcPayload {\n return {\n id: this.id++,\n method,\n params: req,\n jsonrpc: \"2.0\",\n };\n }\n}\n","import {\n Cell,\n OutPoint,\n OutPointLike,\n TransactionLike,\n} from \"../../ckb/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport {\n RequestorJsonRpc,\n RequestorJsonRpcConfig,\n} from \"../../jsonRpc/requestor.js\";\nimport { Num, NumLike, numFrom, numToHex } from \"../../num/index.js\";\nimport { Owner, apply } from \"../../utils/index.js\";\nimport type { ClientConfig } from \"../client.js\";\nimport { Client } from \"../client.js\";\nimport { DEFAULT_MIN_FEE_RATE } from \"../clientTypes.advanced.js\";\nimport {\n ClientFindCellsResponse,\n ClientIndexerSearchKeyLike,\n ClientTransactionResponse,\n ErrorClientBase,\n ErrorClientBaseLike,\n ErrorClientDuplicatedTransaction,\n ErrorClientRBFRejected,\n ErrorClientResolveUnknown,\n ErrorClientVerification,\n OutputsValidator,\n} from \"../clientTypes.js\";\nimport {\n JsonRpcBlock,\n JsonRpcBlockHeader,\n JsonRpcCellOutput,\n JsonRpcTransformers,\n} from \"./advanced.js\";\n\nconst ERROR_PARSERS: [\n string,\n (error: ErrorClientBaseLike, match: RegExpMatchArray) => ErrorClientBase,\n][] = [\n [\n \"Resolve\\\\(Unknown\\\\(OutPoint\\\\((0x.*)\\\\)\\\\)\\\\)\",\n (error, match) =>\n new ErrorClientResolveUnknown(error, OutPoint.fromBytes(match[1])),\n ],\n [\n \"Verification\\\\(Error { kind: Script, inner: TransactionScriptError { source: (Inputs|Outputs)\\\\[([0-9]*)\\\\].(Lock|Type), cause: ValidationFailure: see error code (-?[0-9]+) on page https://nervosnetwork\\\\.github\\\\.io/ckb-script-error-codes/by-(type|data)-hash/(.*)\\\\.html\",\n (error, match) =>\n new ErrorClientVerification(\n error,\n match[3] === \"Lock\"\n ? \"lock\"\n : match[1] === \"Inputs\"\n ? \"inputType\"\n : \"outputType\",\n match[2],\n Number(match[4]),\n match[5] === \"data\" ? \"data\" : \"type\",\n match[6],\n ),\n ],\n [\n \"Duplicated\\\\(Byte32\\\\((0x.*)\\\\)\\\\)\",\n (error, match) => new ErrorClientDuplicatedTransaction(error, match[1]),\n ],\n [\n 'RBFRejected\\\\(\"Tx\\'s current fee is ([0-9]*), expect it to >= ([0-9]*) to replace old txs\"\\\\)',\n (error, match) => new ErrorClientRBFRejected(error, match[1], match[2]),\n ],\n];\n\nfunction handleJsonRpcError(errAny: unknown): never {\n if (\n typeof errAny !== \"object\" ||\n errAny === null ||\n !(\"data\" in errAny) ||\n typeof errAny.data !== \"string\"\n ) {\n throw errAny;\n }\n const err = errAny as ErrorClientBaseLike;\n\n for (const [regexp, builder] of ERROR_PARSERS) {\n const match = err.data.match(regexp);\n if (match) {\n throw builder(err, match);\n }\n }\n\n throw new ErrorClientBase(err);\n}\n\nexport type ClientJsonRpcConfig = RequestorJsonRpcConfig &\n ClientConfig & {\n /**\n * @deprecated Requestor injection is supported only by legacy constructors.\n * Use a borrowed Transport with `Client.new` or let `Client.open` create one.\n */\n requestor?: RequestorJsonRpc;\n };\n\n/**\n * An abstract class implementing JSON-RPC client functionality for a specific URL and timeout.\n * Provides methods for sending transactions and building JSON-RPC payloads.\n */\nexport abstract class ClientJsonRpc extends Client {\n public readonly requestor: RequestorJsonRpc;\n\n /**\n * Creates an instance of ClientJsonRpc.\n *\n * @param url_ - The URL of the JSON-RPC server.\n * @param timeout - The timeout for requests in milliseconds\n * @deprecated Use the concrete Client's `new` or `open` method.\n */\n\n constructor(\n private readonly url_: string,\n config?: ClientJsonRpcConfig,\n ) {\n super(config);\n\n const requestor = config?.requestor;\n if (requestor) {\n this.requestor = requestor;\n } else if (config?.transport) {\n this.requestor = RequestorJsonRpc.new({\n transport: config.transport,\n maxConcurrent: config.maxConcurrent,\n onError: handleJsonRpcError,\n });\n } else {\n // Legacy constructor intentionally discards ownership.\n this.requestor = RequestorJsonRpc.open({\n urls: [url_, ...(config?.fallbacks ?? [])],\n timeout: config?.timeout,\n maxConcurrent: config?.maxConcurrent,\n onError: handleJsonRpcError,\n }).value;\n }\n }\n\n /** Creates a Requestor that borrows an existing Transport. */\n protected static newRequestor(\n config: Omit<Parameters<typeof RequestorJsonRpc.new>[0], \"onError\">,\n ): RequestorJsonRpc {\n return RequestorJsonRpc.new({\n ...config,\n onError: handleJsonRpcError,\n });\n }\n\n /** Opens a Requestor with ownership of its default Transport. */\n protected static openRequestor(\n config: Omit<Parameters<typeof RequestorJsonRpc.open>[0], \"onError\">,\n ): Owner<RequestorJsonRpc> {\n return RequestorJsonRpc.open({\n ...config,\n onError: handleJsonRpcError,\n });\n }\n\n /**\n * Returns the legacy primary URL of the JSON-RPC server.\n *\n * @returns The URL of the JSON-RPC server.\n * @deprecated A Client may use multiple endpoints or a Transport without a\n * URL, so this value does not reliably identify its connection.\n */\n get url(): string {\n return this.url_;\n }\n\n /**\n * Get fee rate statistics\n *\n * @returns Fee rate statistics\n */\n\n getFeeRateStatistics = this.buildSender(\n \"get_fee_rate_statistics\",\n [(n: NumLike) => apply(numFrom, n)],\n // TODO: This is a temporary workaround for the fact that the node may return null for fee rate statistics.\n // We should change the method signature to return null instead of falling back to the default value,\n // but this would be a breaking change.\n (res: { mean: NumLike; median: NumLike } | null) => ({\n mean: numFrom(res?.mean ?? DEFAULT_MIN_FEE_RATE),\n median: numFrom(res?.median ?? DEFAULT_MIN_FEE_RATE),\n }),\n ) as Client[\"getFeeRateStatistics\"];\n\n /**\n * Get tip block number\n *\n * @returns Tip block number\n */\n\n getTip = this.buildSender(\n \"get_tip_block_number\",\n [],\n numFrom,\n ) as () => Promise<Num>;\n\n /**\n * Get tip block header\n *\n * @param verbosity - result format which allows 0 and 1. (Optional, the default is 1.)\n * @returns BlockHeader\n */\n getTipHeader = this.buildSender(\n \"get_tip_header\",\n [],\n (b: JsonRpcBlockHeader) => apply(JsonRpcTransformers.blockHeaderTo, b),\n ) as Client[\"getTipHeader\"];\n\n /**\n * Get block by block number\n *\n * @param blockNumber - The block number.\n * @param verbosity - result format which allows 0 and 2. (Optional, the default is 2.)\n * @param withCycles - whether the return cycles of block transactions. (Optional, default false.)\n * @returns Block\n */\n getBlockByNumberNoCache = this.buildSender(\n \"get_block_by_number\",\n [(v: NumLike) => numToHex(numFrom(v))],\n (b: JsonRpcBlock) => apply(JsonRpcTransformers.blockTo, b),\n ) as Client[\"getBlockByNumberNoCache\"];\n\n /**\n * Get block by block hash\n *\n * @param blockHash - The block hash.\n * @param verbosity - result format which allows 0 and 2. (Optional, the default is 2.)\n * @param withCycles - whether the return cycles of block transactions. (Optional, default false.)\n * @returns Block\n */\n getBlockByHashNoCache = this.buildSender(\n \"get_block\",\n [hexFrom],\n (b: JsonRpcBlock) => apply(JsonRpcTransformers.blockTo, b),\n ) as Client[\"getBlockByHashNoCache\"];\n\n /**\n * Get header by block number\n *\n * @param blockNumber - The block number.\n * @param verbosity - result format which allows 0 and 1. (Optional, the default is 1.)\n * @returns BlockHeader\n */\n getHeaderByNumberNoCache = this.buildSender(\n \"get_header_by_number\",\n [(v: NumLike) => numToHex(numFrom(v))],\n (b: JsonRpcBlockHeader) => apply(JsonRpcTransformers.blockHeaderTo, b),\n ) as Client[\"getHeaderByNumberNoCache\"];\n\n /**\n * Get header by block hash\n *\n * @param blockHash - The block hash.\n * @param verbosity - result format which allows 0 and 1. (Optional, the default is 1.)\n * @returns BlockHeader\n */\n getHeaderByHashNoCache = this.buildSender(\n \"get_header\",\n [hexFrom],\n (b: JsonRpcBlockHeader) => apply(JsonRpcTransformers.blockHeaderTo, b),\n ) as Client[\"getHeaderByHashNoCache\"];\n\n /**\n * Estimate cycles of a transaction.\n *\n * @param transaction - The transaction to estimate.\n * @returns Consumed cycles\n */\n estimateCycles = this.buildSender(\n \"estimate_cycles\",\n [JsonRpcTransformers.transactionFrom],\n ({ cycles }: { cycles: NumLike }) => numFrom(cycles),\n ) as Client[\"estimateCycles\"];\n\n /**\n * Test a transaction.\n *\n * @param transaction - The transaction to test.\n * @param validator - \"passthrough\": Disable validation. \"well_known_scripts_only\": Only accept well known scripts in the transaction.\n * @returns Consumed cycles\n */\n\n sendTransactionDry = this.buildSender(\n \"test_tx_pool_accept\",\n [JsonRpcTransformers.transactionFrom],\n ({ cycles }: { cycles: NumLike }) => numFrom(cycles),\n ) as Client[\"sendTransactionDry\"];\n\n /**\n * Send a transaction to node.\n *\n * @param transaction - The transaction to send.\n * @param validator - \"passthrough\": Disable validation. \"well_known_scripts_only\": Only accept well known scripts in the transaction.\n * @returns Transaction hash.\n */\n\n sendTransactionNoCache = this.buildSender(\n \"send_transaction\",\n [\n JsonRpcTransformers.transactionFrom,\n (validator?: OutputsValidator | null) => validator ?? undefined,\n ],\n hexFrom,\n ) as (\n transaction: TransactionLike,\n validator?: OutputsValidator | null,\n ) => Promise<Hex>;\n\n /**\n * Get a transaction from node.\n *\n * @param txHash - The hash of the transaction.\n * @returns The transaction with status.\n */\n\n getTransactionNoCache = this.buildSender(\n \"get_transaction\",\n [hexFrom],\n JsonRpcTransformers.transactionResponseTo,\n ) as (txHash: HexLike) => Promise<ClientTransactionResponse | undefined>;\n\n /**\n * Get a live cell from node.\n *\n * @param outPoint - The out point of the cell.\n * @param withData - Include data in the response.\n * @param includeTxPool - Include cells in the tx pool.\n * @returns The cell\n */\n getCellLiveNoCache(\n outPoint: OutPointLike,\n withData?: boolean | null,\n includeTxPool?: boolean | null,\n ) {\n return this.buildSender(\n \"get_live_cell\",\n [JsonRpcTransformers.outPointFrom],\n ({\n cell,\n }: {\n cell?: {\n output: JsonRpcCellOutput;\n data?: { content: HexLike; hash: HexLike };\n };\n }) =>\n apply(\n ({\n output,\n data,\n }: {\n output: JsonRpcCellOutput;\n data?: { content: HexLike; hash: HexLike };\n }) =>\n Cell.from({\n cellOutput: JsonRpcTransformers.cellOutputTo(output),\n outputData: data?.content ?? \"0x\",\n outPoint,\n }),\n cell,\n ),\n )(outPoint, withData ?? true, includeTxPool) as Promise<Cell | undefined>;\n }\n\n /**\n * find cells from node.\n *\n * @param key - The search key of cells.\n * @param order - The order of cells.\n * @param limit - The max return size of cells.\n * @param after - Pagination parameter.\n * @returns The found cells.\n */\n\n findCellsPagedNoCache = this.buildSender(\n \"get_cells\",\n [\n JsonRpcTransformers.indexerSearchKeyFrom,\n (order?: \"asc\" | \"desc\") => order ?? \"asc\",\n (limit?: NumLike) => numToHex(limit ?? 10),\n ],\n JsonRpcTransformers.findCellsResponseTo,\n ) as (\n key: ClientIndexerSearchKeyLike,\n order?: \"asc\" | \"desc\",\n limit?: NumLike,\n after?: string,\n ) => Promise<ClientFindCellsResponse>;\n\n /**\n * find transactions from node.\n *\n * @param key - The search key of transactions.\n * @param order - The order of transactions.\n * @param limit - The max return size of transactions.\n * @param after - Pagination parameter.\n * @returns The found transactions.\n */\n\n findTransactionsPaged = this.buildSender(\n \"get_transactions\",\n [\n JsonRpcTransformers.indexerSearchKeyTransactionFrom,\n (order?: \"asc\" | \"desc\") => order ?? \"asc\",\n (limit?: NumLike) => numToHex(limit ?? 10),\n ],\n JsonRpcTransformers.findTransactionsResponseTo,\n ) as Client[\"findTransactionsPaged\"];\n\n /**\n * get cells capacity from node.\n *\n * @param key - The search key of cells.\n * @returns The sum of cells capacity.\n */\n\n getCellsCapacity = this.buildSender(\n \"get_cells_capacity\",\n [JsonRpcTransformers.indexerSearchKeyFrom],\n ({ capacity }: { capacity: NumLike }) => numFrom(capacity),\n ) as (key: ClientIndexerSearchKeyLike) => Promise<Num>;\n\n /**\n * Builds a sender function for a JSON-RPC method.\n *\n * @param rpcMethod - The JSON-RPC method.\n * @param inTransformers - An array of input transformers.\n * @param outTransformer - An output transformer function.\n * @returns A function that sends a JSON-RPC request with the given method and transformed parameters.\n */\n\n buildSender(\n rpcMethod: Parameters<RequestorJsonRpc[\"request\"]>[0],\n inTransformers?: Parameters<RequestorJsonRpc[\"request\"]>[2],\n outTransformer?: Parameters<RequestorJsonRpc[\"request\"]>[3],\n ): (...req: unknown[]) => Promise<unknown> {\n return async (...req: unknown[]) => {\n return this.requestor.request(\n rpcMethod,\n req,\n inTransformers,\n outTransformer,\n );\n };\n }\n}\n","import WebSocket from \"isomorphic-ws\";\nimport { RequestorJsonRpc } from \"../jsonRpc/requestor.js\";\nimport type { ClientConfig } from \"./client.js\";\nimport { MAINNET_SCRIPTS } from \"./clientPublicMainnet.advanced.js\";\nimport { ClientJsonRpc, type ClientJsonRpcConfig } from \"./jsonRpc/client.js\";\n\n/**\n * @public\n */\nexport class ClientPublicMainnet extends ClientJsonRpc {\n private static defaultUrls(): readonly [string, ...string[]] {\n return typeof WebSocket !== \"undefined\"\n ? [\n \"wss://mainnet.ckb.dev/ws\",\n \"https://mainnet.ckb.dev/\",\n \"https://mainnet.ckbapp.dev/\",\n ]\n : [\"https://mainnet.ckb.dev/\", \"https://mainnet.ckbapp.dev/\"];\n }\n\n private static resolveConfig(\n config?: ClientJsonRpcConfig & {\n /** @deprecated URL belongs to Transport construction. */\n url?: string;\n },\n ): ClientJsonRpcConfig & { url: string; fallbacks: string[] } {\n const defaultUrls = this.defaultUrls();\n return {\n ...config,\n url: config?.url ?? defaultUrls[0],\n fallbacks: config?.fallbacks ?? [...defaultUrls],\n scripts: config?.scripts ?? MAINNET_SCRIPTS,\n };\n }\n\n /**\n * @deprecated Use {@link ClientPublicMainnet.new} with a borrowed Transport or\n * {@link ClientPublicMainnet.open} when creating Transports.\n */\n constructor(\n config?: ClientJsonRpcConfig & {\n /** @deprecated URL belongs to Transport construction. */\n url?: string;\n },\n ) {\n const resolved = ClientPublicMainnet.resolveConfig(config);\n super(resolved.url, resolved);\n }\n\n /** Creates a Client that borrows an existing Transport. */\n static new(\n config: Omit<Parameters<typeof RequestorJsonRpc.new>[0], \"onError\"> &\n ClientConfig,\n ): ClientPublicMainnet {\n const { cache, scripts, ...requestorConfig } = config;\n const requestor = this.newRequestor(requestorConfig);\n return new ClientPublicMainnet({ cache, scripts, requestor });\n }\n\n /** Opens a Client with explicit ownership of its default dependencies. */\n static open(\n config?: Omit<\n Parameters<typeof RequestorJsonRpc.open>[0],\n \"onError\" | \"urls\"\n > &\n ClientConfig & {\n urls?: Parameters<typeof RequestorJsonRpc.open>[0][\"urls\"];\n },\n ) {\n const {\n cache,\n scripts,\n urls = this.defaultUrls(),\n ...requestorConfig\n } = config ?? {};\n return this.openRequestor({\n ...requestorConfig,\n urls,\n }).map(\n (requestor) =>\n new ClientPublicMainnet({\n cache,\n scripts,\n requestor,\n url: urls[0],\n fallbacks: [...urls.slice(1)],\n }),\n );\n }\n\n get addressPrefix(): string {\n return \"ckb\";\n }\n}\n","import WebSocket from \"isomorphic-ws\";\nimport { RequestorJsonRpc } from \"../jsonRpc/requestor.js\";\nimport type { ClientConfig } from \"./client.js\";\nimport { TESTNET_SCRIPTS } from \"./clientPublicTestnet.advanced.js\";\nimport { ClientJsonRpc, type ClientJsonRpcConfig } from \"./jsonRpc/client.js\";\n\n/**\n * @public\n */\nexport class ClientPublicTestnet extends ClientJsonRpc {\n private static defaultUrls(): readonly [string, ...string[]] {\n return typeof WebSocket !== \"undefined\"\n ? [\n \"wss://testnet.ckb.dev/ws\",\n \"https://testnet.ckb.dev/\",\n \"https://testnet.ckbapp.dev/\",\n ]\n : [\"https://testnet.ckb.dev/\", \"https://testnet.ckbapp.dev/\"];\n }\n\n private static resolveConfig(\n config?: ClientJsonRpcConfig & {\n /** @deprecated URL belongs to Transport construction. */\n url?: string;\n },\n ): ClientJsonRpcConfig & { url: string; fallbacks: string[] } {\n const defaultUrls = this.defaultUrls();\n return {\n ...config,\n url: config?.url ?? defaultUrls[0],\n fallbacks: config?.fallbacks ?? [...defaultUrls],\n scripts: config?.scripts ?? TESTNET_SCRIPTS,\n };\n }\n\n /**\n * @deprecated Use {@link ClientPublicTestnet.new} with a borrowed Transport or\n * {@link ClientPublicTestnet.open} when creating Transports.\n */\n constructor(\n config?: ClientJsonRpcConfig & {\n /** @deprecated URL belongs to Transport construction. */\n url?: string;\n },\n ) {\n const resolved = ClientPublicTestnet.resolveConfig(config);\n super(resolved.url, resolved);\n }\n\n /** Creates a Client that borrows an existing Transport. */\n static new(\n config: Omit<Parameters<typeof RequestorJsonRpc.new>[0], \"onError\"> &\n ClientConfig,\n ): ClientPublicTestnet {\n const { cache, scripts, ...requestorConfig } = config;\n const requestor = this.newRequestor(requestorConfig);\n return new ClientPublicTestnet({ cache, scripts, requestor });\n }\n\n /** Opens a Client with explicit ownership of its default dependencies. */\n static open(\n config?: Omit<\n Parameters<typeof RequestorJsonRpc.open>[0],\n \"onError\" | \"urls\"\n > &\n ClientConfig & {\n urls?: Parameters<typeof RequestorJsonRpc.open>[0][\"urls\"];\n },\n ) {\n const {\n cache,\n scripts,\n urls = this.defaultUrls(),\n ...requestorConfig\n } = config ?? {};\n return this.openRequestor({\n ...requestorConfig,\n urls,\n }).map(\n (requestor) =>\n new ClientPublicTestnet({\n cache,\n scripts,\n requestor,\n url: urls[0],\n fallbacks: [...urls.slice(1)],\n }),\n );\n }\n\n get addressPrefix(): string {\n return \"ckt\";\n }\n}\n","import { bech32m } from \"bech32\";\nimport { bytesConcat, bytesFrom } from \"../bytes/index.js\";\nimport { Script, ScriptLike, hashTypeToBytes } from \"../ckb/index.js\";\nimport { Client, KnownScript } from \"../client/index.js\";\nimport { HexLike } from \"../hex/index.js\";\nimport {\n ADDRESS_BECH32_LIMIT,\n AddressFormat,\n addressFromPayload,\n addressPayloadFromString,\n} from \"./address.advanced.js\";\n\n/**\n * @public\n */\nexport type AddressLike = {\n script: ScriptLike;\n prefix: string;\n};\n\n/**\n * Represents a ckb address with associated script and prefix.\n * @public\n */\nexport class Address {\n /**\n * Creates an instance of Address.\n *\n * @param script - The script associated with the address.\n * @param prefix - The address prefix.\n */\n constructor(\n public script: Script,\n public prefix: string,\n ) {}\n\n /**\n * Creates an Address instance from an AddressLike object.\n *\n * @param address - An AddressLike object or an instance of Address.\n * @returns An Address instance.\n */\n\n static from(address: AddressLike): Address {\n if (address instanceof Address) {\n return address;\n }\n\n return new Address(Script.from(address.script), address.prefix);\n }\n\n /**\n * Creates an Address instance from an address string.\n *\n * @param address - The address string to parse.\n * @param clients - A Client instance or a record of Client instances keyed by prefix.\n * @returns A promise that resolves to an Address instance.\n *\n * @throws Will throw an error if the address prefix is unknown or mismatched.\n */\n\n static async fromString(\n address: string,\n clients: Client | Record<string, Client>,\n ): Promise<Address> {\n const { prefix, format, payload } = addressPayloadFromString(address);\n\n const client = (clients as Record<string, Client>)[prefix] ?? clients;\n if (!client) {\n throw new Error(`Unknown address prefix ${prefix}`);\n }\n const expectedPrefix = client.addressPrefix;\n if (expectedPrefix !== prefix) {\n throw new Error(\n `Unknown address prefix ${prefix}, expected ${expectedPrefix}`,\n );\n }\n\n return Address.from(\n await addressFromPayload(prefix, format, payload, client),\n );\n }\n\n /**\n * Creates an Address instance from a script and client.\n *\n * @param script - The script-like object.\n * @param client - The client instance used to fetch the address prefix.\n * @returns A promise that resolves to an Address instance.\n */\n\n static fromScript(script: ScriptLike, client: Client): Address {\n return Address.from({ script, prefix: client.addressPrefix });\n }\n\n static async fromKnownScript(\n client: Client,\n script: KnownScript,\n args: HexLike,\n ): Promise<Address> {\n return Address.from({\n script: await Script.fromKnownScript(client, script, args),\n prefix: client.addressPrefix,\n });\n }\n\n /**\n * Converts the Address instance to a string.\n *\n * @returns The address as a string.\n */\n\n toString(): string {\n const data = bytesConcat(\n [AddressFormat.Full],\n bytesFrom(this.script.codeHash),\n hashTypeToBytes(this.script.hashType),\n bytesFrom(this.script.args),\n );\n\n return bech32m.encode(\n this.prefix,\n bech32m.toWords(data),\n ADDRESS_BECH32_LIMIT,\n );\n }\n}\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - Value to inspect.\n * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.\n * @example\n * Guards a value before treating it as raw key material.\n *\n * ```ts\n * isBytes(new Uint8Array());\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy /\n // cross-realm cases. The fallback still requires a real ArrayBuffer view\n // so plain JSON-deserialized `{ constructor: ... }`\n // spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is boolean.\n * @param value - Value to validate.\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validates a boolean option before branching on it.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is a non-negative safe integer.\n * @param n - Value to validate.\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validates a non-negative length or counter.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - Value to validate.\n * @param length - Expected byte length.\n * @param title - Optional label used in error messages.\n * @returns The validated byte array.\n * On Node, `Buffer` is accepted too because it is a Uint8Array view.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument lengths. {@link RangeError}\n * @example\n * Validates a fixed-length nonce or key buffer.\n *\n * ```ts\n * abytes(new Uint8Array([1, 2]), 2);\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(label === 'object'\n ? 'expected valid options object'\n : `\"${label}\" expected object, got type=${typeof value}`);\n};\n/**\n * Asserts a hash- or MAC-like instance has not been destroyed or finished.\n * @param instance - Stateful instance to validate.\n * @param checkFinished - Whether to reject finished instances.\n * When `false`, only `destroyed` is checked.\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Guards against calling `update()` or `digest()` on a finished hash.\n *\n * ```ts\n * aexists({ destroyed: false, finished: false });\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - Output buffer to validate.\n * @param instance - Hash-like instance providing `outputLen`.\n * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,\n * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong output buffer lengths. {@link RangeError}\n * @example\n * Verifies that a caller-provided output buffer is large enough.\n *\n * ```ts\n * aoutput(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Asserts output is a sufficiently-sized, 4-byte-aligned byte array.\n * {@link aoutput} plus an {@link isAligned32} check, for `digestInto()` paths\n * that write through zero-allocation `u32` word views.\n * @param out - Output buffer to validate.\n * @param instance - Hash-like instance providing `outputLen`.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong output buffer lengths. {@link RangeError}\n * @throws On wrong output buffer alignment. {@link Error}\n * @example\n * Verifies that a caller-provided output buffer is large enough and aligned.\n *\n * ```ts\n * aoutput32(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput32(out, instance) {\n aoutput(out, instance);\n if (!isAligned32(out))\n throw new Error('invalid output, must be aligned');\n}\n/**\n * Casts a typed-array view to Uint8Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint8Array view over the same bytes.\n * @example\n * Views 32-bit words as raw bytes without copying.\n *\n * ```ts\n * u8(new Uint32Array([1]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed-array view to Uint32Array.\n * @param arr - Typed-array view to reinterpret.\n * @returns Uint32Array view over the same bytes. Callers are expected to provide a\n * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.\n * @example\n * Views a byte buffer as 32-bit words for block processing.\n *\n * ```ts\n * u32(new Uint8Array(4));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place.\n * Warning: JS provides no guarantees.\n * @param arrays - Arrays to wipe.\n * @example\n * Wipes a temporary key buffer after use.\n *\n * ```ts\n * const bytes = new Uint8Array([1]);\n * clean(bytes);\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - Typed-array view to wrap.\n * @returns DataView over the same bytes.\n * @example\n * Creates an endian-aware view for length encoding.\n *\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Whether the current platform is little-endian.\n * Most are; some IBM systems are not.\n */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Reverses byte order of one 32-bit word.\n * @param word - Unsigned 32-bit word to swap.\n * @returns The same word with bytes reversed.\n * @example\n * Swaps a big-endian word into little-endian byte order.\n *\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Normalizes one 32-bit word to the little-endian representation expected by cipher cores.\n * @param n - Unsigned 32-bit word to normalize.\n * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.\n * @example\n * Normalizes a host-endian word before passing it into an ARX/AES core.\n *\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - Uint32Array whose words should be swapped.\n * @returns The same array after in-place byte swapping.\n * @example\n * Swaps every 32-bit word in a word-view buffer.\n *\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.\n * @param u - Word view to normalize in place.\n * @returns Little-endian normalized word view.\n * @example\n * Normalizes a word-view buffer before block processing.\n *\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion:\n// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry}\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Formats ciphertext bytes for logs or test vectors.\n *\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\nconst _0n = /* @__PURE__ */ BigInt(0);\n// Used in ff1, via bytesToNumberBE\n/**\n * Converts a big-endian hex string into bigint.\n * @param hex - Hexadecimal string without `0x`.\n * @returns Parsed bigint value. The empty string is treated as `0n`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parses a big-endian field element or counter from hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n // Numeric parser, not byte-hex decoder: odd-length forms like 'f' are valid,\n // and malformed syntax follows BigInt's native error behavior.\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// Used in ff1\n// BE: Big Endian, LE: Little Endian\n/**\n * Converts big-endian bytes into bigint.\n * @param bytes - Big-endian bytes.\n * @returns Parsed bigint value. Empty input is treated as `0n`.\n * @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}\n * @example\n * Reads a big-endian integer from serialized bytes.\n *\n * ```ts\n * bytesToNumberBE(new Uint8Array([1, 0]));\n * ```\n */\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n */\nfunction abignumber(n) {\n if (typeof n === 'bigint') {\n if (!(_0n <= n))\n throw new RangeError('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return n;\n}\n// Used in ff1\n/**\n * Converts a number into big-endian bytes of fixed length.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian bytes padded to `len`.\n * Negative values, `len = 0`, and values that do not fit are rejected before\n * downstream hex parsing.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Encodes a counter as fixed-width big-endian bytes.\n *\n * ```ts\n * numberToBytesBE(1, 2);\n * ```\n */\nexport function numberToBytesBE(n, len) {\n anumber(len);\n if (len === 0)\n throw new Error('zero output length is invalid');\n n = abignumber(n);\n const expectedLen = len * 2;\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > expectedLen)\n throw new RangeError('number is too large');\n return hexToBytes(hex.padStart(expectedLen, '0'));\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @param str - String to encode.\n * @returns UTF-8 bytes in a detached fresh Uint8Array copy.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encodes application text before encryption or MACing.\n *\n * ```ts\n * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // {@link https://bugzil.la/1681809 | Firefox bug 1681809}\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @param bytes - UTF-8 bytes.\n * @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed\n * UTF-8 is replacement-decoded instead of rejected.\n * @example\n * Decodes UTF-8 plaintext back into a string.\n *\n * ```ts\n * bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'\n * ```\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Checks if two U8A use same underlying buffer and overlaps.\n * This is invalid and can corrupt data.\n * @param a - First byte view.\n * @param b - Second byte view.\n * @returns `true` when the views overlap in memory.\n * @example\n * Detects whether two slices alias the same backing buffer.\n *\n * ```ts\n * overlapBytes(new Uint8Array(4), new Uint8Array(4));\n * ```\n */\nexport function overlapBytes(a, b) {\n // Zero-length views cannot overwrite anything, even if their offset sits inside another range.\n if (!a.byteLength || !b.byteLength)\n return false;\n return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy\n a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end\n b.byteOffset < a.byteOffset + a.byteLength // b starts before a end\n );\n}\n/**\n * If input and output overlap and input starts before output, we will overwrite end of input before\n * we start processing it, so this is not supported by forward-processing ciphers.\n * @param input - Input bytes.\n * @param output - Output bytes.\n * @throws If the output view would overwrite unread input bytes. {@link Error}\n * @example\n * Rejects an in-place layout that would overwrite unread input bytes.\n *\n * ```ts\n * const buffer = new Uint8Array(8);\n * complexOverlapBytes(buffer.subarray(0, 4), buffer.subarray(2, 6));\n * ```\n */\nexport function complexOverlapBytes(input, output) {\n // This is very cursed. It works somehow, but I'm completely unsure,\n // reasoning about overlapping aligned windows is very hard.\n if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)\n throw new Error('complex overlap of input and output is not supported');\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - Byte arrays to concatenate.\n * @returns Combined byte array.\n * @throws On wrong argument types inside the byte-array list. {@link TypeError}\n * @example\n * Builds a `nonce || ciphertext` style buffer.\n *\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Merges user options into defaults.\n * @param defaults - Default option values.\n * @param opts - User-provided overrides.\n * @returns Combined options object.\n * `defaults` is a library-owned mutable object; user-provided `opts` only need to be\n * object-shaped, since \"plain object\" checks reject valid proxy/cross-realm containers.\n * The merge mutates `defaults` in place and returns the same object, so direct callers\n * should pass a fresh defaults object unless they intentionally want shared state updated.\n * @throws If options are missing or not an object. {@link Error}\n * @example\n * Applies user overrides to the default cipher options.\n *\n * ```ts\n * checkOpts({ rounds: 20 }, { rounds: 8 });\n * ```\n */\nexport function checkOpts(defaults, opts) {\n aobject(defaults, 'defaults');\n aobject(opts, 'opts');\n // Mutates defaults by design. __proto__ follows Object.assign semantics here and can only\n // affect this local option object; callers already control this low-level options surface.\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/**\n * Compares two byte arrays in kinda constant time once lengths already match.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns `true` when the arrays contain the same bytes. Different lengths still return early.\n * @example\n * Compares an expected authentication tag with the received one.\n *\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Wraps a keyed MAC constructor into a one-shot helper with `.create()`.\n * @param keyLen - Valid probe-key length used to read static metadata once.\n * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes\n * can pass any representative size as long as those values stay fixed.\n * @param macCons - Keyed MAC constructor or factory.\n * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.\n * @returns Callable MAC helper with `.create()`.\n */\nexport function wrapMacConstructor(keyLen, macCons, fromMsg) {\n const mac = macCons;\n const getArgs = (fromMsg || (() => []));\n const macC = (msg, key) => mac(key, ...getArgs(msg))\n .update(msg)\n .digest();\n const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));\n macC.outputLen = tmp.outputLen;\n macC.blockLen = tmp.blockLen;\n macC.create = (key, ...args) => mac(key, ...args);\n return macC;\n}\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * Used internally by the exported cipher constructors.\n * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`\n * arity (`fn.length === 2`), so wrapped output-capable methods must use a normal\n * second parameter, not a default/rest parameter. AAD support is explicit in\n * `params.withAAD`; optional AAD starts after the nonce slot when one is present.\n * @__NO_SIDE_EFFECTS__\n * @param params - Static cipher metadata. See {@link CipherParams}.\n * @param constructor - Cipher constructor.\n * @returns Wrapped constructor with validation.\n */\nexport const wrapCipher = (params, constructor) => {\n function wrappedCipher(key, ...args) {\n // Validate key\n abytes(key, undefined, 'key');\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');\n }\n // Keep tag length available for decrypt-size checks after constructor validation.\n const tagl = params.tagLength;\n const aadStart = params.nonceLength !== undefined ? 1 : 0;\n // No-AAD constructors otherwise silently ignore byte args meant as AAD.\n if (!params.withAAD) {\n for (let i = aadStart; i < args.length; i++)\n if (isBytes(args[i]))\n throw new Error('AAD not supported');\n }\n // Validate the first AAD slot early; rest-arg AAD constructors validate the tail themselves.\n if (params.withAAD && args[aadStart] !== undefined)\n abytes(args[aadStart], undefined, 'AAD');\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength, output) => {\n if (output !== undefined) {\n if (fnLength !== 2)\n throw new Error('cipher output not supported');\n abytes(output, undefined, 'output');\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data, output) {\n if (called)\n throw new Error('cannot encrypt() twice with same key + nonce');\n // Any encrypt attempt consumes the instance, even if validation rejects below.\n called = true;\n abytes(data, undefined, 'data');\n checkOutput(cipher.encrypt.length, output);\n return cipher.encrypt(data, output);\n },\n decrypt(data, output) {\n abytes(data, undefined, 'data');\n if (tagl && data.length < tagl)\n throw new Error('\"ciphertext\" expected length >= tagLength=' + tagl);\n checkOutput(cipher.decrypt.length, output);\n return cipher.decrypt(data, output);\n },\n };\n return wrCipher;\n }\n Object.assign(wrappedCipher, params);\n return wrappedCipher;\n};\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n * @param expectedLength - Required output length.\n * @param out - Optional destination buffer.\n * @param onlyAligned - Whether `out` must be 4-byte aligned.\n * @returns Output buffer ready for writing.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If the provided output buffer has the wrong size. {@link RangeError}\n * @throws If the provided output buffer has the wrong alignment. {@link Error}\n * @example\n * Reuses a caller-provided output buffer when lengths match.\n *\n * ```ts\n * getOutput(16, new Uint8Array(16));\n * ```\n */\nexport function getOutput(expectedLength, out, onlyAligned = true) {\n if (out === undefined)\n return new Uint8Array(expectedLength);\n // Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object.\n abytes(out, expectedLength, 'output');\n if (onlyAligned && !isAligned32(out))\n throw new Error('invalid output, must be aligned');\n return out;\n}\n/**\n * Encodes data and AAD lengths into a 16-byte buffer.\n * @param dataLength - Data length. Units are caller-defined: GCM passes bit\n * lengths, ChaCha20-Poly1305 passes byte lengths — the helper writes the raw values.\n * @param aadLength - AAD length, same unit convention as `dataLength`.\n * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305\n * conventions even though the helper parameter order is `(dataLength, aadLength)`.\n * @param isLE - Whether to encode lengths as little-endian.\n * @returns 16-byte length block.\n * @throws On wrong argument types passed to the endian validator. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Builds the length block appended by GCM and Poly1305.\n *\n * ```ts\n * u64Lengths(16, 8, true);\n * ```\n */\nexport function u64Lengths(dataLength, aadLength, isLE) {\n // Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them.\n anumber(dataLength);\n anumber(aadLength);\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n view.setBigUint64(0, BigInt(aadLength), isLE);\n view.setBigUint64(8, BigInt(dataLength), isLE);\n return num;\n}\n/**\n * Checks whether a byte array is aligned to a 4-byte offset.\n * @param bytes - Byte array to inspect.\n * @returns `true` when the view is 4-byte aligned.\n * @example\n * Checks whether a buffer can be safely viewed as Uint32Array.\n *\n * ```ts\n * isAligned32(new Uint8Array(4));\n * ```\n */\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n/**\n * Copies bytes into a new Uint8Array.\n * @param bytes - Bytes to copy.\n * @returns Copied byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Copies input into an aligned Uint8Array before block processing.\n *\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * Uses CSPRNG for nonce, nonce injected in ciphertext.\n * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and\n * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext\n * are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`\n * buffer on encrypt and intentionally does not support caller-provided destination buffers.\n * Too-short decrypt inputs are split into short/empty nonce views and then delegated\n * to the wrapped cipher instead of being rejected here first.\n *\n * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha\n * should be limited to `2**23` (8M) messages to get a collision chance of\n * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to\n * `2**-33`, still negligible but creeping up.\n * @param fn - Cipher constructor that expects a nonce.\n * @param randomBytes_ - Random-byte source used for nonce generation.\n * @returns Cipher constructor that prepends the nonce to ciphertext.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}\n * @example\n * Prepends a fresh random nonce to every ciphertext.\n *\n * ```ts\n * import { gcm } from '@noble/ciphers/aes.js';\n * import { managedNonce, randomBytes } from '@noble/ciphers/utils.js';\n * const wrapped = managedNonce(gcm);\n * const key = randomBytes(16);\n * const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));\n * wrapped(key).decrypt(ciphertext);\n * ```\n */\nexport function managedNonce(fn, randomBytes_ = randomBytes) {\n if (typeof fn !== 'function')\n throw new TypeError('\"fn\" expected cipher constructor, got type=' + typeof fn);\n if (typeof randomBytes_ !== 'function')\n throw new TypeError('\"randomBytes_\" expected function, got type=' + typeof randomBytes_);\n const { nonceLength } = fn;\n anumber(nonceLength, 'fn.nonceLength');\n const addNonce = (nonce, ciphertext, plaintext) => {\n const out = concatBytes(nonce, ciphertext);\n // Wrapped ciphers may alias caller plaintext on encrypt(); never zero\n // caller-owned buffers here.\n if (!overlapBytes(plaintext, ciphertext))\n ciphertext.fill(0);\n return out;\n };\n // NOTE: we cannot support DST here, it would be mistake:\n // - we don't know how much dst length cipher requires\n // - nonce may unalign dst and break everything\n // - we create new u8a anyway (concatBytes)\n // - previously we passed all args to cipher, but that was mistake!\n const res = ((key, ...args) => ({\n encrypt(plaintext) {\n abytes(plaintext, undefined, 'data');\n const nonce = randomBytes_(nonceLength);\n const encrypted = fn(key, nonce, ...args).encrypt(plaintext);\n // @ts-ignore\n if (encrypted instanceof Promise)\n return encrypted.then((ct) => addNonce(nonce, ct, plaintext));\n return addNonce(nonce, encrypted, plaintext);\n },\n decrypt(ciphertext) {\n abytes(ciphertext, undefined, 'data');\n const nonce = ciphertext.subarray(0, nonceLength);\n const decrypted = ciphertext.subarray(nonceLength);\n return fn(key, nonce, ...args).decrypt(decrypted);\n },\n }));\n // Auto-nonce wrappers still preserve the wrapped payload geometry.\n if ('blockSize' in fn)\n res.blockSize = fn.blockSize;\n if ('tagLength' in fn)\n res.tagLength = fn.tagLength;\n if ('withAAD' in fn)\n res.withAAD = fn.withAAD;\n return res;\n}\n","/**\n * {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard | AES}\n * a.k.a. Advanced Encryption Standard\n * is a variant of Rijndael block cipher, standardized by NIST in 2001.\n * We provide the fastest available pure JS implementation.\n *\n * `cipher = encrypt(block, key)`\n *\n * Data is split into 128-bit blocks.\n * Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n * 1. **S-box**, table substitution\n * 2. **Shift rows**, cyclic shift left of all rows of data array\n * 3. **Mix columns**, multiplying every column by fixed polynomial\n * 4. **Add round key**, round_key xor i-th column of array\n *\n * Check out\n * {@link https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf | FIPS-197},\n * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G},\n * and {@link https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf | original proposal}.\n * @module\n */\nimport { ghash, polyval } from \"./_polyval.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput32, byteSwap, clean, complexOverlapBytes, concatBytes, copyBytes, createView, equalBytes, getOutput, isAligned32, isLE, overlapBytes, swap32IfBE, swap8IfBE, u32, u64Lengths, u8, wrapCipher, wrapMacConstructor } from \"./utils.js\";\nconst BLOCK_SIZE = 16;\n// AES operates on 16-byte blocks, i.e. 4 32-bit words.\nconst BLOCK_SIZE32 = 4;\n// Shared zero block (`0^128`) used by GCM's `H = CIPH_K(0^128)` / J0 scratch\n// and by CMAC / SIV helpers; callers take `.slice()` before mutating it.\nconst EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE);\n// RFC 5297 §2.1 / §2.4: S2V uses `<one> = 0^127 || 1` for the `n = 0` special case.\nconst ONE_BLOCK = /* @__PURE__ */ Uint8Array.from([\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,\n]);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n// Validates plain AES key sizes only; AES-SIV's doubled-key contract is checked elsewhere.\nfunction validateKeyLength(key) {\n if (![16, 24, 32].includes(key.length))\n throw new Error('\"aes key\" expected Uint8Array of length 16/24/32, got length=' + key.length);\n}\n// TODO: remove multiplication, binary ops only\n// Doubles one GF(2^8) field element; callers are expected to stay in byte range.\n// FIPS 197 upd1 §4.3 equation (4.5): XTIMES(b) left-shifts by one and, when\n// b7=1, reduces by m(x); using POLY=0x11b here yields the same byte result\n// as XORing with {1b} after the shift.\nfunction mul2(n) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\n// Shift-and-add multiplication in GF(2^8); callers are expected to pass byte values.\n// FIPS 197 upd1 §4.3 equation (4.7): general products are XORs of repeated\n// XTIMES() multiples, e.g. {57}•{13} = {57}⊕{ae}⊕{07}.\nfunction mul(a, b) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Usual shift-and-add step in GF(2^8), not a scalar-multiplication ladder.\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n/**\n * Increments a counter block with wrap around.\n * AES call sites here currently use the big-endian branch, but the helper supports both layouts.\n * NIST SP 800-38A Appendix B.1 and SP 800-38D §6.2 increment the\n * least-significant/rightmost bits.\n * `isLE=false` matches that standard counter-block layout, while `isLE=true`\n * is a generic extension for non-AES callers.\n * The implementation keeps a 32-bit bitwise carry path, so `carry` is capped at `0xffffff00`;\n * larger values throw instead of silently overflowing before the next-byte propagation step.\n */\n// Keep the helper explicitly typed so `--isolatedDeclarations` can expose it\n// through the test-only `__TESTS` export without inference errors.\nconst incBytes = (data, isLE, carry = 1) => {\n // Carry is an increment count, not a signed delta; negatives would wrap through `| 0`.\n // Keep `carry + byte <= 0xffffffff` so the `| 0` / `>>> 8` path below\n // never truncates a real carry bit.\n if (!Number.isSafeInteger(carry) || carry < 0 || carry > 0xffffff00)\n throw new Error('incBytes: wrong carry ' + carry);\n abytes(data);\n for (let i = 0; i < data.length; i++) {\n const pos = !isLE ? data.length - 1 - i : i;\n carry = (carry + (data[pos] & 0xff)) | 0;\n data[pos] = carry & 0xff;\n carry >>>= 8;\n }\n};\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n const t = new Uint8Array(256);\n // Repeated multiplication by {03} walks all 255 nonzero field elements\n // once, so t[255 - i] is the multiplicative inverse of t[i] for the\n // affine step.\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))\n t[i] = x;\n const box = new Uint8Array(256);\n // FIPS 197 upd1 §5.1.1: SBOX({00}) = {63} because the inverse step leaves\n // {00} at {00}, then the affine transform xors in c = {63}.\n box[0] = 0x63;\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n clean(t);\n return box;\n})();\n// FIPS 197 upd1 §5.3.2: INVSBOX() is derived from SBOX() by swapping input\n// and output roles (Table 6).\n// `indexOf` is only used once at module init, so the quadratic setup cost stays off hot paths.\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n// FIPS 197 upd1 §5.2: ROTWORD([a0,a1,a2,a3]) = [a1,a2,a3,a0]; with this LE\n// word packing that is a right rotate by 8 bits.\nconst rotr32_8 = (n) => (n << 24) | (n >>> 8);\n// LE T-table helper: rotates one precomputed word by one byte so T1/T2/T3\n// reuse T0's substitution/mix result in the other byte lanes.\nconst rotl32_8 = (n) => (n << 8) | (n >>> 24);\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox, fn) {\n if (sbox.length !== 256)\n throw new Error('wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n // Pre-xor adjacent lanes so apply0123/applySbox can fetch two substituted\n // byte lanes per lookup in the LE round layout.\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\n// Forward round precompute: the packed word stores the MIXCOLUMNS row\n// [{02},{01},{01},{03}] in LE byte-lane order, and the returned `sbox2`\n// is also reused by key expansion and the final round.\nconst tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));\n// Inverse round precompute: the packed word stores the INVMIXCOLUMNS row\n// [{0e},{09},{0d},{0b}] in LE byte-lane order, and the tables are reused\n// by decrypt() and expandKeyDecLE().\nconst tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));\n// FIPS 197 upd1 §5.2 Table 5: left-most bytes of Rcon[j] = x^(j-1), generated by repeated XTIMES().\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x))\n p[i] = x;\n return p;\n})();\n/** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */\nfunction expandKeyLE(key) {\n abytes(key);\n const len = key.length;\n validateKeyLength(key);\n const { sbox2 } = tableEncoding;\n const toClean = [];\n // Copy on BE or misaligned inputs so the LE word normalization below never\n // mutates caller key bytes in place.\n if (!isLE || !isAligned32(key))\n toClean.push((key = copyBytes(key)));\n const k32 = swap32IfBE(u32(key));\n const Nk = k32.length;\n // `applySbox` normally reads one byte lane from each argument; repeating\n // `n` across all four lanes turns it into SUBWORD(n).\n const subByte = (n) => applySbox(sbox2, n, n, n, n);\n // AES key sizes are 16/24/32 bytes, so len + 28 yields the 44/52/60\n // schedule words from FIPS 197 §5.2 / Table 3.\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0)\n t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4)\n t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n clean(...toClean);\n return xk;\n}\nfunction expandKeyDecLE(key) {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Local decrypt() walks round keys forward from xk[0], so reverse the\n // encryption round-key blocks first before applying the equivalent-inverse\n // middle-round transform.\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++)\n xk[i + j] = encKey[Nk - i - 4 + j];\n }\n clean(encKey);\n // Apply InvMixColumn to the reversed round keys using the same LE sbox2\n // packing as the forward path.\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n// Apply tables\nfunction apply0123(T01, T23, s0, s1, s2, s3) {\n // `T01` takes the low byte lane from `s0` plus the next lane from `s1`;\n // `T23` does the same for `s2`/`s3`.\n // Equivalent to `T0[s0&0xff] ^ T1[(s1>>>8)&0xff] ^ T2[(s2>>>16)&0xff] ^\n // T3[s3>>>24]`, but with two merged-table fetches.\n return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);\n}\nfunction applySbox(sbox2, s0, s1, s2, s3) {\n // `sbox2` packs two substituted byte lanes at a time in the same LE\n // layout used by the round code.\n // Equivalent to `SBOX(byte0(s0)) | SBOX(byte1(s1))<<8 |\n // SBOX(byte2(s2))<<16 | SBOX(byte3(s3))<<24`.\n return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));\n}\nfunction encrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]));\n // `xk` has Nr+1 round-key blocks, so after the initial AddRoundKey and the\n // final S-box-only round there are Nr-1 full table/MixColumns rounds left.\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3));\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different\nfunction decrypt(xk, s0, s1, s2, s3) {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]));\n // With `expandKeyDecLE()` the round keys are already reversed and middle\n // rounds are InvMixColumns-adjusted, so this loop follows the equivalent\n // inverse cipher order directly.\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3));\n }\n // Final equivalent-inverse round omits InvMixColumns, so use inverse\n // S-box lanes in InvShiftRows order.\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\nfunction ctrCounter(xk, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE, 'nonce');\n abytes(src);\n const srcLen = src.length;\n dst = getOutput(srcLen, dst);\n complexOverlapBytes(src, dst);\n // Internal helper: mutate `nonce` in place as the live counter block so\n // each encrypted block uses the next CTR value.\n const ctr = nonce;\n const c32 = u32(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);\n dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);\n dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);\n dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);\n // Full 128 bit big-endian counter with wrap around. Same fixed-shape\n // 16-byte carry walk as incBytes(ctr, false, 1), inlined to skip its\n // per-call argument validation on the per-block hot path.\n for (let j = BLOCK_SIZE - 1, carry = 1; j >= 0; j--) {\n carry = (carry + ctr[j]) | 0;\n ctr[j] = carry & 0xff;\n carry >>>= 8;\n }\n }\n // NIST SP 800-38A CTR mode uses the leading `u` bits of the next output\n // block for the final short block.\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n swap32IfBE(b32);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n // Unsafe mutable-counter API only advances whole blocks. Callers that want to\n // resume after consuming part of this block must re-run from the same counter\n // with left-padding and strip the already-consumed prefix themselves.\n return dst;\n}\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\n// Unsafe 32-bit CTR helper: mutates `nonce` in place, expects aligned `src`/`dst`,\n// and uses `isLE` to choose which 32-bit counter word is incremented.\nfunction ctr32(xk, isLE, nonce, src, dst) {\n abytes(nonce, BLOCK_SIZE, 'nonce');\n abytes(src);\n dst = getOutput(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // NIST SP 800-38D GCTR increments the rightmost 32 bits of J0, while\n // RFC 8452 AES-GCM-SIV increments the first 32 bits as a little-endian u32.\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);\n dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);\n dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);\n dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n swap32IfBE(b32);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(b32);\n }\n // Same unsafe contract as ctrCounter(): only full blocks advance the stored\n // mutable counter state; partial-block continuation is caller-managed.\n return dst;\n}\n/**\n * **CTR** (Counter Mode): turns a block cipher into a stream cipher using a\n * full 16-byte counter block.\n * Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC.\n * @param key - AES key bytes.\n * @param nonce - 16-byte counter block, incremented as a full AES block.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Encrypts a short payload with a fresh AES key and counter block.\n *\n * ```ts\n * import { ctr } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(16);\n * const cipher = ctr(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {\n function processCtr(buf, dst) {\n abytes(buf);\n if (dst !== undefined) {\n abytes(dst);\n // Optional output buffers must stay 4-byte aligned because\n // ctrCounter() reinterprets them as Uint32Array words.\n if (!isAligned32(dst))\n throw new Error('unaligned destination');\n }\n const xk = expandKeyLE(key);\n // Public CTR keeps caller nonce bytes immutable even though ctrCounter()\n // advances the live 16-byte counter block in place.\n const n = copyBytes(nonce); // align + avoid changing\n const toClean = [xk, n];\n if (!isAligned32(buf))\n toClean.push((buf = copyBytes(buf)));\n const out = ctrCounter(xk, n, buf, dst);\n clean(...toClean);\n return out;\n }\n return {\n encrypt: (plaintext, dst) => processCtr(plaintext, dst),\n decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),\n };\n});\nfunction validateBlockDecrypt(data, dst) {\n abytes(data);\n // ECB/CBC decryption always consumes whole ciphertext blocks; PKCS#7/CMS\n // padding, when enabled, is removed only after decrypting the final block.\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error('ciphertext must be multiple of ' + BLOCK_SIZE);\n }\n // Validate caller-provided output before key expansion; allocation happens after it.\n if (dst !== undefined) {\n getOutput(data.length, dst);\n complexOverlapBytes(data, dst);\n }\n}\n// ECB/CBC core modes operate on whole blocks; `pkcs5` enables the library's\n// PKCS#7/CMS-compatible final-block padding convenience before encryption.\nfunction validateBlockEncrypt(plaintext, pkcs5, dst) {\n abytes(plaintext);\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pkcs5 && remaining !== 0)\n throw new Error('plaintext must be multiple of ' + BLOCK_SIZE);\n if (pkcs5) {\n let left = BLOCK_SIZE - remaining;\n // RFC 5652 pads even already-aligned inputs, so a full extra block is\n // appended when the plaintext length is already a multiple of 16 bytes.\n if (!left)\n left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n // Validate caller-provided output before key expansion; allocation happens after it.\n if (dst !== undefined) {\n getOutput(outLen, dst);\n complexOverlapBytes(plaintext, dst);\n }\n return outLen;\n}\nfunction prepareBlockEncrypt(plaintext, outLen, dst) {\n if (dst === undefined)\n dst = new Uint8Array(outLen);\n // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization never\n // mutates caller plaintext bytes in place before ECB/CBC processing.\n if (!isLE || !isAligned32(plaintext))\n plaintext = copyBytes(plaintext);\n const o = u32(dst);\n // Keep the full byte owner so callers can wipe a conditional copy without rebuilding a view.\n return { b: plaintext, o, out: dst };\n}\n// `pkcs5` is the historical option name; for AES's 16-byte block this is the\n// generic PKCS#7/CMS-style block-padding rule on decrypt.\nfunction validatePKCS(data, pkcs5) {\n if (!pkcs5)\n return data;\n const len = data.length;\n // RFC 5652 pads even empty / already-aligned inputs, so a valid padded\n // ECB/CBC ciphertext is never empty when PKCS#7/CMS unpadding is enabled.\n // AES-CBC/ECB ciphertext should be full blocks before unpadding\n if (len === 0)\n throw new Error('pkcs7: empty ciphertext not allowed');\n const lastByte = data[len - 1];\n let valid = 1;\n valid &= ((lastByte - 1) >>> 31) ^ 1; // pad >= 1\n valid &= ((16 - lastByte) >>> 31) ^ 1; // pad <= 16\n // Check exactly 16 tail bytes in constant-shape loop\n // For i < pad: byte must equal pad\n // For i >= pad: ignore byte\n for (let i = 0; i < 16; i++) {\n // const b = data[len - 1 - i];\n const shouldCheck = (i - lastByte) >>> 31; // 1 if i < pad else 0\n const eq = (data[len - 1 - i] ^ lastByte) === 0 ? 1 : 0; // 1 if equal\n valid &= eq | (shouldCheck ^ 1); // pass if equal OR not checked\n }\n // if (invalidLen) throw new Error('aes/pkcs7: ciphertext length must be multiple of 16');\n // Padding rejection is observable as a decrypt failure; authenticate CBC/ECB\n // ciphertexts before decrypting or use `disablePadding` in a higher-level protocol.\n if (!valid)\n throw new Error('aes: bad decrypt');\n return data.subarray(0, len - lastByte);\n}\n// ECB/CBC callers only pass the final short block here, so `left.length` is\n// 0..15 and the helper always emits exactly one padded 16-byte block.\nfunction padPCKS(left) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n // RFC 5652 §6.3 fills the whole suffix with the padding length byte:\n // e.g. `aa 0f..0f` for a 1-byte tail, or `10..10` for a full extra block.\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)\n tmp[i] = paddingByte;\n return tmp32;\n}\n/**\n * **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield\n * identical ciphertexts. Not secure due to pattern leakage.\n * See {@link https://words.filippo.io/the-ecb-penguin/ | the AES Penguin}.\n * @param key - AES key bytes.\n * @param opts - Padding options. See {@link BlockOpts}.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Shows the basic ECB encrypt call shape with a fresh key; avoid ECB in new designs.\n *\n * ```ts\n * import { ecb } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const cipher = ecb(key);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const ecb = /* @__PURE__ */ wrapCipher({ blockSize: 16 }, function aesecb(key, opts = {}) {\n const pkcs5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n const outLen = validateBlockEncrypt(plaintext, pkcs5, dst);\n const xk = expandKeyLE(key);\n const { b: input, o, out: _out } = prepareBlockEncrypt(plaintext, outLen, dst);\n const b = u32(input);\n swap32IfBE(b);\n let i = 0;\n for (; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n if (pkcs5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n swap32IfBE(tmp32);\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n // The padding scratch contains the final plaintext tail; wipe it as soon as consumed.\n clean(tmp32);\n }\n swap32IfBE(o);\n clean(xk);\n if (input !== plaintext)\n clean(input);\n return _out;\n },\n decrypt(ciphertext, dst) {\n // Validate inputs before expanding the key, so a validation throw\n // never leaves an unwiped expanded key behind.\n validateBlockDecrypt(ciphertext, dst);\n const xk = expandKeyDecLE(key);\n if (dst === undefined)\n dst = new Uint8Array(ciphertext.length);\n const toClean = [xk];\n // Copy on BE or misaligned ciphertext so u32()/swap32IfBE()\n // normalization never mutates caller bytes in place before decrypt().\n if (!isLE || !isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(dst);\n swap32IfBE(b);\n for (let i = 0; i + 4 <= b.length;) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n swap32IfBE(o);\n clean(...toClean);\n return validatePKCS(dst, pkcs5);\n },\n };\n});\n/**\n * **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the\n * previous block of ciphertext before encryption.\n * Hard to use: requires proper padding and an unpredictable IV. Unauthenticated: needs MAC.\n * Bad padding is reported as decrypt failure, which can be a padding oracle if exposed.\n * @param key - AES key bytes.\n * @param iv - 16-byte unpredictable initialization vector.\n * @param opts - Padding options. See {@link BlockOpts}.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Encrypts a padded message with a fresh key and 16-byte IV.\n *\n * ```ts\n * import { cbc } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const iv = randomBytes(16);\n * const cipher = cbc(key, iv);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {\n const pkcs5 = !opts.disablePadding;\n return {\n encrypt(plaintext, dst) {\n // Validate inputs before expanding the key, so a validation throw\n // never leaves an unwiped expanded key behind.\n const outLen = validateBlockEncrypt(plaintext, pkcs5, dst);\n const xk = expandKeyLE(key);\n const { b: input, o, out: _out } = prepareBlockEncrypt(plaintext, outLen, dst);\n const b = u32(input);\n swap32IfBE(b);\n let _iv = iv;\n const toClean = [xk];\n // Copy on BE or misaligned inputs so IV normalization and the mutable\n // local chaining state never write back into caller IV bytes.\n if (!isLE || !isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n swap32IfBE(n32);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length;) {\n ((s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]));\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n }\n if (pkcs5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n swap32IfBE(tmp32);\n ((s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]));\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));\n // The padding scratch contains the final plaintext tail; wipe it as soon as consumed.\n clean(tmp32);\n }\n swap32IfBE(o);\n clean(...toClean);\n if (input !== plaintext)\n clean(input);\n return _out;\n },\n decrypt(ciphertext, dst) {\n // Validate inputs before expanding the key, so a validation throw\n // never leaves an unwiped expanded key behind.\n validateBlockDecrypt(ciphertext, dst);\n const xk = expandKeyDecLE(key);\n if (dst === undefined)\n dst = new Uint8Array(ciphertext.length);\n let _iv = iv;\n const toClean = [xk];\n // Copy on BE or misaligned inputs so IV normalization and the mutable\n // local chaining state never write back into caller IV bytes.\n if (!isLE || !isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n const n32 = u32(_iv);\n swap32IfBE(n32);\n // Copy on BE or misaligned ciphertext so u32()/swap32IfBE()\n // normalization never mutates caller bytes in place before decrypt().\n if (!isLE || !isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const b = u32(ciphertext);\n const o = u32(dst);\n swap32IfBE(b);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length;) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n ((s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]));\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n ((o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3));\n }\n swap32IfBE(o);\n clean(...toClean);\n return validatePKCS(dst, pkcs5);\n },\n };\n});\n/**\n * CFB (CFB-128): Cipher Feedback Mode with 128-bit segments. The input for the\n * block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n * @param key - AES key bytes.\n * @param iv - 16-byte unpredictable initialization vector.\n * @returns Cipher instance with `encrypt()` and `decrypt()`.\n * @example\n * Encrypts a short message with feedback mode and a fresh key/IV pair.\n *\n * ```ts\n * import { cfb } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const iv = randomBytes(16);\n * const cipher = cfb(key, iv);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const cfb = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescfb(key, iv) {\n function processCfb(src, isEncrypt, dst) {\n abytes(src);\n const srcLen = src.length;\n dst = getOutput(srcLen, dst);\n // CFB feeds back previous ciphertext, so overlapping src/dst could\n // overwrite bytes that are still needed as the next feedback block.\n if (overlapBytes(src, dst))\n throw new Error('overlapping src and dst not supported');\n const xk = expandKeyLE(key);\n let _iv = iv;\n const toClean = [xk];\n // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization\n // never mutates caller IV/src bytes in place before CFB processing.\n if (!isLE || !isAligned32(_iv))\n toClean.push((_iv = copyBytes(_iv)));\n if (!isLE || !isAligned32(src))\n toClean.push((src = copyBytes(src)));\n const src32 = u32(src);\n const dst32 = u32(dst);\n // NIST SP 800-38A §6.3 feeds back the previous ciphertext segment in\n // both directions: encrypt reuses freshly written dst words, decrypt\n // reuses the source ciphertext words.\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(_iv);\n swap32IfBE(src32);\n swap32IfBE(n32);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length;) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n ((s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]));\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n // The byte tail loop reads `src` directly; restore any BE-swapped tail words first.\n if (!isLE)\n swap32IfBE(src32.subarray(start / 4));\n // Byte-oriented API: for a final short tail, reuse the next CFB-128\n // output block and XOR only the needed prefix. RFC 3826 §3.1.3 /\n // §3.1.4 describes the same no-padding rule at bit granularity for a\n // final r<=128 segment.\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const tmp = new Uint32Array([s0, s1, s2, s3]);\n swap32IfBE(tmp);\n const buf = u8(tmp);\n for (let i = start, pos = 0; i < srcLen; i++, pos++)\n dst[i] = src[i] ^ buf[pos];\n clean(buf);\n }\n if (!isLE)\n swap32IfBE(dst32.subarray(0, start / 4));\n clean(...toClean);\n return dst;\n }\n return {\n encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),\n };\n});\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\n// `data` is the payload covered by the polynomial MAC: ciphertext for GCM,\n// plaintext for GCM-SIV. Keep AAD/data/length as separate updates because\n// GHASH/POLYVAL pad each call to block boundaries, so the chunks must match the\n// spec-defined segments instead of arbitrary concatenation boundaries.\nfunction computeTag(fn, isLE, key, data, AAD) {\n const aadLength = AAD ? AAD.length : 0;\n const h = fn.create(key, data.length + aadLength);\n if (AAD)\n h.update(AAD);\n // u64Lengths() takes (dataBits, aadBits) but still serializes the final\n // block as len(AAD) || len(data), matching both GCM and GCM-SIV.\n const num = u64Lengths(8 * data.length, 8 * aadLength, isLE);\n h.update(data);\n h.update(num);\n const res = h.digest();\n clean(num);\n return res;\n}\n/**\n * **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used.\n * Not perfect:\n * a) conservative key wear-out is `2**32` (4B) msgs.\n * b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance.\n * c) MAC can be forged: see Poly1305 documentation.\n * @param key - AES key bytes.\n * @param nonce - Nonce bytes (12 recommended, minimum 8; other lengths use GHASH J0 derivation).\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance with a fixed 16-byte tag.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and 12-byte nonce.\n *\n * ```ts\n * import { gcm } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(12);\n * const aad = new TextEncoder().encode('session metadata');\n * const cipher = gcm(key, nonce, aad);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const gcm = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, withAAD: true, varSizeNonce: true }, function aesgcm(key, nonce, AAD) {\n // SP 800-38D lets implementations narrow supported IV lengths.\n // This wrapper intentionally requires at least 8 bytes; OpenSSL accepts shorter IVs too.\n // 12-byte nonces take the fast path; other allowed lengths use GHASH to derive J0.\n if (nonce.length < 8)\n throw new Error('aes/gcm: invalid nonce length');\n const tagLength = 16;\n function _computeTag(authKey, tagMask, data) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++)\n tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces\n if (nonce.length === 12) {\n counter.set(nonce);\n }\n else {\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n view.setBigUint64(8, BigInt(nonce.length * 8), false);\n // GHASH.update() pads each call to 16 bytes, so\n // update(nonce).update(nonceLen) realizes\n // IV || 0^s || 0^64 || [len(IV)]_64 for non-96-bit nonces.\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n const g = ghash.create(authKey).update(nonce).update(nonceLen);\n g.digestInto(counter); // digestInto doesn't trigger '.destroy'\n g.destroy();\n }\n // GCTR_K(J0, 0^128) = E_K(J0); reusing ctr32() here extracts that tag\n // mask and leaves `counter` advanced to inc32(J0) for payload GCTR.\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt(plaintext) {\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n const toClean = [xk, authKey, counter, tagMask];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n toClean.push(tag);\n out.set(tag, plaintext.length);\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const toClean = [xk, authKey, tagMask, counter];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n toClean.push(tag);\n // NIST SP 800-38D §7.2 permits equivalent step orderings; verify the\n // tag before CTR so unauthenticated plaintext is never materialized.\n if (!equalBytes(tag, passedTag)) {\n clean(...toClean);\n throw new Error('aes-gcm: invalid tag');\n }\n const out = ctr32(xk, false, counter, data);\n clean(...toClean);\n return out;\n },\n };\n});\nconst limit = (name, min, max) => (value) => {\n // Current AES-SIV/GCM-SIV callers pass protocol limits from RFC 8452 / RFC 5297,\n // not arbitrary library-preference bounds.\n // Callers feed Uint8Array.length values here, so safe-integer rejection\n // does not exclude any representable input even when an RFC bound is larger.\n if (!Number.isSafeInteger(value) || min > value || value > max) {\n const minmax = '[' + min + '..' + max + ']';\n throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value);\n }\n};\n/**\n * **SIV** (Synthetic IV): GCM with nonce-misuse resistance.\n * Repeating nonces reveal only the fact plaintexts are identical.\n * Also suffers from GCM issues: key wear-out limits & MAC forging.\n * See {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.\n * RFC 8452 defines 16-byte and 32-byte AES keys for this mode.\n * This implementation also accepts 24-byte AES-192 keys as a local\n * extension; see the inline comment next to `validateKeyLength(key)` below\n * for the exact scope note.\n * @param key - AES key bytes.\n * @param nonce - 12-byte nonce.\n * @param AAD - Additional authenticated data.\n * @returns AEAD cipher instance.\n * @example\n * Encrypts and authenticates plaintext with a fresh key and nonce, while tolerating reuse.\n *\n * ```ts\n * import { gcmsiv } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(12);\n * const aad = new TextEncoder().encode('session metadata');\n * const cipher = gcmsiv(key, nonce, aad);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const gcmsiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, withAAD: true, varSizeNonce: true }, function aessiv(key, nonce, AAD) {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(key);\n // RFC 8452 only standardizes 16-byte and 32-byte key-generating keys.\n // The accepted 24-byte path is a local AES-192 extension outside the RFC-defined AEADs.\n validateKeyLength(key);\n NONCE_LIMIT(nonce.length);\n if (AAD !== undefined)\n AAD_LIMIT(AAD.length);\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(key.length);\n const authKey = new Uint8Array(16);\n const toClean = [xk, encKey];\n let _nonce = nonce;\n // Copy on BE or misaligned nonce so u32()/swap32IfBE() normalization\n // never mutates caller nonce bytes before RFC 8452 key derivation.\n if (!isLE || !isAligned32(_nonce))\n toClean.push((_nonce = copyBytes(_nonce)));\n const n32 = u32(_nonce);\n swap32IfBE(n32);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n swap32IfBE(d32);\n }\n const res = { authKey, encKey: expandKeyLE(encKey) };\n // Cleanup\n clean(...toClean);\n return res;\n }\n function _computeTag(encKey, authKey, data) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++)\n tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n swap32IfBE(t32);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n ((t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3));\n swap32IfBE(t32);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey, tag, input) {\n let block = copyBytes(tag);\n // RFC 8452 §4 / §5 use the tag with the highest bit of the last byte\n // forced to one as the initial AES-CTR counter block.\n block[15] |= 0x80; // Force highest bit\n const res = ctr32(encKey, true, block, input);\n // Cleanup\n clean(block);\n return res;\n }\n return {\n encrypt(plaintext) {\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const toClean = [encKey, authKey, tag];\n if (!isAligned32(plaintext))\n toClean.push((plaintext = copyBytes(plaintext)));\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n // Cleanup\n clean(...toClean);\n return out;\n },\n decrypt(ciphertext) {\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const toClean = [encKey, authKey];\n if (!isAligned32(ciphertext))\n toClean.push((ciphertext = copyBytes(ciphertext)));\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n toClean.push(expectedTag);\n // RFC 8452 §5: plaintext is unauthenticated here and MUST NOT be\n // returned until the expected-tag check completes successfully.\n if (!equalBytes(tag, expectedTag)) {\n clean(plaintext, ...toClean);\n throw new Error('invalid polyval tag');\n }\n // Cleanup\n clean(...toClean);\n return plaintext;\n },\n };\n});\nfunction isBytes32(a) {\n // Plain `instanceof Uint32Array` is too strict for cross-realm expanded-key views.\n // This is only a best-effort unsafe-export guard, not a provenance proof for `expandKeyLE`.\n return (a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array'));\n}\n// Unsafe single-block helpers: mutate `block` in place and require its 16-byte\n// Uint8Array view to be 4-byte aligned because `u32(block)` reinterprets it.\nfunction encryptBlock(xk, block) {\n abytes(block, 16, 'block');\n if (!isBytes32(xk))\n throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n swap32IfBE(b32);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3));\n swap32IfBE(b32);\n return block;\n}\nfunction decryptBlock(xk, block) {\n abytes(block, 16, 'block');\n if (!isBytes32(xk))\n throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n swap32IfBE(b32);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3));\n swap32IfBE(b32);\n return block;\n}\n/**\n * AES-W (base for AESKW/AESKWP).\n * Specs:\n * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | SP800-38F},\n * {@link https://www.rfc-editor.org/rfc/rfc3394 | RFC 3394},\n * {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.\n * Shared core mutates `out` in place; callers are responsible for prepending\n * the right IV/AIV and checking the recovered value after decrypt.\n */\nconst AESW = {\n /*\n High-level pseudocode:\n ```\n A: u64 = IV\n out = []\n for (let i=0, ctr = 0; i<6; i++) {\n for (const chunk of chunks(plaintext, 8)) {\n A ^= swapEndianess(ctr++)\n [A, res] = chunks(encrypt(A || chunk), 8);\n out ||= res\n }\n }\n out = A || out\n ```\n Decrypt is the same, but reversed.\n */\n encrypt(kek, out) {\n // Current implementation keeps RFC 3394/5649 `t` in a u32-shaped counter,\n // so the shared core caps plaintext below 4 GiB even though the specs allow more.\n if (out.length >= 2 ** 32)\n throw new Error('plaintext should be less than 4gb');\n const xk = expandKeyLE(kek);\n // 16-byte `S = A || P[1]` is the RFC 5649 KWP special case for n=1;\n // KW callers never reach it because KW requires at least two plaintext semiblocks.\n if (out.length === 16)\n encryptBlock(xk, out);\n else {\n const o32 = u32(out);\n swap32IfBE(o32);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = 1; j < 6; j++) {\n for (let pos = 2; pos < o32.length; pos += 2, ctr++) {\n const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n // A = MSB(64, B) ^ t where t = (n*j)+i. Under the 32-bit length cap\n // above, `t` fits in the low half of `[t]_64`, so xor only the low\n // 32 bits of A after converting `ctr` to network order.\n ((a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3));\n }\n }\n ((o32[0] = a0), (o32[1] = a1)); // out = A || out\n swap32IfBE(o32);\n }\n xk.fill(0);\n },\n decrypt(kek, out) {\n // Same implementation cap on the recovered plaintext length after\n // removing the 8-byte A/IV prefix.\n if (out.length - 8 >= 2 ** 32)\n throw new Error('ciphertext should be less than 4gb');\n const xk = expandKeyDecLE(kek);\n const chunks = out.length / 8 - 1; // first chunk is IV\n // `n = 2` semiblocks is the RFC 5649 KWP special case; KW ciphertexts\n // always have at least three semiblocks and therefore use the W^-1 loop.\n if (chunks === 1)\n decryptBlock(xk, out);\n else {\n const o32 = u32(out);\n swap32IfBE(o32);\n // prettier-ignore\n let a0 = o32[0], a1 = o32[1]; // A\n for (let j = 0, ctr = chunks * 6; j < 6; j++) {\n for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {\n a1 ^= byteSwap(ctr);\n const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);\n ((a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3));\n }\n }\n ((o32[0] = a0), (o32[1] = a1));\n swap32IfBE(o32);\n }\n xk.fill(0);\n },\n};\n// RFC 3394 §2.2.3.1 / NIST SP 800-38F Algorithm 3 / Algorithm 4: KW prepends\n// the default 64-bit ICV1 and unwrap must verify the same value.\nconst AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6\n/**\n * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.\n * Reduces block size from 16 to 8 bytes.\n * Plaintext must be a non-empty multiple of 8 bytes with minimum 16 bytes.\n * 8-byte inputs use aeskwp.\n * Wrapped ciphertext must be a multiple of 8 bytes with minimum 24 bytes.\n * For padded version, use aeskwp.\n * See {@link https://www.rfc-editor.org/rfc/rfc3394/ | RFC 3394} and\n * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | NIST SP 800-38F}.\n * @param kek - AES key-encryption key.\n * @returns Key-wrap cipher instance.\n * As with other `wrapCipher(...)` wrappers, `encrypt()` is single-use per\n * instance.\n * @example\n * Wraps a 128-bit content-encryption key with a fresh key-encryption key.\n *\n * ```ts\n * import { aeskw } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const kek = randomBytes(16);\n * const cek = randomBytes(16);\n * const wrap = aeskw(kek);\n * wrap.encrypt(cek);\n * ```\n */\nexport const aeskw = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n if (!plaintext.length || plaintext.length % 8 !== 0)\n throw new Error('invalid plaintext length');\n // RFC 3394 / NIST SP 800-38F define KW only for >=2 plaintext\n // semiblocks; the 1-semiblock case belongs to RFC 5649 KWP.\n if (plaintext.length === 8)\n throw new Error('8-byte keys not allowed, use AESKWP');\n const out = concatBytes(AESKW_IV, plaintext);\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n // ciphertext must be at least 24 bytes and a multiple of 8 bytes\n // 24 because should have at least two block (1 iv + 2).\n // Replace with 16 to enable '8-byte keys'\n if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)\n throw new Error('invalid ciphertext length');\n // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext\n // immutable across the unwrap, ICV1 check, and IV scrubbing below.\n const out = copyBytes(ciphertext);\n AESW.decrypt(kek, out);\n if (!equalBytes(out.subarray(0, 8), AESKW_IV))\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8);\n },\n}));\n/*\nWe don't support 8-byte keys. The rabbit hole:\n\n- Wycheproof says: \"NIST SP 800-38F does not define the wrapping of 8 byte keys.\n RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped\n by directly encrypting one block with AES.\"\n - {@link https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md | Wycheproof key-wrap note}\n - \"RFC 3394 specifies in Section 2, that the input for the key wrap\n algorithm must be at least two blocks and otherwise the constant\n field and key are simply encrypted with ECB as a single block\"\n- What RFC 3394 actually says (in Section 2):\n - \"Before being wrapped, the key data is parsed into n blocks of 64 bits.\n The only restriction the key wrap algorithm places on n is that n be\n at least two\"\n - \"For key data with length less than or equal to 64 bits, the constant\n field used in this specification and the key data form a single\n 128-bit codebook input making this key wrap unnecessary.\"\n- Which means \"assert(n >= 2)\" and \"use something else for 8 byte keys\"\n- NIST SP800-38F actually prohibits 8-byte in \"5.3.1 Mandatory Limits\".\n It states that plaintext for KW should be \"2 to 2^54 -1 semiblocks\".\n- So, where does \"directly encrypt single block with AES\" come from?\n - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses\n loop of 6 for any code path\n - There is a weird W3C spec:\n {@link https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128 | XML Encryption AES key-wrap section}\n - This spec is outdated, as admitted by Wycheproof authors\n - There is RFC 5649 for padded key wrap, which is padding construction on\n top of AESKW. In '4.1.2' it says: \"If the padded plaintext contains exactly\n eight octets, then prepend the AIV as defined in Section 3 above to P[1] and\n encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key\n K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:\"\n - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:\n `Error: error:1C8000E6:Provider routines::invalid input length]\n { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`\n\nIn the end, seems like a bug in Wycheproof.\nThe 8-byte check can be easily disabled inside of AES_W.\n*/\n// RFC 5649 §3 / NIST SP 800-38F Algorithm 5 / Algorithm 6: KWP uses ICV2 as\n// the high 32 bits of the AIV; the low 32 bits carry the MLI in network order.\nconst AESKWP_IV = 0xa65959a6; // single u32le value\n/**\n * AES-KW, but with padding and allows random keys.\n * Uses the RFC 5649 alternative initial value; the second u32 stores the\n * 32-bit MLI in network order.\n * Wrapped ciphertext must be at least 16 bytes; malformed lengths are\n * rejected during AIV/padding checks.\n * See {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.\n * @param kek - AES key-encryption key.\n * @returns Padded key-wrap cipher instance.\n * @example\n * Wraps a short key blob using the padded variant and a fresh key-encryption key.\n *\n * ```ts\n * import { aeskwp } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const kek = randomBytes(16);\n * const wrap = aeskwp(kek);\n * wrap.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const aeskwp = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({\n encrypt(plaintext) {\n if (!plaintext.length)\n throw new Error('invalid plaintext length');\n const padded = Math.ceil(plaintext.length / 8) * 8;\n const out = new Uint8Array(8 + padded);\n out.set(plaintext, 8);\n const out32 = u32(out);\n out32[0] = swap8IfBE(AESKWP_IV);\n // RFC 5649 §3: the low 32 bits of the AIV carry the octet-length MLI in\n // network order, even though this buffer is addressed through LE u32s.\n out32[1] = swap8IfBE(byteSwap(plaintext.length));\n AESW.encrypt(kek, out);\n return out;\n },\n decrypt(ciphertext) {\n // 16 because should have at least one block\n if (ciphertext.length < 16)\n throw new Error('invalid ciphertext length');\n // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext\n // immutable across the unwrap, AIV checks, and IV scrubbing below.\n const out = copyBytes(ciphertext);\n const o32 = u32(out);\n AESW.decrypt(kek, out);\n const len = byteSwap(swap8IfBE(o32[1])) >>> 0;\n const padded = Math.ceil(len / 8) * 8;\n if (swap8IfBE(o32[0]) !== AESKWP_IV || out.length - 8 !== padded)\n throw new Error('integrity check failed');\n // RFC 5649 §3 / NIST SP 800-38F Algorithm 6: recovered padding length\n // must be in [0,7], and every recovered pad octet must be zero.\n for (let i = len; i < padded; i++)\n if (out[8 + i] !== 0)\n throw new Error('integrity check failed');\n out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway\n return out.subarray(8, 8 + len);\n },\n}));\nclass _AesCtrDRBG {\n blockLen;\n key;\n nonce;\n state;\n reseedCnt;\n destroyed = false;\n constructor(keyLen, seed, personalization) {\n this.blockLen = ctr.blockSize;\n const keyLenBytes = keyLen / 8;\n const nonceLen = 16;\n // Store the full seedlen state as key || V so CTR_DRBG_Update-style steps\n // can rewrite the entire internal state in place.\n this.state = new Uint8Array(keyLenBytes + nonceLen);\n this.key = this.state.subarray(0, keyLenBytes);\n this.nonce = this.state.subarray(keyLenBytes, keyLenBytes + nonceLen);\n this.reseedCnt = 1;\n // Keep the stored counter one step ahead of SP 800-90A's formal V so\n // ctr(key, nonce) uses the next counter block directly.\n incBytes(this.nonce, false, 1);\n this.addEntropy(seed, personalization);\n }\n update(data) {\n // cannot re-use state here, because we will wipe current key\n ctr(this.key, this.nonce).encrypt(new Uint8Array(this.state.length), this.state);\n if (data) {\n abytes(data);\n // CTR_DRBG without a derivation function pads shorter additional_input\n // with zeros to seedlen, so XOR only the provided prefix here.\n for (let i = 0; i < data.length; i++)\n this.state[i] ^= data[i];\n }\n // Keep storing V+1 so the next ctr(key, nonce) call starts from the\n // spec's post-update counter state.\n incBytes(this.nonce, false, 1);\n }\n // Optional `info` is additional input XORed into the reseed block and is\n // limited to the internal state width.\n addEntropy(seed, info) {\n if (this.destroyed)\n throw new Error('cannot use destroyed DRBG');\n abytes(seed, this.state.length, 'seed');\n // Copy caller entropy before XORing in personalization/additional input,\n // then wipe the mixed seed material after CTR_DRBG_Update consumes it.\n const _seed = seed.slice();\n if (info) {\n abytes(info);\n if (info.length > _seed.length)\n throw new Error('info length is too big');\n for (let i = 0; i < info.length; i++)\n _seed[i] ^= info[i];\n }\n this.update(_seed);\n _seed.fill(0);\n this.reseedCnt = 1;\n }\n // Optional `info` is additional input for the pre/post-update steps; bytes\n // SP 800-90A Rev. 1 CTR_DRBG without a derivation function limits\n // additional_input to seedlen, which is exactly this internal state width.\n randomBytes(len, info) {\n if (this.destroyed)\n throw new Error('cannot use destroyed DRBG');\n anumber(len);\n // SP 800-90A Table 3 caps AES CTR_DRBG requests at 2^16 bits = 65536 bytes.\n if (len > 2 ** 16)\n throw new Error('requested output is too big');\n // The spec allows generate while reseed_counter == reseed_interval and increments afterwards.\n if (this.reseedCnt > 2 ** 48)\n throw new Error('entropy exhausted');\n if (info) {\n abytes(info);\n if (info.length > this.state.length)\n throw new Error('info length is too big');\n this.update(info);\n }\n const res = new Uint8Array(len);\n ctr(this.key, this.nonce).encrypt(res, res);\n incBytes(this.nonce, false, Math.ceil(len / this.blockLen));\n this.update(info);\n this.reseedCnt++;\n return res;\n }\n // Zeroes the current state and marks the instance destroyed. Fails closed:\n // any later randomBytes()/addEntropy() throws instead of continuing from the\n // zeroed state (which would make subsequent output the predictable zero-key stream).\n clean() {\n // `key` and `nonce` alias this backing buffer, so one fill wipes the full\n // secret state in place.\n this.state.fill(0);\n this.reseedCnt = 0;\n this.destroyed = true;\n }\n}\n// Internal helper for the exported 128-bit and 256-bit aliases; other key\n// lengths are not validated here.\nconst createAesDrbg = (keyLen) => {\n return (seed, personalization = undefined) => new _AesCtrDRBG(keyLen, seed, personalization);\n};\n/**\n * AES-CTR DRBG 128-bit - CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * @param seed - Initial 32-byte entropy input.\n * @param personalization - Optional personalization string.\n * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.\n * @example\n * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.\n *\n * ```ts\n * import { rngAesCtrDrbg128 } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(32);\n * const prg = rngAesCtrDrbg128(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngAesCtrDrbg128 = /* @__PURE__ */ createAesDrbg(128);\n/**\n * AES-CTR DRBG 256-bit - CSPRNG (cryptographically secure pseudorandom number generator).\n * It's best to limit usage to non-production, non-critical cases: for example, test-only.\n * @param seed - Initial 48-byte entropy input.\n * @param personalization - Optional personalization string.\n * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.\n * @example\n * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.\n *\n * ```ts\n * import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const seed = randomBytes(48);\n * const prg = rngAesCtrDrbg256(seed);\n * prg.randomBytes(8);\n * ```\n */\nexport const rngAesCtrDrbg256 = /* @__PURE__ */ createAesDrbg(256);\n//#region CMAC\n/**\n * Left-shift by one bit and conditionally XOR with 0x87:\n * ```\n * if MSB(L) is equal to 0\n * then K1 := L << 1;\n * else K1 := (L << 1) XOR const_Rb;\n * ```\n *\n * Specs:\n * {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3},\n * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.3 | RFC 5297 Section 2.3}\n *\n * @returns modified `block` (for chaining)\n */\nfunction dbl(block) {\n let carry = 0;\n // Left shift by 1 bit\n for (let i = BLOCK_SIZE - 1; i >= 0; i--) {\n const newCarry = (block[i] & 0x80) >>> 7;\n block[i] = (block[i] << 1) | carry;\n carry = newCarry;\n }\n // XOR with 0x87 if there was a carry from the most significant bit.\n // RFC 4493 §2.3 / RFC 5297 §2.1: 0x87 is const_Rb for doubling in the\n // CMAC/S2V finite field with primitive polynomial x^128 + x^7 + x^2 + x + 1.\n // Branchless: `carry` derives from secret CMAC subkey material.\n block[BLOCK_SIZE - 1] ^= 0x87 & -carry;\n return block;\n}\n/**\n * `a XOR b`, running in-place on `a`.\n * @param a left operand and output\n * @param b right operand\n * @returns `a` (for chaining)\n */\nfunction xorBlock(a, b) {\n if (a.length !== b.length)\n throw new Error('xorBlock: blocks must have same length');\n for (let i = 0; i < a.length; i++) {\n a[i] = a[i] ^ b[i];\n }\n return a;\n}\n/**\n * xorend as defined in\n * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.1 | RFC 5297 Section 2.1}.\n *\n * ```\n * leftmost(A, len(A)-len(B)) || (rightmost(A, len(B)) xor B)\n * ```\n *\n * Mutates `a` in place so the left prefix stays untouched and only the\n * rightmost `len(B)` bytes are xored with `b`.\n */\nfunction xorend(a, b) {\n if (b.length > a.length) {\n throw new Error('xorend: expected len(B) <= len(A)');\n }\n // keep leftmost part of `a` unchanged\n // and xor only the rightmost part:\n const offset = a.length - b.length;\n for (let i = 0; i < b.length; i++) {\n a[offset + i] = a[offset + i] ^ b[i];\n }\n return a;\n}\n/**\n * Internal CMAC class.\n */\nclass _CMAC {\n blockLen = BLOCK_SIZE;\n outputLen = BLOCK_SIZE;\n // CMAC can only decide between `K1` and `K2` once the true final block is known,\n // so updates process older blocks eagerly but keep one pending block buffered.\n buffer;\n pos;\n finished;\n destroyed;\n k1;\n k2;\n x;\n x32;\n xk;\n constructor(key) {\n abytes(key);\n validateKeyLength(key);\n this.xk = expandKeyLE(key);\n this.buffer = new Uint8Array(BLOCK_SIZE);\n this.pos = 0;\n this.finished = false;\n this.destroyed = false;\n this.x = new Uint8Array(BLOCK_SIZE);\n // Cached word view over `x`: process() runs once per 16 input bytes, so\n // it must not re-create views or re-validate per block like encryptBlock().\n this.x32 = u32(this.x);\n // L = AES_encrypt(K, const_Zero)\n const L = new Uint8Array(BLOCK_SIZE);\n encryptBlock(this.xk, L);\n // Generate subkeys K1 and K2 from the main key according to\n // {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3}\n // K1\n this.k1 = dbl(L);\n this.k2 = dbl(new Uint8Array(this.k1));\n }\n // Consumes 16 bytes of `data` starting at `pos`; `pos` avoids a per-block\n // subarray view allocation in update().\n process(data, pos) {\n // RFC 4493 §2.4 step 6 loop body: Y := X XOR M_i; X := AES-128(K, Y).\n const { x, x32, xk } = this;\n for (let i = 0; i < BLOCK_SIZE; i++)\n x[i] ^= data[pos + i];\n swap32IfBE(x32);\n const { s0, s1, s2, s3 } = encrypt(xk, x32[0], x32[1], x32[2], x32[3]);\n ((x32[0] = s0), (x32[1] = s1), (x32[2] = s2), (x32[3] = s3));\n swap32IfBE(x32);\n }\n update(data) {\n aexists(this);\n abytes(data);\n let pos = 0;\n if (this.pos) {\n const take = Math.min(BLOCK_SIZE - this.pos, data.length);\n this.buffer.set(data.subarray(0, take), this.pos);\n this.pos += take;\n pos = take;\n if (this.pos === BLOCK_SIZE && pos < data.length) {\n this.process(this.buffer, 0);\n this.pos = 0;\n }\n }\n // Keep one complete block buffered: an exact 16-byte tail may still be\n // M_n, and digestInto() must decide there whether RFC 4493 uses K1 or K2.\n while (pos + BLOCK_SIZE < data.length) {\n this.process(data, pos);\n pos += BLOCK_SIZE;\n }\n if (pos < data.length) {\n this.buffer.set(data.subarray(pos), 0);\n this.pos = data.length - pos;\n }\n return this;\n }\n // See {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.4 | RFC 4493 Section 2.4}.\n digestInto(out) {\n aexists(this);\n // `digestInto(out)` is the no-allocation fast path, so AES block re-use below\n // requires a 32-bit-aligned caller buffer instead of hidden temp copies.\n aoutput32(out, this);\n this.finished = true;\n // `digestInto()` accepts out.length >= outputLen, so only the first block stores the tag.\n const view = out.subarray(0, this.outputLen);\n let last = new Uint8Array(BLOCK_SIZE);\n if (this.pos === BLOCK_SIZE) {\n // M_last := M_n XOR K1;\n last.set(this.buffer);\n xorBlock(last, this.k1);\n }\n else {\n // M_last := padding(M_n) XOR K2;\n //\n // [...] padding(x) is the concatenation of x and a single '1',\n // followed by the minimum number of '0's, so that the total length is\n // equal to 128 bits.\n last.set(this.buffer.subarray(0, this.pos));\n last[this.pos] = 0x80; // single '1' bit\n xorBlock(last, this.k2);\n }\n view.set(this.x); // X := AES_CBC(K, M_1..M_{n-1})\n xorBlock(view, last); // Y := X XOR M_last\n encryptBlock(this.xk, view); // T := AES-128(K, Y)\n clean(last);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy out before destroy() wipes the internal digest buffer in place.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n destroy() {\n const { buffer, destroyed, x, xk, k1, k2 } = this;\n if (destroyed)\n return;\n this.destroyed = true;\n // Wipe the buffered tail, chaining value, expanded AES key, and both CMAC subkeys.\n clean(buffer, x, xk, k1, k2);\n }\n}\n/**\n * AES-CMAC (Cipher-based Message Authentication Code).\n * Specs: {@link https://www.rfc-editor.org/rfc/rfc4493.html | RFC 4493}.\n * @param msg - Message bytes to authenticate.\n * @param key - AES key bytes.\n * @returns 16-byte authentication tag. `cmac.create(...)` follows the same incremental MAC shape as\n * the other keyed helpers in this repo, including `blockLen`,\n * `outputLen`, `digestInto()` and `destroy()`.\n * @example\n * Authenticates a message with AES-CMAC and a fresh key.\n *\n * ```ts\n * import { cmac } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * cmac(new Uint8Array(), key);\n * ```\n */\n// The 16-byte probe key is only used to read static metadata; runtime CMAC\n// still accepts AES-128/192/256 keys.\nexport const cmac = /* @__PURE__ */ wrapMacConstructor(16, (key) => new _CMAC(key));\n/**\n * S2V (Synthetic Initialization Vector) function as described in\n * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.4 | RFC 5297 Section 2.4}.\n *\n * ```\n * S2V(K, S1, ..., Sn) {\n * if n = 0 then\n * return V = AES-CMAC(K, <one>)\n * fi\n * D = AES-CMAC(K, <zero>)\n * for i = 1 to n-1 do\n * D = dbl(D) xor AES-CMAC(K, Si)\n * done\n * if len(Sn) >= 128 then\n * T = Sn xorend D\n * else\n * T = dbl(D) xor pad(Sn)\n * fi\n * return V = AES-CMAC(K, T)\n * }\n * ```\n *\n * S2V takes a key and a vector of strings S1, S2, ..., Sn and returns a 128-bit string.\n * The S2V function is used to generate a synthetic IV for AES-SIV.\n *\n * @param key - AES key (128, 192, or 256 bits)\n * @param strings - Array of byte arrays to process\n * @returns 128-bit synthetic IV\n */\nfunction s2v(key, strings) {\n validateKeyLength(key);\n const len = strings.length;\n if (len > 127) {\n // RFC 5297 §7 only proves S2V secure for at most 127 components; SIV\n // spends one of those on the plaintext, leaving at most 126 AAD inputs.\n throw new Error('s2v: expected <= 127 inputs');\n }\n if (len === 0)\n return cmac(ONE_BLOCK, key);\n // D = AES-CMAC(K, <zero>)\n let d = cmac(EMPTY_BLOCK, key);\n // for i = 1 to n-1 do\n // D = dbl(D) xor AES-CMAC(K, Si)\n for (let i = 0; i < len - 1; i++) {\n dbl(d);\n const cmacResult = cmac(strings[i], key);\n xorBlock(d, cmacResult);\n clean(cmacResult);\n }\n const s_n = strings[len - 1];\n // Earlier components are validated through cmac(...); validate the final one explicitly because\n // the Uint8Array.from()/set() paths below would otherwise coerce array-like inputs silently.\n abytes(s_n);\n let t;\n // if len(Sn) >= 128 then\n if (s_n.byteLength >= BLOCK_SIZE) {\n // T = Sn xorend D\n t = xorend(Uint8Array.from(s_n), d);\n }\n else {\n // pad(Sn):\n const paddedSn = new Uint8Array(BLOCK_SIZE);\n paddedSn.set(s_n);\n paddedSn[s_n.length] = 0x80; // padding: 0x80 followed by zeros\n // T = dbl(D) xor pad(Sn)\n t = xorBlock(dbl(d), paddedSn);\n clean(paddedSn);\n }\n // V = AES-CMAC(K, T)\n const result = cmac(t, key);\n clean(d, t);\n return result;\n}\n/**\n * Use `gcmsiv` or `aessiv`.\n * @returns Never; always throws with the migration hint.\n * @throws If called; `siv()` is a removed v1 alias. {@link Error}\n * @example\n * `siv()` was removed in v2; use `gcmsiv()` for nonce-based SIV instead.\n *\n * ```ts\n * import { gcmsiv } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(16);\n * const nonce = randomBytes(12);\n * const cipher = gcmsiv(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const siv = () => {\n throw new Error('\"siv\" from v1 is now \"gcmsiv\"');\n};\n/**\n * **SIV**: Synthetic Initialization Vector (SIV) Authenticated Encryption\n * Nonce is derived from the plaintext and AAD using the S2V function.\n * Supports at most 126 AAD components. RFC 5297 nonce-based use is expressed by\n * passing the nonce as the final AAD component before the plaintext.\n * See {@link https://datatracker.ietf.org/doc/html/rfc5297.html | RFC 5297}.\n * @param key - 32-byte, 48-byte, or 64-byte key.\n * @param AAD - Additional authenticated data chunks (up to 126).\n * @returns AEAD cipher instance.\n * @example\n * Authenticates and encrypts plaintext with a fresh key without requiring unique nonces.\n *\n * ```ts\n * import { aessiv } from '@noble/ciphers/aes.js';\n * import { randomBytes } from '@noble/ciphers/utils.js';\n * const key = randomBytes(32);\n * const cipher = aessiv(key);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const aessiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, tagLength: 16, withAAD: true }, function aessiv(key, ...AAD) {\n // From RFC 5297: Section 6.1, 6.2, 6.3:\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 132);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 132 + 16);\n if (AAD.length > 126) {\n // RFC 5297 §2.6 / §2.7 / §7: SIV passes the plaintext as the last S2V\n // component, so callers only get 126 associated-data components.\n throw new Error('\"AAD\" expected <= 126 items');\n }\n AAD.forEach((aad) => abytes(aad));\n abytes(key);\n if (![32, 48, 64].includes(key.length))\n throw new Error('\"aes key\" expected Uint8Array of length 32/48/64, got length=' + key.length);\n // The key is split into equal halves, K1 = leftmost(K, len(K)/2) and\n // K2 = rightmost(K, len(K)/2). K1 is used for S2V and K2 is used for CTR.\n // This borrows caller key/AAD buffers by reference; mutating them after\n // construction changes future encrypt/decrypt results.\n const k1 = key.subarray(0, key.length / 2);\n const k2 = key.subarray(key.length / 2);\n return {\n // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.6 | RFC 5297 Section 2.6}\n encrypt(plaintext) {\n PLAIN_LIMIT(plaintext.length);\n const v = s2v(k1, [...AAD, plaintext]);\n // clear out the 31st and 63rd (rightmost) bit:\n const q = Uint8Array.from(v);\n q[8] &= 0x7f;\n q[12] &= 0x7f;\n // encrypt:\n const c = ctr(k2, q).encrypt(plaintext);\n return concatBytes(v, c);\n },\n // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.7 | RFC 5297 Section 2.7}\n decrypt(ciphertext) {\n CIPHER_LIMIT(ciphertext.length);\n const v = ciphertext.subarray(0, BLOCK_SIZE);\n const c = ciphertext.subarray(BLOCK_SIZE);\n // clear out the 31st and 63rd (rightmost) bit:\n const q = Uint8Array.from(v);\n q[8] &= 0x7f;\n q[12] &= 0x7f;\n // decrypt:\n const p = ctr(k2, q).decrypt(c);\n // verify tag:\n const t = s2v(k1, [...AAD, p]);\n if (equalBytes(t, v)) {\n return p;\n }\n else {\n clean(p);\n throw new Error('invalid siv tag');\n }\n },\n };\n});\n//#endregion\n/**\n * Unsafe low-level internal methods. May change at any time.\n * Callers are expected to use reviewed expanded-key outputs, pass mutable and\n * aligned 16-byte blocks where required, and treat several helpers as in-place\n * mutations of their input buffers or counters.\n */\nexport const unsafe = /* @__PURE__ */ Object.freeze({\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n dbl,\n xorBlock,\n xorend,\n s2v,\n});\nexport const __TESTS = /* @__PURE__ */ Object.freeze({\n incBytes: incBytes,\n});\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, aoutput, clean, } from \"./utils.js\";\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 §3 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC {\n oHash;\n iHash;\n blockLen;\n outputLen;\n canXOF = false;\n finished = false;\n destroyed = false;\n constructor(hash, key) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('expected Hash instance');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of the first block) of the outer hash here,\n // we can re-use it between multiple calls via clone.\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const buf = out.subarray(0, this.outputLen);\n // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n this.iHash.digestInto(buf);\n this.oHash.update(buf);\n this.oHash.digestInto(buf);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since the key\n // is already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.canXOF = canXOF;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\nexport const hmac = /* @__PURE__ */ (() => {\n const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());\n hmac_.create = (hash, key) => new _HMAC(hash, key);\n return hmac_;\n})();\n","/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from \"./hmac.js\";\n// prettier-ignore\nimport { ahash, anumber, asyncLoop, checkOpts, clean, createView, kdfInputToBytes } from \"./utils.js\";\n// Common validation and per-call state setup for sync/async functions.\nfunction pbkdf2Init(hash, _password, _salt, _opts) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c, 'c');\n anumber(dkLen, 'dkLen');\n anumber(asyncTick, 'asyncTick');\n if (c < 1)\n throw new Error('\"c\" (iterations) must be >= 1');\n // RFC 8018 §5.2 defines `dkLen` as \"a positive integer\".\n if (dkLen < 1)\n throw new Error('\"dkLen\" must be >= 1');\n // RFC 8018 §5.2 step 1 requires rejecting oversize `dkLen`\n // before allocating the destination buffer.\n if (dkLen > (2 ** 32 - 1) * hash.outputLen)\n throw new Error('derived key too long');\n const p = kdfInputToBytes(_password, 'password');\n try {\n const s = kdfInputToBytes(_salt, 'salt');\n try {\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n const { iHash, oHash, outputLen } = hmac.create(hash, p);\n // Drive keyed hashes directly; the wrapper is only needed to initialize their HMAC midstates.\n const u = new Uint8Array(outputLen);\n const eng = pbkdf2Engine(iHash, oHash, s, u);\n return { c, dkLen, asyncTick, DK, outputLen, eng };\n }\n finally {\n // Uint8Array inputs belong to the caller; only wipe our UTF-8 conversion.\n if (typeof _salt === 'string')\n clean(s);\n }\n }\n finally {\n if (typeof _password === 'string')\n clean(p);\n }\n}\n// Per-call PRF driver writes U1 into both `u` and `Ti`, then later digests into `u`;\n// shared by the sync and async variants.\nfunction pbkdf2Engine(iHash, oHash, salt, u) {\n const counter = new Uint8Array(4);\n const view = createView(counter);\n // Full clones retain tree/config state; absorb salt before async yields without cloning input.\n const salted = iHash._cloneInto().update(salt);\n // u1() overwrites the worker before reading it. Seed from the outer midstate so a long salt\n // cannot pre-populate a tree stack that the first reset would abandon without wiping.\n const work = oHash._cloneInto();\n const iClone = iHash._cloneInto; // Capture before mixed feedback can materialize state tuples.\n const oClone = oHash._cloneInto;\n return {\n u1: (ti, Ti) => {\n view.setInt32(0, ti, false);\n salted._cloneInto(work).update(counter).digestInto(u);\n oHash._cloneInto(work).update(u).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n },\n // Whole `F` inner loop for the sync variant: one optimized function owns the hot loop.\n rounds: (c, Ti) => {\n for (let ui = 1; ui < c; ui++) {\n iClone.call(iHash, work).update(u).digestInto(u);\n oClone.call(oHash, work).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n }\n },\n output: (DK) => {\n // Keyed templates and derived worker states are secret material.\n iHash.destroy();\n oHash.destroy();\n salted.destroy();\n work.destroy();\n // Shared sync/async cleanup point: wipe transient PRF state\n // while preserving the derived key buffer.\n clean(u);\n return DK;\n },\n };\n}\n/**\n * PBKDF2-HMAC: RFC 8018 key derivation function.\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated;\n * JS string inputs are UTF-8 encoded first\n * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first\n * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,\n * must be `>= 1` per RFC 8018 §5.2. See {@link Pbkdf2Opt}.\n * @returns Derived key bytes.\n * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}\n * @example\n * PBKDF2-HMAC: RFC 2898 key derivation function.\n * ```ts\n * import { pbkdf2 } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n * ```\n */\nexport function pbkdf2(hash, password, salt, opts) {\n const { c, dkLen, DK, outputLen, eng } = pbkdf2Init(hash, password, salt, opts);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += outputLen) {\n // Ti = F(Password, Salt, c, i)\n // The last Ti view can be shorter than hLen, which applies\n // RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies.\n const Ti = DK.subarray(pos, pos + outputLen);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n eng.u1(ti, Ti);\n // Uc = PRF(Password, Uc−1); Ti ^= Uc\n eng.rounds(c, Ti);\n }\n return eng.output(DK);\n}\n/**\n * PBKDF2-HMAC: RFC 8018 key derivation function. Async version.\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated;\n * JS string inputs are UTF-8 encoded first\n * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first\n * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,\n * must be `>= 1` per RFC 8018 §5.2. `asyncTick` is only a local\n * scheduler-yield knob for this JS wrapper, not part of RFC 8018.\n * See {@link Pbkdf2Opt}.\n * @returns Promise resolving to derived key bytes.\n * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}\n * @example\n * PBKDF2-HMAC: RFC 2898 key derivation function.\n * ```ts\n * import { pbkdf2Async } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n * ```\n * @example\n * Tune the async PBKDF2 scheduler for short UI tasks.\n * ```ts\n * import { pbkdf2Async } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = await pbkdf2Async(sha256, 'password', 'salt', {\n * dkLen: 32,\n * c: 32,\n * asyncTick: 1,\n * });\n * ```\n */\nexport async function pbkdf2Async(hash, password, salt, opts) {\n const { c, dkLen, asyncTick, DK, outputLen, eng } = pbkdf2Init(hash, password, salt, opts);\n // Reuse normal state destruction, then wipe the incomplete output if a host yield aborts.\n const abort = () => {\n eng.output(DK);\n clean(DK);\n };\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += outputLen) {\n // Ti = F(Password, Salt, c, i)\n // The last Ti view can be shorter than hLen, which applies\n // RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies.\n const Ti = DK.subarray(pos, pos + outputLen);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n eng.u1(ti, Ti);\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n eng.rounds(2, Ti); // c=2 runs exactly one PRF iteration per callback.\n }, abort);\n }\n return eng.output(DK);\n}\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nclass SHA2_32B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and makes sha256 3x slower (measured).\n A = 0;\n B = 0;\n C = 0;\n D = 0;\n E = 0;\n F = 0;\n G = 0;\n H = 0;\n constructor(outputLen, IV) {\n super(64, outputLen, 8, false);\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B {\n constructor() {\n super(32, SHA256_IV);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n constructor() {\n super(28, SHA224_IV);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nclass SHA2_64B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and slows hashing down (measured on sha256).\n Ah = 0;\n Al = 0;\n Bh = 0;\n Bl = 0;\n Ch = 0;\n Cl = 0;\n Dh = 0;\n Dl = 0;\n Eh = 0;\n El = 0;\n Fh = 0;\n Fl = 0;\n Gh = 0;\n Gl = 0;\n Hh = 0;\n Hl = 0;\n constructor(outputLen, IV) {\n super(128, outputLen, 16, false);\n this.Ah = IV[0] | 0;\n this.Al = IV[1] | 0;\n this.Bh = IV[2] | 0;\n this.Bl = IV[3] | 0;\n this.Ch = IV[4] | 0;\n this.Cl = IV[5] | 0;\n this.Dh = IV[6] | 0;\n this.Dl = IV[7] | 0;\n this.Eh = IV[8] | 0;\n this.El = IV[9] | 0;\n this.Fh = IV[10] | 0;\n this.Fl = IV[11] | 0;\n this.Gh = IV[12] | 0;\n this.Gl = IV[13] | 0;\n this.Hh = IV[14] | 0;\n this.Hl = IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B {\n constructor() {\n super(64, SHA512_IV);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n constructor() {\n super(48, SHA384_IV);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n constructor() {\n super(28, T224_IV);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n constructor() {\n super(32, T256_IV);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n","/**\n * RFC 7914 Scrypt KDF. Can be used to create a key from password and salt.\n * @module\n */\nimport { pbkdf2 } from \"./pbkdf2.js\";\nimport { sha256 } from \"./sha2.js\";\n// prettier-ignore\nimport { anumber, asyncLoop, checkOpts, clean, rotl, swap32IfBE, u32 } from \"./utils.js\";\n// The main Scrypt loop: uses Salsa extensively.\n// Six versions of the function were tried, this is the fastest one.\n// RFC 7914 §3 / §4 step 2 applies Salsa20/8 to one 16-word (64-byte) block\n// after xor'ing two such blocks.\n// The local `y*` snapshot keeps the xor input stable even when `out` aliases `prev` or `input`.\n// prettier-ignore\nfunction XorAndSalsa(prev, pi, input, ii, out, oi) {\n // Based on https://cr.yp.to/salsa20.html and RFC 7914's Salsa20/8 core.\n // Xor blocks\n let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];\n let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];\n let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];\n let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];\n let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];\n let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];\n let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];\n let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];\n // Save state to temporary variables (salsa)\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n // Main loop (salsa)\n for (let i = 0; i < 8; i += 2) {\n x04 ^= rotl(x00 + x12 | 0, 7);\n x08 ^= rotl(x04 + x00 | 0, 9);\n x12 ^= rotl(x08 + x04 | 0, 13);\n x00 ^= rotl(x12 + x08 | 0, 18);\n x09 ^= rotl(x05 + x01 | 0, 7);\n x13 ^= rotl(x09 + x05 | 0, 9);\n x01 ^= rotl(x13 + x09 | 0, 13);\n x05 ^= rotl(x01 + x13 | 0, 18);\n x14 ^= rotl(x10 + x06 | 0, 7);\n x02 ^= rotl(x14 + x10 | 0, 9);\n x06 ^= rotl(x02 + x14 | 0, 13);\n x10 ^= rotl(x06 + x02 | 0, 18);\n x03 ^= rotl(x15 + x11 | 0, 7);\n x07 ^= rotl(x03 + x15 | 0, 9);\n x11 ^= rotl(x07 + x03 | 0, 13);\n x15 ^= rotl(x11 + x07 | 0, 18);\n x01 ^= rotl(x00 + x03 | 0, 7);\n x02 ^= rotl(x01 + x00 | 0, 9);\n x03 ^= rotl(x02 + x01 | 0, 13);\n x00 ^= rotl(x03 + x02 | 0, 18);\n x06 ^= rotl(x05 + x04 | 0, 7);\n x07 ^= rotl(x06 + x05 | 0, 9);\n x04 ^= rotl(x07 + x06 | 0, 13);\n x05 ^= rotl(x04 + x07 | 0, 18);\n x11 ^= rotl(x10 + x09 | 0, 7);\n x08 ^= rotl(x11 + x10 | 0, 9);\n x09 ^= rotl(x08 + x11 | 0, 13);\n x10 ^= rotl(x09 + x08 | 0, 18);\n x12 ^= rotl(x15 + x14 | 0, 7);\n x13 ^= rotl(x12 + x15 | 0, 9);\n x14 ^= rotl(x13 + x12 | 0, 13);\n x15 ^= rotl(x14 + x13 | 0, 18);\n }\n // Write output (salsa)\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\nfunction BlockMix(input, ii, out, oi, r) {\n // The block B is `r` 128-byte chunks, i.e. `2r` 16-word (64-byte) Salsa blocks.\n let head = oi + 0;\n let tail = oi + 16 * r;\n for (let i = 0; i < 16; i++)\n out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]\n for (let i = 0; i < r; i++, head += 16, ii += 16) {\n // RFC 7914 §4 step 3 outputs `Y[0], Y[2], ...` first, then `Y[1], Y[3], ...`;\n // `head` and `tail` lay out those even/odd halves in place.\n XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1])\n if (i > 0)\n tail += 16; // First iteration overwrites tmp value in tail\n // tail[i] = Salsa(blockIn[2*i+1] ^ head[i])\n XorAndSalsa(out, head, input, (ii += 16), out, tail);\n }\n}\n// 128*r*(N+p+1) for N=2**20, r=8, p=1: 1 GiB main table plus 2 KiB workspace.\nconst SCRYPT_DEFAULT_MAXMEM = 128 * 8 * (2 ** 20 + 1 + 1);\n// Common prologue and epilogue for sync/async functions\nfunction scryptInit(password, salt, _opts) {\n const opts = checkOpts({\n dkLen: 32,\n asyncTick: 10,\n maxmem: SCRYPT_DEFAULT_MAXMEM,\n }, _opts);\n const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;\n anumber(N, 'N');\n anumber(r, 'r');\n anumber(p, 'p');\n anumber(dkLen, 'dkLen');\n anumber(asyncTick, 'asyncTick');\n anumber(maxmem, 'maxmem');\n if (onProgress !== undefined && typeof onProgress !== 'function')\n throw new Error('\"onProgress\" must be a function');\n // Without this, r=0 slips through: blockSize=0 turns the `p` upper bound into\n // Infinity and the failure surfaces later as a confusing pbkdf2 dkLen error.\n if (r < 1)\n throw new Error('\"r\" expected integer >= 1');\n const blockSize = 128 * r;\n const blockSize32 = blockSize / 4;\n // Max N is 2^32 (Integrify is 32-bit).\n // Real limit can be 2^22: some JS engines limit Uint8Array to 4GB.\n // Spec check `N >= 2^(blockSize / 8)` is not done for compat with popular libs,\n // which used incorrect r: 1, p: 8. Also, the check seems to be a spec error:\n // https://www.rfc-editor.org/errata_search.php?rfc=7914\n const pow32 = Math.pow(2, 32);\n if (N <= 1 || (N & (N - 1)) !== 0 || N > pow32)\n throw new Error('\"N\" expected a power of 2, and 2^1 <= N <= 2^32');\n if (p < 1 || p > ((pow32 - 1) * 32) / blockSize)\n throw new Error('\"p\" expected integer 1..((2^32 - 1) * 32) / (128 * r)');\n // RFC 7914 §2 defines `dkLen` as a positive integer.\n if (dkLen < 1 || dkLen > (pow32 - 1) * 32)\n throw new Error('\"dkLen\" expected integer 1..(2^32 - 1) * 32');\n // Include the shared `tmp` scratch block so `maxmem` matches noble's actual temporary allocation.\n // Node requires more headroom here, so this accounting is intentionally noble-specific.\n const memUsed = blockSize * (N + p + 1);\n if (memUsed > maxmem)\n throw new Error('\"maxmem\" limit was hit: memUsed(128*r*(N+p+1))=' + memUsed + ', maxmem=' + maxmem);\n // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)\n // Since it has only one iteration there is no reason to use async variant\n const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });\n const B32 = u32(B);\n // Re-used between parallel iterations. Array(iterations) of B\n const V = u32(new Uint8Array(blockSize * N));\n const tmp = u32(new Uint8Array(blockSize));\n let blockMixCb = () => { };\n if (onProgress) {\n const totalBlockMix = 2 * N * p;\n // Invoke callback if progress changes from 10.01 to 10.02\n // Allows to draw smooth progress bar on up to 8K screen\n const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);\n let blockMixCnt = 0;\n blockMixCb = () => {\n blockMixCnt++;\n if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) {\n // Wiping here instead of a try/catch around the main loops keeps them\n // try-free: measured ~1% slower at N=2^21 with the loops inside a try.\n // onProgress is the only user code that can throw mid-derivation.\n try {\n onProgress(blockMixCnt / totalBlockMix);\n }\n catch (e) {\n clean(B, V, tmp);\n throw e;\n }\n }\n };\n }\n return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };\n}\nfunction scryptOutput(password, dkLen, B, V, tmp) {\n // Shared final PBKDF2-and-cleanup step: keep the derived key, wipe the scrypt workspace.\n const res = pbkdf2(sha256, password, B, { c: 1, dkLen });\n clean(B, V, tmp);\n return res;\n}\n/**\n * Scrypt KDF from RFC 7914. See {@link ScryptOpts}.\n * @param password - password or key material to derive from;\n * JS string inputs are UTF-8 encoded first\n * @param salt - unique salt bytes or string; JS string inputs are UTF-8 encoded first\n * @param opts - Scrypt cost and memory parameters. `dkLen`, if provided,\n * must be `>= 1` per RFC 7914 §2. See {@link ScryptOpts}.\n * @returns Derived key bytes.\n * @throws If the Scrypt cost, memory, or callback options are invalid. {@link Error}\n * @example\n * Derive a key with scrypt.\n * ```ts\n * scrypt('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 });\n * ```\n * @example\n * Derive a key with small demo costs and progress/memory controls.\n * ```ts\n * const progressLog: number[] = [];\n * scrypt('password', 'salt', {\n * N: 16,\n * r: 8,\n * p: 1,\n * dkLen: 32,\n * maxmem: 1024 * 1024,\n * asyncTick: 10,\n * onProgress(progress) {\n * progressLog.push(progress);\n * },\n * });\n * ```\n */\nexport function scrypt(password, salt, opts) {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts);\n swap32IfBE(B32);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++)\n V[i] = B32[Pi + i]; // V[0] = B[i]\n for (let i = 0, pos = 0; i < N - 1; i++) {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n }\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n for (let i = 0; i < N; i++) {\n // First u32 of the last 64-byte block (u32 is LE)\n // RFC 7914 Integerify(X) uses the whole last 64-byte block, but mod N\n // only depends on the low word here because N is a power of two and\n // this implementation caps N at 2^32.\n // & (N - 1) is % N as N is a power of 2, N & (N - 1) = 0 is checked\n // above; >>> 0 for unsigned, input fits in u32.\n const j = (B32[Pi + blockSize32 - 16] & (N - 1)) >>> 0; // j = Integrify(X) % iterations\n // tmp = B ^ V[j]\n for (let k = 0; k < blockSize32; k++)\n tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k];\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n }\n }\n swap32IfBE(B32);\n return scryptOutput(password, dkLen, B, V, tmp);\n}\n/**\n * Scrypt KDF from RFC 7914. Async version. See {@link ScryptOpts}.\n * @param password - password or key material to derive from;\n * JS string inputs are UTF-8 encoded first\n * @param salt - unique salt bytes or string; JS string inputs are UTF-8 encoded first\n * @param opts - Scrypt cost and memory parameters. `dkLen`, if provided,\n * must be `>= 1` per RFC 7914 §2. `asyncTick` is only a local\n * scheduler-yield control for this JS wrapper, not part of RFC 7914.\n * See {@link ScryptOpts}.\n * @returns Promise resolving to derived key bytes.\n * @throws If the Scrypt cost, memory, or callback options are invalid. {@link Error}\n * @example\n * Derive a key with scrypt asynchronously.\n * ```ts\n * await scryptAsync('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 });\n * ```\n * @example\n * Derive a key asynchronously with small demo costs and progress/memory controls.\n * ```ts\n * await scryptAsync('password', 'salt', {\n * N: 16,\n * r: 8,\n * p: 1,\n * dkLen: 32,\n * maxmem: 1024 * 1024,\n * asyncTick: 1,\n * onProgress(progress) {\n * if (progress > 1) throw new Error('invalid progress');\n * },\n * });\n * ```\n */\nexport async function scryptAsync(password, salt, opts) {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);\n // One failure handler covers both yield boundaries without putting the hot loops in a try block.\n const abort = () => clean(B, V, tmp);\n swap32IfBE(B32);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++)\n V[i] = B32[Pi + i]; // V[0] = B[i]\n let pos = 0;\n await asyncLoop(N - 1, asyncTick, () => {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n }, abort);\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n await asyncLoop(N, asyncTick, () => {\n // First u32 of the last 64-byte block (u32 is LE)\n // RFC 7914 Integerify(X) uses the whole last 64-byte block, but mod N\n // only depends on the low word here because N is a power of two and\n // this implementation caps N at 2^32.\n // & (N - 1) is % N as N is a power of 2, N & (N - 1) = 0 is checked\n // above; >>> 0 for unsigned, input fits in u32.\n const j = (B32[Pi + blockSize32 - 16] & (N - 1)) >>> 0; // j = Integrify(X) % iterations\n // tmp = B ^ V[j]\n for (let k = 0; k < blockSize32; k++)\n tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k];\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n }, abort);\n }\n swap32IfBE(B32);\n return scryptOutput(password, dkLen, B, V, tmp);\n}\n","import { ctr } from \"@noble/ciphers/aes.js\";\nimport { scryptAsync } from \"@noble/hashes/scrypt.js\";\nimport { keccak_256 } from \"@noble/hashes/sha3.js\";\nimport { randomBytes } from \"@noble/hashes/utils.js\";\nimport { Bytes, BytesLike, bytesConcat, bytesFrom } from \"../bytes/index.js\";\nimport { hexFrom } from \"../hex/index.js\";\n\n// The parameter r (\"blockSize\")\nconst DEFAULT_SCRYPT_PARAM_R = 8;\n// The parallelization parameter p\nconst DEFAULT_SCRYPT_PARAM_P = 1;\n// The CPU/Memory cost parameter N\nconst DEFAULT_SCRYPT_PARAM_N = 262144;\n\nfunction mac(derivedKey: Bytes, cipherText: Bytes) {\n return hexFrom(\n keccak_256(bytesConcat(derivedKey.subarray(16, 32), cipherText)),\n ).slice(2);\n}\n\n/**\n * @public\n */\nexport async function keystoreEncrypt(\n privateKeyLike: BytesLike,\n chainCodeLike: BytesLike,\n password: string,\n): Promise<{\n id: string;\n crypto: {\n ciphertext: string;\n cipherparams: {\n iv: string;\n };\n cipher: string;\n kdf: string;\n kdfparams: {\n n: number;\n r: number;\n p: number;\n dklen: number;\n salt: string;\n };\n mac: string;\n };\n}> {\n const salt = randomBytes(32);\n const iv = randomBytes(16);\n const kdfparams = {\n dklen: 32,\n salt: hexFrom(salt).slice(2),\n n: DEFAULT_SCRYPT_PARAM_N,\n r: DEFAULT_SCRYPT_PARAM_R,\n p: DEFAULT_SCRYPT_PARAM_P,\n };\n const derivedKey = await scryptAsync(bytesFrom(password, \"utf8\"), salt, {\n N: kdfparams.n,\n r: kdfparams.r,\n p: kdfparams.p,\n dkLen: kdfparams.dklen,\n });\n const cipher = ctr(\n derivedKey.subarray(0, 16),\n iv.map((v) => v),\n );\n const ciphertext = cipher.encrypt(\n bytesConcat(bytesFrom(privateKeyLike), bytesFrom(chainCodeLike)),\n );\n\n return {\n id: hexFrom(randomBytes(16)).slice(2),\n crypto: {\n ciphertext: hexFrom(ciphertext).slice(2),\n cipherparams: {\n iv: hexFrom(iv).slice(2),\n },\n cipher: \"aes-128-ctr\",\n kdf: \"scrypt\",\n kdfparams,\n mac: mac(derivedKey, ciphertext),\n },\n };\n}\n\n/**\n * @public\n */\nexport async function keystoreDecrypt(\n keystore: unknown,\n password: string,\n): Promise<{\n privateKey: Bytes;\n chainCode: Bytes;\n}> {\n if (\n typeof keystore !== \"object\" ||\n keystore === null ||\n !(\"crypto\" in keystore)\n ) {\n throw Error(\"Invalid keystore\");\n }\n const crypto = keystore.crypto;\n\n if (\n typeof crypto !== \"object\" ||\n crypto === null ||\n !(\"kdfparams\" in crypto) ||\n !(\"ciphertext\" in crypto) ||\n typeof crypto.ciphertext !== \"string\" ||\n !(\"mac\" in crypto) ||\n typeof crypto.mac !== \"string\" ||\n !(\"cipherparams\" in crypto) ||\n typeof crypto.cipherparams !== \"object\" ||\n crypto.cipherparams === null ||\n !(\"iv\" in crypto.cipherparams) ||\n typeof crypto.cipherparams.iv !== \"string\"\n ) {\n throw Error(\"Invalid crypto\");\n }\n const kdfparams = crypto.kdfparams;\n\n if (\n typeof kdfparams !== \"object\" ||\n kdfparams === null ||\n !(\"n\" in kdfparams) ||\n typeof kdfparams.n !== \"number\" ||\n !(\"r\" in kdfparams) ||\n typeof kdfparams.r !== \"number\" ||\n !(\"p\" in kdfparams) ||\n typeof kdfparams.p !== \"number\" ||\n !(\"dklen\" in kdfparams) ||\n typeof kdfparams.dklen !== \"number\" ||\n !(\"salt\" in kdfparams) ||\n typeof kdfparams.salt !== \"string\"\n ) {\n throw Error(\"Invalid kdfparams\");\n }\n\n const derivedKey = await scryptAsync(\n bytesFrom(password, \"utf8\"),\n bytesFrom(kdfparams.salt),\n {\n N: kdfparams.n,\n r: kdfparams.r,\n p: kdfparams.p,\n dkLen: kdfparams.dklen,\n },\n );\n const ciphertext = bytesFrom(crypto.ciphertext);\n if (mac(derivedKey, ciphertext) !== crypto.mac) {\n throw Error(\"Invalid password\");\n }\n const cipher = ctr(\n derivedKey.subarray(0, 16),\n bytesFrom(crypto.cipherparams.iv),\n );\n const result = cipher.decrypt(ciphertext);\n return {\n privateKey: result.slice(0, 32),\n chainCode: result.slice(32),\n };\n}\n","import { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\n\n/**\n * Options for signing a PSBT (Partially Signed Bitcoin Transaction)\n */\nexport type SignPsbtOptionsLike = {\n /**\n * Whether to attempt to finalize the signed inputs after signing.\n * Default is true.\n */\n autoFinalized?: boolean;\n /**\n * Array of inputs to sign\n */\n inputsToSign?: InputToSignLike[];\n};\n\nexport class SignPsbtOptions {\n constructor(\n public autoFinalized: boolean,\n public inputsToSign: InputToSign[],\n ) {}\n\n static from(\n options?: SignPsbtOptionsLike | SignPsbtOptions,\n ): SignPsbtOptions {\n if (options instanceof SignPsbtOptions) {\n return options;\n }\n return new SignPsbtOptions(\n options?.autoFinalized ?? true,\n options?.inputsToSign?.map((i) => InputToSign.from(i)) ?? [],\n );\n }\n}\n\n/**\n * Specification for an input to sign in a PSBT.\n * Must specify at least one of: address or pubkey.\n */\nexport type InputToSignLike = {\n /**\n * Which input to sign (index in the PSBT inputs array)\n */\n index: number;\n /**\n * (Optional) Sighash types to use for signing.\n */\n sighashTypes?: number[];\n /**\n * (Optional) When signing and unlocking Taproot addresses, the tweakSigner is used by default\n * for signature generation. Setting this to true allows for signing with the original private key.\n * Default value is false.\n */\n disableTweakSigner?: boolean;\n} & (\n | {\n /**\n * The address whose corresponding private key to use for signing.\n */\n address: string;\n /**\n * The public key whose corresponding private key to use for signing.\n */\n publicKey?: HexLike;\n }\n | {\n /**\n * The address whose corresponding private key to use for signing.\n */\n address?: string;\n /**\n * The public key whose corresponding private key to use for signing.\n */\n publicKey: HexLike;\n }\n);\n\nexport class InputToSign {\n constructor(\n public index: number,\n public sighashTypes?: number[],\n public disableTweakSigner?: boolean,\n public address?: string,\n public publicKey?: Hex,\n ) {}\n\n static from(input: InputToSignLike): InputToSign {\n if (input instanceof InputToSign) {\n return input;\n }\n return new InputToSign(\n input.index,\n input.sighashTypes,\n input.disableTweakSigner,\n input.address,\n input.publicKey ? hexFrom(input.publicKey) : undefined,\n );\n }\n}\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, anumber as anumber_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, randomBytes as randomBytes_, } from '@noble/hashes/utils.js';\n/**\n * Validates that a value is an array, optionally validating each element.\n * @param item - Value to validate.\n * @param title - Label included in thrown errors.\n * @param inner - Optional per-element validator, called with the element and its label.\n * @returns The validated array.\n * @example\n * Validate an array of points before batch processing.\n *\n * ```ts\n * aarray([1n, 2n], 'scalars');\n * ```\n */\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\n/**\n * Validates that a value is a byte array.\n * @param value - Value to validate.\n * @param length - Optional exact byte length.\n * @param title - Optional field name.\n * @returns Original byte array.\n * @example\n * Reject non-byte input before passing data into curve code.\n *\n * ```ts\n * abytes(new Uint8Array(1));\n * ```\n */\nexport const abytes = (value, length, title) => abytes_(value, length, title);\n/**\n * Validates that a value is a non-negative safe integer.\n * @param n - Value to validate.\n * @param title - Optional field name.\n * @returns The validated number.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber = anumber_;\n/**\n * Asserts something is a string.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a label string.\n *\n * ```ts\n * astring('example', 'label');\n * ```\n */\nexport function astring(value, title = '') {\n if (typeof value !== 'string') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected string, got type=' + typeof value);\n }\n return value;\n}\n/**\n * Asserts something is a plain object-ish value, not null or array.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated object.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate an options object before checking fields.\n *\n * ```ts\n * aobject({ flag: true });\n * ```\n */\nexport function aobject(value, title = 'object') {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(title === 'object'\n ? 'expected valid options object'\n : `\"${title}\" expected object, got type=${typeof value}`);\n return value;\n}\n/**\n * Asserts something is a function.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated function.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a required method before calling it.\n *\n * ```ts\n * afunction(() => true, 'predicate');\n * ```\n */\nexport function afunction(value, title) {\n if (typeof value !== 'function')\n throw new TypeError(`\"${title}\" is invalid: expected function, got ${typeof value}`);\n return value;\n}\n/**\n * Encodes bytes as lowercase hex.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hex string.\n * @example\n * Serialize bytes as hex for logging or fixtures.\n *\n * ```ts\n * bytesToHex(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport const bytesToHex = bytesToHex_;\n/**\n * Concatenates byte arrays.\n * @param arrays - Byte arrays to join.\n * @returns Concatenated bytes.\n * @example\n * Join domain-separated chunks into one buffer.\n *\n * ```ts\n * concatBytes(Uint8Array.of(1), Uint8Array.of(2));\n * ```\n */\nexport const concatBytes = (...arrays) => concatBytes_(...arrays);\n/**\n * Decodes lowercase or uppercase hex into bytes.\n * @param hex - Hex string to decode.\n * @returns Decoded bytes.\n * @example\n * Parse fixture hex into bytes before hashing.\n *\n * ```ts\n * hexToBytes('0102');\n * ```\n */\nexport const hexToBytes = (hex) => hexToBytes_(hex);\n/**\n * Checks whether a value is a Uint8Array.\n * @param a - Value to inspect.\n * @returns `true` when `a` is a Uint8Array.\n * @example\n * Branch on byte input before decoding it.\n *\n * ```ts\n * isBytes(new Uint8Array(1));\n * ```\n */\nexport const isBytes = isBytes_;\n/**\n * Reads random bytes from the platform CSPRNG.\n * @param bytesLength - Number of random bytes to read.\n * @returns Fresh random bytes.\n * @example\n * Generate a random seed for a keypair.\n *\n * ```ts\n * randomBytes(2);\n * ```\n */\nexport const randomBytes = (bytesLength) => randomBytes_(bytesLength);\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Validates that a flag is boolean.\n * @param value - Value to validate.\n * @param title - Optional field name.\n * @returns Original value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Reject non-boolean option flags early.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate one integer-like value before serializing it.\n *\n * ```ts\n * abignumber(1n);\n * ```\n */\nexport function abignumber(n) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n))\n throw new RangeError('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return n;\n}\n/**\n * Validates that a value is a safe integer.\n * @param value - Integer to validate.\n * @param title - Optional field name.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a window size before scalar arithmetic uses it.\n *\n * ```ts\n * asafenumber(1);\n * ```\n */\nexport function asafenumber(value, title = '') {\n if (typeof value !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected number, got type=' + typeof value);\n }\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(prefix + 'expected safe integer, got ' + value);\n }\n}\n/**\n * Encodes a bigint into even-length big-endian hex.\n * The historical \"unpadded\" name only means \"no fixed-width field padding\"; odd-length hex still\n * gets one leading zero nibble so the result always represents whole bytes.\n * @param num - Number to encode.\n * @returns Big-endian hex string.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Encode a scalar into hex without a `0x` prefix.\n *\n * ```ts\n * numberToHexUnpadded(255n);\n * ```\n */\nexport function numberToHexUnpadded(num) {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n/**\n * Parses a big-endian hex string into bigint.\n * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the\n * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.\n * @param hex - Hex string without `0x`.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parse a scalar from fixture hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// BE: Big Endian, LE: Little Endian\n/**\n * Parses big-endian bytes into bigint.\n * @param bytes - Bytes in big-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in network byte order.\n *\n * ```ts\n * bytesToNumberBE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex_(bytes));\n}\n/**\n * Parses little-endian bytes into bigint.\n * @param bytes - Bytes in little-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in little-endian form.\n *\n * ```ts\n * bytesToNumberLE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberLE(bytes) {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n/**\n * Encodes a bigint into fixed-length big-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar into a 32-byte field element.\n *\n * ```ts\n * numberToBytesBE(255n, 2);\n * ```\n */\nexport function numberToBytesBE(n, len) {\n anumber_(len);\n if (len === 0)\n throw new Error('zero output length is invalid');\n n = abignumber(n);\n const expectedLen = len * 2;\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > expectedLen)\n throw new RangeError('number is too large');\n return hexToBytes_(hex.padStart(expectedLen, '0'));\n}\n/**\n * Encodes a bigint into fixed-length little-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Little-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\n/**\n * Encodes a bigint into variable-length big-endian bytes.\n * @param n - Number to encode.\n * @returns Variable-length big-endian bytes.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a bigint without fixed-width padding.\n *\n * ```ts\n * numberToVarBytesBE(255n);\n * ```\n */\nexport function numberToVarBytesBE(n) {\n return hexToBytes_(numberToHexUnpadded(abignumber(n)));\n}\n// Compares 2 u8a-s in kinda constant time\n/**\n * Compares two byte arrays in constant-ish time.\n * @param a - Left byte array.\n * @param b - Right byte array.\n * @returns `true` when bytes match.\n * @example\n * Compare two encoded points without early exit.\n *\n * ```ts\n * equalBytes(Uint8Array.of(1), Uint8Array.of(1));\n * ```\n */\nexport function equalBytes(a, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n * @param bytes - Bytes to copy.\n * @returns Detached copy.\n * @example\n * Make an isolated copy before mutating serialized bytes.\n *\n * ```ts\n * copyBytes(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n * @param ascii - ASCII input text.\n * @returns Encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode an ASCII domain-separation tag.\n *\n * ```ts\n * asciiToBytes('ABC');\n * ```\n */\nexport function asciiToBytes(ascii) {\n if (typeof ascii !== 'string')\n throw new TypeError('ascii string expected, got ' + typeof ascii);\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new RangeError(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n/**\n * Checks whether n is non-negative bigint. Historical name.\n * @param n - candidate value\n * @returns `true` when the value is bigint and 0 or larger\n * @example\n * Check a candidate scalar before range validation.\n *\n * ```ts\n * isPosBig(2n);\n * ```\n */\nexport function isPosBig(n) {\n return typeof n === 'bigint' && _0n <= n;\n}\n/**\n * Checks whether a bigint lies inside a half-open range.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * @returns `true` when the value is inside the range.\n * @example\n * Check whether a candidate scalar fits the field order.\n *\n * ```ts\n * inRange(2n, 1n, 3n);\n * ```\n */\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts `min <= n < max`. NOTE: upper bound is exclusive.\n * @param title - Value label for error messages.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * Wrong-type inputs are not separated from out-of-range values here: they still flow through the\n * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Assert that a bigint stays within one half-open range.\n *\n * ```ts\n * aInRange('x', 2n, 1n, 256n);\n * ```\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n * @param n - Value to inspect.\n * @returns Bit length.\n * @throws If the value is negative. {@link Error}\n * @example\n * Measure the bit length of a scalar before serialization.\n *\n * ```ts\n * bitLen(8n);\n * ```\n */\nexport function bitLen(n) {\n // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a\n // contract bug and must not silently collapse to zero bits.\n if (n < _0n)\n throw new Error('expected non-negative bigint, got ' + n);\n // Native radix conversion beats a shift loop at every size, and the loop is quadratic in bits.\n return n === _0n ? 0 : n.toString(2).length;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw\n * bigint shift semantics; because the mask is built as `1n << pos`,\n * they currently collapse to `0n` and make the helper a no-op.\n * @returns Bit as bigint.\n * @example\n * Gets single bit at position.\n *\n * ```ts\n * bitGet(5n, 0);\n * ```\n */\nexport function bitGet(n, pos) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics,\n * so they currently behave like left shifts.\n * @param value - Whether the bit should be set.\n * @returns Updated bigint.\n * @example\n * Sets single bit at position.\n *\n * ```ts\n * bitSet(0n, 1, true);\n * ```\n */\nexport function bitSet(n, pos, value) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n abool(value, 'value');\n const mask = _1n << BigInt(pos);\n // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched.\n return value ? n | mask : n & ~mask;\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift\n * semantics and therefore produce `-1n`.\n * @returns Bitmask value.\n * @example\n * Calculate mask for N bits.\n *\n * ```ts\n * bitMask(4);\n * ```\n */\nexport const bitMask = (n) => {\n asafenumber(n, 'n');\n return (_1n << BigInt(n)) - _1n;\n};\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`\n * is not rejected here and would make the internal generate loop non-progressing.\n * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.\n * @param hmacFn - HMAC implementation.\n * @returns Function that will call DRBG until the predicate returns anything\n * other than `undefined`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Build a deterministic nonce generator for RFC6979-style signing.\n *\n * ```ts\n * import { createHmacDrbg } from '@noble/curves/utils.js';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hmacFn = (key: Uint8Array, msg: Uint8Array) => hmac(sha256, key, msg);\n * const drbg = createHmacDrbg(32, 32, hmacFn);\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n anumber_(hashLen, 'hashLen');\n anumber_(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function')\n throw new TypeError('hmacFn must be a function');\n // creates Uint8Array\n const u8n = (len) => new Uint8Array(len);\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n // Step B, Step C: set hashLen to 8*ceil(hlen/8).\n // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.\n let v = u8n(hashLen);\n // Steps B and C of RFC6979 3.2.\n let k = u8n(hashLen);\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n // hmac(k)(v, ...values)\n const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));\n const reseed = (seed = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters)\n throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until the predicate accepts a candidate.\n // Falsy values like 0 are valid outputs.\n while ((res = pred(gen())) === undefined)\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * Extra keys are intentionally ignored because many callers validate only the subset they use from\n * richer option bags or runtime objects.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `aobject()`, `afunction()`, `abool()`, or `asafenumber()` instead.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @param title - Object label included in thrown errors.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Check user options before building a curve helper.\n *\n * ```ts\n * validateObject({ flag: true }, { flag: 'boolean' });\n * ```\n */\nexport function validateObject(object, fields = {}, optFields = {}, title = 'object') {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n/**\n * Throws not implemented error.\n * @returns Never returns.\n * @throws If the unfinished code path is reached. {@link Error}\n * @example\n * Surface the placeholder error from an unfinished code path.\n *\n * ```ts\n * try {\n * notImplemented();\n * } catch {}\n * ```\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, abytes, afunction, anumber, aobject, asafenumber, bitLen, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, } from \"../utils.js\";\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _15n = /* @__PURE__ */ BigInt(15), _16n = /* @__PURE__ */ BigInt(16);\n// 2^64: exponents below this use plain square-and-multiply in pow()/FpPow(); the windowed path's\n// table build (14 multiplications) only pays off for longer exponents (break-even ~50 bits).\nconst POW_WINDOWED_MIN = /* @__PURE__ */ BigInt('0x10000000000000000');\n/**\n * @param a - Dividend value.\n * @param b - Positive modulus.\n * @returns Reduced value in `[0, b)` only when `b` is positive.\n * @throws If the modulus is not positive. {@link Error}\n * @example\n * Normalize a bigint into one field residue.\n *\n * ```ts\n * mod(-1n, 5n);\n * ```\n */\nexport function mod(a, b) {\n if (b <= _0n)\n throw new Error('mod: expected positive modulus, got ' + b);\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to a power with modular reduction.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen\n * modulus instead of relying on the `power===0/1` fast paths to normalize it.\n * @param num - Base value.\n * @param power - Exponent value.\n * @param modulo - Reduction modulus.\n * @returns Modular exponentiation result.\n * @throws If the modulus or exponent is invalid. {@link Error}\n * @example\n * Raise one bigint to a modular power.\n *\n * ```ts\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n * ```\n */\nexport function pow(num, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow: expected modulus > 1, got ' + modulo);\n // Non-bigint exponents coerce every comparison below to false and would silently return 1.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return _1n;\n if (power === _1n)\n return num;\n let d = num % modulo;\n if (d < _0n)\n d += modulo;\n // Control flow in both branches below depends only on the exponent, never on `num` — invertCt()\n // relies on that for its (public-exponent) secret-independence guarantee.\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents.\n let p = _1n;\n while (power > _0n) {\n if (power & _1n)\n p = (p * d) % modulo;\n d = (d * d) % modulo;\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first: a 14-multiplication table drops per-window cost to <1\n // multiplication (vs ~2 per window for square-and-multiply), ~25-30% faster for the dense\n // 256-bit exponents of sqrt / Legendre / invertCt.\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = _1n;\n table[1] = d;\n for (let i = 2; i < 16; i++)\n table[i] = (table[i - 1] * d) % modulo;\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n const digit = digits[w];\n if (digit !== 0)\n p = (p * table[digit]) % modulo;\n }\n return p;\n}\n/**\n * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.\n * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen\n * modulus; the `power===0` fast path intentionally returns the input unchanged.\n * @param x - Base value.\n * @param power - Number of squarings.\n * @param modulo - Reduction modulus.\n * @returns Repeated-squaring result.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Apply repeated squaring inside one field.\n *\n * ```ts\n * pow2(3n, 2n, 11n);\n * ```\n */\nexport function pow2(x, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow2: expected modulus > 1, got ' + modulo);\n if (power < _0n)\n throw new Error('pow2: expected non-negative exponent, got ' + power);\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.\n * @param number - Value to invert.\n * @param modulo - Modulus greater than 1.\n * @returns Multiplicative inverse.\n * @throws If the modulus is invalid or the inverse does not exist. {@link Error}\n * @example\n * Compute one modular inverse with the extended Euclidean algorithm.\n *\n * ```ts\n * invert(3n, 11n);\n * ```\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n // modulo = 1 is the zero ring: gcd(x, 1) = 1 makes the loop below \"succeed\" and return the\n // useless inverse 0. Reject it like pow() and invertCt() do.\n if (modulo <= _1n)\n throw new Error('invert: expected modulus > 1, got ' + modulo);\n // This is variable-time: the loop count depends on `number`. For a secret-independent\n // (Fermat) alternative over a prime modulus, see {@link invertCt} (~4x slower).\n let a = mod(number, modulo);\n let b = modulo;\n // Only the Bézout coefficient of `number` (x/u chain) is tracked; the coefficient of `modulo`\n // never affects the output, so it is not computed.\n // prettier-ignore\n let x = _0n, u = _1n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n // prettier-ignore\n b = a, a = r, x = u, u = m;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Inverses number over modulo using Fermat's little theorem: `a^(p-2) ≡ a⁻¹ (mod p)`.\n *\n * Unlike {@link invert} (extended Euclidean), the exponent `p-2` is a public constant, so the\n * underlying square-and-multiply has the same control flow for every secret `a`: there is no\n * data-dependent branching or loop count that could leak `a` through timing (e.g. Minerva-style\n * ECDSA nonce-inversion attacks). This is only \"algorithmically\" constant-time — JS bigint\n * multiplication/reduction is still value-dependent — and it is roughly 4x slower than\n * {@link invert}.\n *\n * REQUIRES a prime modulus; Fermat's theorem does not hold otherwise. The result is verified to be\n * a real inverse, so a non-prime modulus (or a non-invertible input) fails closed with an error\n * instead of returning a wrong value.\n * @param a - Value to invert.\n * @param prime - Prime modulus.\n * @returns Multiplicative inverse in `[1, prime)`.\n * @throws If the modulus is below 2, the input reduces to zero, or the inverse does not exist.\n * {@link Error}\n * @example\n * Compute one modular inverse without secret-dependent branching.\n *\n * ```ts\n * invertCt(3n, 11n); // 4n, since 3 * 4 = 12 ≡ 1 (mod 11)\n * ```\n */\nexport function invertCt(a, prime) {\n if (prime <= _1n)\n throw new Error('invertCt: expected prime modulus > 1, got ' + prime);\n const an = mod(a, prime);\n if (an === _0n)\n throw new Error('invertCt: expected non-zero number');\n // Exponent (prime - 2) is public, so FpPow's square-and-multiply is secret-independent.\n const inverse = pow(an, prime - _2n, prime);\n // O(1) safety net: verifies the inverse and rejects composite moduli where a^(p-2) is not one.\n if (mod(an * inverse, prime) !== _1n)\n throw new Error('invertCt: does not exist');\n return inverse;\n}\nfunction assertIsSquare(Fp, root, n) {\n const F = Fp;\n if (!F.eql(F.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// The Legendre symbol and every sqrt variant here are only defined over an odd (prime) modulus.\n// An even ORDER makes their integer divisions — (p-1)/2, (p+1)/4, (p-5)/8, (p+7)/16 — truncate and\n// silently return a wrong result, so reject it explicitly at the entry points instead. This is a\n// cheap necessary-condition check, not a primality test (composite odd moduli are caught later by\n// the Legendre-result / assertIsSquare checks).\nfunction aoddModulus(order, fnName) {\n if ((order & _1n) === _0n)\n throw new Error(fnName + ': expected odd modulus, got ' + order);\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const F = Fp;\n const p1div4 = (F.ORDER + _1n) / _4n;\n const root = F.pow(n, p1div4);\n assertIsSquare(F, root, n);\n return root;\n}\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8(Fp, n) {\n const F = Fp;\n const p5div8 = (F.ORDER - _5n) / _8n;\n const n2 = F.mul(n, _2n);\n const v = F.pow(n2, p5div8);\n const nv = F.mul(n, v);\n const i = F.mul(F.mul(nv, _2n), v);\n const root = F.mul(nv, F.sub(i, F.ONE));\n assertIsSquare(F, root, n);\n return root;\n}\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return ((Fp, n) => {\n const F = Fp;\n let tv1 = F.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(F, root, n);\n return root;\n });\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`\n * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.\n * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P - field order\n * @returns function that takes field Fp (created from P) and number n\n * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}\n * @example\n * Construct a square-root helper for primes that need Tonelli-Shanks.\n *\n * ```ts\n * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = tonelliShanks(17n)(Fp, 4n);\n * ```\n */\nexport function tonelliShanks(P) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n aoddModulus(P, 'tonelliShanks');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000)\n throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1)\n return sqrt3mod4;\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n const F = Fp;\n if (F.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(F, n) !== 1)\n throw new Error('Cannot find square root');\n // Initialize variables for the main loop\n let M = S;\n let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n // Main loop\n // while t != 1\n while (!F.eql(t, F.ONE)) {\n // Unreachable over a genuine field (no zero divisors; n=0 already returned above). A zero t\n // means composite ORDER, where a fabricated root would be wrong: fail closed instead.\n if (F.is0(t))\n throw new Error('Cannot find square root: probably non-prime P');\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = F.sqr(t); // t^(2^1)\n while (!F.eql(t_tmp, F.ONE)) {\n i++;\n t_tmp = F.sqr(t_tmp); // t^(2^2)...\n if (i === M)\n throw new Error('Cannot find square root');\n }\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = F.pow(c, exponent); // b = 2^(M - i - 1)\n // Update variables\n M = i;\n c = F.sqr(b); // c = b^2\n t = F.mul(t, c); // t = (t * b^2)\n R = F.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness\n * (used for hash-to-curve).\n * @param P - Field order.\n * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time\n * behavior and this selector assumes prime-field-style integer moduli.\n * @throws If the field is unsupported or the square root does not exist. {@link Error}\n * @example\n * Choose the square-root helper appropriate for one field modulus.\n *\n * ```ts\n * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = FpSqrt(17n)(Fp, 4n);\n * ```\n */\nexport function FpSqrt(P) {\n aoddModulus(P, 'Fp.sqrt');\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n)\n return sqrt5mod8;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n)\n return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n/**\n * @param num - Value to inspect.\n * @param modulo - Field modulus.\n * @returns `true` when the least-significant little-endian bit is set.\n * @throws If the modulus is invalid for `mod(...)`. {@link Error}\n * @example\n * Inspect the low bit used by little-endian sign conventions.\n *\n * ```ts\n * isNegativeLE(3n, 11n);\n * ```\n */\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\n// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime\n// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and\n// field-specific extras like `isOdd` are left to the callers that actually need them.\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\n/**\n * @param field - Field implementation.\n * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it\n * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or\n * field-specific extras beyond positive `BYTES` / `BITS`.\n * @throws If the field shape or numeric metadata are invalid. {@link Error}\n * @example\n * Check that a field implementation exposes the operations curve code expects.\n *\n * ```ts\n * import { Field, validateField } from '@noble/curves/abstract/modular.js';\n * const Fp = validateField(Field(17n));\n * ```\n */\nexport function validateField(field) {\n aobject(field, 'field');\n if (typeof field.ORDER !== 'bigint')\n throw new TypeError('param \"ORDER\" is invalid: expected bigint, got ' + typeof field.ORDER);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\n for (const name of FIELD_FIELDS)\n afunction(field[name], 'field.' + name);\n // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the\n // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.\n if (field.BYTES < 1 || field.BITS < 1)\n throw new Error('invalid field: expected BYTES/BITS > 0');\n if (field.ORDER <= _1n)\n throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n return field;\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @param Fp - Field implementation.\n * @param num - Base value.\n * @param power - Exponent value.\n * @returns Powered field element.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Raise one field element to a public exponent.\n *\n * ```ts\n * import { Field, FpPow } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpPow(Fp, 3n, 5n);\n * ```\n */\nexport function FpPow(Fp, num, power) {\n validateField(Fp);\n const F = Fp;\n // Non-bigint exponents (e.g. an accidental field element) coerce every comparison below to\n // false and would silently return ONE.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return F.ONE;\n if (power === _1n)\n return num;\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents (e.g. poseidon\n // sbox x^5), which would waste the 14-multiplication table build.\n let p = F.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = F.mul(p, d);\n d = F.sqr(d);\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first — same shape as pow() above, over generic field ops.\n // Speeds up dense long exponents (extension-field sqrt / Legendre, e.g. Fp2 decompression).\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = F.ONE;\n table[1] = num;\n for (let i = 2; i < 16; i++)\n table[i] = F.mul(table[i - 1], num);\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = F.sqr(F.sqr(F.sqr(F.sqr(p))));\n const digit = digits[w];\n if (digit !== 0)\n p = F.mul(p, table[digit]);\n }\n return p;\n}\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n validateField(Fp);\n aarray(nums, 'nums');\n abool(passZero, 'passZero');\n const F = Fp;\n const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (F.is0(num))\n return acc;\n inverted[i] = acc;\n return F.mul(acc, num);\n }, F.ONE);\n // Invert last element\n const invertedAcc = F.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (F.is0(num))\n return acc;\n // Non-zero `num` means the forward pass already stored a defined prefix product at index i.\n inverted[i] = F.mul(acc, inverted[i]);\n return F.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n/**\n * @param Fp - Field implementation.\n * @param lhs - Dividend value.\n * @param rhs - Divisor value.\n * @returns Division result.\n * @throws If the divisor is non-invertible. {@link Error}\n * @example\n * Divide one field element by another.\n *\n * ```ts\n * import { Field, FpDiv } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpDiv(Fp, 6n, 3n);\n * ```\n */\nexport function FpDiv(Fp, lhs, rhs) {\n validateField(Fp);\n const F = Fp;\n return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the powered value does not match a valid Legendre symbol. {@link Error}\n * @example\n * Compute the Legendre symbol of one field element.\n *\n * ```ts\n * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const symbol = FpLegendre(Fp, 4n);\n * ```\n */\nexport function FpLegendre(Fp, n) {\n validateField(Fp);\n const F = Fp;\n aoddModulus(F.ORDER, 'FpLegendre');\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (F.ORDER - _1n) / _2n;\n const powered = F.pow(n, p1mod2);\n const yes = F.eql(powered, F.ONE);\n const zero = F.eql(powered, F.ZERO);\n const no = F.eql(powered, F.neg(F.ONE));\n if (!yes && !zero && !no)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n/**\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict \"quadratic\n * residue\" terminology often reserves that name for the non-zero square class.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Check whether one field element has a square root in the field.\n *\n * ```ts\n * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const isSquare = FpIsSquare(Fp, 4n);\n * ```\n */\nexport function FpIsSquare(Fp, n) {\n const l = FpLegendre(Fp, n);\n // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n return l !== -1;\n}\n/**\n * @param n - Curve order. Callers are expected to pass a positive order.\n * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached\n * value when overriding the derived bit length.\n * @returns Byte and bit lengths.\n * @throws If the order or cached bit length is invalid. {@link Error}\n * @example\n * Measure the encoding sizes needed for one modulus.\n *\n * ```ts\n * nLength(255n);\n * ```\n */\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n if (n <= _0n)\n throw new Error('invalid n length: expected positive n, got ' + n);\n if (nBitLength !== undefined && nBitLength < 1)\n throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);\n const bits = bitLen(n);\n // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison\n // any math that relies on the derived field metadata.\n if (nBitLength !== undefined && nBitLength < bits)\n throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the\n// cached helper write would keep the field surface externally mutable.\nconst FIELD_SQRT = new WeakMap();\nclass _Field {\n ORDER;\n BITS;\n BYTES;\n isLE;\n ZERO = _0n;\n ONE = _1n;\n _lengths;\n _mod;\n constructor(ORDER, opts = {}) {\n // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv\n // would stop modeling field arithmetic.\n if (ORDER <= _1n)\n throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n let _nbitLength = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n // Cached bit lengths are trusted here and should already be positive / consistent with ORDER.\n if (typeof opts.BITS === 'number')\n _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function')\n // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties\n // explicitly instead of relying on writable prototype shadowing via assignment.\n Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });\n if (typeof opts.isLE === 'boolean')\n this.isLE = opts.isLE;\n if (opts.allowedLengths)\n this._lengths = Object.freeze(opts.allowedLengths.slice());\n if (typeof opts.modFromBytes === 'boolean')\n this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n Object.freeze(this);\n }\n create(num) {\n return mod(num, this.ORDER);\n }\n isValid(num) {\n if (typeof num !== 'bigint')\n throw new TypeError('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num) {\n return (num & _1n) === _1n;\n }\n neg(num) {\n return mod(-num, this.ORDER);\n }\n eql(lhs, rhs) {\n return lhs === rhs;\n }\n sqr(num) {\n return mod(num * num, this.ORDER);\n }\n add(lhs, rhs) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs, rhs) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs, rhs) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num, power) {\n return pow(num, power, this.ORDER);\n }\n div(lhs, rhs) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n // Same as above, but doesn't normalize\n sqrN(num) {\n return num * num;\n }\n addN(lhs, rhs) {\n return lhs + rhs;\n }\n subN(lhs, rhs) {\n return lhs - rhs;\n }\n mulN(lhs, rhs) {\n return lhs * rhs;\n }\n inv(num) {\n return invert(num, this.ORDER);\n }\n sqrt(num) {\n // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping\n // the field instance itself mutable.\n let sqrt = FIELD_SQRT.get(this);\n if (!sqrt)\n FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n return sqrt(this, num);\n }\n toBytes(num) {\n // Serialize fixed-width limbs without re-validating the field range. Callers that need a\n // canonical encoding must pass a valid element; some protocols intentionally serialize raw\n // residues here and reduce or validate them elsewhere.\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n // `allowedLengths` must list real positive byte lengths; otherwise empty input would get\n // padded into zero and silently decode as a field element.\n if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes)\n scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // Range validation is optional here because some protocols intentionally decode raw residues\n // and reduce or validate them elsewhere.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst) {\n // `passZero` keeps the `bigint[]` contract honest: zero inputs map to `0` instead of leaking\n // `undefined` into a `bigint[]`. Callers that must distinguish non-invertible inputs should use\n // `FpInvertBatch` directly, whose default omits `passZero` and returns `(bigint | undefined)[]`.\n return FpInvertBatch(this, lst, true);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a, b, condition) {\n // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject\n // non-boolean selectors here instead of letting JS truthiness silently change arithmetic.\n abool(condition, 'condition');\n return condition ? b : a;\n }\n}\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for\n * all elements for performance and protocol-flexibility reasons; callers are responsible for\n * supplying valid elements when they need canonical field behavior.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER - field order, probably prime, or could be composite\n * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.\n * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight\n * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.\n * @example\n * Construct one prime field with optional overrides.\n *\n * ```ts\n * Field(11n);\n * ```\n */\nexport function Field(ORDER, opts = {}) {\n // Freeze the shared method surface before any instance is reachable; otherwise callers can\n // poison every Field instance by monkey-patching `_Field.prototype` even if each instance is\n // frozen. Freezing here instead of module scope keeps `_Field` tree-shakeable for importers\n // that never construct a field; the call is idempotent and cheap.\n Object.freeze(_Field.prototype);\n return new _Field(ORDER, opts);\n}\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,\n * which is the only square root but is not odd.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the odd square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtOdd(Fp, 4n);\n * ```\n */\nexport function FpSqrtOdd(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? root : F.neg(root);\n}\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Even square root.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the even square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtEven(Fp, 4n);\n * ```\n */\nexport function FpSqrtEven(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? F.neg(root) : root;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an\n * order greater than 1.\n * @returns byte length of field\n * @throws If the field order is not a bigint. {@link Error}\n * @example\n * Read the fixed-width byte length of one field.\n *\n * ```ts\n * getFieldBytesLength(255n);\n * ```\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.\n if (fieldOrder <= _1n)\n throw new Error('field order must be greater than 1');\n // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.\n const bitLength = bitLen(fieldOrder - _1n);\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger\n * absolute floor for policy reasons.\n * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.\n * @returns byte length of target hash\n * @throws If the field order is invalid. {@link Error}\n * @example\n * Compute the minimum hash length needed for field reduction.\n *\n * ```ts\n * getMinHashLength(255n);\n * ```\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard\n * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look\n * accidentally acceptable for real scalar derivation.\n * See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},\n * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and\n * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380\n * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.\n * @param key - Uniform input bytes.\n * @param fieldOrder - Size of subgroup.\n * @param isLE - interpret hash bytes as LE num\n * @returns valid private scalar\n * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}\n * @example\n * Map hash output into a private scalar range.\n *\n * ```ts\n * mapHashToField(new Uint8Array(48).fill(1), 255n);\n * ```\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = Math.max(getMinHashLength(fieldOrder), 16);\n // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge\n // inputs: easier to reason about JS timing / allocation behavior.\n if (len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // Map into the non-zero scalar range [1, fieldOrder-1]: reduce mod (fieldOrder-1) to land in\n // [0, fieldOrder-2], then add 1. This shifts the range off zero; it is NOT equal to\n // `mod(num, fieldOrder)` (which spans [0, fieldOrder-1] and can be 0). A residual modulo bias\n // remains but is negligible (~2^-(nBits/2), e.g. ~2^-128 for a 256-bit order) because `key` is\n // required to be at least `getMinHashLength(fieldOrder)` (~1.5x field size) bytes of input.\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF-based ScalarMultiplier, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, afunction, aobject, bitLen, bitMask, bytesToNumberBE, inRange, isBytes, isPosBig, validateObject, } from \"../utils.js\";\nimport { Field, FpInvertBatch, validateField } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _4n = /* @__PURE__ */ BigInt(4);\nconst BLIND_BYTES = 16;\nconst BLIND_BITS = 128;\n// Fixed-window width for the constant-time multiply of un-precomputed points (W===1).\n// A flat 2^FW_WINDOW table has a small, scalar-independent build cost that amortizes over a single\n// multiply, unlike the larger per-point wNAF tables that only pay off when cached.\nconst FW_WINDOW = 5;\n// Precompute tables are capped at ~2 GiB of estimated heap. Rejecting larger windows up front\n// turns a typo'd window size into an immediate error instead of a multi-GB allocation (or an\n// effective hang) when the lazy table is built on first multiply.\nconst TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();\n/**\n * Validates the static surface of a point constructor.\n * This is only a cheap sanity check for the constructor hooks and fields consumed by generic\n * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.\n * @param Point - Runtime point constructor.\n * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}\n * @example\n * Check that one point constructor exposes the static hooks generic helpers need.\n *\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { validatePointCons } from '@noble/curves/abstract/curve.js';\n * validatePointCons(ed25519.Point);\n * ```\n */\nexport function validatePointCons(Point) {\n const pc = Point;\n if (typeof pc !== 'function')\n throw new TypeError('\"Point\" expected constructor, got type=' + typeof Point);\n afunction(pc.fromAffine, 'Point.fromAffine');\n afunction(pc.fromBytes, 'Point.fromBytes');\n afunction(pc.fromHex, 'Point.fromHex');\n // Generic helpers (ScalarMultiplier, normalizeZ, MSM) dereference BASE / ZERO:\n // fail here with a typed error instead of an `undefined` access later.\n aobject(pc.BASE, 'Point.BASE');\n aobject(pc.ZERO, 'Point.ZERO');\n validateField(pc.Fp);\n validateField(pc.Fn);\n}\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n * Input points are left unchanged; the normalized points are returned as fresh instances.\n * @param c - Point constructor.\n * @param points - Projective points.\n * @returns Fresh projective points reconstructed from normalized affine coordinates.\n * @example\n * Batch-normalize projective points with a single shared inversion.\n *\n * ```ts\n * import { normalizeZ } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);\n * ```\n */\nexport function normalizeZ(c, points) {\n // Match MSM helpers: reject malformed public inputs before reading projective internals.\n validatePointCons(c);\n validateMSMPoints(points, c);\n // Identity points (Z=0) rely on an implicit contract: FpInvertBatch without `passZero`\n // yields `undefined` for zero inputs, and `toAffine(undefined)` falls back to its internal\n // is0 handling instead of using the batch inverse.\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits, min = 1) {\n if (!Number.isSafeInteger(W) || W < min || W > bits)\n throw new Error('invalid window size, expected [' + min + '..' + bits + '], got W=' + W);\n}\n// Rough per-point heap estimate for the {@link TABLE_BYTES_MAX} cap: up to 4 projective/extended\n// coordinates of Fp.BYTES each, plus bigint/object overhead. Callers pass the point count of the\n// largest table the checked parameters can produce.\nfunction validateTableBytes(numPoints, fpBytes) {\n const bytes = numPoints * (4 * fpBytes + 128);\n if (bytes > TABLE_BYTES_MAX)\n throw new Error('invalid window size: table would need ~' +\n Math.ceil(bytes / 2 ** 20) +\n ' MiB, max ' +\n TABLE_BYTES_MAX / 2 ** 20 +\n ' MiB');\n}\n/**\n * Probes an RNG once, at construction time: returns `undefined` when it is unavailable —\n * throws or returns malformed bytes — so callers can downgrade to their unblinded /\n * deterministic constant-time fallback. Blinding is defense-in-depth (DPA/template\n * hardening), not a correctness or key-secrecy requirement, so availability-based\n * downgrade is acceptable.\n *\n * The downgrade decision is deliberately static. After a successful probe the RNG becomes\n * part of the trusted contract: later misbehavior must fail closed in per-call validation\n * (throw), never downgrade — a dynamic fallback would let a tampered RNG silently strip\n * blinding on demand. A probe can only ever classify broken environments, not adversarial\n * RNGs: a stateful RNG can always behave while probed and misbehave later.\n * @param randomBytes - RNG to probe, or `undefined` when the environment provides none.\n * @param length - Byte length requested from the probe call.\n * @returns The RNG when the probe produced `length` valid bytes; `undefined` otherwise.\n * @example\n * Probe an RNG once before enabling scalar blinding.\n *\n * ```ts\n * import { probeRandomBytes } from '@noble/curves/abstract/curve.js';\n * import { randomBytes } from '@noble/hashes/utils.js';\n * const rng = probeRandomBytes(randomBytes, 16);\n * ```\n */\nexport function probeRandomBytes(randomBytes, length) {\n if (randomBytes === undefined)\n return undefined;\n afunction(randomBytes, 'randomBytes');\n try {\n const probe = randomBytes(length);\n if (!isBytes(probe) || probe.length !== length)\n return undefined;\n }\n catch {\n return undefined;\n }\n return randomBytes;\n}\nfunction validateMSMPoints(points, c) {\n aarray(points, 'points');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\n// Default bound is field membership (0 <= s < field.ORDER); a `maxScalar` override widens it\n// to 0 <= s < maxScalar for callers that accept oversized scalars.\nfunction validateMSMScalars(scalars, field, maxScalar) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n const ok = maxScalar === undefined ? field.isValid(s) : isPosBig(s) && s < maxScalar;\n if (!ok)\n throw new Error('invalid scalar at index ' + i);\n });\n}\nconst pointWindowSizes = new WeakMap();\nfunction getWindowSize(P) {\n // `1` is the uncached sentinel: use the non-precomputed (wNAF / fixed-window) path.\n return pointWindowSizes.get(P) || 1;\n}\n/** Table of odd multiples [1P, 3P, ..., (2⋅size−1)P]; width-W wNAF uses size = 2^(W−2). */\nfunction oddMultiples(p, size) {\n const dbl = p.double();\n const t = [p];\n for (let j = 1; j < size; j++)\n t.push(t[j - 1].add(dbl));\n return t;\n}\n/**\n * Width-W wNAF signed-digit recoding (W >= 2), LSB-first: digits are 0 or odd with\n * |digit| < 2^(W−1); nonzero density ~1/(W+1) (a nonzero digit is followed by W−1 zeros).\n */\nfunction wnafDigits(n, W) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const d = [];\n while (n > _0n) {\n let w = 0;\n if (n & _1n) {\n w = Number(n & mask); // n mod 2^W, odd\n if (w >= half)\n w -= size; // signed residue\n n -= BigInt(w); // n - w ≡ 0 mod 2^W: next W−1 digits are zero\n }\n d.push(w);\n n >>= _1n;\n }\n return d;\n}\n/**\n * Fixed-position signed-window recoding for precomputed wNAF: `n = Σ digits[w]⋅2^(w⋅W)` with\n * digits in `[−2^(W−1)+1, 2^(W−1)]`. Digit count is fixed by `windows` (callers reserve one\n * extra window for the final carry), so recoding length does not depend on the scalar.\n */\nfunction signedWindowDigits(n, W, windows) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const shiftBy = BigInt(W);\n const d = [];\n for (let w = 0; w < windows; w++) {\n let v = Number(n & mask);\n n >>= shiftBy;\n if (v > half) {\n v -= size; // negative digit, carry into the next window\n n += _1n;\n }\n d.push(v);\n }\n // Internal invariant: leftover bits mean the window count did not cover the scalar.\n if (n !== _0n)\n throw new Error('invalid wnaf');\n return d;\n}\n/**\n * Shared vartime walk over per-scalar wNAF digit streams: one doubling of a single shared\n * accumulator per bit position of the longest recoding, one signed table addition per\n * nonzero digit. `tables[i]` must hold the odd multiples of the i-th point.\n */\nfunction wnafWalk(zero, tables, digits) {\n let max = 0;\n for (const d of digits)\n max = Math.max(max, d.length);\n let acc = zero;\n for (let bit = max - 1; bit >= 0; bit--) {\n if (bit !== max - 1)\n acc = acc.double();\n for (let i = 0; i < digits.length; i++) {\n const w = digits[i][bit]; // reads past shorter recodings yield undefined, skipped below\n if (w) {\n const item = tables[i][(Math.abs(w) - 1) >> 1];\n acc = acc.add(w < 0 ? item.negate() : item);\n }\n }\n }\n return acc;\n}\n/**\n * Elliptic curve multiplication of Point by scalar.\n * Routes between cached-table, fixed-window, and one-shot wNAF paths; entry points validate\n * their own scalars (`mulCT`/`mulCTBlinded`: `1 <= s < Fn.ORDER`; `mulUnsafe`: up to the\n * `Fn.ORDER^4` DoS cap via {@link mulAddUnsafe}).\n * Table generation is expensive and happens on first call of `multiply()`\n * (or eagerly via `precompute(W, false)`). By default, `BASE` point is precomputed.\n *\n * Cached algorithm is signed fixed-window wNAF:\n * - table stores, for every window w, the multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P` — all doublings\n * are baked in, so a multiplication is exactly one table addition per window\n * - window count is fixed (`ceil(bits/W) + 1`), so the point-operation count is scalar-independent\n * (basis of the constant-time path)\n * - for a 256-bit curve and W=6: 44⋅32 = 1408 table points, 44 additions per multiply\n * - secret scalars are additionally blinded (see {@link ScalarMultiplier.mulCTBlinded}), which\n * widens tables by 128 bits\n * @param Point - Point constructor.\n * @param randomBytes - RNG used for scalar blinding; required by the blinded secret path.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { ScalarMultiplier } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const mul = new ScalarMultiplier(p256.Point);\n * ```\n */\nexport class ScalarMultiplier {\n Point;\n BASE;\n ZERO;\n randomBytes;\n wnafPrecomputes = new WeakMap();\n baseCanBeBlinded;\n bits;\n // Parametrized with a given Point class (not individual point)\n constructor(Point, randomBytes) {\n validatePointCons(Point);\n // Probe the RNG once (see {@link probeRandomBytes}): in environments without working\n // randomness (e.g. no WebCrypto), shouldBlind() then routes secret multiplication to the\n // unblinded constant-time path instead of throwing on every multiply(). The shape of\n // returned bytes is still validated on every blinded call, where breakage fails closed.\n this.randomBytes = probeRandomBytes(randomBytes, BLIND_BYTES);\n this.Point = Point;\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.bits = Point.Fn.BITS;\n }\n /**\n * Creates a signed fixed-window wNAF precomputation table: for every window w, the\n * multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,\n * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra\n * window absorbs the final carry of signed-digit recoding.\n * For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.\n * @param point - Point instance\n * @param W - window size\n * @param bits - scalar bitlength the table must cover\n */\n buildWnafTable(point, W, bits) {\n // W needs no re-validation: its only source is setWindowSize(), which enforces\n // 1 <= W <= Fn.BITS <= bits (the blinded path only ever widens bits) and caps the\n // resulting table at ~2 GiB (sized against the wider blinded layout).\n const windows = Math.ceil(bits / W) + 1;\n const half = 2 ** (W - 1);\n const comp = [];\n let base = point;\n for (let w = 0; w < windows; w++) {\n let acc = base;\n for (let i = 0; i < half; i++) {\n comp.push(acc);\n acc = acc.add(base);\n }\n base = comp[comp.length - 1].double(); // 2⋅(2^(W−1)⋅base) = next window's base\n }\n return { W, bits, windows, comp };\n }\n /**\n * Implements ec multiplication using precomputed signed fixed-window wNAF tables.\n * Constant-time: fixed window count with one table addition per window — zero digits feed\n * the fake accumulator — and no doublings; the lookup scans the whole window slice.\n * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},\n * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});\n * signedWindowDigits throws if `n` exceeds the table.\n * @returns real and fake (for const-time) points\n */\n wnafCachedCT(precomputes, n) {\n const { W, windows, comp } = precomputes;\n const half = 2 ** (W - 1);\n const digits = signedWindowDigits(n, W, windows);\n let p = this.ZERO;\n let f = this.BASE;\n for (let w = 0; w < windows; w++) {\n const digit = digits[w];\n const start = w * half;\n // Data-oblivious select: touch every entry of the window before the digit branch.\n const idx = Math.abs(digit) - 1; // -1 for zero digits: matches nothing, `sel` unused\n let sel = comp[start];\n for (let i = 1; i < half; i++)\n sel = i === idx ? comp[start + i] : sel;\n const neg = sel.negate(); // compute both signs; the digit only picks one\n if (digit === 0)\n f = f.add(comp[start]);\n else\n p = p.add(digit < 0 ? neg : sel);\n }\n return { p, f };\n }\n // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width\n // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with\n // incompatible `transform(...)` layouts and expect a separate cache entry.\n getWnafPrecomputes(W, point, bits, transform) {\n let entries = this.wnafPrecomputes.get(point);\n let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);\n if (!comp) {\n comp = this.buildWnafTable(point, W, bits);\n if (typeof transform === 'function')\n comp = { ...comp, comp: transform(comp.comp) };\n if (!entries) {\n entries = [];\n this.wnafPrecomputes.set(point, entries);\n }\n entries.push(comp);\n }\n return comp;\n }\n assertPoint(point) {\n if (!(point instanceof this.Point))\n throw new TypeError('\"point\" expected Point instance, got type=' + typeof point);\n }\n // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style\n // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.\n // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.\n validateMulInput(point, scalar) {\n this.assertPoint(point);\n if (!inRange(scalar, _1n, this.Point.Fn.ORDER))\n throw new Error('invalid scalar');\n }\n // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.\n // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window\n // multiply. `n` must be < 2^bits.\n runCT(point, n, bits, transform) {\n const W = getWindowSize(point);\n if (W === 1)\n return this.fixedWindowCT(point, n, bits);\n return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);\n }\n mulCT(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n return this.runCT(point, scalar, this.bits, transform);\n }\n mulCTBlinded(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n // Blinding computes n = scalar + blind*Fn.ORDER, then n*P via a constant-time multiply. This\n // equals scalar*P only when Fn.ORDER*P == O; callers guarantee that via shouldBlind() (always\n // for cofactor-1 curves; for cofactored curves only BASE, and only after checking BASE*n == O).\n // Fail before building the (large) precompute table if randomness is unavailable.\n if (this.randomBytes === undefined)\n throw new Error('randomBytes is required for scalar blinding');\n const bits = this.Point.Fn.BITS + BLIND_BITS;\n const blind = this.randomBytes(BLIND_BYTES);\n if (!isBytes(blind) || blind.length !== BLIND_BYTES)\n throw new Error('randomBytes returned invalid byte array');\n // Force the top two bits of the 128-bit blind to 10xxxxxx, so blind is in [2^127, 1.5*2^127):\n // * `| 0x80` (bit 127 = 1) is the load-bearing part: it guarantees blind >= 2^127, so the blind\n // is always a full-width, nonzero factor and the scalar is masked even with a degenerate RNG.\n // * `& 0x3f` (bit 126 = 0) is a safety margin: it caps blind < 1.5*2^127, keeping\n // blind*Fn.ORDER + scalar < 0.75*2^(nBits+128), i.e. ~half a window below the 2^(nBits+128)\n // ceiling. Not strictly required for the bound (see below), but it reserves headroom so the\n // guarantee does not rest on the tight `Fn.ORDER < 2^Fn.BITS` fact and the final carry window\n // only ever holds a small carry, never a full digit.\n blind[0] = (blind[0] & 0x3f) | 0x80;\n // Even at the extreme (blind < 2^128, scalar < Fn.ORDER < 2^nBits): n <= 2^128*Fn.ORDER - 1 <\n // 2^(nBits+128), so n stays below 2^bits and within the blinded table's\n // window count. Both cached CT kernels run a fixed number of windows/rows with one point-add\n // each, so the add count is independent of scalar (constant-time).\n const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;\n return this.runCT(point, n, bits, transform);\n }\n /**\n * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.\n * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is\n * far cheaper to build for a single use. The point-operation sequence is independent of `n`:\n * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over\n * every table entry, and one addition (adds the identity when the window digit is 0 — never\n * skipped).\n *\n * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any\n * add), which holds for the Weierstrass/Edwards point types used here. The table is left in\n * projective form (no normalizeZ): normalizing this small a table costs more than the\n * mixed-add savings it would buy for a single multiply.\n * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape\n * (this path needs no fake accumulator — its op-count is already scalar-independent).\n */\n fixedWindowCT(point, n, bits) {\n const W = FW_WINDOW;\n const size = 1 << W;\n const mask = bitMask(W);\n // Flat table [O, point, 2*point, ..., (size-1)*point].\n const table = new Array(size);\n table[0] = this.ZERO;\n for (let i = 1; i < size; i++)\n table[i] = table[i - 1].add(point);\n // Horner MSB->LSB. windows*W >= bits and n < 2^bits, so every bit of n is consumed.\n const windows = Math.ceil(bits / W);\n let acc = this.ZERO;\n for (let window = windows - 1; window >= 0; window--) {\n // W doublings per window; skipped for the first (topmost) window, where acc is still the\n // identity. The skip is scalar-independent: it depends only on the loop index.\n if (window !== windows - 1)\n for (let d = 0; d < W; d++)\n acc = acc.double();\n const digit = Number((n >> BigInt(window * W)) & mask);\n // Data-oblivious select: touch every entry, same as wnafCachedCT.\n let sel = table[0];\n for (let i = 1; i < size; i++)\n sel = i === digit ? table[i] : sel;\n acc = acc.add(sel); // one add per window, even for digit 0\n }\n return { p: acc, f: acc };\n }\n shouldBlind(point, cofactor) {\n // No usable RNG (probed in the constructor): blinding is impossible, use the plain CT path.\n if (this.randomBytes === undefined)\n return false;\n if (cofactor === _1n)\n return true;\n if (point !== this.BASE)\n return false;\n if (this.baseCanBeBlinded === undefined)\n this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();\n return this.baseCanBeBlinded;\n }\n mulSecret(point, scalar, cofactor, transform) {\n return this.shouldBlind(point, cofactor)\n ? this.mulCTBlinded(point, scalar, transform)\n : this.mulCT(point, scalar, transform);\n }\n mulUnsafe(point, scalar, transform) {\n this.assertPoint(point);\n if (!isPosBig(scalar))\n throw new Error('invalid scalar');\n const W = getWindowSize(point);\n // W === 1 (un-precomputed): one-shot width-4 wNAF via {@link mulAddUnsafe} with L=1 —\n // a cached table would be thrown away after one use. `allowOversized` swaps the\n // `s < Fn.ORDER` check for mulAddUnsafe's `Fn.ORDER^4` DoS cap.\n //\n // Oversized scalar could happen when:\n // a) user passes large scalar on their own (rare)\n // b) `assertValidity()` calls `isTorsionFree()`, which multiplies point by `Fn.ORDER`\n if (W === 1 || scalar >= this.Point.Fn.ORDER)\n return mulAddUnsafe(this.Point, [point], [scalar], true);\n // Precomputed points reuse the CT kernel (fake accumulator discarded): with W=6 only\n // ~1/64 of window-adds are skippable, so a dedicated vartime kernel saved just ~6% on\n // this path while doubling the cached-table code surface.\n const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);\n return this.wnafCachedCT(precomputes, scalar).p;\n }\n // Remembers the window size used for precomputed wNAF multiplication of the given point\n // and drops any previously built tables. Usually only the base point is precomputed.\n // W=1 resets the point to the un-precomputed (table-less) paths.\n // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).\n setWindowSize(point, W) {\n this.assertPoint(point);\n validateW(W, this.bits);\n // Size against the widest table this W can produce: the blinded path adds BLIND_BITS.\n const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;\n validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);\n pointWindowSizes.set(point, W);\n this.wnafPrecomputes.delete(point);\n }\n // True when a window size is set: tables themselves are built lazily on first multiply.\n hasWindowSize(point) {\n return getWindowSize(point) !== 1;\n }\n}\n/**\n * Combined multi-scalar multiplication `Σ scalars[i]⋅points[i]` via interleaved width-4 wNAF\n * (Strauss–Shamir). Every input gets its own table of odd multiples `[1P, 3P, 5P, 7P]` and\n * signed-digit recoding, but all walks share one doubling chain, so total cost is\n * `~bits` doublings + `L⋅bits/5` additions instead of `L⋅bits` doublings for separate\n * multiplications. Intended for the 2-4 point shapes of signature verification\n * (`R = u1⋅G + u2⋅P`); use {@link pippenger} for larger batches.\n *\n * Not constant-time: only for public inputs. Scalars must satisfy `0 <= s < Fn.ORDER`;\n * fold negative signs into the points before calling.\n * @param c - Point constructor.\n * @param points - Array of curve points.\n * @param scalars - Array of non-negative scalars, same length as points.\n * @param allowOversized - Replace the `s < Fn.ORDER` scalar check with a `Fn.ORDER^4` DoS cap.\n * Off by default. For scalars that must NOT be reduced mod ORDER: torsion checks\n * (`Fn.ORDER⋅P ≟ O`) and cofactor-clearing multiples. Walk length grows with `bitLen(s)`.\n * @returns Combined multiplication result; identity for empty input.\n * @throws If the point set or scalar set is invalid. {@link Error}\n * @example\n * Combined multi-scalar multiplication via Strauss–Shamir.\n *\n * ```ts\n * import { mulAddUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const G = p256.Point.BASE;\n * const R = mulAddUnsafe(p256.Point, [G, G.double()], [2n, 3n]); // 2⋅G + 3⋅(2⋅G)\n * ```\n */\nexport function mulAddUnsafe(c, points, scalars, allowOversized = false) {\n validatePointCons(c);\n validateMSMPoints(points, c);\n abool(allowOversized, 'allowOversized');\n // Oversized cap is ORDER^4: hard bound to mitigate DoS, walk length grows with bitLen(s).\n validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n : undefined);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const tables = points.map((p) => oddMultiples(p, 4));\n const digits = scalars.map((n) => wnafDigits(n, 4));\n return wnafWalk(c.ZERO, tables, digits);\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Point-operation count is scalar-independent (for same L), even when 1 point + scalar, or when\n * scalar = 0 — but bucket indices are scalar windows, so the memory-access pattern is\n * scalar-dependent: do not rely on this for secret scalars.\n *\n * A repaired LFG bucket-set variant from ePrint 2024/750 was benchmarked on BLS12-381 G1\n * against this implementation: ~1.4x faster at 2048 points and ~1.1-1.25x faster at\n * 4096-32768 points, at the cost of extra recoding and multiplier-table complexity.\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param scalars - array of L scalars (aka secret keys / bigints)\n * @returns MSM result point. Empty input is accepted and returns the identity.\n * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}\n * @example\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { pippenger } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);\n * ```\n */\nexport function pippenger(c, points, scalars) {\n // 0 is accepted in scalars\n validatePointCons(c);\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n // Without this, the window loop below would still run ~Fn.BITS doublings of ZERO.\n if (plength === 0)\n return zero;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...) over a FIXED set\n * of points: each point gets a one-time table of odd multiples\n * `[1P, 3P, ..., (2^(W−1)−1)P]`, and the returned closure evaluates MSMs against those\n * tables. All scalars share one doubling chain (Straus 1964) — one doubling per scalar bit\n * plus one signed table addition per nonzero width-W wNAF digit (density ~1/(W+1)) — the\n * \"interleaving\" method of Möller, \"Algorithms for multi-exponentiation\" (SAC 2001).\n *\n * Table memory is `L⋅2^(W−2)` points, capped at ~2 GiB. Prefer this over {@link pippenger}\n * when the same points are reused across many MSMs (fixed-base commitments etc.) and up to a\n * few hundred points; prefer pippenger for one-shot MSMs or thousands of points, where\n * bucketing beats per-point tables.\n *\n * Not constant-time (zero digits are skipped): public inputs only.\n * @param c - Curve Point constructor\n * @param points - array of L curve points, captured by the returned closure\n * @param windowSize - window width W in bits, from 2 to Fn.BITS; also capped so the\n * per-closure tables stay under ~2 GiB\n * @returns Function which multiplies points with scalars. The closure accepts at most\n * `points.length` scalars, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { interleavedMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = interleavedMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function interleavedMSMUnsafe(c, points, windowSize) {\n validatePointCons(c);\n const fieldN = c.Fn;\n // Signed odd digits need at least width 2 (W=2 is plain NAF with a single-entry table).\n validateW(windowSize, fieldN.BITS, 2);\n validateMSMPoints(points, c);\n validateTableBytes(points.length * 2 ** (windowSize - 2), c.Fp.BYTES);\n const tables = points.map((p) => oddMultiples(p, 2 ** (windowSize - 2)));\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must not be larger than array of points');\n return wnafWalk(c.ZERO, tables, scalars.map((n) => wnafDigits(n, windowSize)));\n };\n}\nfunction createField(order, field, isLE) {\n if (field) {\n // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback\n // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov\n // behavior.\n if (field.ORDER !== order)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\n }\n}\n/**\n * Validates basic CURVE shape and field membership, then creates fields.\n * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or\n * that the curve equation itself is otherwise sane.\n * @param type - Curve family.\n * @param CURVE - Curve parameters.\n * @param curveOpts - Optional field overrides. See {@link FpFn}:\n * - `Fp` (optional): Optional base-field override.\n * - `Fn` (optional): Optional scalar-field override.\n * @param FpFnLE - Whether field encoding is little-endian.\n * @returns Frozen curve parameters and fields.\n * @throws If the curve parameters or field overrides are invalid. {@link Error}\n * @example\n * Build curve fields from raw constants before constructing a curve instance.\n *\n * ```ts\n * const curve = createCurveFields('weierstrass', {\n * p: 17n,\n * n: 19n,\n * h: 1n,\n * a: 2n,\n * b: 2n,\n * Gx: 5n,\n * Gy: 1n,\n * });\n * ```\n */\nexport function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {\n if (type !== 'weierstrass' && type !== 'edwards')\n throw new Error('expected curve type \"weierstrass\" or \"edwards\"');\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n // Validate before reading Fp/Fn so explicit null fails with an options-object error.\n validateObject(curveOpts);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(isPosBig(val) && val !== _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n/**\n * @param randomSecretKey - Secret-key generator.\n * @param getPublicKey - Public-key derivation helper.\n * @returns Keypair generator.\n * @example\n * Build a `keygen()` helper from existing secret-key and public-key primitives.\n *\n * ```ts\n * import { createKeygen } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);\n * const pair = keygen();\n * ```\n */\nexport function createKeygen(randomSecretKey, getPublicKey) {\n return function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n","/**\n * ASN.1 DER (Distinguished Encoding Rules) helpers for ECDSA signatures.\n * Only implements the tiny subset needed for `SEQUENCE(INTEGER r, INTEGER s)`.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abignumber, abytes, asafenumber, astring, bytesToNumberBE, numberToHexUnpadded, validateObject, } from \"../utils.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\n/**\n * @param m - Error message.\n * @example\n * Throw a DER-specific error when signature parsing encounters invalid bytes.\n *\n * ```ts\n * new DERErr('bad der');\n * ```\n */\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n// Plain const so the freezes can live inside the pure initializer of the `DER` export below:\n// bare top-level `Object.freeze(...)` calls would defeat tree-shaking for every importer.\nconst _DER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = _DER;\n asafenumber(tag, 'tag');\n if (tag < 0 || tag > 255)\n throw new E('tlv.encode: wrong tag');\n astring(data, 'data');\n // Internal helper: callers hand this already-validated hex payload, so we only enforce\n // byte alignment here instead of re-validating every nibble.\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = _DER;\n data = abytes(data, undefined, 'DER data');\n let pos = 0;\n if (tag < 0 || tag > 255)\n throw new E('tlv.decode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n // First bit of first length byte is the short/long form flag.\n const isLong = !!(first & 0b1000_0000);\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n // This would overflow u32 in JS.\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big');\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = _DER;\n abignumber(num);\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = _DER;\n if (data.length < 1)\n throw new E('invalid signature integer: empty');\n if (data[0] & 0b1000_0000)\n throw new E('invalid signature integer: negative');\n // Single-byte zero `00` is the canonical DER INTEGER encoding for zero.\n if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(bytes, maxScalarBytes) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = _DER;\n if (maxScalarBytes !== undefined) {\n asafenumber(maxScalarBytes, 'maxScalarBytes');\n if (maxScalarBytes < 1)\n throw new E('invalid signature: maxScalarBytes must be positive');\n }\n const data = abytes(bytes, undefined, 'signature');\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n // Enforce curve-provided bounds before bytes-to-hex-to-BigInt conversion can amplify memory.\n if (maxScalarBytes !== undefined &&\n (rBytes.length > maxScalarBytes || sBytes.length > maxScalarBytes))\n throw new E('invalid signature: integer too large');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = _DER;\n validateObject(sig, { r: 'bigint', s: 'bigint' }, {}, 'sig');\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and\n * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.\n * @example\n * ASN.1 DER encoding utilities.\n *\n * ```ts\n * const der = DER.hexFromSig({ r: 1n, s: 2n });\n * ```\n */\nexport const DER = /* @__PURE__ */ (() => {\n Object.freeze(_DER._tlv);\n Object.freeze(_DER._int);\n return Object.freeze(_DER);\n})();\n","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport { abool, abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, hexToBytes, isBytes, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, mulAddUnsafe, normalizeZ, probeRandomBytes, ScalarMultiplier, validatePointCons, } from \"./curve.js\";\nimport { DER } from \"./der.js\";\nimport { getMinHashLength, invertCt, mapHashToField } from \"./modular.js\";\n// DER codec lives in der.ts; re-exported here because ECDSA signatures are its main consumer.\nexport { DER, DERErr } from \"./der.js\";\n// We construct the basis so `den` is always positive and equals `n`,\n// but the `num` sign depends on the basis, not on the secret value.\n// Exact half-way cases round away from zero, which keeps the split symmetric\n// around the reduced-basis boundaries used by endomorphism decomposition.\nconst divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;\n/** Splits scalar for GLV endomorphism. */\nexport function _splitEndoScalar(k, basis, n) {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // Callers must provide a reduced GLV basis whose vectors satisfy\n // `a + b * lambda ≡ 0 (mod n)`; this helper only sees the basis and `n`.\n // Reject unreduced scalars instead of silently treating them mod n.\n aInRange('scalar', k, _0n, n);\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg)\n k1 = -k1;\n if (k2neg)\n k2 = -k2;\n // Double check that resulting scalar is less than half bits of N: the wNAF pair walk\n // relies on the halves being short. This should only happen on wrong bases.\n // Also, the math inside is complex enough that this guard is worth keeping.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed for k');\n }\n return { k1neg, k1, k2neg, k2 };\n}\nfunction validateSigFormat(format) {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format;\n}\nfunction validateSigOpts(opts, def) {\n validateObject(opts);\n const optsn = {};\n // Normalize only the declared option subset from `def`; unknown keys are\n // intentionally ignored so shared / superset option bags stay valid here too.\n // `extraEntropy` stays an opaque payload until the signing path consumes it.\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS, 'lowS');\n abool(optsn.prehash, 'prehash');\n if (optsn.format !== undefined)\n validateSigFormat(optsn.format);\n return optsn;\n}\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n * @param params - Curve parameters. See {@link WeierstrassOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.\n * @returns Weierstrass point constructor.\n * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}\n *\n * @example\n * Construct a point type from explicit Weierstrass curve parameters.\n *\n * ```js\n * const opts = {\n * p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n * n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n * h: 1n,\n * a: 0n,\n * b: 7n,\n * Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n * Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n * };\n * const secp160k1_Point = weierstrass(opts);\n * ```\n */\nexport function weierstrass(params, extraOpts = {}) {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const Fp = validated.Fp;\n const Fn = validated.Fn;\n let CURVE = validated.CURVE;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(extraOpts, {}, {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n randomBytes: 'function',\n });\n // Snapshot every hook and take an owned copy of nested GLV configuration. Later mutations of\n // the caller's options must not change arithmetic, subgroup, or codec policy.\n const { endo: endoOpts, allowInfinityPoint, clearCofactor, isTorsionFree, fromBytes, toBytes, } = extraOpts;\n const randomBytes = extraOpts.randomBytes === undefined ? wcRandomBytes : extraOpts.randomBytes;\n if (endoOpts) {\n if (!Fp.is0(CURVE.a) || typeof endoOpts.beta !== 'bigint' || !Array.isArray(endoOpts.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n const endo = endoOpts\n ? {\n beta: endoOpts.beta,\n basises: endoOpts.basises.map((basis) => [...basis]),\n }\n : undefined;\n const lengths = getWLengths(Fp, Fn);\n function assertCompressionIsSupported() {\n if (!Fp.isOdd)\n throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n // Implements IEEE P1363 point encoding\n function pointToBytes(_c, point, isCompressed) {\n // Handle infinity before toAffine(), which maps ZERO to (0, 0) silently: without this the\n // encoder would emit an all-zero byte string that decodes back as a different point. Only\n // curves that opt into infinity as a public point value get the SEC 1 byte form.\n if (point.is0()) {\n if (!allowInfinityPoint)\n throw new Error('bad point: ZERO');\n return Uint8Array.of(0); // SEC 1 v2.0 §2.3.3\n }\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd(y);\n return concatBytes(pprefix(hasEvenY), bx);\n }\n else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // SEC 1 v2.0 §2.3.4 decodes 0x00 as infinity, but §3.2.2 rejects infinity as a public key.\n // Leaving 0x00 undecodable by default makes that rejection structural rather than a check:\n // callers reuse this parser as the strict key boundary, and infinity is simply not\n // expressible. Curves where infinity is a real wire value opt into the codec instead.\n // secp256k1 crosstests show OpenSSL raw point codecs accept 0x00 too.\n if (allowInfinityPoint && length === 1 && head === 0x00)\n return { x: Fp.ZERO, y: Fp.ZERO };\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x))\n throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y))\n throw new Error('bad point: is not on curve');\n return { x, y };\n }\n else {\n throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);\n }\n }\n const encodePoint = toBytes === undefined ? pointToBytes : toBytes;\n const decodePoint = fromBytes === undefined ? pointFromBytes : fromBytes;\n // Hoisted from double() / add(): curve params never change after construction.\n // Koblitz curves (a=0, e.g. secp256k1) skip the three a-multiplications per operation;\n // the selection depends only on public curve constants.\n const b3 = Fp.mul(CURVE.b, _3n);\n const mulA = Fp.is0(CURVE.a) ? (_) => Fp.ZERO : (x) => Fp.mul(CURVE.a, x);\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x);\n const x3 = Fp.mul(x2, x);\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x, y) {\n const left = Fp.sqr(y);\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n // Keep constructor-time generator validation cheap: callers are responsible for supplying the\n // correct prime-order base point, while eager subgroup checks here would slow heavy module imports.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2)))\n throw new Error('bad curve params: a or b');\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title, n, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n)))\n throw new Error(`bad point coordinate ${title}`);\n // Extension-field elements are objects. Keep point coordinates detached from caller-owned\n // objects so their mutation cannot invalidate cached on-curve / subgroup checks. Primitive\n // field elements (bigints in shipped prime fields) are already immutable values.\n return typeof n === 'object' && n !== null ? Fp.create(n) : n;\n }\n function aprjpoint(other) {\n if (!(other instanceof Point))\n throw new Error('Weierstrass Point expected');\n }\n function splitEndoScalarN(k) {\n if (!endo || !endo.basises)\n throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n /**\n * Appends a (point, scalar) pair to the inputs of a vartime wNAF walk\n * ({@link mulAddUnsafe}). With GLV endomorphism the scalar is split into two half-width\n * pairs against P and ψ(P) = (β⋅x, y), halving the walk's shared doubling chain;\n * split signs fold into the points.\n */\n function pushWnafPair(points, scalars, p, k) {\n if (!Fn.isValid(k))\n throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(k);\n const psi = new Point(Fp.mul(p.X, endo.beta), p.Y, p.Z);\n points.push(k1neg ? p.negate() : p, k2neg ? psi.negate() : psi);\n scalars.push(k1, k2);\n }\n else {\n points.push(p);\n scalars.push(k);\n }\n }\n // Successful assertValidity() results are cached: Point instances are frozen at construction,\n // so on-curve + subgroup facts cannot change afterwards. Only success is cached — invalid\n // points re-throw on every call. This matters most for pairing curves, where subgroup checks\n // cost a scalar multiplication and the same instance is re-validated across layers\n // (signature fromBytes, pairingBatch) or across repeated verifies with a cached public key.\n const validityCache = new WeakSet();\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n static Fp = Fp;\n static Fn = Fn;\n X;\n Y;\n Z;\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X, Y, Z) {\n this.X = acoord('x', X);\n // This is not just about ZERO / infinity: ambient curves can have real\n // finite points with y=0. Those points are 2-torsion, so they cannot lie\n // in the odd prime-order subgroups this point type is meant to represent.\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n static fromBytes(bytes) {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n static fromHex(hex) {\n return Point.fromBytes(hexToBytes(hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * @param isLazy - true will defer table computation until the first multiplication\n */\n precompute(windowSize = 6, isLazy = true) {\n wnaf.setWindowSize(this, windowSize);\n if (!isLazy)\n this.multiply(_3n); // random number\n return this;\n }\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity() {\n const p = this;\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points\n // like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard.\n if (allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))\n return;\n throw new Error('bad point: ZERO');\n }\n if (validityCache.has(p))\n return;\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n validityCache.add(p);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n /** Compare one point to another. */\n equals(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate() {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = mulA(Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = mulA(t2);\n t3 = Fp.sub(t0, t2);\n t3 = mulA(t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = mulA(t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = mulA(t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = mulA(t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aprjpoint(other);\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n /**\n * Constant time multiplication.\n * Uses precomputed tables (signed fixed-window wNAF) when available.\n * Uses scalar blinding and avoids endomorphism splitting in the secret-scalar path.\n * @param scalar - by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In key/signature-style callers, those values usually mean broken hash/scalar plumbing,\n // and failing closed is safer than silently producing the identity point.\n if (!Fn.isValidNot0(scalar))\n throw new RangeError('invalid scalar: out of range'); // 0 is invalid\n const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);\n return normalize([p, f])[0];\n }\n /**\n * Non-constant-time multiplication. Uses width-4 wNAF with GLV endomorphism splitting\n * when available (two half-width scalars sharing one halved doubling chain).\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(scalar) {\n const p = this;\n const sc = scalar;\n // Public-scalar callers may need 0, but n and larger values stay rejected here too.\n // Reducing them mod n would turn bad caller input into an accidental identity point.\n if (!Fn.isValid(sc))\n throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0())\n return Point.ZERO;\n if (sc === _1n)\n return p;\n if (wnaf.hasWindowSize(this))\n return wnaf.mulUnsafe(p, sc, normalize); // precomputes\n const points = [];\n const scalars = [];\n pushWnafPair(points, scalars, p, sc);\n return mulAddUnsafe(Point, points, scalars);\n }\n /**\n * Non-constant-time double-scalar multiplication `a⋅this + b⋅other` (Strauss–Shamir).\n * Both walks share one doubling chain via {@link mulAddUnsafe}, and GLV endomorphism\n * (when available) halves the chain again by splitting each scalar into two half-width\n * parts. Used by ECDSA verification and public-key recovery for `R = u1⋅G + u2⋅P`.\n * Only for public scalars.\n */\n mulAddUnsafe(a, other, b) {\n aprjpoint(other);\n const points = [];\n const scalars = [];\n pushWnafPair(points, scalars, this, a);\n pushWnafPair(points, scalars, other, b);\n return mulAddUnsafe(Point, points, scalars);\n }\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * (X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ) {\n const p = this;\n let iz = invertedZ;\n if (iz != null && !Fp.isValid(iz))\n throw new RangeError('\"invertedZ\" expected valid field element');\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE))\n return { x: X, y: Y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n }\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree() {\n if (cofactor === _1n)\n return true;\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n // unsafe() will use the uncached wNAF path internally, since CURVE_ORDER >= Fn.ORDER\n return wnaf.mulUnsafe(this, CURVE_ORDER).is0();\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n // Default fallback assumes the cofactor fits the usual subgroup-scalar\n // multiplyUnsafe() contract. Curves with larger / structured cofactors\n // should define a clearCofactor override anyway (e.g. psi/Frobenius maps).\n return this.multiplyUnsafe(cofactor);\n }\n isSmallOrder() {\n if (cofactor === _1n)\n return this.is0(); // Fast-path\n return this.clearCofactor().is0();\n }\n toBytes(isCompressed = true) {\n abool(isCompressed, 'isCompressed');\n // assertValidity() covers on-curve and subgroup membership. The encoder below repeats the\n // infinity check rather than relying on this call, so it stays correct for any caller.\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const normalize = (points) => normalizeZ(Point, points);\n const wnaf = new ScalarMultiplier(Point, randomBytes);\n // Enable W=6 wNAF precomputes. Slows down first publicKey computation.\n // Disable for tiny toy curves, with scalar fields < 6 bits.\n if (wnaf.bits >= 6)\n Point.BASE.precompute(6);\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY) {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\nfunction getWLengths(Fp, Fn) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n // Raw compact `(r || s)` signature width; DER and recovered signatures use\n // different lengths outside this helper.\n signature: 2 * Fn.BYTES,\n };\n}\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n * @param Point - Weierstrass point constructor.\n * @param ecdhOpts - Optional randomness helpers:\n * - `randomBytes` (optional): Optional RNG override.\n * @returns ECDH helper namespace.\n * @example\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n *\n * ```ts\n * import { ecdh } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const dh = ecdh(p256.Point);\n * const alice = dh.keygen();\n * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);\n * ```\n */\nexport function ecdh(Point, ecdhOpts = {}) {\n validatePointCons(Point);\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes === undefined ? wcRandomBytes : ecdhOpts.randomBytes;\n // Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte\n // minimum even on toy curves.\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), {\n seed: Math.max(getMinHashLength(Fn.ORDER), 16),\n });\n function isValidSecretKey(secretKey) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n }\n catch (error) {\n return false;\n }\n }\n function isValidPublicKey(publicKey, isCompressed) {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp)\n return false;\n if (isCompressed === false && l !== publicKeyUncompressed)\n return false;\n // SEC 1 §3.2.2: the identity is never a valid public key, even on curves whose codec\n // can decode it.\n return !Point.fromBytes(publicKey).is0();\n }\n catch (error) {\n return false;\n }\n }\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed) {\n seed = seed === undefined ? randomBytes_(lengths.seed) : seed;\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n /**\n * Computes public key for a secret key. Checks for validity of the secret key.\n * @param isCompressed - whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(secretKey, isCompressed = true) {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n const allowedLengths = Fn._lengths;\n if (!isBytes(item))\n return undefined;\n const l = abytes(item, undefined, 'key').length;\n const isPub = l === publicKey || l === publicKeyUncompressed;\n const isSec = l === secretKey || !!allowedLengths?.includes(l);\n // P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous.\n if (isPub && isSec)\n return undefined;\n return isPub;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes encoded shared point from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.\n * Returns the encoded shared point on purpose: callers that need `x_P`\n * can derive it from the encoded point, but `x_P` alone cannot recover the\n * point/parity back.\n * This helper only exposes the fully validated public-key path, not cofactor DH.\n * @param isCompressed - whether to return compact (default), or full key\n * @returns shared point encoding\n */\n function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {\n if (isProbPub(secretKeyA) === true)\n throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false)\n throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n if (b.is0())\n throw new Error('invalid public key: point at infinity');\n return b.multiply(s).toBytes(isCompressed);\n }\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n Object.freeze(utils);\n Object.freeze(lengths);\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point - created using {@link weierstrass} function\n * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:\n * - `lowS`: Default low-S policy.\n * - `hmac`: HMAC implementation used by RFC6979 DRBG.\n * - `randomBytes`: Optional RNG override.\n * - `bits2int`: Optional hash-to-int conversion override.\n * - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.\n *\n * @returns ECDSA helper namespace.\n * @example\n * Create an ECDSA signer/verifier bundle for one curve implementation.\n *\n * ```ts\n * import { ecdsa } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const p256ecdsa = ecdsa(p256.Point, sha256);\n * const { secretKey, publicKey } = p256ecdsa.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256ecdsa.sign(msg, secretKey);\n * const isValid = p256ecdsa.verify(sig, msg, publicKey);\n * ```\n */\nexport function ecdsa(Point, hash, ecdsaOpts = {}) {\n validatePointCons(Point);\n // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.\n const hash_ = hash;\n ahash(hash_);\n validateObject(ecdsaOpts, {}, {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n });\n const opts = Object.assign({}, ecdsaOpts);\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n const hmac = opts.hmac === undefined\n ? (key, msg) => nobleHmac(hash_, key, msg)\n : opts.hmac;\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n // Nonce-inversion blinding in k2sig draws `getMinHashLength(n)` bytes per sign. Probe the RNG\n // once (see {@link probeRandomBytes}, shared with ScalarMultiplier): in environments without\n // working randomness, signing downgrades to Fermat inversion (invertCt) instead of throwing on\n // every sign(). The shape of returned bytes is still validated (by mapHashToField) on every\n // blinded call, where breakage fails closed.\n const blindLength = getMinHashLength(CURVE_ORDER);\n const csprng = probeRandomBytes(randomBytes, blindLength);\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, opts);\n const defaultSigOpts = {\n prehash: true,\n lowS: typeof opts.lowS === 'boolean' ? opts.lowS : true,\n format: 'compact',\n extraEntropy: false,\n };\n // SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature\n // format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n.\n // A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the\n // smallest such lift is 1 + 2n, not 2n.\n const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER;\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title, num) {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertFieldSignIsSupported() {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n }\n // Recovery id of an affine point (x, y) whose x reduces to signature `r` mod n:\n // bit 0 = y parity, bit 1 = x overflowed the group order (x = r + n).\n function getRecoveryBit(x, y, r) {\n assertFieldSignIsSupported();\n return (x === r ? 0 : 2) | Number(Fp.isOdd(y));\n }\n function assertRecoverableCurve() {\n // ECDSA recovery only supports curves where the current recovery id can distinguish\n // q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches.\n // SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1.\n // The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit recovered signatures for those curves.\n if (hasLargeRecoveryLifts)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes, format) {\n validateSigFormat(format);\n const size = lengths.signature;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature {\n r;\n s;\n recovery;\n constructor(r, s, recovery) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertRecoverableCurve();\n if (![0, 1, 2, 3].includes(recovery))\n throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n static fromBytes(bytes, format = defaultSigOpts.format) {\n validateSigLength(bytes, format);\n let recid;\n if (format === 'der') {\n // Valid scalar INTEGERs use at most Fn.BYTES plus one DER sign-padding byte. Keep the\n // total bound conservative so malformed inputs are rejected before parsing any INTEGER.\n if (bytes.length > 2 * Fn.BYTES + 16)\n throw new DER.Err('invalid signature: DER signature too long');\n const { r, s } = DER.toSig(abytes(bytes), Fn.BYTES + 1);\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n static fromHex(hex, format) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n assertRecovery() {\n const { recovery } = this;\n if (recovery == null)\n throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n // Unlike the top-level helper below, this method expects a digest that has\n // already been hashed to the curve's message representative.\n recoverPublicKey(messageHash) {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj))\n throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.mulAddUnsafe(u1, R, u2);\n if (Q.is0())\n throw new Error('invalid recovery: point at infinify');\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n toBytes(format = defaultSigOpts.format) {\n validateSigFormat(format);\n if (format === 'der')\n return hexToBytes(DER.hexFromSig(this));\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertRecoverableCurve();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);\n }\n return concatBytes(rb, sb);\n }\n toHex(format) {\n return bytesToHex(this.toBytes(format));\n }\n }\n Object.freeze(Signature.prototype);\n Object.freeze(Signature);\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = opts.bits2int === undefined\n ? function bits2int_def(bytes) {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192)\n throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n }\n : opts.bits2int;\n const bits2int_modN = opts.bits2int_modN === undefined\n ? function bits2int_modN_def(bytes) {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n }\n : opts.bits2int_modN;\n const ORDER_MASK = bitMask(fnBits);\n // Pads output with zero as per spec.\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num) {\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n function validateMsgAndHash(message, prehash) {\n abytes(message, undefined, 'message');\n return (prehash ? abytes(hash_(message), undefined, 'prehashed message') : message);\n }\n /**\n * Steps A, D of RFC6979 3.2.\n * Creates RFC6979 seed; converts msg/privKey to numbers.\n * Used only in sign, not in verify.\n *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(message, secretKey, opts) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d))\n throw new Error('invalid private key');\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // The nonce inversion is blinded: with random b ∈ [1,n−1], s = (bk)^-1(bm + bdr) per\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. Fn.inv()'s extended-Euclidean\n // loop count depends on its input (cf. Minerva), but here it only ever sees b·k — uniformly\n // random, independent of k — so its timing reveals nothing about the nonce; b also masks d in\n // the products. Without a CSPRNG (probed in ecdsa()) we fall back to Fermat inversion\n // (invertCt), whose control flow is data-independent, at ~4x the inversion cost.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k))\n return; // Valid scalars (including k) must be in 1..N-1\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n let s;\n if (csprng !== undefined) {\n // mapHashToField maps 1.5x-order-length uniform bytes into [1, n-1], negligible bias.\n const b = bytesToNumberBE(mapHashToField(csprng(blindLength), CURVE_ORDER));\n const ibk = Fn.inv(Fn.mul(b, k)); // (bk)^-1: inversion input is decorrelated from k\n const bm = Fn.mul(b, m);\n const bd = Fn.mul(b, d);\n s = Fn.create(ibk * Fn.create(bm + bd * r)); // s = (bk)^-1(bm + bdr) = k^-1(m + rd) mod n\n }\n else {\n const ik = invertCt(k, CURVE_ORDER); // k^-1 mod n with data-independent control flow\n s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n }\n if (s === _0n)\n return;\n let recovery = getRecoveryBit(q.x, q.y, r); // recovery bit (2 or 3 when q.x>n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n /**\n * Signs a message or message hash with a secret key.\n * With the default `prehash: true`, raw message bytes are hashed internally;\n * only `{ prehash: false }` expects a caller-supplied digest.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message, secretKey, opts = {}) {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * u1 = hs^-1 mod n\n * u2 = rs^-1 mod n\n * R = u1⋅G + u2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, message, publicKey, opts = {}) {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n // SEC 1 verification keys must not be the identity, even when the generic point decoder\n // permits infinity for another protocol (for example, a pairing curve).\n if (P.is0())\n return false;\n if (lowS && sig.hasHighS())\n return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.mulAddUnsafe(u1, P, u2); // u1⋅G + u2⋅P, joint Strauss–Shamir\n if (R.is0())\n return false;\n const q = R.toAffine();\n const v = Fn.create(q.x); // v = R.x mod n\n if (v !== r)\n return false;\n // R is the exact point `recoverPublicKey(r, recid)` reconstructs (sR = hG + rP),\n // so binding the signature to its recovery id only needs R's parity/overflow bits.\n if (format === 'recovered' && sig.recovery !== getRecoveryBit(q.x, q.y, r))\n return false;\n return true;\n }\n catch (e) {\n return false;\n }\n }\n function recoverPublicKey(signature, message, opts = {}) {\n // Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message\n // bytes first unless the caller passes `{ prehash: false }`.\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n // utils.isValidPublicKey() already rejects the identity, so ECDSA needs no shadow copy.\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash: hash_,\n });\n}\n","/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen } from \"./abstract/curve.js\";\nimport { createFROST, } from \"./abstract/frost.js\";\nimport { createHasher, isogenyMap, mapToCurveSimpleSWU, } from \"./abstract/hash-to-curve.js\";\nimport { Field, mapHashToField, pow2 } from \"./abstract/modular.js\";\nimport { ecdsa, weierstrass, } from \"./abstract/weierstrass.js\";\nimport { abytes, asciiToBytes, bytesToNumberBE, concatBytes, copyBytes, } from \"./utils.js\";\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\nconst secp256k1_ENDO = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fpk1 = /* @__PURE__ */ Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * Generate one secp256k1 keypair, sign a message, and verify it.\n *\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = Object.create(null);\n// BIP-340 phrases tags as UTF-8, but all current standardized names here are 7-bit ASCII.\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(asciiToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toBytes(true).slice(1);\nconst affineXToBytes = ({ x }) => Fpk1.toBytes(x);\nconst hasEven = (y) => !Fpk1.isOdd(y);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(abytes(priv, 32, 'secretKey'));\n const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const affine = p.toAffine();\n const scalar = hasEven(affine.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: affineXToBytes(affine) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x))\n throw new Error('invalid x: Fail if x ≥ p');\n const xx = Fp.sqr(x);\n const c = Fp.add(Fp.mulN(xx, x), BigInt(7)); // Let c = x³ + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y))\n y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\n// BIP-340 callers still need to supply canonical 32-byte inputs where required; this alias only\n// parses big-endian bytes and does not enforce the fixed-width contract itself.\nconst num = bytesToNumberBE;\n/** Create tagged hash, convert it to bigint, reduce modulo-n. */\nfunction challenge(...args) {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/** Schnorr public key is just `x` coordinate of Point as per BIP340. */\nfunction schnorrGetPublicKey(secretKey) {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not\n * be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden\n * deterministic signing against side-channel and fault-injection attacks.\n */\nfunction schnorrSign(message, secretKey, auxRand = randomBytes(32)) {\n const { Fn, BASE } = Pointk1;\n // Snapshot once: nonce, challenge, and self-verification must use one transcript.\n const m = copyBytes(abytes(message, undefined, 'message'));\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n // Let t be the byte-wise xor of bytes(d) and hash/aux(a).\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a)));\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // BIP340 defines k' = int(rand) mod n. We can't reuse schnorrGetExtPubKey(rand)\n // here: that helper parses canonical secret keys and rejects rand >= n instead\n // of reducing the nonce hash modulo the group order.\n const k_ = Fn.create(num(rand));\n // BIP-340: \"Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G.\"\n if (k_ === _0n)\n throw new Error('sign failed: k is zero');\n const p = BASE.multiply(k_); // Rejects zero; only the raw nonce hash needs reduction.\n const affine = p.toAffine();\n const k = hasEven(affine.y) ? k_ : Fn.neg(k_);\n const rx = affineXToBytes(affine);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const rBytes = sig.subarray(0, 32);\n const r = num(rBytes); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!Fp.isValidNot0(r))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n // Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches\n // s = 0 only with negligible probability (k + e*d ≡ 0 mod n), so treat zero-s inputs as\n // crafted edge cases and fail closed instead of carrying that extra verification surface.\n if (!Fn.isValidNot0(s))\n return false;\n // int(challenge(bytes(r) || bytes(P) || m)) % n\n const e = challenge(rBytes, pointToBytes(P), m);\n // R = s⋅G - e⋅P, where -eP == (n-e)P\n const R = BASE.mulAddUnsafe(s, P, Fn.neg(e)); // s⋅G + (-e)⋅P, joint Strauss–Shamir\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n if (R.is0() || !hasEven(y) || !Fp.eql(x, r))\n return false;\n return true;\n }\n catch (error) {\n return false;\n }\n}\nexport const __TEST = /* @__PURE__ */ Object.freeze({ lift_x, frostTweakPublic, frostTweakSecret });\n/**\n * Schnorr signatures over secp256k1.\n * See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}.\n * @example\n * Generate one BIP340 Schnorr keypair, sign a message, and verify it.\n *\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed) => {\n seed = seed === undefined ? randomBytes(seedLength) : seed;\n return mapHashToField(abytes(seed, seedLength, 'seed'), secp256k1_CURVE.n);\n };\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: Object.freeze({\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n }),\n lengths: Object.freeze({\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n }),\n });\n})();\n// RFC 9380 Appendix E.1 3-isogeny coefficients for secp256k1, stored in ascending degree order.\n// The final `1` in each denominator array is the explicit monic leading term.\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\n// RFC 9380 §8.7 secp256k1 E' parameters for the SWU-to-isogeny pipeline below.\nlet mapSWU;\nconst getMapSWU = () => mapSWU ||\n (mapSWU = mapToCurveSimpleSWU(Fpk1, {\n // Building the SWU sqrt-ratio helper eagerly adds noticeable `secp256k1.js` import cost, so\n // defer it to first use; after that the cached mapper is reused directly.\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }));\n/**\n * Hashing / encoding to secp256k1 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto secp256k1.\n *\n * ```ts\n * const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(Pointk1, (scalars) => {\n const { x, y } = getMapSWU()(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\n/**\n * FROST threshold signatures over secp256k1. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 secp256k1 signing.\n *\n * ```ts\n * const alice = secp256k1_FROST.Identifier.derive('alice@example.com');\n * const bob = secp256k1_FROST.Identifier.derive('bob@example.com');\n * const carol = secp256k1_FROST.Identifier.derive('carol@example.com');\n * const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const secp256k1_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-secp256k1-SHA256-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n}))();\n// Taproot utils\n// `undefined` means \"disable TapTweak entirely\"; callers that want the BIP-341/BIP-386 empty\n// merkle root must pass `new Uint8Array(0)` explicitly.\nfunction tweak(point, merkleRoot) {\n if (merkleRoot === undefined)\n return _0n;\n const x = pointToBytes(point);\n const t = bytesToNumberBE(taggedHash('TapTweak', x, merkleRoot));\n // BIP-341 taproot_tweak_pubkey/taproot_tweak_seckey: \"if t >= SECP256K1_ORDER:\n // raise ValueError\". TapTweak must reject overflow instead of reducing modulo n.\n if (!Pointk1.Fn.isValid(t))\n throw new Error('invalid TapTweak hash');\n return t;\n}\nfunction frostPubToEvenY(pub) {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can skip unnecessary cloning.\n if (hasEven(VK.y))\n return pub;\n return {\n signers: { min: pub.signers.min, max: pub.signers.max },\n commitments: pub.commitments.map((i) => Pointk1.fromBytes(i).negate().toBytes()),\n verifyingShares: Object.fromEntries(Object.entries(pub.verifyingShares).map(([k, v]) => [\n k,\n Pointk1.fromBytes(v).negate().toBytes(),\n ])),\n };\n}\nfunction frostSecretToEvenY(s, pub) {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can preserve package identity.\n if (hasEven(VK.y))\n return s;\n const Fn = Pointk1.Fn;\n return {\n ...s,\n signingShare: Fn.toBytes(Fn.neg(Fn.fromBytes(s.signingShare))),\n };\n}\nfunction frostNoncesToEvenY(groupCommitment, nonces) {\n if (hasEven(groupCommitment.y))\n return nonces;\n const Fn = Pointk1.Fn;\n return {\n binding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.binding))),\n hiding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.hiding))),\n };\n}\nfunction frostTweakSecret(s, pub, merkleRoot) {\n const Fn = Pointk1.Fn;\n const keyPackage = frostSecretToEvenY(s, pub);\n const evenPub = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(evenPub.commitments[0]), merkleRoot);\n const signingShare = Fn.toBytes(Fn.add(Fn.fromBytes(keyPackage.signingShare), t));\n return {\n identifier: keyPackage.identifier,\n signingShare,\n };\n}\nfunction frostTweakPublic(pub, merkleRoot) {\n const PKPackage = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(PKPackage.commitments[0]), merkleRoot);\n // Disabled TapTweak (t=0): return the even-Y-normalized package as-is. multiply() rejects\n // zero scalars, and adding [0]G would be a no-op anyway.\n if (t === _0n)\n return PKPackage;\n const tp = Pointk1.BASE.multiply(t);\n const commitments = PKPackage.commitments.map((c, i) => (i === 0 ? Pointk1.fromBytes(c).add(tp) : Pointk1.fromBytes(c)).toBytes());\n const verifyingShares = {};\n for (const k in PKPackage.verifyingShares) {\n verifyingShares[k] = Pointk1.fromBytes(PKPackage.verifyingShares[k]).add(tp).toBytes();\n }\n return {\n signers: { min: PKPackage.signers.min, max: PKPackage.signers.max },\n commitments,\n verifyingShares,\n };\n}\n/**\n * FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591.\n * DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while\n * `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves.\n * @example\n * Create one trusted-dealer package for Taproot-compatible FROST signing.\n *\n * ```ts\n * const alice = schnorr_FROST.Identifier.derive('alice@example.com');\n * const bob = schnorr_FROST.Identifier.derive('bob@example.com');\n * const carol = schnorr_FROST.Identifier.derive('carol@example.com');\n * const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const schnorr_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-secp256k1-SHA256-TR-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n // Taproot related hacks\n parsePublicKey(publicKey) {\n // External Taproot keys are x-only, but local key packages still use compressed points.\n if (publicKey.length === 32)\n return lift_x(bytesToNumberBE(publicKey));\n if (publicKey.length === 33)\n return Pointk1.fromBytes(publicKey);\n throw new Error(`expected x-only or compressed public key, got length=${publicKey.length}`);\n },\n adjustScalar(n) {\n const PK = Pointk1.BASE.multiply(n);\n return hasEven(PK.y) ? n : Pointk1.Fn.neg(n);\n },\n adjustPoint: (p) => (hasEven(p.y) ? p : p.negate()),\n challenge(R, PK, msg) {\n return challenge(pointToBytes(R), pointToBytes(PK), msg);\n },\n adjustNonces: frostNoncesToEvenY,\n adjustGroupCommitmentShare: (GC, GCShare) => (!hasEven(GC.y) ? GCShare.negate() : GCShare),\n adjustPublic: frostPubToEvenY,\n adjustSecret: frostSecretToEvenY,\n adjustTx: {\n // Compat with official implementation\n encode: (tx) => tx.subarray(1),\n decode: (tx) => concatBytes(Uint8Array.of(0x02), tx),\n },\n adjustDKG: (k) => {\n // Compatibility with frost-secp256k1-tr: DKG output is auto-tweaked with the\n // empty Taproot merkle root, while dealer-generated keys stay untweaked.\n const merkleRoot = new Uint8Array(0);\n return {\n public: frostTweakPublic(k.public, merkleRoot),\n secret: frostTweakSecret(k.secret, k.public, merkleRoot),\n };\n },\n}))();\n","/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321), and RIPEMD160 legacy, weak hash functions.\nRFC 2286 only covers HMAC-RIPEMD160 wrapper material and test vectors,\nnot the base RIPEMD-160 compression spec.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from \"./_md.js\";\nimport { clean, createHasher, rotl } from \"./utils.js\";\n/** Initial SHA-1 state from RFC 3174 §6.1. */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Reusable 80-word SHA-1 message schedule buffer.\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD {\n A = SHA1_IV[0] | 0;\n B = SHA1_IV[1] | 0;\n C = SHA1_IV[2] | 0;\n D = SHA1_IV[3] | 0;\n E = SHA1_IV[4] | 0;\n constructor() {\n super(64, 20, 8, false);\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n roundClean() {\n clean(SHA1_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/**\n * SHA1 (RFC 3174) legacy hash function. It was cryptographically broken.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA1.\n * ```ts\n * sha1(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha1 = /* @__PURE__ */ createHasher(() => new _SHA1());\n/** RFC 1321 `T[i]` uses `floor(2^32 * abs(sin(i)))`; this is the shared `2^32` scale factor. */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\n/** RFC 1321 `T[1..64]` table. */\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));\n/** MD5 initial state from RFC 1321, stored as 4 u32 words. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n// Reusable 16-word MD5 message block buffer.\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n// RFC 1321 §3.4 per-round rotate amounts, flattened to 64 entries so the round loop\n// avoids allocating a 4-element array literal every round (measured ~5% of md5).\nconst MD5_SHIFTS = /* @__PURE__ */ (() => {\n const S = [\n [7, 12, 17, 22],\n [5, 9, 14, 20],\n [4, 11, 16, 23],\n [6, 10, 15, 21],\n ];\n return Uint8Array.from({ length: 64 }, (_, i) => S[Math.floor(i / 16)][i % 4]);\n})();\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD {\n A = MD5_IV[0] | 0;\n B = MD5_IV[1] | 0;\n C = MD5_IV[2] | 0;\n D = MD5_IV[3] | 0;\n constructor() {\n super(64, 16, 8, true);\n }\n get() {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n set(A, B, C, D) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n }\n else if (i < 32) {\n // RFC 1321 round 2 uses G(B,C,D) = (B & D) | (C & ~D), which is `Chi(D, B, C)`.\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n }\n else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n }\n else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, MD5_SHIFTS[i]);\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n this.set(A, B, C, D);\n }\n roundClean() {\n clean(MD5_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with MD5.\n * ```ts\n * md5(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const md5 = /* @__PURE__ */ createHasher(() => new _MD5());\n// RIPEMD-160\n// Permutation repeatedly applied to derive the later RIPEMD-160 message-order tables.\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\n// Five left/right message-word orderings for the RIPEMD-160 dual-lane rounds.\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++)\n for (let j of res)\n j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\n// Base per-group shift table before the left/right message-order permutations are applied.\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\n// Five left-lane additive constants for RIPEMD-160.\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\n// Five right-lane additive constants for RIPEMD-160.\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// Called `f()` in the spec; valid `group` values are 0..4, and out-of-range\n// inputs currently fall through to the group-4 branch.\nfunction ripemd_f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n if (group === 1)\n return (x & y) | (~x & z);\n if (group === 2)\n return (x | ~y) ^ z;\n if (group === 3)\n return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable 16-word RIPEMD-160 message block buffer.\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\n/**\n * Internal RIPEMD-160 legacy hash class.\n * RFC 2286 only adds HMAC-RIPEMD160 material, not the core hash specification.\n */\nexport class _RIPEMD160 extends HashMD {\n h0 = 0x67452301 | 0;\n h1 = 0xefcdab89 | 0;\n h2 = 0x98badcfe | 0;\n h3 = 0x10325476 | 0;\n h4 = 0xc3d2e1f0 | 0;\n constructor() {\n super(64, 20, 8, true);\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n 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;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n // Final recombination cross-adds the left/right lane accumulators into the next h0..h4 order.\n 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);\n }\n roundClean() {\n clean(BUF_160);\n }\n destroy() {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * RFC 2286 only covers HMAC-RIPEMD160 test material; the links below point\n * at the base RIPEMD-160 references.\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160.html}\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf}\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with RIPEMD-160.\n * ```ts\n * ripemd160(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport { SHA224 as SHA224n, sha224 as sha224n, SHA256 as SHA256n, sha256 as sha256n, } from \"./sha2.js\";\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256 = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256 = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224 = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224 = sha224n;\n//# sourceMappingURL=sha256.js.map","// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n const BASE_MAP = new Uint8Array(256)\n for (let j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (let i = 0; i < ALPHABET.length; i++) {\n const x = ALPHABET.charAt(i)\n const xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n const BASE = ALPHABET.length\n const LEADER = ALPHABET.charAt(0)\n const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n // eslint-disable-next-line no-empty\n if (source instanceof Uint8Array) { } else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source)\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n let zeroes = 0\n let length = 0\n let pbegin = 0\n const pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n const size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n const b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n let carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n let i = 0\n for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n let it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n let str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n let psz = 0\n // Skip and count leading '1's.\n let zeroes = 0\n let length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n const b256 = new Uint8Array(size)\n // Process the characters.\n while (psz < source.length) {\n // Find code of next character\n const charCode = source.charCodeAt(psz)\n // Base map can not be indexed using char code\n if (charCode > 255) { return }\n // Decode character\n let carry = BASE_MAP[charCode]\n // Invalid character\n if (carry === 255) { return }\n let i = 0\n for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n let it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n const vch = new Uint8Array(zeroes + (size - it4))\n let j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n const buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode,\n decodeUnsafe,\n decode\n }\n}\nexport default base\n","import basex from 'base-x';\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nexport default basex(ALPHABET);\n","'use strict';\nimport base58 from 'bs58';\nexport default function (checksumFn) {\n // Encode a buffer as a base58-check encoded string\n function encode(payload) {\n var payloadU8 = Uint8Array.from(payload);\n var checksum = checksumFn(payloadU8);\n var length = payloadU8.length + 4;\n var both = new Uint8Array(length);\n both.set(payloadU8, 0);\n both.set(checksum.subarray(0, 4), payloadU8.length);\n return base58.encode(both);\n }\n function decodeRaw(buffer) {\n var payload = buffer.slice(0, -4);\n var checksum = buffer.slice(-4);\n var newChecksum = checksumFn(payload);\n // eslint-disable-next-line\n if (checksum[0] ^ newChecksum[0] |\n checksum[1] ^ newChecksum[1] |\n checksum[2] ^ newChecksum[2] |\n checksum[3] ^ newChecksum[3])\n return;\n return payload;\n }\n // Decode a base58-check encoded string to a buffer, no result if checksum is wrong\n function decodeUnsafe(str) {\n var buffer = base58.decodeUnsafe(str);\n if (buffer == null)\n return;\n return decodeRaw(buffer);\n }\n function decode(str) {\n var buffer = base58.decode(str);\n var payload = decodeRaw(buffer);\n if (payload == null)\n throw new Error('Invalid checksum');\n return payload;\n }\n return {\n encode: encode,\n decode: decode,\n decodeUnsafe: decodeUnsafe\n };\n}\n","'use strict';\nimport { sha256 } from '@noble/hashes/sha256';\nimport bs58checkBase from './base.js';\n// SHA256(SHA256(buffer))\nfunction sha256x2(buffer) {\n return sha256(sha256(buffer));\n}\nexport default bs58checkBase(sha256x2);\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport bs58check from \"bs58check\";\nimport { Bytes, bytesConcat, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { Hex, hexFrom } from \"../../hex/index.js\";\nimport { numFrom, numLeToBytes, NumLike } from \"../../num/index.js\";\n\n/**\n * Encodes a number into a variable-length byte array according to the Bitcoin protocol.\n * This format is used for encoding lengths of data, such as script lengths.\n *\n * @param len - The number to encode. Can be a NumLike.\n * @returns The encoded length as a Bytes.\n * @public\n */\nexport function btcVarLengthBytesFrom(len: NumLike): Bytes {\n const num = numFrom(len);\n\n return num < 0xfd\n ? numLeToBytes(num, 1)\n : num <= 0xffff\n ? bytesConcat([0xfd], numLeToBytes(num, 2))\n : num <= 0xffffffff\n ? bytesConcat([0xfe], numLeToBytes(num, 4))\n : bytesConcat([0xff], numLeToBytes(num, 8));\n}\n\n/**\n * Computes the message hash for Bitcoin ECDSA signatures.\n * This function follows the Bitcoin message signing standard, which involves\n * prefixing the message with a magic string and its length, then double SHA256 hashing the result.\n *\n * @param message - The message to be hashed. Can be a string or BytesLike.\n * @param messagePrefix - Optional. A custom prefix to use instead of the default \"\\u0018Bitcoin Signed Message:\\n\".\n * @returns The Bitcoin hash of the prefixed message as Bytes.\n * @public\n */\nexport function messageHashBtcEcdsa(\n message: string | BytesLike,\n messagePrefix?: string | BytesLike,\n): Bytes {\n const prefix = messagePrefix ?? \"\\u0018Bitcoin Signed Message:\\n\";\n const rawPrefix: Bytes =\n typeof prefix === \"string\" ? bytesFrom(prefix, \"utf8\") : bytesFrom(prefix);\n const rawMsg: Bytes =\n typeof message === \"string\"\n ? bytesFrom(message, \"utf8\")\n : bytesFrom(message);\n\n return sha256(\n sha256(\n bytesConcat(rawPrefix, btcVarLengthBytesFrom(rawMsg.length), rawMsg),\n ),\n );\n}\n\n/**\n * @public\n */\nexport function btcEcdsaPublicKeyHash(publicKey: BytesLike): Bytes {\n return ripemd160(sha256(bytesFrom(publicKey)));\n}\n\n/**\n * @public\n */\nexport function btcP2pkhAddressFromPublicKey(\n publicKey: BytesLike,\n network: number,\n): string {\n return bs58check.encode(\n bytesConcat([network], btcEcdsaPublicKeyHash(publicKey)),\n );\n}\n\n/**\n * @public\n */\nexport function btcPublicKeyFromP2pkhAddress(address: string): Hex {\n return hexFrom(bs58check.decode(address).subarray(1));\n}\n\n/**\n * @public\n */\nexport function verifyMessageBtcEcdsa(\n message: string | BytesLike,\n signature: string,\n publicKey: string,\n): boolean {\n const challenge =\n typeof message === \"string\" ? message : hexFrom(message).slice(2);\n\n const rawSign = bytesFrom(signature, \"base64\").subarray(1);\n\n return secp256k1.verify(\n bytesFrom(rawSign),\n messageHashBtcEcdsa(challenge),\n bytesFrom(publicKey),\n { prehash: false },\n );\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { bytesConcat, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { hashCkb } from \"../../hasher/index.js\";\nimport { Hex, hexFrom } from \"../../hex/index.js\";\n\nexport const SECP256K1_SIGNATURE_LENGTH = 65;\n\n/**\n * Sign a message using Secp256k1.\n *\n * @param message - The message to sign.\n * @param privateKey - The private key.\n * @returns The signature.\n * @public\n */\nexport function signMessageSecp256k1(\n message: BytesLike,\n privateKey: BytesLike,\n): Hex {\n const signature = secp256k1.sign(bytesFrom(message), bytesFrom(privateKey), {\n format: \"recovered\",\n prehash: false,\n });\n return hexFrom(bytesConcat(signature.subarray(1), signature.subarray(0, 1)));\n}\n\n/**\n * Verify a message using Secp256k1.\n *\n * @param message - The message to verify.\n * @param signature - The signature.\n * @param publicKey - The public key.\n * @returns True if the signature is valid, false otherwise.\n * @public\n */\nexport function verifyMessageSecp256k1(\n message: BytesLike,\n signature: BytesLike,\n publicKey: BytesLike,\n): boolean {\n const signatureBytes = bytesFrom(signature);\n return secp256k1.verify(\n bytesConcat(signatureBytes.subarray(64), signatureBytes.subarray(0, 64)),\n bytesFrom(message),\n bytesFrom(publicKey),\n { format: \"recovered\", prehash: false },\n );\n}\n\n/**\n * Recover the public key from a Secp256k1 signature.\n *\n * @param message - The message.\n * @param signature - The signature.\n * @returns The recovered public key.\n * @public\n */\nexport function recoverMessageSecp256k1(\n message: BytesLike,\n signature: BytesLike,\n): Hex {\n const signatureBytes = bytesFrom(signature);\n return hexFrom(\n secp256k1.recoverPublicKey(\n bytesConcat(signatureBytes.subarray(64), signatureBytes.subarray(0, 64)),\n bytesFrom(message),\n { prehash: false },\n ),\n );\n}\n\n/**\n * @public\n */\nexport function messageHashCkbSecp256k1(message: string | BytesLike): Hex {\n const msg = typeof message === \"string\" ? message : hexFrom(message);\n const buffer = bytesFrom(`Nervos Message:${msg}`, \"utf8\");\n return hashCkb(buffer);\n}\n\n/**\n * @public\n */\nexport function verifyMessageCkbSecp256k1(\n message: string | BytesLike,\n signature: string,\n publicKey: string,\n): boolean {\n return verifyMessageSecp256k1(\n messageHashCkbSecp256k1(message),\n signature,\n publicKey,\n );\n}\n","import { verifySignature } from \"@joyid/ckb\";\nimport { BytesLike } from \"../../bytes/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\n\n/**\n * @public\n */\nexport function verifyMessageJoyId(\n message: string | BytesLike,\n signature: string,\n identity: string,\n): Promise<boolean> {\n const challenge =\n typeof message === \"string\" ? message : hexFrom(message).slice(2);\n const { publicKey, keyType } = JSON.parse(identity) as {\n publicKey: string;\n keyType: string;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return verifySignature({\n challenge,\n pubkey: publicKey,\n keyType,\n ...JSON.parse(signature),\n });\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { Bytes, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport {\n btcEcdsaPublicKeyHash,\n btcPublicKeyFromP2pkhAddress,\n messageHashBtcEcdsa,\n} from \"../btc/verify.js\";\n\n/**\n * Computes the message hash for Dogecoin ECDSA signatures.\n * This function follows the Dogecoin message signing standard, which involves\n * prefixing the message with a magic string and its length, then double SHA256 hashing the result.\n *\n * @param message - The message to be hashed. Can be a string or BytesLike.\n * @param messagePrefix - Optional. A custom prefix to use instead of the default \"\\x19Dogecoin Signed Message:\\n\".\n * @returns The Dogecoin hash of the prefixed message as Bytes.\n * @public\n */\nexport function messageHashDogeEcdsa(\n message: string | BytesLike,\n messagePrefix?: string | BytesLike,\n): Bytes {\n return messageHashBtcEcdsa(\n message,\n messagePrefix ?? \"\\x19Dogecoin Signed Message:\\n\",\n );\n}\n\n/**\n * @public\n */\nexport function verifyMessageDogeEcdsa(\n message: string | BytesLike,\n signature: string,\n address: string,\n): boolean {\n const challenge =\n typeof message === \"string\" ? message : hexFrom(message).slice(2);\n const signatureBytes = bytesFrom(signature, \"base64\");\n signatureBytes[0] -= 31;\n\n return (\n btcPublicKeyFromP2pkhAddress(address) ===\n hexFrom(\n btcEcdsaPublicKeyHash(\n secp256k1.recoverPublicKey(\n signatureBytes,\n messageHashDogeEcdsa(challenge),\n { prehash: false },\n ),\n ),\n )\n );\n}\n","import { verifyMessage } from \"ethers\";\nimport { BytesLike, bytesFrom } from \"../../bytes/index.js\";\n\n/**\n * @public\n */\nexport function verifyMessageEvmPersonal(\n message: string | BytesLike,\n signature: string,\n address: string,\n): boolean {\n return (\n address.toLowerCase() ===\n verifyMessage(\n typeof message === \"string\" ? message : bytesFrom(message),\n signature,\n ).toLowerCase()\n );\n}\n","import { schnorr } from \"@noble/curves/secp256k1.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bech32 } from \"bech32\";\nimport { Bytes, BytesLike, bytesFrom } from \"../../bytes/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport { NostrEvent } from \"./signerNostr.js\";\n\n/**\n * @public\n */\nexport function buildNostrEventFromMessage(\n message: string | BytesLike,\n): NostrEvent {\n if (typeof message === \"string\") {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const event = JSON.parse(message);\n if (\n typeof event === \"object\" &&\n typeof event.created_at === \"number\" &&\n typeof event.kind === \"number\" &&\n typeof event.content === \"string\" &&\n Array.isArray(event.tags) &&\n (event.tags as unknown[]).every(\n (tag) =>\n Array.isArray(tag) &&\n (tag as unknown[]).every((v) => typeof v === \"string\"),\n )\n ) {\n return event as NostrEvent;\n }\n } catch (_) {}\n }\n\n return {\n kind: 23335,\n created_at: 0,\n content: typeof message === \"string\" ? message : hexFrom(message),\n tags: [],\n };\n}\n\nexport function nostrEventHash(event: NostrEvent): Bytes {\n const serialized = JSON.stringify([\n 0,\n event.pubkey,\n event.created_at,\n event.kind,\n event.tags,\n event.content,\n ]);\n\n return sha256(bytesFrom(serialized, \"utf8\"));\n}\n\nexport function verifyMessageNostrEvent(\n message: string | BytesLike,\n signature: string,\n address: string,\n): boolean {\n const { words } = bech32.decode(address);\n const pubkey = hexFrom(bech32.fromWords(words)).slice(2);\n\n const event = buildNostrEventFromMessage(message);\n const eventHash = nostrEventHash({ ...event, pubkey });\n\n try {\n return schnorr.verify(bytesFrom(signature), eventHash, bytesFrom(pubkey));\n } catch (_) {\n return false;\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { ClientCollectableSearchKeyFilterLike } from \"../../advancedBarrel.js\";\nimport { BytesLike } from \"../../bytes/index.js\";\nimport { Cell, Transaction, TransactionLike } from \"../../ckb/index.js\";\nimport {\n Client,\n ClientFindTransactionsGroupedResponse,\n ClientFindTransactionsResponse,\n ClientIndexerSearchKeyFilterLike,\n} from \"../../client/index.js\";\nimport { Hex } from \"../../hex/index.js\";\nimport { Num } from \"../../num/index.js\";\nimport { verifyMessageBtcEcdsa } from \"../btc/verify.js\";\nimport { verifyMessageCkbSecp256k1 } from \"../ckb/secp256k1Signing.js\";\nimport { verifyMessageJoyId } from \"../ckb/verifyJoyId.js\";\nimport { verifyMessageDogeEcdsa } from \"../doge/verify.js\";\nimport { verifyMessageEvmPersonal } from \"../evm/verify.js\";\nimport { verifyMessageNostrEvent } from \"../nostr/verify.js\";\n\n/**\n * @public\n */\nexport enum SignerSignType {\n Unknown = \"Unknown\",\n BtcEcdsa = \"BtcEcdsa\",\n EvmPersonal = \"EvmPersonal\",\n JoyId = \"JoyId\",\n NostrEvent = \"NostrEvent\",\n CkbSecp256k1 = \"CkbSecp256k1\",\n DogeEcdsa = \"DogeEcdsa\",\n}\n\n/**\n * An enumeration of signer display types in wallet.\n * @public\n */\nexport enum SignerType {\n EVM = \"EVM\",\n BTC = \"BTC\",\n CKB = \"CKB\",\n Nostr = \"Nostr\",\n Doge = \"Doge\",\n}\n\n/**\n * @public\n * @deprecated Wallet integrations now expose one signer per selectable network.\n * This compatibility type will be removed in the next major release.\n */\nexport type NetworkPreference = {\n addressPrefix: string;\n signerType: SignerType;\n network: string;\n};\n\n/**\n * @public\n */\nexport class Signature {\n constructor(\n public signature: string,\n public identity: string,\n public signType: SignerSignType,\n ) {}\n}\n\n/**\n * An abstract class representing a generic signer.\n * This class provides methods to connect, get addresses, and sign transactions.\n * @public\n */\nexport abstract class Signer {\n constructor(protected client_: Client) {}\n\n abstract get type(): SignerType;\n abstract get signType(): SignerSignType;\n\n get client(): Client {\n return this.client_;\n }\n\n /**\n * @deprecated Wallet integrations now use fixed-network signers.\n */\n matchNetworkPreference(\n preferences: NetworkPreference[],\n currentNetwork: string | undefined,\n ): NetworkPreference | undefined {\n if (\n currentNetwork !== undefined &&\n preferences.some(\n ({ signerType, addressPrefix, network }) =>\n signerType === this.type &&\n addressPrefix === this.client.addressPrefix &&\n network === currentNetwork,\n )\n ) {\n return;\n }\n return preferences.find(\n ({ signerType, addressPrefix }) =>\n signerType === this.type && addressPrefix === this.client.addressPrefix,\n );\n }\n\n static async verifyMessage(\n message: string | BytesLike,\n signature: Signature,\n ): Promise<boolean> {\n switch (signature.signType) {\n case SignerSignType.EvmPersonal:\n return verifyMessageEvmPersonal(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.BtcEcdsa:\n return verifyMessageBtcEcdsa(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.JoyId:\n return verifyMessageJoyId(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.NostrEvent:\n return verifyMessageNostrEvent(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.CkbSecp256k1:\n return verifyMessageCkbSecp256k1(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.DogeEcdsa:\n return verifyMessageDogeEcdsa(\n message,\n signature.signature,\n signature.identity,\n );\n case SignerSignType.Unknown:\n throw new Error(\"Unknown signer sign type\");\n }\n }\n\n /**\n * Connects to the signer.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n abstract connect(): Promise<void>;\n\n /**\n * Register a listener to be called when this signer is replaced.\n *\n * @returns A function for unregister\n */\n onReplaced(_: () => void): () => void {\n return () => {};\n }\n\n /**\n * Disconnects to the signer.\n *\n * @returns A promise that resolves when the signer is disconnected.\n */\n async disconnect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n abstract isConnected(): Promise<boolean>;\n\n /**\n * Gets the internal address associated with the signer.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n abstract getInternalAddress(): Promise<string>;\n\n /**\n * Gets the identity for verifying signature, usually it's address\n *\n * @returns A promise that resolves to a string representing the identity\n */\n async getIdentity(): Promise<string> {\n return this.getInternalAddress();\n }\n\n /**\n * Gets an array of Address objects associated with the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n abstract getAddressObjs(): Promise<Address[]>;\n\n /**\n * Gets the recommended Address object for the signer.\n *\n * @param _preference - Optional preference parameter.\n * @returns A promise that resolves to the recommended Address object.\n */\n async getRecommendedAddressObj(_preference?: unknown): Promise<Address> {\n return (await this.getAddressObjs())[0];\n }\n\n /**\n * Gets the recommended address for the signer as a string.\n *\n * @param preference - Optional preference parameter.\n * @returns A promise that resolves to the recommended address as a string.\n */\n async getRecommendedAddress(preference?: unknown): Promise<string> {\n return (await this.getRecommendedAddressObj(preference)).toString();\n }\n\n /**\n * Gets an array of addresses associated with the signer as strings.\n *\n * @returns A promise that resolves to an array of addresses as strings.\n */\n async getAddresses(): Promise<string[]> {\n return this.getAddressObjs().then((addresses) =>\n addresses.map((address) => address.toString()),\n );\n }\n\n /**\n * Find cells of this signer\n *\n * @param filter - The filter for the search key.\n * @param withData - Whether to include cell data in the response.\n * @param order - The order of the returned cells, can be \"asc\" or \"desc\".\n * @param limit - The maximum number of cells for every querying chunk.\n * @returns A async generator that yields all matching cells\n */\n async *findCellsOnChain(\n filter: ClientIndexerSearchKeyFilterLike,\n withData?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<Cell> {\n const scripts = await this.getAddressObjs();\n for (const { script } of scripts) {\n for await (const cell of this.client.findCellsOnChain(\n {\n script,\n scriptType: \"lock\",\n filter,\n scriptSearchMode: \"exact\",\n withData,\n },\n order,\n limit,\n )) {\n yield cell;\n }\n }\n }\n\n /**\n * Find cells of this signer\n *\n * @returns A async generator that yields all matches cells\n */\n async *findCells(\n filter: ClientCollectableSearchKeyFilterLike,\n withData?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<Cell> {\n const scripts = await this.getAddressObjs();\n for (const { script } of scripts) {\n for await (const cell of this.client.findCells(\n {\n script,\n scriptType: \"lock\",\n filter,\n scriptSearchMode: \"exact\",\n withData,\n },\n order,\n limit,\n )) {\n yield cell;\n }\n }\n }\n\n /**\n * Find transactions of this signer\n *\n * @returns A async generator that yields all matches transactions\n */\n findTransactions(\n filter: ClientCollectableSearchKeyFilterLike,\n groupByTransaction?: false | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsResponse[\"transactions\"][0]>;\n /**\n * Find transactions of this signer\n *\n * @returns A async generator that yields all matches transactions\n */\n findTransactions(\n filter: ClientCollectableSearchKeyFilterLike,\n groupByTransaction: true,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<ClientFindTransactionsGroupedResponse[\"transactions\"][0]>;\n /**\n * Find transactions of this signer\n *\n * @returns A async generator that yields all matches transactions\n */\n findTransactions(\n filter: ClientCollectableSearchKeyFilterLike,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n >;\n /**\n * Find transactions of this signer\n *\n * @returns A async generator that yields all matches transactions\n */\n async *findTransactions(\n filter: ClientCollectableSearchKeyFilterLike,\n groupByTransaction?: boolean | null,\n order?: \"asc\" | \"desc\",\n limit?: number,\n ): AsyncGenerator<\n | ClientFindTransactionsResponse[\"transactions\"][0]\n | ClientFindTransactionsGroupedResponse[\"transactions\"][0]\n > {\n const scripts = await this.getAddressObjs();\n for (const { script } of scripts) {\n for await (const transaction of this.client.findTransactions(\n {\n script,\n scriptType: \"lock\",\n filter,\n scriptSearchMode: \"exact\",\n groupByTransaction,\n },\n order,\n limit,\n )) {\n yield transaction;\n }\n }\n }\n\n /**\n * Gets balance of all addresses\n *\n * @returns A promise that resolves to the balance\n */\n async getBalance(): Promise<Num> {\n return this.client.getBalance(\n (await this.getAddressObjs()).map(({ script }) => script),\n );\n }\n\n /**\n * Signs a message.\n *\n * @param message - The message to sign, as a string or BytesLike object.\n * @returns A promise that resolves to the signature info.\n * @throws Will throw an error if not implemented.\n */\n async signMessage(message: string | BytesLike): Promise<Signature> {\n return {\n signature: await this.signMessageRaw(message),\n identity: await this.getIdentity(),\n signType: this.signType,\n };\n }\n\n /**\n * Signs a message and returns signature only. This method is not implemented and should be overridden by subclasses.\n *\n * @param _ - The message to sign, as a string or BytesLike object.\n * @returns A promise that resolves to the signature as a string.\n * @throws Will throw an error if not implemented.\n */\n signMessageRaw(_: string | BytesLike): Promise<string> {\n throw Error(\"Signer.signMessageRaw not implemented\");\n }\n\n /**\n * Verify a signature.\n *\n * @param message - The original message.\n * @param signature - The signature to verify.\n * @returns A promise that resolves to the verification result.\n * @throws Will throw an error if not implemented.\n */\n async verifyMessage(\n message: string | BytesLike,\n signature: string | Signature,\n ): Promise<boolean> {\n if (typeof signature === \"string\") {\n return Signer.verifyMessage(message, {\n signType: this.signType,\n signature,\n identity: await this.getIdentity(),\n });\n }\n\n if (\n signature.identity !== (await this.getIdentity()) ||\n ![SignerSignType.Unknown, this.signType].includes(signature.signType)\n ) {\n return false;\n }\n\n return Signer.verifyMessage(message, signature);\n }\n\n /**\n * Sends a transaction after signing it.\n *\n * @param tx - The transaction to send, represented as a TransactionLike object.\n * @returns A promise that resolves to the transaction hash as a Hex string.\n */\n async sendTransaction(tx: TransactionLike): Promise<Hex> {\n return this.client.sendTransaction(await this.signTransaction(tx));\n }\n\n /**\n * Signs a transaction.\n *\n * @param tx - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to the signed Transaction object.\n */\n async signTransaction(tx: TransactionLike): Promise<Transaction> {\n const preparedTx = await this.prepareTransaction(tx);\n return this.signOnlyTransaction(preparedTx);\n }\n\n /**\n * Prepares a transaction before signing.\n * This method can be overridden by subclasses to perform any necessary steps,\n * such as adding cell dependencies or witnesses, before the transaction is signed.\n * The default implementation converts the {@link TransactionLike} object to a {@link Transaction} object\n * without modification.\n *\n * @remarks\n * Note that this default implementation does not add any cell dependencies or dummy witnesses.\n * This may lead to an underestimation of transaction size and fees if used with methods\n * like `Transaction.completeFee`. Subclasses for signers that are intended to sign\n * transactions should override this method to perform necessary preparations.\n *\n * @param tx - The transaction to prepare.\n * @returns A promise that resolves to the prepared {@link Transaction} object.\n */\n async prepareTransaction(tx: TransactionLike): Promise<Transaction> {\n return Transaction.from(tx);\n }\n\n /**\n * Signs a transaction without preparing information for it. This method is not implemented and should be overridden by subclasses.\n *\n * @param _ - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to the signed Transaction object.\n * @throws Will throw an error if not implemented.\n */\n signOnlyTransaction(_: TransactionLike): Promise<Transaction> {\n throw Error(\"Signer.signOnlyTransaction not implemented\");\n }\n}\n\n/**\n * An abstract class representing a multisig signer.\n * @public\n */\nexport abstract class SignerMultisig extends Signer {\n /**\n * Get the number of members in the multisig script.\n * @returns The number of members.\n */\n abstract getMemberCount(): Promise<number>;\n\n /**\n * Get the threshold of the multisig script.\n * @returns The threshold.\n */\n abstract getMemberThreshold(): Promise<number>;\n\n /**\n * Get the count of required member of the multisig script.\n * @returns The must match count.\n */\n abstract getMemberRequiredCount(): Promise<number>;\n\n /**\n * Get the number of valid signatures for matching multisig inputs in the transaction.\n *\n * @remarks\n * Returns `undefined` when the transaction has no inputs locked by any multisig address\n * supported by this signer. This method only evaluates matching multisig inputs and does\n * not indicate whether the transaction itself is expected to be signed by this multisig.\n *\n * @param _ - The transaction.\n * @returns The matched multisig signature count, or `undefined` when the transaction is unrelated to any multisig address supported by this signer.\n */\n abstract getSignaturesCount(_: TransactionLike): Promise<number | undefined>;\n\n /**\n * Check if related multisig inputs in the transaction need more signatures.\n *\n * @remarks\n * Returns `false` when the transaction has no inputs locked by any multisig address\n * supported by this signer.\n * A `false` result therefore means either the related multisig inputs are already fulfilled,\n * or the transaction is unrelated to all multisig addresses supported by this signer.\n *\n * @param txLike - The transaction to check.\n * @returns A promise that resolves to `true` when related multisig inputs still need signatures, and `false` otherwise.\n */\n abstract needMoreSignatures(_: TransactionLike): Promise<boolean>;\n\n /**\n * Aggregate transactions.\n * @param _ - The transactions to aggregate.\n * @returns The aggregated transaction.\n */\n abstract aggregateTransactions(_: TransactionLike[]): Promise<Transaction>;\n\n /**\n * Send a transaction.\n *\n * @remarks\n * This method rejects the transaction only when related multisig inputs still need signatures.\n * It does not verify that the transaction actually contains inputs locked by any multisig\n * address supported by this signer, so transactions unrelated to those multisig addresses\n * are not rejected by this check.\n *\n * @param tx - The transaction to send.\n * @returns The transaction hash.\n */\n async sendTransaction(tx: TransactionLike): Promise<Hex> {\n const signedTx = await this.signTransaction(tx);\n if (await this.needMoreSignatures(signedTx)) {\n const count = (await this.getSignaturesCount(signedTx)) ?? 0;\n const threshold = await this.getMemberThreshold();\n throw new SignerMultisigNotEnoughSignaturesError(count, threshold);\n }\n\n return this.client.sendTransaction(signedTx);\n }\n}\n\n/**\n * Thrown when a multisig transaction is sent before enough signatures are collected.\n *\n * @public\n */\nexport class SignerMultisigNotEnoughSignaturesError extends Error {\n readonly signaturesCount: number;\n readonly threshold: number;\n\n constructor(signaturesCount: number, threshold: number) {\n const message = `Not enough signatures: got ${signaturesCount}, need ${threshold}`;\n super(message);\n this.name = \"SignerMultisigNotEnoughSignaturesError\";\n this.signaturesCount = signaturesCount;\n this.threshold = threshold;\n }\n}\n\n/**\n * A class representing information about a signer, including its type and the signer instance.\n * @public\n */\nexport class SignerInfo {\n constructor(\n public name: string,\n public signer: Signer,\n ) {}\n}\n\n/**\n * Represents a wallet with a name, icon, and an array of signer information.\n * @public\n */\nexport type Wallet = {\n name: string;\n icon: string;\n};\n","import { Address } from \"../../address/index.js\";\nimport { bytesConcat, bytesFrom } from \"../../bytes/index.js\";\nimport { Transaction, TransactionLike, WitnessArgs } from \"../../ckb/index.js\";\nimport { KnownScript } from \"../../client/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { numToBytes } from \"../../num/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\nimport { SignPsbtOptionsLike } from \"./psbt.js\";\nimport { btcEcdsaPublicKeyHash } from \"./verify.js\";\n\n/**\n * An abstract class extending the Signer class for Bitcoin-like signing operations.\n * This class provides methods to get Bitcoin account, public key, and internal address,\n * as well as signing transactions.\n * @public\n */\nexport abstract class SignerBtc extends Signer {\n get type(): SignerType {\n return SignerType.BTC;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.BtcEcdsa;\n }\n\n /**\n * Sign and broadcast a PSBT.\n *\n * @param psbtHex - The hex string of PSBT to sign and broadcast.\n * @param options - Options for signing the PSBT.\n * @returns A promise that resolves to the transaction ID as a Hex string.\n */\n async signAndBroadcastPsbt(\n psbtHex: HexLike,\n options?: SignPsbtOptionsLike,\n ): Promise<Hex> {\n const signedPsbt = await this.signPsbt(psbtHex, options);\n return this.broadcastPsbt(signedPsbt, options);\n }\n\n /**\n * Gets the Bitcoin account associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Bitcoin account.\n */\n abstract getBtcAccount(): Promise<string>;\n\n /**\n * Gets the Bitcoin public key associated with the signer.\n *\n * @returns A promise that resolves to a HexLike value representing the Bitcoin public key.\n */\n abstract getBtcPublicKey(): Promise<HexLike>;\n\n /**\n * Gets the internal address, which is the Bitcoin account in this case.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n async getInternalAddress(): Promise<string> {\n return this.getBtcAccount();\n }\n\n /**\n * Gets the identity, which is the Bitcoin public key in this case.\n *\n * @returns A promise that resolves to a string representing the identity\n */\n async getIdentity(): Promise<string> {\n return hexFrom(await this.getBtcPublicKey()).slice(2);\n }\n\n /**\n * Gets an array of Address objects representing the known script addresses for the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n async getAddressObjs(): Promise<Address[]> {\n const publicKey = await this.getBtcPublicKey();\n const hash = btcEcdsaPublicKeyHash(publicKey);\n\n return [\n await Address.fromKnownScript(\n this.client,\n KnownScript.OmniLock,\n hexFrom([0x04, ...hash, 0x00]),\n ),\n ];\n }\n\n /**\n * prepare a transaction before signing. This method is not implemented and should be overridden by subclasses.\n *\n * @param txLike - The transaction to prepare, represented as a TransactionLike object.\n * @returns A promise that resolves to the prepared Transaction object.\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.OmniLock);\n await tx.prepareSighashAllWitness(script, 85, this.client);\n return tx;\n }\n\n /**\n * Signs a transaction without modifying it.\n *\n * @param txLike - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to a signed Transaction object.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n const info = await tx.getSignHashInfo(script, this.client);\n if (!info) {\n return tx;\n }\n\n const signature = bytesFrom(\n await this.signMessageRaw(\n `CKB (Bitcoin Layer) transaction: ${info.message}`,\n ),\n \"base64\",\n );\n signature[0] = 31 + ((signature[0] - 27) % 4);\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(\n bytesConcat(\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(4 * 4, 4),\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(signature.length, 4),\n signature,\n ),\n );\n\n tx.setWitnessArgs(info.position, witness);\n return tx;\n }\n\n /**\n * Signs a Partially Signed Bitcoin Transaction (PSBT).\n *\n * @param psbtHex - The hex string of PSBT to sign.\n * @param options - Options for signing the PSBT\n * @returns A promise that resolves to the signed PSBT as a Hex string.\n */\n abstract signPsbt(\n psbtHex: HexLike,\n options?: SignPsbtOptionsLike,\n ): Promise<Hex>;\n\n /**\n * Broadcasts a PSBT to the Bitcoin network.\n *\n * @param psbtHex - The hex string of the PSBT to broadcast.\n * @param options - Options for broadcasting the PSBT.\n * @returns A promise that resolves to the transaction ID as a Hex string.\n */\n abstract broadcastPsbt(\n psbtHex: HexLike,\n options?: SignPsbtOptionsLike,\n ): Promise<Hex>;\n}\n","import { Client } from \"../../client/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { SignPsbtOptionsLike } from \"./psbt.js\";\nimport { SignerBtc } from \"./signerBtc.js\";\n\n/**\n * A class extending SignerBtc that provides read-only access to a Bitcoin public key and account.\n * This class does not support signing operations.\n * @public\n */\nexport class SignerBtcPublicKeyReadonly extends SignerBtc {\n private readonly publicKey: Hex;\n\n /**\n * Creates an instance of SignerBtcPublicKeyReadonly.\n *\n * @param client - The client instance used for communication.\n * @param account - The Bitcoin account associated with the signer.\n * @param publicKey - The public key associated with the signer.\n */\n constructor(\n client: Client,\n private readonly account: string,\n publicKey: HexLike,\n ) {\n super(client);\n\n this.publicKey = hexFrom(publicKey);\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is read-only.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n /**\n * Gets the Bitcoin account associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Bitcoin account.\n *\n * @example\n * ```typescript\n * const account = await signer.getBtcAccount(); // Outputs the Bitcoin account\n * ```\n */\n async getBtcAccount(): Promise<string> {\n return this.account;\n }\n\n /**\n * Gets the Bitcoin public key associated with the signer.\n *\n * @returns A promise that resolves to a Hex string representing the Bitcoin public key.\n *\n * @example\n * ```typescript\n * const publicKey = await signer.getBtcPublicKey(); // Outputs the Bitcoin public key\n * ```\n */\n async getBtcPublicKey(): Promise<Hex> {\n return this.publicKey;\n }\n\n async signPsbt(\n _psbtHex: HexLike,\n _options?: SignPsbtOptionsLike,\n ): Promise<Hex> {\n throw new Error(\"Read-only signer does not support signPsbt\");\n }\n\n async broadcastPsbt(\n _psbtHex: HexLike,\n _options?: SignPsbtOptionsLike,\n ): Promise<Hex> {\n throw new Error(\"Read-only signer does not support broadcastPsbt\");\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { Transaction, TransactionLike } from \"../../ckb/index.js\";\nimport { Client, KnownScript } from \"../../client/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * A signer for the well-known always-success lock script.\n *\n * The always-success script does not require a signature, so signing a\n * transaction only needs to add its cell dependency.\n *\n * @public\n */\nexport class SignerCkbAlwaysSuccess extends Signer {\n get type(): SignerType {\n return SignerType.CKB;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.Unknown;\n }\n\n /**\n * Creates an instance of SignerCkbAlwaysSuccess.\n *\n * @param client - The client instance used for communication and resolving\n * the always-success deployment.\n */\n constructor(client: Client) {\n super(client);\n }\n\n async connect(): Promise<void> {}\n\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n async getInternalAddress(): Promise<string> {\n return this.getRecommendedAddress();\n }\n\n /**\n * Gets the address of the always-success lock script.\n */\n async getAddressObjs(): Promise<Address[]> {\n return [\n await Address.fromKnownScript(\n this.client,\n KnownScript.AlwaysSuccess,\n \"0x\",\n ),\n ];\n }\n\n /**\n * Adds the always-success cell dependency to a transaction.\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.AlwaysSuccess);\n return tx;\n }\n\n /**\n * The always-success script requires no signature.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n return Transaction.from(txLike);\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { bytesFrom } from \"../../bytes/index.js\";\nimport { Script, Transaction, TransactionLike } from \"../../ckb/index.js\";\nimport { CellDepInfo, Client, KnownScript } from \"../../client/index.js\";\nimport { hashCkbShort } from \"../../hasher/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\nimport { SECP256K1_SIGNATURE_LENGTH } from \"./secp256k1Signing.js\";\n\n/**\n * @public\n */\nexport class SignerCkbPublicKey extends Signer {\n get type(): SignerType {\n return SignerType.CKB;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.CkbSecp256k1;\n }\n\n public readonly publicKey: Hex;\n\n constructor(client: Client, publicKey: HexLike) {\n super(client);\n this.publicKey = hexFrom(publicKey);\n\n if (bytesFrom(this.publicKey).length !== 33) {\n throw new Error(\"Public key must be 33 bytes!\");\n }\n }\n\n async connect(): Promise<void> {}\n\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n async getInternalAddress(): Promise<string> {\n return this.getRecommendedAddress();\n }\n\n async getIdentity(): Promise<string> {\n return this.publicKey;\n }\n\n async getAddressObjSecp256k1(): Promise<Address> {\n return Address.fromKnownScript(\n this.client,\n KnownScript.Secp256k1Blake160,\n hashCkbShort(this.publicKey),\n );\n }\n\n async getRecommendedAddressObj(_preference?: unknown): Promise<Address> {\n return this.getAddressObjSecp256k1();\n }\n\n async getAddressObjs(): Promise<Address[]> {\n const secp256k1 = await this.getAddressObjSecp256k1();\n\n const addresses: Address[] = [];\n let count = 0;\n for await (const cell of this.client.findCells({\n script: await Script.fromKnownScript(\n this.client,\n KnownScript.AnyoneCanPay,\n secp256k1.script.args,\n ),\n scriptType: \"lock\",\n scriptSearchMode: \"prefix\",\n withData: false,\n })) {\n if (count >= 10) {\n break;\n }\n count += 1;\n\n if (addresses.some(({ script }) => script.eq(cell.cellOutput.lock))) {\n continue;\n }\n\n addresses.push(\n Address.from({\n prefix: this.client.addressPrefix,\n script: cell.cellOutput.lock,\n }),\n );\n }\n\n return [secp256k1, ...addresses];\n }\n\n async getRelatedScripts(\n txLike: TransactionLike,\n ): Promise<{ script: Script; cellDeps: CellDepInfo[] }[]> {\n const tx = Transaction.from(txLike);\n\n const secp256k1 = await this.getAddressObjSecp256k1();\n const acp = await Script.fromKnownScript(\n this.client,\n KnownScript.AnyoneCanPay,\n secp256k1.script.args,\n );\n\n const scripts: { script: Script; cellDeps: CellDepInfo[] }[] = [];\n for (const input of tx.inputs) {\n const {\n cellOutput: { lock },\n } = await input.getCell(this.client);\n\n if (scripts.some(({ script }) => script.eq(lock))) {\n continue;\n }\n\n if (lock.eq(secp256k1.script)) {\n scripts.push({\n script: lock,\n cellDeps: (\n await this.client.getKnownScript(KnownScript.Secp256k1Blake160)\n ).cellDeps,\n });\n } else if (\n lock.codeHash === acp.codeHash &&\n lock.hashType === acp.hashType &&\n lock.args.startsWith(acp.args)\n ) {\n scripts.push({\n script: lock,\n cellDeps: (await this.client.getKnownScript(KnownScript.AnyoneCanPay))\n .cellDeps,\n });\n }\n }\n\n return scripts;\n }\n\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n\n await Promise.all(\n (await this.getRelatedScripts(tx)).map(async ({ script, cellDeps }) => {\n await tx.prepareSighashAllWitness(\n script,\n SECP256K1_SIGNATURE_LENGTH,\n this.client,\n );\n await tx.addCellDepInfos(this.client, cellDeps);\n }),\n );\n return tx;\n }\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { Transaction, TransactionLike, WitnessArgs } from \"../../ckb/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { Hex, hexFrom, HexLike } from \"../../hex/index.js\";\nimport {\n messageHashCkbSecp256k1,\n signMessageSecp256k1,\n} from \"./secp256k1Signing.js\";\nimport { SignerCkbPublicKey } from \"./signerCkbPublicKey.js\";\n\n/**\n * @public\n */\nexport class SignerCkbPrivateKey extends SignerCkbPublicKey {\n public readonly privateKey: Hex;\n\n constructor(client: Client, privateKey: HexLike) {\n const pk = hexFrom(privateKey);\n if (bytesFrom(pk).length !== 32) {\n throw new Error(\"Private key must be 32 bytes!\");\n }\n\n super(client, secp256k1.getPublicKey(bytesFrom(pk), true));\n this.privateKey = pk;\n }\n\n async _signMessage(message: HexLike): Promise<Hex> {\n return signMessageSecp256k1(message, this.privateKey);\n }\n\n async signMessageRaw(message: string | BytesLike): Promise<Hex> {\n return this._signMessage(messageHashCkbSecp256k1(message));\n }\n\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n\n for (const { script } of await this.getRelatedScripts(tx)) {\n const info = await tx.getSignHashInfo(script, this.client);\n if (!info) {\n return tx;\n }\n\n const signature = await this._signMessage(info.message);\n\n const witness = tx.getWitnessArgs(info.position) ?? WitnessArgs.from({});\n witness.lock = signature;\n tx.setWitnessArgs(info.position, witness);\n }\n\n return tx;\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { Script, ScriptLike } from \"../../ckb/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * A read-only signer for a CKB script. It can be used to get addresses,\n * but not to sign transactions. This is useful when you want to watch an address\n * without having the private key.\n *\n * @public\n */\nexport class SignerCkbScriptReadonly extends Signer {\n /**\n * The type of the signer.\n */\n get type(): SignerType {\n return SignerType.CKB;\n }\n\n /**\n * The sign type of the signer.\n * As this is a read-only signer, the sign type is {@link SignerSignType.Unknown}.\n */\n get signType(): SignerSignType {\n return SignerSignType.Unknown;\n }\n\n /**\n * The scripts associated with the signer.\n */\n public readonly scripts: Script[];\n\n /**\n * Creates an instance of SignerCkbScriptReadonly.\n *\n * @param client - The client instance used for communication.\n * @param scripts - The scripts associated with the signer. Can be a single script, an array of scripts, or multiple script arguments.\n */\n constructor(client: Client, ...scripts: (ScriptLike | ScriptLike[])[]) {\n super(client);\n\n this.scripts = scripts.flat().map(Script.from);\n if (this.scripts.length === 0) {\n throw new Error(\"SignerCkbScriptReadonly requires at least one script.\");\n }\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is read-only.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n /**\n * Gets the internal address for the script.\n *\n * @returns A promise that resolves to a string representing the internal address.\n *\n * @example\n * ```typescript\n * const internalAddress = await signer.getInternalAddress(); // Outputs the internal address\n * ```\n */\n async getInternalAddress(): Promise<string> {\n return this.getRecommendedAddress();\n }\n\n /**\n * Gets an array of Address objects representing the script address.\n *\n * @returns A promise that resolves to an array of Address objects.\n *\n * @example\n * ```typescript\n * const addressObjs = await signer.getAddressObjs(); // Outputs the array of Address objects\n * ```\n */\n async getAddressObjs(): Promise<Address[]> {\n return this.scripts.map((script) =>\n Address.fromScript(script, this.client),\n );\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { Bytes, bytesConcat, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport {\n Script,\n ScriptLike,\n Since,\n SinceLike,\n Transaction,\n TransactionLike,\n WitnessArgs,\n WitnessArgsLike,\n} from \"../../ckb/index.js\";\nimport {\n CellDepInfo,\n CellDepInfoLike,\n Client,\n KnownScript,\n ScriptInfo,\n ScriptInfoLike,\n} from \"../../client/index.js\";\nimport { codec, Entity } from \"../../codec/index.js\";\nimport { HASH_CKB_SHORT_LENGTH, hashCkbShort } from \"../../hasher/index.js\";\nimport { Hex, hexFrom, HexLike } from \"../../hex/index.js\";\nimport { numFrom, NumLike, numToBytes } from \"../../num/index.js\";\nimport { apply, reduceAsync } from \"../../utils/index.js\";\nimport { SignerMultisig, SignerSignType, SignerType } from \"../signer/index.js\";\nimport {\n recoverMessageSecp256k1,\n SECP256K1_SIGNATURE_LENGTH,\n} from \"./secp256k1Signing.js\";\n\nexport type MultisigCkbWitnessLike = (\n | {\n publicKeyHashes: HexLike[];\n publicKeys?: undefined | null;\n }\n | {\n publicKeyHashes?: undefined | null;\n publicKeys: HexLike[];\n }\n) & {\n threshold: NumLike;\n mustMatch?: NumLike | null;\n signatures?: HexLike[] | null;\n};\n\n/**\n * A class representing multisig information, holding information ingredients and containing utilities.\n * @public\n */\n@codec({\n encode: (encodable: MultisigCkbWitness) => {\n const { publicKeyHashes, threshold, mustMatch, signatures } =\n MultisigCkbWitness.from(encodable);\n\n if (\n signatures.some((s) => s.length !== SECP256K1_SIGNATURE_LENGTH * 2 + 2)\n ) {\n throw Error(\"MultisigCkbWitness: invalid signature length\");\n }\n if (\n publicKeyHashes.some((s) => s.length !== HASH_CKB_SHORT_LENGTH * 2 + 2)\n ) {\n throw Error(\"MultisigCkbWitness: invalid public key hash length\");\n }\n\n return bytesConcat(\n \"0x00\",\n numToBytes(mustMatch ?? 0),\n numToBytes(threshold),\n numToBytes(publicKeyHashes.length),\n ...publicKeyHashes,\n ...signatures,\n );\n },\n decode: (raw: Bytes) => {\n if (raw.length < 4) {\n throw Error(\"MultisigCkbWitness: data length too short\");\n }\n\n const [\n _reserved,\n mustMatch,\n threshold,\n publicKeyHashesLength,\n ...rawKeyAndSignatures\n ] = raw;\n\n if (\n rawKeyAndSignatures.length <\n publicKeyHashesLength * HASH_CKB_SHORT_LENGTH\n ) {\n throw Error(\"MultisigCkbWitness: invalid public key hashes length\");\n }\n\n const signatures = rawKeyAndSignatures.slice(\n publicKeyHashesLength * HASH_CKB_SHORT_LENGTH,\n );\n\n return MultisigCkbWitness.from({\n publicKeyHashes: Array.from(new Array(publicKeyHashesLength), (_, i) =>\n hexFrom(\n rawKeyAndSignatures.slice(\n i * HASH_CKB_SHORT_LENGTH,\n (i + 1) * HASH_CKB_SHORT_LENGTH,\n ),\n ),\n ),\n threshold: numFrom(threshold),\n mustMatch: numFrom(mustMatch),\n signatures: Array.from(\n new Array(Math.floor(signatures.length / SECP256K1_SIGNATURE_LENGTH)),\n (_, i) =>\n hexFrom(\n signatures.slice(\n i * SECP256K1_SIGNATURE_LENGTH,\n (i + 1) * SECP256K1_SIGNATURE_LENGTH,\n ),\n ),\n ),\n });\n },\n})\nexport class MultisigCkbWitness extends Entity.Base<\n MultisigCkbWitnessLike,\n MultisigCkbWitness\n>() {\n /**\n * @param publicKeyHashes - The public key hashes.\n * @param threshold - The threshold.\n * @param mustMatch - The number of signatures that must match.\n * @param signatures - The signatures.\n */\n constructor(\n public publicKeyHashes: Hex[],\n public threshold: number,\n public mustMatch: number,\n public signatures: Hex[],\n ) {\n super();\n\n const keysLength = publicKeyHashes.length;\n\n if (threshold <= 0 || threshold > keysLength) {\n throw new Error(\n \"threshold should be in range from 1 to public keys length\",\n );\n }\n if (mustMatch < 0 || mustMatch > Math.min(keysLength, threshold)) {\n throw new Error(\n \"mustMatch should be in range from 0 to min(public keys length, threshold)\",\n );\n }\n if (keysLength > 255) {\n throw new Error(\"public keys length should be less than 256\");\n }\n }\n\n /**\n * Create a MultisigCkbWitness from a MultisigCkbWitnessLike.\n *\n * @param witness - The witness like object.\n * @returns The MultisigCkbWitness.\n */\n static from(witness: MultisigCkbWitnessLike): MultisigCkbWitness {\n const publicKeyHashes = (() => {\n if (witness.publicKeyHashes) {\n return witness.publicKeyHashes;\n }\n return witness.publicKeys.map((k) => hashCkbShort(k));\n })();\n\n return new MultisigCkbWitness(\n publicKeyHashes.map(hexFrom),\n Number(numFrom(witness.threshold)),\n Number(numFrom(witness.mustMatch ?? 0)),\n witness.signatures?.map(hexFrom) ?? [],\n );\n }\n\n /**\n * Get the threshold of flexible signatures.\n */\n get flexibleThreshold() {\n return this.threshold - this.mustMatch;\n }\n\n /**\n * Get the script args of the multisig script.\n *\n * @param since - The since value.\n * @returns The script args.\n */\n scriptArgs(since?: SinceLike | null): Bytes {\n const hash = hashCkbShort(\n MultisigCkbWitness.from({ ...this, signatures: [] }).toBytes(),\n );\n\n if (since != null) {\n return bytesConcat(hash, Since.from(since).toBytes());\n }\n\n return bytesFrom(hash);\n }\n\n /**\n * Check if the multisig info is equal to another.\n *\n * @param otherLike - The other multisig info.\n * @returns True if the multisig info is equal, false otherwise.\n */\n eqInfo(otherLike: MultisigCkbWitnessLike): boolean {\n const other = MultisigCkbWitness.from(otherLike);\n return (\n this.publicKeyHashes.length === other.publicKeyHashes.length &&\n this.publicKeyHashes.every((h, i) => h === other.publicKeyHashes[i]) &&\n this.threshold === other.threshold &&\n this.mustMatch === other.mustMatch\n );\n }\n\n /**\n * Generate valid public key hashes and their signatures from the witness.\n * This method filters out invalid signatures, duplicate signatures, and signatures not in the multisig script.\n *\n * @param message - The message signed.\n * @returns A generator of public key hashes, signatures, and whether the signature is required.\n */\n *generatePublicKeyHashesFromSignatures(message: BytesLike): Generator<{\n pubkeyHash: Hex;\n signature: Hex;\n isRequired: boolean;\n }> {\n const publicKeyHashesFromSignature = new Set<Hex>();\n\n for (const signature of this.signatures.filter(\n (sig) => sig !== SignerMultisigCkbReadonly.EmptySignature,\n )) {\n const pubkey = (() => {\n try {\n return recoverMessageSecp256k1(message, signature);\n } catch (_) {\n // Ignore invalid signature\n return;\n }\n })();\n if (pubkey === undefined) {\n continue;\n }\n\n const pubkeyHash = hashCkbShort(pubkey);\n if (publicKeyHashesFromSignature.has(pubkeyHash)) {\n continue;\n }\n\n const index = this.publicKeyHashes.indexOf(pubkeyHash);\n if (index === -1) {\n continue;\n }\n publicKeyHashesFromSignature.add(pubkeyHash);\n const isRequired = index < this.mustMatch;\n\n yield {\n pubkeyHash,\n signature,\n isRequired,\n };\n }\n }\n\n /**\n * Calculate the number of matched signatures in the witness.\n *\n * @param message - The message signed.\n * @returns The number of required and flexible signatures.\n */\n calcMatchedSignaturesCount(message: BytesLike): {\n required: number;\n flexible: number;\n } {\n let required = 0;\n let flexible = 0;\n\n for (const { isRequired } of this.generatePublicKeyHashesFromSignatures(\n message,\n )) {\n if (isRequired) {\n required += 1;\n } else {\n flexible += 1;\n }\n }\n\n return { required, flexible };\n }\n}\n\n/**\n * A class extending Signer that provides access to a CKB multisig script.\n * This class does not support signing operations.\n * @public\n */\nexport class SignerMultisigCkbReadonly extends SignerMultisig {\n static EmptySignature = hexFrom(\"00\".repeat(SECP256K1_SIGNATURE_LENGTH));\n\n get type(): SignerType {\n return SignerType.CKB;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.Unknown;\n }\n\n public readonly multisigInfo: MultisigCkbWitness;\n\n public readonly since?: Since;\n public readonly scriptInfos: Promise<\n {\n script: Script;\n cellDeps: CellDepInfo[];\n }[]\n >;\n\n /**\n * Creates an instance of SignerMultisigCkbReadonly.\n *\n * @param client - The client instance.\n * @param multisigInfoLike - The multisig information.\n * @param options - The options.\n */\n constructor(\n client: Client,\n multisigInfoLike: MultisigCkbWitnessLike,\n options?: {\n since?: SinceLike | null;\n scriptInfos?: (KnownScript | ScriptInfoLike)[] | null;\n } | null,\n ) {\n super(client);\n\n this.multisigInfo = MultisigCkbWitness.from(multisigInfoLike);\n this.since = apply(Since.from, options?.since);\n\n const args = this.multisigInfo.scriptArgs(this.since);\n this.scriptInfos = Promise.all(\n (\n options?.scriptInfos ?? [\n KnownScript.Secp256k1MultisigV2,\n KnownScript.Secp256k1MultisigV2Beta,\n KnownScript.Secp256k1Multisig,\n ]\n ).map(async (v) => {\n if (typeof v !== \"string\") {\n return ScriptInfo.from(v);\n }\n\n try {\n return await client.getKnownScript(v);\n } catch (_) {\n return undefined;\n }\n }),\n ).then((infos) =>\n infos\n .filter((s) => s !== undefined)\n .map((i) => ({\n script: Script.from({ ...i, args }),\n cellDeps: i.cellDeps,\n })),\n );\n }\n\n /**\n * Get the number of members in the multisig script.\n *\n * @returns The number of members.\n */\n async getMemberCount() {\n return this.multisigInfo.publicKeyHashes.length;\n }\n\n /**\n * Get the threshold of the multisig script.\n *\n * @returns The threshold.\n */\n async getMemberThreshold() {\n return this.multisigInfo.threshold;\n }\n\n /**\n * Get the count of required member of the multisig script.\n *\n * @returns The must match count.\n */\n async getMemberRequiredCount() {\n return this.multisigInfo.mustMatch;\n }\n\n async connect(): Promise<void> {}\n\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n async getInternalAddress(): Promise<string> {\n return this.getRecommendedAddress();\n }\n\n async getAddressObjs(): Promise<Address[]> {\n return (await this.scriptInfos).map(({ script }) =>\n Address.fromScript(script, this.client),\n );\n }\n\n /**\n * Decode the witness args at a specific index.\n *\n * @param txLike - The transaction.\n * @param index - The index of the witness args.\n * @returns The decoded MultisigCkbWitness.\n */\n decodeWitnessArgsAt(\n txLike: TransactionLike,\n index: number,\n ): MultisigCkbWitness | undefined {\n const tx = Transaction.from(txLike);\n\n return this.decodeWitnessArgs(tx.getWitnessArgs(index));\n }\n\n /**\n * Decode the witness args.\n *\n * @param witnessLike - The witness args like object.\n * @returns The decoded MultisigCkbWitness.\n */\n decodeWitnessArgs(\n witnessLike?: WitnessArgsLike | null,\n ): MultisigCkbWitness | undefined {\n if (!witnessLike) {\n return;\n }\n const witness = WitnessArgs.from(witnessLike);\n\n if (witness.lock == null) {\n return;\n }\n\n try {\n const decoded = MultisigCkbWitness.decode(witness.lock);\n if (decoded.eqInfo(this.multisigInfo)) {\n return decoded;\n }\n } catch (_) {\n // Returns undefined for invalid data\n }\n }\n\n /**\n * Prepare the witness args at a specific index.\n *\n * @param txLike - The transaction.\n * @param index - The index of the witness args.\n * @param transformer - The transformer function.\n * @returns The prepared transaction.\n */\n async prepareWitnessArgsAt(\n txLike: TransactionLike,\n index: number,\n transformer?:\n | ((\n witness: MultisigCkbWitness,\n witnessArgs: WitnessArgs,\n ) =>\n | MultisigCkbWitnessLike\n | undefined\n | null\n | void\n | Promise<MultisigCkbWitnessLike | undefined | null | void>)\n | null,\n ): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n\n const witnessArgs = tx.getWitnessArgs(index) ?? WitnessArgs.from({});\n const multisigWitness =\n this.decodeWitnessArgs(witnessArgs) ?? this.multisigInfo.clone();\n\n const transformed = MultisigCkbWitness.from(\n (await transformer?.(multisigWitness, witnessArgs)) ?? multisigWitness,\n );\n\n transformed.signatures = transformed.signatures.slice(\n 0,\n this.multisigInfo.threshold,\n );\n transformed.signatures.push(\n ...Array.from(\n new Array(this.multisigInfo.threshold - transformed.signatures.length),\n () => SignerMultisigCkbReadonly.EmptySignature,\n ),\n );\n\n witnessArgs.lock = transformed.toHex();\n tx.setWitnessArgs(index, witnessArgs);\n\n return tx;\n }\n\n /**\n * Prepare multisig witness, if the existence of multisig witness is detected, nothing happens\n *\n * @param txLike - The transaction to prepare.\n * @param scriptLike - The script to prepare.\n * @returns A promise that resolves to the prepared transaction\n */\n async prepareTransactionOneScript(\n txLike: TransactionLike,\n script: ScriptLike,\n cellDeps: CellDepInfoLike[],\n ) {\n const tx = Transaction.from(txLike);\n const position = await tx.findInputIndexByLock(script, this.client);\n if (position === undefined) {\n return tx;\n }\n\n await tx.addCellDepInfos(this.client, cellDeps);\n return this.prepareWitnessArgsAt(tx, position);\n }\n\n /**\n * Prepare transaction for multisig witness and adding related cell deps\n *\n * @param txLike - The transaction to prepare.\n * @returns A promise that resolves to the prepared transaction\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n return await reduceAsync(\n await this.scriptInfos,\n (tx, { script, cellDeps }) =>\n this.prepareTransactionOneScript(tx, script, cellDeps),\n Transaction.from(txLike),\n );\n }\n\n /**\n * Get the number of valid signatures for matching multisig inputs in the transaction.\n *\n * @remarks\n * Returns `undefined` when the transaction has no inputs locked by any multisig address\n * supported by this signer. This method only counts signatures for matching multisig inputs\n * and does not imply that the transaction should be signed by this multisig.\n *\n * @param txLike - The transaction.\n * @returns The matched multisig signature count, or `undefined` when the transaction is unrelated to any multisig address supported by this signer.\n */\n async getSignaturesCount(\n txLike: TransactionLike,\n ): Promise<number | undefined> {\n const tx = Transaction.from(txLike);\n let minSignaturesCount = undefined;\n\n for (const { script } of await this.scriptInfos) {\n const info = await this.getSignInfo(tx, script);\n if (info === undefined) {\n continue;\n }\n\n const multisigWitness = this.decodeWitnessArgsAt(tx, info.position);\n if (!multisigWitness) {\n minSignaturesCount = 0;\n continue;\n }\n\n const { required, flexible } = multisigWitness.calcMatchedSignaturesCount(\n info.message,\n );\n\n minSignaturesCount = Math.min(\n minSignaturesCount ?? 256,\n required + Math.min(flexible, this.multisigInfo.flexibleThreshold),\n );\n }\n\n return minSignaturesCount;\n }\n\n /**\n * Check if related multisig inputs in the transaction need more signatures.\n *\n * @remarks\n * Returns `false` when the transaction has no inputs locked by any multisig address\n * supported by this signer.\n * A `false` result therefore means either the related multisig inputs are already fulfilled,\n * or the transaction is unrelated to all multisig addresses supported by this signer.\n *\n * @param txLike - The transaction to check.\n * @returns A promise that resolves to `true` when related multisig inputs still need signatures, and `false` otherwise.\n */\n async needMoreSignatures(txLike: TransactionLike): Promise<boolean> {\n const count = await this.getSignaturesCount(txLike);\n if (count == null) {\n return false;\n }\n return count < (await this.getMemberThreshold());\n }\n\n /**\n * Get the sign info for a script.\n *\n * @param txLike - The transaction.\n * @param script - The script.\n * @returns The sign info.\n */\n async getSignInfo(\n txLike: TransactionLike,\n script: ScriptLike,\n ): Promise<{ message: Hex; position: number } | undefined> {\n const tx = Transaction.from(txLike);\n\n const position = await tx.findInputIndexByLock(script, this.client);\n if (position == null) {\n return;\n }\n\n // === Replace the witness with a dummy one ===\n const witness = tx.getWitnessArgs(position) ?? WitnessArgs.from({});\n witness.lock = MultisigCkbWitness.from({\n ...this.multisigInfo,\n signatures: Array.from(\n new Array(this.multisigInfo.threshold),\n () => SignerMultisigCkbReadonly.EmptySignature,\n ),\n }).toHex();\n\n const clonedTx = tx.clone();\n clonedTx.setWitnessArgs(position, witness);\n // === Replace the witness with a dummy one ===\n\n return clonedTx.getSignHashInfo(script, this.client);\n }\n\n /**\n * Aggregate transactions.\n *\n * @param txs - The transactions to aggregate.\n * @returns The aggregated transaction.\n */\n async aggregateTransactions(txs: TransactionLike[]): Promise<Transaction> {\n if (txs.length === 0) {\n throw Error(\"No transaction to aggregate\");\n }\n\n let res = Transaction.from(txs[0]);\n\n for (const { script } of await this.scriptInfos) {\n const info = await this.getSignInfo(res, script);\n if (info === undefined) {\n continue;\n }\n\n const signatures = new Map<Hex, Hex>();\n let requiredCount = 0;\n for (const txLike of txs) {\n const tx = Transaction.from(txLike);\n const multisigWitness = this.decodeWitnessArgsAt(tx, info.position);\n\n if (!multisigWitness) {\n continue;\n }\n\n for (const {\n pubkeyHash,\n signature,\n isRequired,\n } of multisigWitness.generatePublicKeyHashesFromSignatures(\n info.message,\n )) {\n if (signatures.has(pubkeyHash)) {\n continue;\n }\n\n if (isRequired) {\n // A required public key\n requiredCount += 1;\n } else if (\n signatures.size - requiredCount >=\n this.multisigInfo.flexibleThreshold\n ) {\n // Not a required public key, and we have too many optional public key\n continue;\n }\n\n signatures.set(pubkeyHash, signature);\n if (signatures.size >= this.multisigInfo.threshold) {\n break;\n }\n }\n\n if (signatures.size >= this.multisigInfo.threshold) {\n break;\n }\n }\n\n res = await this.prepareWitnessArgsAt(res, info.position, (witness) => {\n witness.signatures = Array.from(signatures.values());\n });\n }\n\n return res;\n }\n}\n","import { SinceLike, Transaction, TransactionLike } from \"../../ckb/index.js\";\nimport { Client, KnownScript, ScriptInfoLike } from \"../../client/index.js\";\nimport { hashCkbShort } from \"../../hasher/index.js\";\nimport { Hex, hexFrom, HexLike } from \"../../hex/index.js\";\nimport { signMessageSecp256k1 } from \"./secp256k1Signing.js\";\nimport { SignerCkbPrivateKey } from \"./signerCkbPrivateKey.js\";\nimport {\n MultisigCkbWitnessLike,\n SignerMultisigCkbReadonly,\n} from \"./signerMultisigCkbReadonly.js\";\n\n/**\n * A class extending Signer that provides access to a CKB multisig script and supports signing operations.\n * @public\n */\nexport class SignerMultisigCkbPrivateKey extends SignerMultisigCkbReadonly {\n private readonly privateKey: Hex;\n private readonly signer: SignerCkbPrivateKey;\n\n /**\n * Creates an instance of SignerMultisigCkbPrivateKey.\n *\n * @param client - The client instance.\n * @param privateKey - The private key.\n * @param multisigInfo - The multisig information.\n * @param options - The options.\n */\n constructor(\n client: Client,\n privateKey: HexLike,\n multisigInfo: MultisigCkbWitnessLike,\n options?: {\n since?: SinceLike | null;\n scriptInfos?: (KnownScript | ScriptInfoLike)[] | null;\n } | null,\n ) {\n super(client, multisigInfo, options);\n\n this.privateKey = hexFrom(privateKey);\n this.signer = new SignerCkbPrivateKey(client, this.privateKey);\n }\n\n /**\n * Sign a transaction only (without preparing).\n *\n * @param txLike - The transaction to sign.\n * @returns The signed transaction.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n let tx = Transaction.from(txLike);\n\n const thisPubkeyHash = hashCkbShort(this.signer.publicKey);\n\n const index = this.multisigInfo.publicKeyHashes.indexOf(thisPubkeyHash);\n if (index === -1) {\n return tx;\n }\n const isSelfRequired = index < this.multisigInfo.mustMatch;\n\n for (const { script } of await this.scriptInfos) {\n const info = await this.getSignInfo(tx, script);\n if (!info) {\n continue;\n }\n\n // === Find a position for the signature ===\n tx = await this.prepareWitnessArgsAt(\n tx,\n info.position,\n async (witness) => {\n // We re-evaluate the signatures to filter invalid / excessive signatures\n const signatures: Hex[] = [];\n let requiredCount = 0;\n let isSignNeeded = true;\n\n for (const {\n pubkeyHash,\n signature,\n isRequired,\n } of witness.generatePublicKeyHashesFromSignatures(info.message)) {\n if (pubkeyHash === thisPubkeyHash) {\n if (!isSignNeeded) {\n // Has signed and added to the signatures list already. We will not add it again.\n continue;\n }\n isSignNeeded = false;\n }\n\n if (isRequired) {\n requiredCount += 1;\n } else if (\n signatures.length - requiredCount >=\n this.multisigInfo.flexibleThreshold\n ) {\n // Too many flexible signatures\n continue;\n }\n\n signatures.push(signature);\n if (signatures.length >= this.multisigInfo.threshold) {\n // We have got enough signatures\n isSignNeeded = false;\n break;\n }\n }\n\n if (\n isSignNeeded &&\n (isSelfRequired ||\n signatures.length - requiredCount <\n this.multisigInfo.flexibleThreshold)\n ) {\n // Add the signature from this signer only when\n // 1. The signature is needed\n // 2. It's required or...\n // 3. We haven't got enough flexible signatures\n signatures.push(\n signMessageSecp256k1(info.message, this.privateKey),\n );\n }\n witness.signatures = signatures;\n return witness;\n },\n );\n }\n\n return tx;\n }\n}\n","import bs58check from \"bs58check\";\nimport { Address } from \"../../address/index.js\";\nimport { bytesConcat, bytesFrom } from \"../../bytes/index.js\";\nimport { Transaction, TransactionLike, WitnessArgs } from \"../../ckb/index.js\";\nimport { KnownScript } from \"../../client/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport { numToBytes } from \"../../num/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * An abstract class extending the Signer class for Dogecoin-like signing operations.\n * This class provides methods to get Doge account, public key, and internal address,\n * as well as signing transactions.\n * @public\n */\nexport abstract class SignerDoge extends Signer {\n get type(): SignerType {\n return SignerType.Doge;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.DogeEcdsa;\n }\n\n /**\n * Gets the Doge address associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Doge account.\n */\n abstract getDogeAddress(): Promise<string>;\n\n /**\n * Gets the internal address, which is the Doge account in this case.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n async getInternalAddress(): Promise<string> {\n return this.getDogeAddress();\n }\n\n /**\n * Gets the identity, which is the Doge address in this case.\n *\n * @returns A promise that resolves to a string representing the identity\n */\n async getIdentity(): Promise<string> {\n return this.getDogeAddress();\n }\n\n /**\n * Gets an array of Address objects representing the known script addresses for the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n async getAddressObjs(): Promise<Address[]> {\n const hash = bs58check.decode(await this.getDogeAddress()).subarray(1);\n\n return [\n await Address.fromKnownScript(\n this.client,\n KnownScript.OmniLock,\n hexFrom([0x05, ...hash, 0x00]),\n ),\n ];\n }\n\n /**\n * prepare a transaction before signing. This method is not implemented and should be overridden by subclasses.\n *\n * @param txLike - The transaction to prepare, represented as a TransactionLike object.\n * @returns A promise that resolves to the prepared Transaction object.\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.OmniLock);\n await tx.prepareSighashAllWitness(script, 85, this.client);\n return tx;\n }\n\n /**\n * Signs a transaction without modifying it.\n *\n * @param txLike - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to a signed Transaction object.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n const info = await tx.getSignHashInfo(script, this.client);\n if (!info) {\n return tx;\n }\n\n const signature = bytesFrom(\n await this.signMessageRaw(info.message.slice(2)),\n \"base64\",\n );\n signature[0] = 31 + ((signature[0] - 27) % 4);\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(\n bytesConcat(\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(4 * 4, 4),\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(5 * 4 + signature.length, 4),\n numToBytes(signature.length, 4),\n signature,\n ),\n );\n\n tx.setWitnessArgs(info.position, witness);\n return tx;\n }\n}\n","import { Client } from \"../../client/index.js\";\nimport { SignerDoge } from \"./signerDoge.js\";\n\n/**\n * A class extending SignerDoge that provides read-only access to a Doge address.\n * This class does not support signing operations.\n * @public\n */\nexport class SignerDogeAddressReadonly extends SignerDoge {\n /**\n * Creates an instance of SignerDogeAddressReadonly.\n *\n * @param client - The client instance used for communication.\n * @param address - The Doge address with the signer.\n */\n constructor(\n client: Client,\n private readonly address: string,\n ) {\n super(client);\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is read-only.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n /**\n * Gets the Doge address associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Doge address.\n *\n * @example\n * ```typescript\n * const account = await signer.getDogeAddress(); // Outputs the Doge address\n * ```\n */\n async getDogeAddress(): Promise<string> {\n return this.address;\n }\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport {\n Bytes,\n bytesConcat,\n bytesFrom,\n BytesLike,\n bytesTo,\n} from \"../../bytes/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { Hex, hexFrom } from \"../../hex/index.js\";\nimport { btcP2pkhAddressFromPublicKey } from \"../btc/verify.js\";\nimport { SignerDoge } from \"./signerDoge.js\";\nimport { messageHashDogeEcdsa } from \"./verify.js\";\n\n/**\n * A class extending SignerDoge that provides access to a Doge address.\n * @public\n */\nexport class SignerDogePrivateKey extends SignerDoge {\n private readonly privateKey: Bytes;\n\n /**\n * Creates an instance of SignerDogePrivateKey\n *\n * @param client - The client instance used for communication.\n * @param privateKey - The Doge private key with the signer.\n */\n constructor(\n client: Client,\n privateKey: BytesLike,\n public readonly dogeNetwork = 0x1e,\n ) {\n super(client);\n this.privateKey = bytesFrom(privateKey);\n if (this.privateKey.length !== 32) {\n throw new Error(\"Private key must be 32 bytes!\");\n }\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is always connected.\n *\n * @returns A promise that resolves when the connection is complete.\n */\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n async getDogePublicKey(): Promise<Hex> {\n return hexFrom(secp256k1.getPublicKey(this.privateKey, true));\n }\n\n /**\n * Gets the Doge address associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Doge address.\n *\n * @example\n * ```typescript\n * const account = await signer.getDogeAddress(); // Outputs the Doge address\n * ```\n */\n async getDogeAddress(): Promise<string> {\n return btcP2pkhAddressFromPublicKey(\n await this.getDogePublicKey(),\n this.dogeNetwork,\n );\n }\n\n /**\n * Signs a message and returns signature only.\n *\n * @param msg - The message to sign, as a string or BytesLike object.\n * @returns A promise that resolves to the signature as a string.\n * @throws Will throw an error if not implemented.\n */\n async signMessageRaw(msg: string | BytesLike): Promise<string> {\n const challenge = typeof msg === \"string\" ? msg : hexFrom(msg).slice(2);\n\n const signature = secp256k1.sign(\n messageHashDogeEcdsa(challenge),\n this.privateKey,\n {\n format: \"recovered\",\n prehash: false,\n },\n );\n return bytesTo(\n bytesConcat([31 + Number(signature[0])], signature.subarray(1)),\n \"base64\",\n );\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * @public\n */\nexport abstract class SignerDummy extends Signer {\n get signType(): SignerSignType {\n return SignerSignType.Unknown;\n }\n\n constructor(\n client: Client,\n public readonly type: SignerType,\n ) {\n super(client);\n }\n\n async isConnected(): Promise<boolean> {\n return false;\n }\n\n async getInternalAddress(): Promise<string> {\n throw new Error(\"Can't get address from SignerDummy\");\n }\n\n async getAddressObjs(): Promise<Address[]> {\n throw new Error(\"Can't get addresses from SignerDummy\");\n }\n}\n","import { Client } from \"../../client/index.js\";\nimport { SignerType } from \"../signer/index.js\";\nimport { SignerDummy } from \"./dummy.js\";\n\n/**\n * @public\n */\nexport class SignerAlwaysError extends SignerDummy {\n constructor(\n client: Client,\n type: SignerType,\n private readonly message: string,\n ) {\n super(client, type);\n }\n\n async connect(): Promise<void> {\n throw new Error(this.message);\n }\n}\n","import { Client } from \"../../client/index.js\";\nimport { SignerType } from \"../signer/index.js\";\nimport { SignerDummy } from \"./dummy.js\";\n\n/**\n * @public\n */\nexport class SignerOpenLink extends SignerDummy {\n constructor(\n client: Client,\n type: SignerType,\n private readonly link: string,\n ) {\n super(client, type);\n }\n\n async connect(): Promise<void> {\n window.open(this.link, \"_blank\")?.focus();\n }\n}\n","import { Address } from \"../../address/index.js\";\nimport { Bytes, BytesLike, bytesConcat, bytesFrom } from \"../../bytes/index.js\";\nimport {\n Script,\n Transaction,\n TransactionLike,\n WitnessArgs,\n} from \"../../ckb/index.js\";\nimport { KnownScript } from \"../../client/index.js\";\nimport { Hasher, HasherKeecak256 } from \"../../hasher/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { numToBytes } from \"../../num/index.js\";\nimport { reduceAsync } from \"../../utils/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\n\n/**\n * An abstract class extending Signer for Ethereum Virtual Machine (EVM) based signing operations.\n * This class provides methods to get EVM account, internal address, and signing transactions.\n * @public\n */\nexport abstract class SignerEvm extends Signer {\n get type(): SignerType {\n return SignerType.EVM;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.EvmPersonal;\n }\n\n /**\n * Gets the EVM account associated with the signer.\n *\n * @returns A promise that resolves to a string representing the EVM account.\n */\n abstract getEvmAccount(): Promise<Hex>;\n\n /**\n * Gets the internal address, which is the EVM account in this case.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n async getInternalAddress(): Promise<string> {\n return this.getEvmAccount();\n }\n\n /**\n * Gets an array of Address objects representing the known script addresses for the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n async getAddressObjs(): Promise<Address[]> {\n const account = await this.getEvmAccount();\n const addresses = await Promise.all([\n this._getOmniLockAddresses(account),\n this._getPWLockAddresses(account),\n ]);\n\n return addresses.flat();\n }\n\n _getOmniLockAddresses(account: HexLike): Promise<Address[]> {\n return Promise.all([\n this._getOmniLockEvmAddressObj(account),\n this._getOmniLockOldEvmAddressObj(account),\n ]);\n }\n\n async _getPWLockAddresses(account: HexLike): Promise<Address[]> {\n const addr = await this._getPWLockEvmAddressObj(account);\n if (!addr) {\n return [];\n }\n return [addr];\n }\n\n async _getOmniLockEvmAddressObj(account: HexLike): Promise<Address> {\n return Address.fromKnownScript(\n this.client,\n KnownScript.OmniLock,\n hexFrom([0x12, ...bytesFrom(account), 0x00]),\n );\n }\n\n async _getOmniLockOldEvmAddressObj(account: HexLike): Promise<Address> {\n return Address.fromKnownScript(\n this.client,\n KnownScript.OmniLock,\n hexFrom([0x1, ...bytesFrom(account), 0x00]),\n );\n }\n\n async _getPWLockEvmAddressObj(\n account: HexLike,\n ): Promise<Address | undefined> {\n try {\n return Address.fromKnownScript(\n this.client,\n KnownScript.PWLock,\n hexFrom(bytesFrom(account)),\n );\n } catch {}\n return;\n }\n\n /**\n * prepare a transaction before signing. This method is not implemented and should be overridden by subclasses.\n *\n * @param txLike - The transaction to prepare, represented as a TransactionLike object.\n * @returns A promise that resolves to the prepared Transaction object.\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n if (\n (await tx.findInputIndexByLockId(\n await this.client.getKnownScript(KnownScript.OmniLock),\n this.client,\n )) !== undefined\n ) {\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.OmniLock);\n }\n if (\n (await tx.findInputIndexByLockId(\n await this.client.getKnownScript(KnownScript.PWLock),\n this.client,\n )) !== undefined\n ) {\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.PWLock);\n }\n\n const account = await this.getEvmAccount();\n const omniLockAddresses = await this._getOmniLockAddresses(account);\n const pwLockAddresses = await this._getPWLockAddresses(account);\n\n const omniTx = reduceAsync(\n omniLockAddresses,\n (tx: Transaction, { script }) =>\n tx.prepareSighashAllWitness(script, 85, this.client),\n tx,\n );\n\n return reduceAsync(\n pwLockAddresses,\n (tx: Transaction, { script }) =>\n tx.prepareSighashAllWitness(script, 65, this.client),\n omniTx,\n );\n }\n\n /**\n * Signs a transaction without modifying it.\n *\n * @param txLike - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to a signed Transaction object.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n let tx = Transaction.from(txLike);\n\n const account = await this.getEvmAccount();\n const { script: evmScript } = await this._getOmniLockEvmAddressObj(account);\n const { script: oldEvmScript } =\n await this._getOmniLockOldEvmAddressObj(account);\n\n tx = await this._signOmniLockScriptForTransaction(\n tx,\n evmScript,\n (hash) => `CKB transaction: ${hash}`,\n );\n tx = await this._signOmniLockScriptForTransaction(\n tx,\n oldEvmScript,\n (hash) => bytesFrom(hash),\n );\n\n const pwAddress = await this._getPWLockEvmAddressObj(account);\n if (pwAddress) {\n tx = await this._signPWLockScriptForTransaction(\n tx,\n pwAddress.script,\n (hash) => bytesFrom(hash),\n );\n }\n\n return tx;\n }\n\n async _signOmniLockScriptForTransaction(\n tx: Transaction,\n script: Script,\n messageTransformer: (hash: string) => BytesLike,\n ): Promise<Transaction> {\n const info = await this._signPersonalEvmForTransaction(\n tx,\n script,\n messageTransformer,\n );\n if (!info) {\n return tx;\n }\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(\n bytesConcat(\n numToBytes(5 * 4 + info.signature.length, 4),\n numToBytes(4 * 4, 4),\n numToBytes(5 * 4 + info.signature.length, 4),\n numToBytes(5 * 4 + info.signature.length, 4),\n numToBytes(info.signature.length, 4),\n info.signature,\n ),\n );\n\n tx.setWitnessArgs(info.position, witness);\n\n return tx;\n }\n\n async _signPWLockScriptForTransaction(\n tx: Transaction,\n script: Script,\n messageTransformer: (hash: string) => BytesLike,\n ): Promise<Transaction> {\n const info = await this._signPersonalEvmForTransaction(\n tx,\n script,\n messageTransformer,\n new HasherKeecak256(),\n );\n if (!info) {\n return tx;\n }\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(info.signature);\n tx.setWitnessArgs(info.position, witness);\n\n return tx;\n }\n\n async _signPersonalEvmForTransaction(\n tx: Transaction,\n script: Script,\n messageTransformer: (hash: string) => BytesLike,\n hasher?: Hasher,\n ): Promise<{ signature: Bytes; position: number } | undefined> {\n const info = await tx.getSignHashInfo(script, this.client, hasher);\n if (!info) {\n return;\n }\n\n const signature = bytesFrom(\n await this.signMessageRaw(messageTransformer(info.message)),\n );\n if (signature[signature.length - 1] >= 27) {\n signature[signature.length - 1] -= 27;\n }\n\n return { signature, position: info.position };\n }\n}\n","import { Client } from \"../../client/index.js\";\nimport { Hex, HexLike, hexFrom } from \"../../hex/index.js\";\nimport { SignerEvm } from \"./signerEvm.js\";\n\n/**\n * A class extending SignerEvm that provides read-only access to an EVM address.\n * This class does not support signing operations.\n * @public\n */\nexport class SignerEvmAddressReadonly extends SignerEvm {\n private readonly address: Hex;\n\n /**\n * Creates an instance of SignerEvmAddressReadonly.\n *\n * @param client - The client instance used for communication.\n * @param address - The EVM address associated with the signer.\n */\n constructor(client: Client, address: HexLike) {\n super(client);\n\n this.address = hexFrom(address);\n }\n\n /**\n * Connects to the client. This implementation does nothing as the class is read-only.\n *\n * @returns A promise that resolves when the connection is complete.\n *\n * @example\n * ```typescript\n * await signer.connect();\n * ```\n */\n\n async connect(): Promise<void> {}\n\n /**\n * Check if the signer is connected.\n *\n * @returns A promise that resolves the connection status.\n */\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n /**\n * Gets the EVM account associated with the signer.\n *\n * @returns A promise that resolves to a string representing the EVM account.\n *\n * @example\n * ```typescript\n * const account = await signer.getEvmAccount(); // Outputs the EVM account\n * ```\n */\n async getEvmAccount(): Promise<Hex> {\n return this.address;\n }\n}\n","const CKB_MAINNET_NETWORK_ID = \"ckb-mainnet\";\nconst CKB_TESTNET_NETWORK_ID = \"ckb-testnet\";\n\n// TODO: In the next major version, read the network ID directly from Client\n// instead of inferring it from addressPrefix.\nexport function signerJsonRpcNetworkIdFromAddressPrefix(addressPrefix: string) {\n if (addressPrefix === \"ckb\") {\n return CKB_MAINNET_NETWORK_ID;\n }\n if (addressPrefix === \"ckt\") {\n return CKB_TESTNET_NETWORK_ID;\n }\n\n throw new Error(`Unsupported address prefix: ${addressPrefix}`);\n}\n","import { randomBytes } from \"@noble/hashes/utils.js\";\nimport type { Transaction } from \"../../ckb/index.js\";\nimport { JsonRpcTransformers } from \"../../client/jsonRpc/advanced.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport { JsonRpcError, type JsonRpcPayload } from \"../../jsonRpc/index.js\";\nimport { abortSignalAny, sleep } from \"../../utils/index.js\";\nimport { OwnerUnique } from \"../../utils/owner/unique.js\";\nimport type { Signer } from \"../signer/index.js\";\nimport { signerJsonRpcNetworkIdFromAddressPrefix } from \"./network.js\";\nimport {\n SignerJsonRpcTransformers,\n type SignerJsonRpcInfo,\n type SignerJsonRpcInfoPayload,\n type SignerJsonRpcMessageToSign,\n} from \"./transformers.js\";\n\nexport type SignerJsonRpcConfirmation =\n | { method: \"connect\"; networkId: string }\n | { method: \"sign_message\"; message: SignerJsonRpcMessageToSign }\n | { method: \"sign_transaction\"; transaction: Transaction };\n\nconst GET_RESULT_CACHE_MS = 120_000;\nconst GET_RESULT_HISTORY_CAPACITY = 128;\nconst GET_RESULT_WAIT_MS = 10_000;\nconst GET_RESULT_PENDING_RESULT = Symbol(\"pending\");\n\ntype SignerJsonRpcResultEntry = {\n completion: Promise<unknown>;\n retrieved: boolean;\n};\n\nexport enum SignerJsonRpcErrorCode {\n MethodNotFound = -32601,\n InvalidParams = -32602,\n ServerError = -32000,\n InvalidState = -32001,\n NetworkMismatch = -32002,\n UserRejected = -32003,\n InvalidSession = -32004,\n DuplicateRequestId = -32005,\n}\n\nexport type SignerJsonRpcProviderSessionOptions = {\n /** Aborts when the provider session is disposed. */\n signal?: AbortSignal;\n};\n\nexport type SignerJsonRpcResultRecord =\n | { status: \"not_found\" }\n | { status: \"pending\" }\n | { status: \"completed\"; result: unknown };\n\nexport type SignerJsonRpcProviderSessionConfig = {\n getSigner: () => Signer | undefined;\n getSignerMetadata?: () => Pick<SignerJsonRpcInfo, \"name\" | \"icon\">;\n /** Connects the requested network and returns its connected Signer. */\n connect: (\n networkId: string,\n options?: SignerJsonRpcProviderSessionOptions,\n ) => Promise<Signer>;\n confirmRequest: (\n request: SignerJsonRpcConfirmation,\n options?: SignerJsonRpcProviderSessionOptions,\n ) => Promise<boolean>;\n};\n\nexport class SignerJsonRpcProviderSession {\n private readonly abortController = new AbortController();\n private readonly id = hexFrom(randomBytes(16));\n private readonly resultRecords = new Map<string, SignerJsonRpcResultEntry>();\n private readonly resultHistory = new Map<string, SignerJsonRpcResultEntry>();\n private readonly handlers;\n private info?: SignerJsonRpcInfoPayload;\n private connected = false;\n\n private constructor(\n private readonly config: SignerJsonRpcProviderSessionConfig,\n ) {\n this.handlers = new Map<\n string,\n readonly [\n number,\n (\n params: unknown[],\n options?: SignerJsonRpcProviderSessionOptions,\n ) => unknown,\n ]\n >([\n [\n \"get_info\",\n [\n 0,\n () =>\n (this.info ??= buildSignerInfo(\n this.id,\n this.requireSigner(),\n this.config.getSignerMetadata?.() ?? {},\n )),\n ],\n ],\n [\n \"connect\",\n [\n 1,\n async ([networkId], options) => {\n this.connected = false;\n if (typeof networkId !== \"string\" || !networkId) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.InvalidParams,\n message: \"Invalid network ID\",\n });\n }\n\n await this.requireConfirmation(\n { method: \"connect\", networkId },\n options,\n );\n\n const signer = await this.config.connect(networkId, options);\n options?.signal?.throwIfAborted();\n const actualNetworkId = signerJsonRpcNetworkIdFromAddressPrefix(\n signer.client.addressPrefix,\n );\n if (actualNetworkId !== networkId) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.NetworkMismatch,\n message: `Signer uses ${actualNetworkId}, expected ${networkId}`,\n });\n }\n\n this.connected = true;\n return null;\n },\n ],\n ],\n [\n \"get_scripts\",\n [\n 0,\n async () =>\n (await this.requireSigner().getAddressObjs()).map(({ script }) =>\n JsonRpcTransformers.scriptFrom(script),\n ),\n ],\n ],\n [\n \"get_native_address\",\n [0, () => this.requireSigner().getInternalAddress()],\n ],\n [\"get_identity\", [0, () => this.requireSigner().getIdentity()]],\n [\n \"sign_message\",\n [\n 1,\n async ([message], options) => {\n const parsedMessage = parseMessageParam(message);\n await this.requireConfirmation(\n {\n method: \"sign_message\",\n message: SignerJsonRpcTransformers.messageFrom(parsedMessage),\n },\n options,\n );\n return this.requireSigner().signMessageRaw(parsedMessage);\n },\n ],\n ],\n [\n \"prepare_transaction\",\n [\n 1,\n async ([transaction]) =>\n JsonRpcTransformers.transactionFrom(\n await this.requireSigner().prepareTransaction(\n parseTransactionParam(transaction),\n ),\n ),\n ],\n ],\n [\n \"sign_transaction\",\n [\n 1,\n async ([transaction], options) => {\n const parsedTransaction = parseTransactionParam(transaction);\n await this.requireConfirmation(\n { method: \"sign_transaction\", transaction: parsedTransaction },\n options,\n );\n return JsonRpcTransformers.transactionFrom(\n await this.requireSigner().signOnlyTransaction(parsedTransaction),\n );\n },\n ],\n ],\n ]);\n }\n\n static open(\n config: SignerJsonRpcProviderSessionConfig,\n ): OwnerUnique<SignerJsonRpcProviderSession> {\n const session = new SignerJsonRpcProviderSession(config);\n return new OwnerUnique(session, (session) => session.dispose());\n }\n\n get isConnected() {\n return this.connected;\n }\n\n handle = (payload: JsonRpcPayload) => {\n const signal = this.abortController.signal;\n signal.throwIfAborted();\n\n const [metadata, ...params] = requireParams(payload);\n const { requestId, sessionId } = parseRequestMetadata(metadata);\n\n if (payload.method === \"get_result\") {\n const [targetRequestId] = params;\n requireParams(payload, 2);\n requireRequestId(targetRequestId);\n return this.getResult(\n this.resultRecords.get(targetRequestId) ??\n this.resultHistory.get(targetRequestId),\n signal,\n );\n }\n\n requireRequestId(requestId);\n if (\n this.resultRecords.has(requestId) ||\n this.resultHistory.has(requestId)\n ) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.DuplicateRequestId,\n message: \"Request ID already exists\",\n });\n }\n\n return this.executeRequest(requestId, async () => {\n signal.throwIfAborted();\n const isGetInfo = payload.method === \"get_info\";\n if (isGetInfo) {\n if (sessionId !== undefined) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.InvalidParams,\n message: \"get_info does not accept a session ID\",\n });\n }\n } else {\n this.requireSession(sessionId);\n }\n\n const entry = this.handlers.get(payload.method);\n if (!entry) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.MethodNotFound,\n message: `Unsupported method: ${payload.method}`,\n });\n }\n const [paramCount, handler] = entry;\n requireParams(payload, paramCount + 1);\n\n if (!isGetInfo && payload.method !== \"connect\" && !this.connected) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.InvalidState,\n message: \"Connect must be approved before this request\",\n });\n }\n const result = await handler(params, { signal });\n signal.throwIfAborted();\n return result;\n });\n };\n\n private dispose() {\n this.connected = false;\n this.resultRecords.clear();\n this.resultHistory.clear();\n this.abortController.abort(\n new JsonRpcError({\n code: SignerJsonRpcErrorCode.InvalidSession,\n message: \"Invalid or expired session\",\n }),\n );\n }\n\n private requireSession(value: unknown) {\n if (value === this.id) {\n return;\n }\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.InvalidSession,\n message: \"Invalid or expired session\",\n });\n }\n\n private requireSigner() {\n const signer = this.config.getSigner();\n if (!signer) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.ServerError,\n message: \"No signer is connected\",\n });\n }\n\n return signer;\n }\n\n private async requireConfirmation(\n request: SignerJsonRpcConfirmation,\n options?: SignerJsonRpcProviderSessionOptions,\n ) {\n const confirmed = await this.config.confirmRequest(request, options);\n options?.signal?.throwIfAborted();\n if (!confirmed) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.UserRejected,\n message: \"User rejected request\",\n });\n }\n }\n\n private executeRequest(requestId: string, request: () => unknown) {\n const completion = Promise.resolve().then(request);\n const entry = { completion, retrieved: false };\n this.resultRecords.set(requestId, entry);\n const expire = () => {\n setTimeout(() => {\n if (this.resultRecords.get(requestId) === entry) {\n this.resultRecords.delete(requestId);\n this.resultHistory.set(requestId, entry);\n this.trimResultHistory();\n }\n }, GET_RESULT_CACHE_MS);\n };\n void completion.then(expire, expire);\n return completion;\n }\n\n private trimResultHistory() {\n while (this.resultHistory.size > GET_RESULT_HISTORY_CAPACITY) {\n let oldestRetrieved: string | undefined;\n for (const [requestId, entry] of this.resultHistory) {\n if (entry.retrieved) {\n oldestRetrieved = requestId;\n break;\n }\n }\n\n this.resultHistory.delete(\n oldestRetrieved ?? this.resultHistory.keys().next().value!,\n );\n }\n }\n\n private async getResult(\n entry: SignerJsonRpcResultEntry | undefined,\n signal?: AbortSignal,\n ): Promise<SignerJsonRpcResultRecord> {\n if (!entry) {\n return { status: \"not_found\" };\n }\n\n const controller = new AbortController();\n try {\n const result = await Promise.race([\n entry.completion.then(\n (value) => ({ status: \"fulfilled\" as const, value }),\n (reason: unknown) => ({ status: \"rejected\" as const, reason }),\n ),\n sleep(\n GET_RESULT_WAIT_MS,\n signal\n ? abortSignalAny([signal, controller.signal])\n : controller.signal,\n ).then(\n (): typeof GET_RESULT_PENDING_RESULT => GET_RESULT_PENDING_RESULT,\n ),\n ]);\n if (result === GET_RESULT_PENDING_RESULT) {\n return { status: \"pending\" };\n }\n\n entry.retrieved = true;\n if (result.status === \"rejected\") {\n throw result.reason;\n }\n return { status: \"completed\", result: result.value };\n } finally {\n controller.abort();\n }\n }\n}\n\nfunction parseMessageParam(message: unknown) {\n try {\n return SignerJsonRpcTransformers.messageTo(message);\n } catch (cause) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.InvalidParams,\n message:\n cause instanceof Error ? cause.message : \"Invalid signer message\",\n });\n }\n}\n\nfunction parseTransactionParam(transaction: unknown) {\n try {\n return JsonRpcTransformers.transactionTo(\n transaction as Parameters<typeof JsonRpcTransformers.transactionTo>[0],\n );\n } catch (cause) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.InvalidParams,\n message:\n cause instanceof Error ? cause.message : \"Invalid signer transaction\",\n });\n }\n}\n\nfunction requireParams(payload: JsonRpcPayload, count?: number) {\n if (!Array.isArray(payload.params)) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.InvalidParams,\n message: `${payload.method} expects positional parameters`,\n });\n }\n if (count !== undefined && payload.params.length !== count) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.InvalidParams,\n message: `${payload.method} expects ${count} parameter${count === 1 ? \"\" : \"s\"}`,\n });\n }\n\n return payload.params;\n}\n\nfunction parseRequestMetadata(value: unknown) {\n if (\n typeof value !== \"object\" ||\n value === null ||\n (\"request_id\" in value && typeof value.request_id !== \"string\") ||\n (\"session_id\" in value && typeof value.session_id !== \"string\")\n ) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.InvalidParams,\n message: \"Invalid request metadata\",\n });\n }\n\n return {\n requestId: \"request_id\" in value ? value.request_id : undefined,\n sessionId: \"session_id\" in value ? value.session_id : undefined,\n };\n}\n\nfunction requireRequestId(value: unknown): asserts value is string {\n if (typeof value !== \"string\" || !value) {\n throw new JsonRpcError({\n code: SignerJsonRpcErrorCode.InvalidParams,\n message: \"Invalid request ID\",\n });\n }\n}\n\nfunction buildSignerInfo(\n sessionId: string,\n signer: Signer,\n metadata: Pick<SignerJsonRpcInfo, \"name\" | \"icon\">,\n) {\n return SignerJsonRpcTransformers.infoFrom({\n sessionId,\n type: signer.type,\n signType: signer.signType,\n name: metadata.name,\n icon: metadata.icon,\n });\n}\n","import { randomBytes } from \"@noble/hashes/utils.js\";\nimport { Address } from \"../../address/index.js\";\nimport { Script } from \"../../ckb/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport {\n JsonRpcScript,\n JsonRpcTransformers,\n} from \"../../client/jsonRpc/advanced.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport { JsonRpcError, RequestorJsonRpc } from \"../../jsonRpc/index.js\";\nimport { retry, sleep, waitForAvailability } from \"../../utils/index.js\";\nimport { Signer } from \"../signer/index.js\";\nimport {\n SignerJsonRpcErrorCode,\n type SignerJsonRpcResultRecord,\n} from \"./handler.js\";\nimport { signerJsonRpcNetworkIdFromAddressPrefix } from \"./network.js\";\nimport {\n SignerJsonRpcInfo,\n SignerJsonRpcTransformers,\n} from \"./transformers.js\";\n\nexport type SignerJsonRpcConfig = Omit<\n Parameters<typeof RequestorJsonRpc.new>[0],\n \"onError\"\n> & {\n /** Cleans up integration-owned resources before replacement is announced. */\n disconnectHandler?: () => PromiseLike<void> | void;\n};\n\nconst GET_RESULT_RETRY_DELAYS = [1_000, 2_000, 4_000, 8_000] as const;\nconst GET_RESULT_MIN_POLL_INTERVAL_MS = 5_000;\nconst GET_RESULT_RETRY_REPEAT_MS = 10_000;\nconst GET_RESULT_TIMEOUT_MS = 20_000;\nconst REQUEST_RETRY_DELAYS = [5_000, 10_000, 20_000] as const;\nconst REQUEST_TIMEOUT_MS = 10_000;\n\nexport class SignerJsonRpc extends Signer {\n private connecting?: Promise<void>;\n private disconnecting?: Promise<void>;\n private scriptsPromise?: Promise<Script[]>;\n private internalAddressPromise?: Promise<string>;\n private identityPromise?: Promise<string>;\n private requestsController = new AbortController();\n private readonly replacedListeners = new Set<() => void>();\n\n private constructor(\n client: Client,\n readonly requestor: RequestorJsonRpc,\n private info: SignerJsonRpcInfo,\n private readonly disconnectHandler?: () => PromiseLike<void> | void,\n ) {\n super(client);\n }\n\n /** Creates a Signer that borrows an existing Transport. */\n static async new(client: Client, config: SignerJsonRpcConfig) {\n const { disconnectHandler, ...requestorConfig } = config;\n const requestor = RequestorJsonRpc.new(requestorConfig);\n const signer = new SignerJsonRpc(\n client,\n requestor,\n {} as SignerJsonRpcInfo,\n disconnectHandler,\n );\n signer.info = (await signer.request(\n \"get_info\",\n [],\n [],\n SignerJsonRpcTransformers.infoTo,\n )) as SignerJsonRpcInfo;\n return signer;\n }\n\n get type() {\n return this.info.type;\n }\n\n get signType() {\n return this.info.signType;\n }\n\n get name() {\n return this.info.name;\n }\n\n get icon() {\n return this.info.icon;\n }\n\n connect(): Promise<void> {\n if (this.disconnecting) {\n return this.disconnecting.then(() => this.connect());\n }\n if (this.connecting) {\n return this.connecting;\n }\n\n const connecting = this.requestConnect(\n signerJsonRpcNetworkIdFromAddressPrefix(this.client.addressPrefix),\n ).catch((cause: unknown) => {\n if (this.connecting === connecting) {\n this.connecting = undefined;\n }\n throw cause;\n });\n this.connecting = connecting;\n return connecting;\n }\n\n disconnect(): Promise<void> {\n this.clearReadCache();\n if (this.disconnecting) {\n return this.disconnecting;\n }\n if (!this.connecting) {\n return Promise.resolve();\n }\n\n this.connecting = undefined;\n this.disconnecting = Promise.resolve()\n .then(() => this.disconnectHandler?.())\n .finally(() => {\n this.replace();\n this.disconnecting = undefined;\n });\n return this.disconnecting;\n }\n\n private requestConnect = this.buildSender(\"connect\", []) as (\n networkId: string,\n ) => Promise<void>;\n\n onReplaced(listener: () => void) {\n this.replacedListeners.add(listener);\n return () => this.replacedListeners.delete(listener);\n }\n\n replace() {\n const requestsController = this.requestsController;\n this.requestsController = new AbortController();\n requestsController.abort(new Error(\"Signer JSON-RPC was replaced\"));\n this.connecting = undefined;\n this.clearReadCache();\n const listeners = [...this.replacedListeners];\n this.replacedListeners.clear();\n listeners.forEach((listener) => listener());\n }\n\n async isConnected() {\n return (\n this.connecting?.then(\n () => true,\n () => false,\n ) ?? false\n );\n }\n\n getScripts(): Promise<Script[]> {\n if (this.scriptsPromise) {\n return this.scriptsPromise.then((scripts) => [...scripts]);\n }\n\n const pending = this.request(\n \"get_scripts\",\n [],\n [],\n (scripts: JsonRpcScript[]) =>\n scripts.map((script) => JsonRpcTransformers.scriptTo(script)),\n ).catch((cause: unknown) => {\n if (this.scriptsPromise === pending) {\n this.scriptsPromise = undefined;\n }\n throw cause;\n }) as Promise<Script[]>;\n this.scriptsPromise = pending;\n return pending.then((scripts) => [...scripts]);\n }\n\n async getAddressObjs() {\n return (await this.getScripts()).map((script) =>\n Address.fromScript(script, this.client),\n );\n }\n\n getInternalAddress(): Promise<string> {\n if (this.internalAddressPromise) {\n return this.internalAddressPromise;\n }\n\n const pending = this.request(\"get_native_address\", [], []).catch(\n (cause: unknown) => {\n if (this.internalAddressPromise === pending) {\n this.internalAddressPromise = undefined;\n }\n throw cause;\n },\n ) as Promise<string>;\n this.internalAddressPromise = pending;\n return pending;\n }\n\n getIdentity(): Promise<string> {\n if (this.identityPromise) {\n return this.identityPromise;\n }\n\n const pending = this.request(\"get_identity\", [], []).catch(\n (cause: unknown) => {\n if (this.identityPromise === pending) {\n this.identityPromise = undefined;\n }\n throw cause;\n },\n ) as Promise<string>;\n this.identityPromise = pending;\n return pending;\n }\n\n signMessageRaw = this.buildSender(\"sign_message\", [\n SignerJsonRpcTransformers.messageFrom,\n ]) as Signer[\"signMessageRaw\"];\n\n prepareTransaction = this.buildSender(\n \"prepare_transaction\",\n [JsonRpcTransformers.transactionFrom],\n JsonRpcTransformers.transactionTo,\n ) as Signer[\"prepareTransaction\"];\n\n signOnlyTransaction = this.buildSender(\n \"sign_transaction\",\n [JsonRpcTransformers.transactionFrom],\n JsonRpcTransformers.transactionTo,\n ) as Signer[\"signOnlyTransaction\"];\n\n buildSender(\n rpcMethod: Parameters<RequestorJsonRpc[\"request\"]>[0],\n inTransformers?: Parameters<RequestorJsonRpc[\"request\"]>[2],\n outTransformer?: Parameters<RequestorJsonRpc[\"request\"]>[3],\n ): (...request: unknown[]) => Promise<unknown> {\n return async (...request: unknown[]) =>\n this.request(rpcMethod, request, inTransformers, outTransformer);\n }\n\n private clearReadCache() {\n this.scriptsPromise = undefined;\n this.internalAddressPromise = undefined;\n this.identityPromise = undefined;\n }\n\n private async request(\n method: string,\n params: unknown[],\n inTransformers?: Parameters<RequestorJsonRpc[\"request\"]>[2],\n outTransformer?: Parameters<RequestorJsonRpc[\"request\"]>[3],\n ): Promise<unknown> {\n const requestId = hexFrom(randomBytes(16));\n const sessionId = method === \"get_info\" ? undefined : this.info.sessionId;\n const signal = this.requestsController.signal;\n\n const result = retry(\n REQUEST_RETRY_DELAYS,\n async ({ resolve, reject }) => {\n try {\n return resolve(\n await this.requestor.request(\n method,\n [\n {\n request_id: requestId,\n ...(sessionId ? { session_id: sessionId } : {}),\n },\n ...params,\n ],\n inTransformers ? [undefined, ...inTransformers] : undefined,\n outTransformer,\n { signal, timeout: REQUEST_TIMEOUT_MS },\n ),\n );\n } catch (cause) {\n if (cause instanceof JsonRpcError) {\n return reject(cause);\n }\n throw cause;\n }\n },\n { signal },\n ).catch((cause: unknown) => {\n signal.throwIfAborted();\n if (\n cause instanceof JsonRpcError &&\n cause.code !== Number(SignerJsonRpcErrorCode.DuplicateRequestId)\n ) {\n throw cause;\n }\n\n return this.recoverResult(requestId, cause, signal, outTransformer);\n });\n\n try {\n const value = await result;\n signal.throwIfAborted();\n return value;\n } catch (cause) {\n if (\n cause instanceof JsonRpcError &&\n cause.code === Number(SignerJsonRpcErrorCode.InvalidSession)\n ) {\n this.replace();\n }\n throw cause;\n }\n }\n\n private async recoverResult(\n requestId: string,\n requestError: unknown,\n signal: AbortSignal,\n outTransformer?: Parameters<RequestorJsonRpc[\"request\"]>[3],\n ) {\n return retry(\n [],\n async ({ resolve, reject, next }) => {\n try {\n let getResultStartedAt = Date.now();\n const result = await retry<SignerJsonRpcResultRecord>(\n GET_RESULT_RETRY_DELAYS,\n async ({ resolve, reject }) => {\n await waitForAvailability(signal);\n getResultStartedAt = Date.now();\n\n try {\n return resolve(\n (await this.requestor.request(\n \"get_result\",\n [{}, requestId],\n undefined,\n undefined,\n { signal, timeout: GET_RESULT_TIMEOUT_MS },\n )) as SignerJsonRpcResultRecord,\n );\n } catch (cause) {\n if (cause instanceof JsonRpcError) {\n return reject(cause);\n }\n throw cause;\n }\n },\n { repeat: GET_RESULT_RETRY_REPEAT_MS, signal },\n );\n signal.throwIfAborted();\n\n if (result.status === \"not_found\") {\n return reject(requestError);\n }\n if (result.status === \"pending\") {\n const remaining =\n GET_RESULT_MIN_POLL_INTERVAL_MS -\n (Date.now() - getResultStartedAt);\n if (remaining > 0) {\n await sleep(remaining, signal);\n }\n return next();\n }\n if (result.status !== \"completed\" || !(\"result\" in result)) {\n return reject(new Error(\"Invalid signer request result\"));\n }\n return resolve(\n outTransformer ? outTransformer(result.result) : result.result,\n );\n } catch (cause) {\n return reject(cause);\n }\n },\n { repeat: 0, signal },\n );\n }\n}\n","import { bech32 } from \"bech32\";\nimport { Address } from \"../../address/index.js\";\nimport { BytesLike, bytesConcat, bytesFrom } from \"../../bytes/index.js\";\nimport { Transaction, TransactionLike, WitnessArgs } from \"../../ckb/index.js\";\nimport { KnownScript } from \"../../client/index.js\";\nimport { hashCkb } from \"../../hasher/index.js\";\nimport { Hex, hexFrom } from \"../../hex/index.js\";\nimport { Signer, SignerSignType, SignerType } from \"../signer/index.js\";\nimport { buildNostrEventFromMessage } from \"./verify.js\";\n\n/**\n * @public\n */\nexport interface NostrEvent {\n id?: string;\n pubkey?: string;\n sig?: string;\n created_at: number;\n kind: number;\n tags: string[][];\n content: string;\n}\n\n/**\n * @public\n */\nexport abstract class SignerNostr extends Signer {\n static CKB_SIG_HASH_ALL_TAG = \"ckb_sighash_all\";\n static CKB_UNLOCK_EVENT_KIND = 23334;\n static CKB_UNLOCK_EVENT_CONTENT =\n \"Signing a CKB transaction\\n\\nIMPORTANT: Please verify the integrity and authenticity of connected Nostr client before signing this message\\n\";\n\n get type(): SignerType {\n return SignerType.Nostr;\n }\n\n get signType(): SignerSignType {\n return SignerSignType.NostrEvent;\n }\n\n /**\n * Gets the Nostr public key associated with the signer.\n *\n * @returns A promise that resolves to a string representing the Nostr public key.\n */\n abstract getNostrPublicKey(): Promise<Hex>;\n\n /**\n * Sign a nostr event.\n *\n * @returns A promise that resolves to the signed event.\n */\n async signNostrEvent(_event: NostrEvent): Promise<Required<NostrEvent>> {\n throw Error(\"SignerNostr.signNostrEvent not implemented\");\n }\n\n /**\n * Sign a message.\n *\n * @returns A promise that resolves to the signature.\n */\n async signMessageRaw(message: string | BytesLike): Promise<Hex> {\n return hexFrom(\n (await this.signNostrEvent(buildNostrEventFromMessage(message))).sig,\n );\n }\n\n /**\n * Gets the internal address, which is the EVM account in this case.\n *\n * @returns A promise that resolves to a string representing the internal address.\n */\n async getInternalAddress(): Promise<string> {\n return bech32.encode(\n \"npub\",\n bech32.toWords(bytesFrom(await this.getNostrPublicKey())),\n );\n }\n\n /**\n * Gets an array of Address objects representing the known script addresses for the signer.\n *\n * @returns A promise that resolves to an array of Address objects.\n */\n async getAddressObjs(): Promise<Address[]> {\n const publicKey = await this.getNostrPublicKey();\n return [\n await Address.fromKnownScript(\n this.client,\n KnownScript.NostrLock,\n hexFrom(bytesConcat([0x00], hashCkb(publicKey).slice(0, 42))),\n ),\n ];\n }\n\n /**\n * prepare a transaction before signing.\n *\n * @param txLike - The transaction to prepare, represented as a TransactionLike object.\n * @returns A promise that resolves to the prepared Transaction object.\n */\n async prepareTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n await tx.addCellDepsOfKnownScripts(this.client, KnownScript.NostrLock);\n await tx.prepareSighashAllWitness(script, 572, this.client);\n return tx;\n }\n\n /**\n * Signs a transaction without modifying it.\n *\n * @param txLike - The transaction to sign, represented as a TransactionLike object.\n * @returns A promise that resolves to a signed Transaction object.\n */\n async signOnlyTransaction(txLike: TransactionLike): Promise<Transaction> {\n const tx = Transaction.from(txLike);\n const { script } = await this.getRecommendedAddressObj();\n const info = await tx.getSignHashInfo(script, this.client);\n if (!info) {\n return tx;\n }\n\n const signedEvent = bytesFrom(\n JSON.stringify(\n await this.signNostrEvent({\n pubkey: (await this.getNostrPublicKey()).slice(2),\n tags: [[SignerNostr.CKB_SIG_HASH_ALL_TAG, info.message.slice(2)]],\n created_at: Math.floor(Date.now() / 1000),\n kind: SignerNostr.CKB_UNLOCK_EVENT_KIND,\n content: SignerNostr.CKB_UNLOCK_EVENT_CONTENT,\n }),\n ),\n \"utf8\",\n );\n\n const witness = WitnessArgs.fromBytes(tx.witnesses[info.position]);\n witness.lock = hexFrom(signedEvent);\n tx.setWitnessArgs(info.position, witness);\n\n return tx;\n }\n}\n","import { bech32 } from \"bech32\";\nimport { Client } from \"../../client/index.js\";\nimport { Hex, hexFrom, HexLike } from \"../../hex/index.js\";\nimport { SignerNostr } from \"./signerNostr.js\";\n\n/**\n * Signer from Nostr public key\n * Support npub and hex format\n */\nexport class SignerNostrPublicKeyReadonly extends SignerNostr {\n public readonly publicKey: Hex;\n\n constructor(client: Client, publicKey: HexLike) {\n super(client);\n\n if (typeof publicKey === \"string\" && publicKey.startsWith(\"npub\")) {\n const { words } = bech32.decode(publicKey);\n this.publicKey = hexFrom(bech32.fromWords(words));\n } else {\n this.publicKey = hexFrom(publicKey);\n }\n }\n\n async connect(): Promise<void> {}\n\n async isConnected(): Promise<boolean> {\n return true;\n }\n\n async getNostrPublicKey(): Promise<Hex> {\n return this.publicKey;\n }\n}\n","import { schnorr } from \"@noble/curves/secp256k1.js\";\nimport { bech32 } from \"bech32\";\nimport { Bytes, bytesFrom, BytesLike } from \"../../bytes/index.js\";\nimport { Client } from \"../../client/index.js\";\nimport { hexFrom } from \"../../hex/index.js\";\nimport { NostrEvent } from \"./signerNostr.js\";\nimport { SignerNostrPublicKeyReadonly } from \"./signerNostrPublicKeyReadonly.js\";\nimport { nostrEventHash } from \"./verify.js\";\n\n/**\n * Signer from Nostr private key\n * Support nsec and hex format\n */\nexport class SignerNostrPrivateKey extends SignerNostrPublicKeyReadonly {\n private readonly privateKey: Bytes;\n\n constructor(client: Client, privateKeyLike: BytesLike) {\n const privateKey = (() => {\n if (\n typeof privateKeyLike === \"string\" &&\n privateKeyLike.startsWith(\"nsec\")\n ) {\n const { words } = bech32.decode(privateKeyLike);\n return bytesFrom(bech32.fromWords(words));\n }\n\n return bytesFrom(privateKeyLike);\n })();\n\n super(client, schnorr.getPublicKey(privateKey));\n\n this.privateKey = privateKey;\n }\n\n async signNostrEvent(event: NostrEvent): Promise<Required<NostrEvent>> {\n const pubkey = (await this.getNostrPublicKey()).slice(2);\n const eventHash = nostrEventHash({ ...event, pubkey });\n const signature = schnorr.sign(eventHash, this.privateKey);\n\n return {\n ...event,\n id: hexFrom(eventHash).slice(2),\n pubkey,\n sig: hexFrom(signature).slice(2),\n };\n }\n}\n","export * from \"./address/index.js\";\nexport * from \"./bytes/index.js\";\nexport * from \"./ckb/index.js\";\nexport * from \"./client/index.js\";\nexport * from \"./codec/index.js\";\nexport * from \"./fixedPoint/index.js\";\nexport * from \"./hasher/index.js\";\nexport * from \"./hex/index.js\";\nexport * from \"./jsonRpc/index.js\";\nexport * from \"./keystore/index.js\";\nexport * from \"./molecule/index.js\";\nexport * from \"./num/index.js\";\nexport * from \"./signer/index.js\";\nexport * from \"./utils/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