@ckb-ccc/core 1.15.0 → 1.16.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.
- package/CHANGELOG.md +22 -0
- package/README.md +2 -0
- package/dist/address.advanced-C5UrS2uk.mjs +2 -0
- package/dist/address.advanced-C5UrS2uk.mjs.map +1 -0
- package/dist/advanced.d.mts +1 -1
- package/dist/advanced.mjs +1 -1
- package/dist/{advancedBarrel-Dwyn3WMm.d.mts → advancedBarrel-66JgvInl.d.mts} +146 -4
- package/dist/advancedBarrel-66JgvInl.d.mts.map +1 -0
- package/dist/advancedBarrel.d.mts +1 -1
- package/dist/advancedBarrel.mjs +1 -1
- package/dist/{barrel-DO-IW8Ui.mjs → barrel-yZm3ICzn.mjs} +2 -2
- package/dist/barrel-yZm3ICzn.mjs.map +1 -0
- package/dist/barrel.d.mts +1 -1
- package/dist/barrel.mjs +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist.commonjs/address.advanced-CQJ24Iei.js +2 -0
- package/dist.commonjs/address.advanced-CQJ24Iei.js.map +1 -0
- package/dist.commonjs/advanced.d.ts +1 -1
- package/dist.commonjs/advanced.js +1 -1
- package/dist.commonjs/{advancedBarrel-D97MfkUZ.d.ts → advancedBarrel-CiJnF8me.d.ts} +146 -4
- package/dist.commonjs/advancedBarrel-CiJnF8me.d.ts.map +1 -0
- package/dist.commonjs/advancedBarrel.d.ts +1 -1
- package/dist.commonjs/advancedBarrel.js +1 -1
- package/dist.commonjs/{barrel-D5PRJCB6.js → barrel-CddEgDBp.js} +2 -2
- package/dist.commonjs/barrel-CddEgDBp.js.map +1 -0
- package/dist.commonjs/barrel.d.ts +1 -1
- package/dist.commonjs/barrel.js +1 -1
- package/dist.commonjs/index.d.ts +1 -1
- package/dist.commonjs/index.js +1 -1
- package/package.json +2 -2
- package/src/ckb/epoch.ts +9 -9
- package/src/ckb/script.ts +10 -2
- package/src/ckb/transaction.ts +45 -31
- package/src/client/cache/cache.ts +1 -2
- package/src/client/cache/memory.ts +1 -2
- package/src/client/client.ts +1 -2
- package/src/client/clientPublicMainnet.advanced.ts +17 -0
- package/src/client/clientPublicTestnet.advanced.ts +17 -0
- package/src/client/clientTypes.ts +1 -6
- package/src/client/jsonRpc/transformers.ts +1 -2
- package/src/client/knownScript.ts +1 -0
- package/src/codec/entity.ts +2 -1
- package/src/molecule/codec.ts +19 -15
- package/src/utils/index.ts +3 -3
- package/dist/address.advanced-BHxWrbFc.mjs +0 -2
- package/dist/address.advanced-BHxWrbFc.mjs.map +0 -1
- package/dist/advancedBarrel-Dwyn3WMm.d.mts.map +0 -1
- package/dist/barrel-DO-IW8Ui.mjs.map +0 -1
- package/dist.commonjs/address.advanced-UCU9Hn8t.js +0 -2
- package/dist.commonjs/address.advanced-UCU9Hn8t.js.map +0 -1
- package/dist.commonjs/advancedBarrel-D97MfkUZ.d.ts.map +0 -1
- package/dist.commonjs/barrel-D5PRJCB6.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"barrel-CddEgDBp.js","names":["_0n","_1n","_2n","_7n","split","rotlBH","rotlSH","rotlBL","rotlSL","u32","createHasher","bytesFrom","hexFrom","Transaction","numFrom","DEFAULT_CONFIRMED_BLOCK_TIME","DEFAULT_CONFIRMED_BLOCK_TIME","MapLru","numFrom","Cell","hexFrom","OutPoint","filterCell","ClientTransactionResponse","ClientBlockHeader","ClientBlock","numMax","DEFAULT_MIN_FEE_RATE","numFrom","DEFAULT_MAX_FEE_RATE","numMin","OutPoint","Cell","ClientIndexerSearchKey","CellDepInfo","CellDep","reduceAsync","Zero","Transaction","ErrorClientMaxFeeRateExceeded","hexFrom","ErrorClientWaitTransactionTimeout","sleep","TransportFallback","transportFromUri","ErrorClientResolveUnknown","OutPoint","ErrorClientVerification","ErrorClientDuplicatedTransaction","ErrorClientRBFRejected","apply","numFrom","JsonRpcTransformers","numToHex","hexFrom","ErrorClientBase","Cell","WebSocket","MAINNET_SCRIPTS","ScriptInfo","WebSocket","TESTNET_SCRIPTS","ScriptInfo","hashCkb","CellInput","numLeToBytes","Script","addressPayloadFromString","addressFromPayload","bytesConcat","bytesFrom","hashTypeToBytes","bech32m","ADDRESS_BECH32_LIMIT","isBytes","abytes","clean","copyBytes","copyBytes","checkOpts","kdfInputToBytes","createView","SHA256_K","SHA256_W","HashMD","rotr","Chi","Maj","SHA256_IV","sha256","rotl","checkOpts","sha256","u32","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","_2n","_0n","abytes","wcRandomBytes","isBytes","randomBytes","hmac","nobleHmac","sha256","randomBytes","abytes","HashMD","rotl","sha256","sha256n","basex","base58","bs58checkBase","numFrom","numLeToBytes","bytesConcat","bytesFrom","sha256","bs58check","hexFrom","bytesFrom","hexFrom","bytesConcat","hashCkb","hexFrom","hexFrom","bytesFrom","bytesFrom","hexFrom","sha256","bytesFrom","Transaction","hexFrom","Transaction","bytesFrom","WitnessArgs","bytesConcat","numToBytes","hexFrom","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","bytesFrom","bytesConcat","hashCkb","Transaction","WitnessArgs","hexFrom","bytesFrom","hexFrom"],"sources":["../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha3.js","../src/hasher/hasherKeecak256.ts","../src/molecule/barrel.ts","../src/client/cache/cache.ts","../src/client/cache/memory.ts","../src/client/client.ts","../src/jsonRpc/requestor.ts","../src/client/jsonRpc/client.ts","../src/client/clientPublicMainnet.ts","../src/client/clientPublicTestnet.ts","../src/ckb/hash.ts","../src/address/index.ts","../../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/utils.js","../../../node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/aes.js","../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hmac.js","../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/pbkdf2.js","../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha2.js","../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/scrypt.js","../src/keystore/index.ts","../src/signer/btc/psbt.ts","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/utils.js","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/modular.js","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/curve.js","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/weierstrass.js","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/secp256k1.js","../../../node_modules/.pnpm/@noble+hashes@2.2.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/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/nostr/signerNostr.ts","../src/signer/nostr/signerNostrPublicKeyReadonly.ts","../src/signer/nostr/signerNostrPrivateKey.ts","../src/barrel.ts"],"sourcesContent":["/**\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 { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./_u64.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput, 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// Left rotation (without 0, 32, 64)\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/**\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 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 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 const B = new Uint32Array(5 * 2);\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 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 // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\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 } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\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 possible for this instance');\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.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 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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true), 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//# sourceMappingURL=sha3.js.map","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 {\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} from \"./clientTypes.js\";\nimport { KnownScript } from \"./knownScript.js\";\n\n/**\n * @public\n */\nexport abstract class Client {\n public cache: ClientCache;\n\n constructor(config?: { cache?: ClientCache }) {\n this.cache = config?.cache ?? new ClientCacheMemory();\n }\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 client = new ccc.ClientPublicTestnet();\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 abstract getKnownScript(script: KnownScript): Promise<ScriptInfo>;\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 client = new ccc.ClientPublicTestnet();\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 client = new ccc.ClientPublicTestnet();\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 client = new ccc.ClientPublicTestnet();\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 client = new ccc.ClientPublicTestnet();\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 client = new ccc.ClientPublicTestnet();\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 client = new ccc.ClientPublicTestnet();\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 await this.cache.recordCells(res.cells);\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 client = new ccc.ClientPublicTestnet();\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 client = new ccc.ClientPublicTestnet();\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 client = new ccc.ClientPublicTestnet();\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 * If a CellDepInfo specifies a type script, the actual deployed cell is located on-chain.\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 client = new ccc.ClientPublicTestnet();\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 client = new ccc.ClientPublicTestnet();\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 client = new ccc.ClientPublicTestnet();\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 client = new ccc.ClientPublicTestnet();\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 client = new ccc.ClientPublicTestnet();\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 client = new ccc.ClientPublicTestnet();\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 client = new ccc.ClientPublicTestnet();\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 Transport,\n TransportFallback,\n transportFromUri,\n} from \"./transports/advanced.js\";\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\nexport type RequestorJsonRpcConfig = {\n fallbacks?: string[];\n timeout?: number;\n maxConcurrent?: number;\n transport?: Transport;\n};\n\nexport class RequestorJsonRpc {\n public readonly maxConcurrent?: number;\n private concurrent = 0;\n private readonly pending: (() => void)[] = [];\n\n public readonly transport: Transport;\n\n private id = 0;\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 */\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 this.transport =\n config?.transport ??\n new TransportFallback(\n Array.from(\n new Set([url_, ...(config?.fallbacks ?? [])]).values(),\n (url) => transportFromUri(url, config),\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 */\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 ): 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),\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(payload: JsonRpcPayload): Promise<unknown> {\n if (\n this.maxConcurrent !== undefined &&\n this.concurrent >= this.maxConcurrent\n ) {\n const pending = new Promise<void>((resolve) =>\n this.pending.push(resolve),\n );\n await pending;\n }\n\n this.concurrent += 1;\n const res = (await this.transport.request(payload)) as {\n id: number;\n error: unknown;\n result: unknown;\n };\n this.concurrent -= 1;\n this.pending.shift()?.();\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 res.error as unknown;\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 { apply } from \"../../utils/index.js\";\nimport { ClientCache } from \"../cache/index.js\";\nimport { Client } from \"../client.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\nexport type ClientJsonRpcConfig = RequestorJsonRpcConfig & {\n cache?: ClientCache;\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 */\n\n constructor(url_: string, config?: ClientJsonRpcConfig) {\n super(config);\n\n this.requestor =\n config?.requestor ??\n new RequestorJsonRpc(url_, config, (errAny) => {\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 }\n\n /**\n * Returns the URL of the JSON-RPC server.\n *\n * @returns The URL of the JSON-RPC server.\n */\n get url(): string {\n return this.requestor.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 ({ mean, median }: { mean: NumLike; median: NumLike }) => ({\n mean: numFrom(mean),\n median: numFrom(median),\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 { MAINNET_SCRIPTS } from \"./clientPublicMainnet.advanced.js\";\nimport { ScriptInfo, ScriptInfoLike } from \"./clientTypes.js\";\nimport { ClientJsonRpc, ClientJsonRpcConfig } from \"./jsonRpc/index.js\";\nimport { KnownScript } from \"./knownScript.js\";\n\n/**\n * @public\n */\nexport class ClientPublicMainnet extends ClientJsonRpc {\n constructor(\n private readonly config?: ClientJsonRpcConfig & {\n url?: string;\n scripts?: Record<KnownScript, ScriptInfoLike | undefined>;\n },\n ) {\n const hasWebSocket = typeof WebSocket !== \"undefined\";\n super(\n config?.url ??\n (hasWebSocket\n ? \"wss://mainnet.ckb.dev/ws\"\n : \"https://mainnet.ckb.dev/\"),\n {\n ...config,\n fallbacks:\n config?.fallbacks ??\n (hasWebSocket\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 }\n\n get scripts(): Record<KnownScript, ScriptInfoLike | undefined> {\n return this.config?.scripts ?? MAINNET_SCRIPTS;\n }\n\n get addressPrefix(): string {\n return \"ckb\";\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","import WebSocket from \"isomorphic-ws\";\nimport { TESTNET_SCRIPTS } from \"./clientPublicTestnet.advanced.js\";\nimport { ScriptInfo, ScriptInfoLike } from \"./clientTypes.js\";\nimport { ClientJsonRpc, ClientJsonRpcConfig } from \"./jsonRpc/index.js\";\nimport { KnownScript } from \"./knownScript.js\";\n\n/**\n * @public\n */\nexport class ClientPublicTestnet extends ClientJsonRpc {\n constructor(\n private readonly config?: ClientJsonRpcConfig & {\n url?: string;\n scripts?: Record<KnownScript, ScriptInfoLike | undefined>;\n },\n ) {\n const hasWebSocket = typeof WebSocket !== \"undefined\";\n super(\n config?.url ??\n (hasWebSocket\n ? \"wss://testnet.ckb.dev/ws\"\n : \"https://testnet.ckb.dev/\"),\n {\n ...config,\n fallbacks:\n config?.fallbacks ??\n (hasWebSocket\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 }\n\n get scripts(): Record<KnownScript, ScriptInfoLike | undefined> {\n return this.config?.scripts ?? TESTNET_SCRIPTS;\n }\n\n get addressPrefix(): string {\n return \"ckt\";\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","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 { 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) */\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/**\n * Asserts something is boolean.\n * @param b - Value to validate.\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(b) {\n if (typeof b !== 'boolean')\n throw new TypeError(`boolean expected, not ${b}`);\n}\n/**\n * Asserts something is a non-negative safe integer.\n * @param n - Value to validate.\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) {\n if (typeof n !== 'number')\n throw new TypeError('number expected, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError('positive integer expected, got ' + 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 const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n }\n return 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 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/**\n * Asserts output is a properly-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 * @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views.\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.\n *\n * ```ts\n * aoutput(new Uint8Array(16), { outputLen: 16 });\n * ```\n */\nexport function aoutput(out, instance, onlyAligned = false) {\n abytes(out, undefined, 'output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('digestInto() expects output buffer of length at least ' + min);\n }\n if (onlyAligned && !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 const byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\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 const byteSwap32 = (arr) => {\n for (let i = 0; i < arr.length; i++)\n arr[i] = byteSwap(arr[i]);\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// 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 * @param hex - Hexadecimal string to decode.\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On malformed hexadecimal input. {@link RangeError}\n * @example\n * Parses a hex test vector into bytes.\n *\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));\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 RangeError('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// Used in micro\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 return BigInt(hex === '' ? '0' : '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// Used in micro, 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.\n * @returns Big-endian bytes padded to `len`.\n * Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`,\n * and values that do not fit surface through the downstream hex parser instead of a\n * dedicated range guard here.\n * @throws On wrong argument types. {@link TypeError}\n * @throws If the requested output length cannot represent the encoded value. {@link RangeError}\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 // Reject coercible non-numeric inputs before string/hex conversion changes behavior.\n if (typeof n === 'number')\n anumber(n);\n else if (typeof n !== 'bigint')\n throw new TypeError(`number or bigint expected, got ${typeof n}`);\n anumber(len);\n return hexToBytes(n.toString(16).padStart(len * 2, '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 for most ciphers\n * (except chacha/salsa, which were designed for this)\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 * complexOverlapBytes(new Uint8Array(4), new Uint8Array(4));\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 * The merge mutates `defaults` in place and returns the same object.\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 if (opts == null || typeof opts !== 'object')\n throw new Error('options must be defined');\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 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`), and tag-bearing constructors are expected to use\n * `args[1]` for optional AAD.\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 // Validate AAD if tagLength present\n const tagl = params.tagLength;\n if (tagl && args[1] !== undefined)\n abytes(args[1], 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 called = true;\n abytes(data);\n checkOutput(cipher.encrypt.length, output);\n return cipher.encrypt(data, output);\n },\n decrypt(data, output) {\n abytes(data);\n if (tagl && data.length < tagl)\n throw new Error('\"ciphertext\" expected length bigger than 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 or 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, undefined, 'output');\n if (out.length !== expectedLength)\n throw new Error('\"output\" expected Uint8Array of length ' + expectedLength + ', got: ' + out.length);\n if (onlyAligned && !isAligned32(out))\n throw new Error('invalid output, must be aligned');\n return out;\n}\n/**\n * Encodes data and AAD bit lengths into a 16-byte buffer.\n * @param dataLength - Data length in bits.\n * @param aadLength - AAD length in bits.\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.\n * Uses internal OS-level `crypto.getRandomValues`.\n * @param bytesLength - Number of bytes to produce.\n * Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so\n * non-integers, negative lengths, and oversize requests surface backend/runtime errors.\n * @returns Random byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error}\n * @example\n * Generates a fresh nonce or key.\n *\n * ```ts\n * randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Validate upfront so fractional / coercible lengths do not silently\n // truncate through Uint8Array().\n anumber(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 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 const { nonceLength } = fn;\n anumber(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);\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);\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 return res;\n}\n//# sourceMappingURL=utils.js.map","/**\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, anumber, aoutput, 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 // Keep `carry + byte <= 0xffffffff` so the `| 0` / `>>> 8` path below\n // never truncates a real carry bit.\n if (!Number.isSafeInteger(carry) || 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 // Fill block (empty, ctr=0)\n let { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\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 incBytes(ctr, false, 1); // Full 128 bit counter with wrap around\n ({ s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3])));\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 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 // Fill block (empty, ctr=0)\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n let { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\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 ({ s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3])));\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\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) {\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('aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE);\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('aec/(cbc-ecb): unpadded plaintext with disabled padding');\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 dst = getOutput(outLen, dst);\n complexOverlapBytes(plaintext, dst);\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 b = u32(plaintext);\n swap32IfBE(b);\n const o = u32(dst);\n return { b, 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('aes/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 if (!valid)\n throw new Error('aes/pkcs7: wrong padding');\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 { b, o, out: _out } = validateBlockEncrypt(plaintext, pkcs5, dst);\n const xk = expandKeyLE(key);\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 }\n swap32IfBE(o);\n clean(xk);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n dst = getOutput(ciphertext.length, dst);\n const toClean = [xk];\n complexOverlapBytes(ciphertext, dst);\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 * @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 const xk = expandKeyLE(key);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pkcs5, dst);\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 }\n swap32IfBE(o);\n clean(...toClean);\n return _out;\n },\n decrypt(ciphertext, dst) {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\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 dst = getOutput(ciphertext.length, dst);\n complexOverlapBytes(ciphertext, dst);\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 // 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 swap32IfBE(dst32);\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 cipher = gcm(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const gcm = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, 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 ghash 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 cipher = gcmsiv(key, nonce);\n * cipher.encrypt(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport const gcmsiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, 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(...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 in AESKW, use AESKWP instead');\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 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 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 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 resets the counter, but does not make the\n // instance unusable: later calls continue from the zeroed state.\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 }\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 if (carry) {\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 block[BLOCK_SIZE - 1] ^= 0x87;\n }\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: len(B) must be less than or equal to 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 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 // 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 process(data) {\n // RFC 4493 §2.4 step 6 loop body: Y := X XOR M_i; X := AES-128(K, Y).\n xorBlock(this.x, data);\n encryptBlock(this.xk, this.x);\n }\n update(data) {\n if (this.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (this.finished)\n throw new Error('Hash#digest() has already been called');\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);\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.subarray(pos, pos + BLOCK_SIZE));\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 if (this.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (this.finished)\n throw new Error('Hash#digest() has already been called');\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 aoutput(out, this, true);\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: number of input strings must be less than or equal to 127');\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 }, 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\" number of elements must be less than or equal to 126');\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 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//# sourceMappingURL=aes.js.map","/**\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 instance of class which extends utils.Hash');\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 } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\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//# sourceMappingURL=hmac.js.map","/**\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 start and end 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('iterations (c) 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 password = kdfInputToBytes(_password, 'password');\n const salt = kdfInputToBytes(_salt, 'salt');\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n // Cache PRF(P, S || ...) prefix state so each block only appends INT_32_BE(i).\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\nfunction pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {\n // Shared sync/async cleanup point: wipe transient PRF state\n // while preserving the derived key buffer.\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW)\n prfW.destroy();\n clean(u);\n return DK;\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, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.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 + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\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 */\nexport async function pbkdf2Async(hash, password, salt, opts) {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.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 + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n//# sourceMappingURL=pbkdf2.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 {@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 constructor(outputLen) {\n super(64, outputLen, 8, false);\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 // 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 // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n A = SHA224_IV[0] | 0;\n B = SHA224_IV[1] | 0;\n C = SHA224_IV[2] | 0;\n D = SHA224_IV[3] | 0;\n E = SHA224_IV[4] | 0;\n F = SHA224_IV[5] | 0;\n G = SHA224_IV[6] | 0;\n H = SHA224_IV[7] | 0;\n constructor() {\n super(28);\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 constructor(outputLen) {\n super(128, outputLen, 16, false);\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 // 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 Ah = SHA512_IV[0] | 0;\n Al = SHA512_IV[1] | 0;\n Bh = SHA512_IV[2] | 0;\n Bl = SHA512_IV[3] | 0;\n Ch = SHA512_IV[4] | 0;\n Cl = SHA512_IV[5] | 0;\n Dh = SHA512_IV[6] | 0;\n Dl = SHA512_IV[7] | 0;\n Eh = SHA512_IV[8] | 0;\n El = SHA512_IV[9] | 0;\n Fh = SHA512_IV[10] | 0;\n Fl = SHA512_IV[11] | 0;\n Gh = SHA512_IV[12] | 0;\n Gl = SHA512_IV[13] | 0;\n Hh = SHA512_IV[14] | 0;\n Hl = SHA512_IV[15] | 0;\n constructor() {\n super(64);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n Ah = SHA384_IV[0] | 0;\n Al = SHA384_IV[1] | 0;\n Bh = SHA384_IV[2] | 0;\n Bl = SHA384_IV[3] | 0;\n Ch = SHA384_IV[4] | 0;\n Cl = SHA384_IV[5] | 0;\n Dh = SHA384_IV[6] | 0;\n Dl = SHA384_IV[7] | 0;\n Eh = SHA384_IV[8] | 0;\n El = SHA384_IV[9] | 0;\n Fh = SHA384_IV[10] | 0;\n Fl = SHA384_IV[11] | 0;\n Gh = SHA384_IV[12] | 0;\n Gl = SHA384_IV[13] | 0;\n Hh = SHA384_IV[14] | 0;\n Hl = SHA384_IV[15] | 0;\n constructor() {\n super(48);\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 Ah = T224_IV[0] | 0;\n Al = T224_IV[1] | 0;\n Bh = T224_IV[2] | 0;\n Bl = T224_IV[3] | 0;\n Ch = T224_IV[4] | 0;\n Cl = T224_IV[5] | 0;\n Dh = T224_IV[6] | 0;\n Dl = T224_IV[7] | 0;\n Eh = T224_IV[8] | 0;\n El = T224_IV[9] | 0;\n Fh = T224_IV[10] | 0;\n Fl = T224_IV[11] | 0;\n Gh = T224_IV[12] | 0;\n Gl = T224_IV[13] | 0;\n Hh = T224_IV[14] | 0;\n Hl = T224_IV[15] | 0;\n constructor() {\n super(28);\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 Ah = T256_IV[0] | 0;\n Al = T256_IV[1] | 0;\n Bh = T256_IV[2] | 0;\n Bl = T256_IV[3] | 0;\n Ch = T256_IV[4] | 0;\n Cl = T256_IV[5] | 0;\n Dh = T256_IV[6] | 0;\n Dl = T256_IV[7] | 0;\n Eh = T256_IV[8] | 0;\n El = T256_IV[9] | 0;\n Fh = T256_IV[10] | 0;\n Fl = T256_IV[11] | 0;\n Gh = T256_IV[12] | 0;\n Gl = T256_IV[13] | 0;\n Hh = T256_IV[14] | 0;\n Hl = T256_IV[15] | 0;\n constructor() {\n super(32);\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 * @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 * @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 * @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 * @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 * @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 * @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//# sourceMappingURL=sha2.js.map","/**\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// Common prologue and epilogue for sync/async functions\nfunction scryptInit(password, salt, _opts) {\n // Maxmem - 1GB+1KB by default\n const opts = checkOpts({\n dkLen: 32,\n asyncTick: 10,\n maxmem: 1024 ** 3 + 1024,\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('progressCb must be a function');\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 onProgress(blockMixCnt / totalBlockMix);\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 */\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 */\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 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 });\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 });\n }\n swap32IfBE(B32);\n return scryptOutput(password, dkLen, B, V, tmp);\n}\n//# sourceMappingURL=scrypt.js.map","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.slice(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.slice(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.slice(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 finalize the PSBT 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(options?: SignPsbtOptionsLike): 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 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 * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber = anumber_;\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/**\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 const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected boolean, got type=' + typeof value);\n }\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 * @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 RangeError('zero length');\n n = abignumber(n);\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 > len * 2)\n throw new RangeError('number too large');\n return hexToBytes_(hex.padStart(len * 2, '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 * @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// Historical name: this accepts non-negative bigints, including zero.\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= 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 let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\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 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 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) => (_1n << BigInt(n)) - _1n;\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 drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg));\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 * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\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 = {}) {\n if (Object.prototype.toString.call(object) !== '[object Object]')\n throw new TypeError('expected valid options object');\n function checkField(fieldName, expectedType, isOpt) {\n // Config/data fields must be explicit own properties, but runtime objects such as Field\n // instances intentionally satisfy required method slots via their shared prototype.\n if (!isOpt && expectedType !== 'function' && !Object.hasOwn(object, fieldName))\n throw new TypeError(`param \"${fieldName}\" is invalid: expected own property`);\n const val = object[fieldName];\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`param \"${fieldName}\" 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//# sourceMappingURL=utils.js.map","/**\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 { abool, abytes, anumber, asafenumber, bitLen, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, validateObject, } 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 _16n = /* @__PURE__ */ BigInt(16);\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 return FpPow(Field(modulo), num, power);\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 (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 - Positive modulus.\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 if (modulo <= _0n)\n throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\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// 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 // 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 if (F.is0(t))\n return F.ZERO; // if t=0 return R=0\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 // 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 const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata leaks through validateObject(type='number') but breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\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 const F = Fp;\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 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/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.\n * @param Fp - Field implementation.\n * @param nums - Values to invert.\n * @param passZero - map 0 to 0 (instead of undefined)\n * @returns Inverted values.\n * @example\n * Invert several field elements with one shared inversion.\n *\n * ```ts\n * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);\n * ```\n */\nexport function FpInvertBatch(Fp, nums, passZero = false) {\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 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 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 field returns an invalid Legendre symbol value. {@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 const F = Fp;\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 bit length (${bits}) >= n.length (${nBitLength})`);\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 FpPow(this, num, power);\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 return FpInvertBatch(this, lst);\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// Freeze the shared method surface too; otherwise callers can still poison every Field instance by\n// monkey-patching `_Field.prototype` even if each instance is frozen.\nObject.freeze(_Field.prototype);\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 return new _Field(ORDER, opts);\n}\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\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 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 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 // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject } from \"../utils.js\";\nimport { Field, FpInvertBatch, validateField } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\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 must be a constructor');\n // validateObject only accepts plain objects, so copy the constructor statics into one bag first.\n validateObject({\n Fp: pc.Fp,\n Fn: pc.Fn,\n fromAffine: pc.fromAffine,\n fromBytes: pc.fromBytes,\n fromHex: pc.fromHex,\n }, {\n Fp: 'object',\n Fn: 'object',\n fromAffine: 'function',\n fromBytes: 'function',\n fromHex: 'function',\n });\n validateField(pc.Fp);\n validateField(pc.Fn);\n}\n/**\n * Computes both candidates first, but the final selection still branches on `condition`, so this\n * is not a strict constant-time CMOV primitive.\n * @param condition - Whether to negate the point.\n * @param item - Point-like value.\n * @returns Original or negated value.\n * @example\n * Keep the point or return its negation based on one boolean branch.\n *\n * ```ts\n * import { negateCt } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const maybeNegated = negateCt(true, p256.Point.BASE);\n * ```\n */\nexport function negateCt(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\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 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) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, scalarBits) {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\nfunction calcOffsets(n, window, wOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero; ignore when isZero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake branch noise only\n const offsetF = offsetStart; // fake branch noise only\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\nfunction validateMSMPoints(points, c) {\n if (!Array.isArray(points))\n throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars, field) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error('invalid scalar at index ' + i);\n });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\nfunction getW(P) {\n // To disable precomputes:\n // return 1;\n // `1` is also the uncached sentinel: use the ladder / non-precomputed path.\n return pointWindowSizes.get(P) || 1;\n}\nfunction assert0(n) {\n // Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop\n // count is inconsistent, not that the original caller provided a bad scalar.\n if (n !== _0n)\n throw new Error('invalid wNAF');\n}\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * TODO: research returning a 2d JS array of windows instead of a single window.\n * This would allow windows to be in different memory locations.\n * @param Point - Point constructor.\n * @param bits - Scalar bit length.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { wNAF } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);\n * ```\n */\nexport class wNAF {\n BASE;\n ZERO;\n Fn;\n bits;\n // Parametrized with a given Point class (not individual point)\n constructor(Point, bits) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n // non-const time multiplication ladder\n _unsafeLadder(elm, n, p = this.ZERO) {\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point - Point instance\n * @param W - window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(point, W) {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points = [];\n let p = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n))\n throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n }\n else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points so JIT keeps the noise path alive.\n // Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not,\n // which weakens the noise path and leaves this only \"less const-time\" by about one bigint mul.\n return { p, f };\n }\n /**\n * Implements unsafe EC multiplication using precomputed tables\n * and w-ary non-adjacent form.\n * @param acc - accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n)\n break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n }\n else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n getPrecomputes(W, point, transform) {\n // Cache key is only point identity plus the remembered window size; callers must not reuse the\n // same point with incompatible `transform(...)` layouts and expect a separate cache entry.\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W);\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function')\n comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n cached(point, scalar, transform) {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n unsafe(point, scalar, transform, prev) {\n const W = getW(point);\n if (W === 1)\n return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P, W) {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n hasCache(elm) {\n return getW(elm) !== 1;\n }\n}\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n * @param Point - Point constructor.\n * @param point - Input point.\n * @param k1 - First non-negative absolute scalar chunk.\n * @param k2 - Second non-negative absolute scalar chunk.\n * @returns Partial multiplication results.\n * @example\n * Endomorphism-specific multiplication for Koblitz curves.\n *\n * ```ts\n * import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js';\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);\n * ```\n */\nexport function mulEndoUnsafe(Point, point, k1, k2) {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n p1 = p1.add(acc);\n if (k2 & _1n)\n p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\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 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\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 // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\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 // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.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 * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param windowSize - Precompute window size.\n * @returns Function which multiplies points with scalars. The closure accepts\n * `scalars.length <= points.length`, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function precomputeMSMUnsafe(c, points, windowSize) {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n const fieldN = c.Fn;\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero)\n for (let j = 0; j < windowSize; j++)\n res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr)\n continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\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:\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 (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && 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//# sourceMappingURL=curve.js.map","/**\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 { abignumber, abool, abytes, aInRange, asafenumber, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, hexToBytes, isBytes, numberToHexUnpadded, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, mulEndoUnsafe, negateCt, normalizeZ, wNAF, } from \"./curve.js\";\nimport { FpInvertBatch, FpIsSquare, getMinHashLength, mapHashToField, validateField, } from \"./modular.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 less than half bits of N: otherwise wNAF will fail.\n // 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/**\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/**\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 = {\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 if (typeof data !== 'string')\n throw new TypeError('\"data\" expected string, got type=' + typeof 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.encode: 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) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\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 return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\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};\nObject.freeze(DER._tlv);\nObject.freeze(DER._int);\nObject.freeze(DER);\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 });\n // Snapshot constructor-time flags whose later mutation would otherwise change\n // validity semantics of an already-built point type.\n const { endo, allowInfinityPoint } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\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 // SEC 1 v2.0 §2.3.3 encodes infinity as the single octet 0x00. Only curves\n // that opt into infinity as a public point value should expose that byte form.\n if (allowInfinityPoint && point.is0())\n return Uint8Array.of(0);\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 if (allowInfinityPoint && length === 1 && head === 0x00)\n return { x: Fp.ZERO, y: Fp.ZERO };\n // SEC 1 v2.0 §2.3.4 decodes 0x00 as infinity, but §3.2.2 public-key validation\n // rejects infinity. We therefore keep 0x00 rejected by default because callers\n // reuse this parser as the strict public-key boundary, and only admit it when\n // the curve explicitly opts into infinity as a public point value. secp256k1\n // crosstests show OpenSSL raw point codecs accept 0x00 too.\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 = extraOpts.toBytes === undefined ? pointToBytes : extraOpts.toBytes;\n const decodePoint = extraOpts.fromBytes === undefined ? pointFromBytes : extraOpts.fromBytes;\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * 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); // 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 return 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 function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\n }\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 // base / generator point\n static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static Fp = Fp;\n // scalar field\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 *\n * @param windowSize\n * @param isLazy - true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize = 8, isLazy = true) {\n wnaf.createCache(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 (extraOpts.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 // 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 }\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 { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\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 = Fp.mul(a, 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 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, 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 const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\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 = Fp.mul(a, 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 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, 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 wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar - by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo } = extraOpts;\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 let point, fake; // Fake point is used to const-time mult\n const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n }\n else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\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 { endo } = extraOpts;\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; // 0\n if (sc === _1n)\n return p; // 1\n if (wnaf.hasCache(this))\n return this.multiply(sc); // precomputes\n // We don't have method for double scalar multiplication (aP + bQ):\n // Even with using Strauss-Shamir trick, it's 35% slower than naïve mul+add.\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n }\n else {\n return wnaf.unsafe(p, sc);\n }\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 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 const { isTorsionFree } = extraOpts;\n if (cofactor === _1n)\n return true;\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n clearCofactor() {\n const { clearCofactor } = extraOpts;\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 // Same policy as pointFromBytes(): keep ZERO out of the default byte surface because\n // callers use these encodings as public keys, where SEC 1 validation rejects infinity.\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 bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n // Tiny toy curves can have scalar fields narrower than 8 bits. Skip the\n // eager W=8 cache there instead of rejecting an otherwise valid constructor.\n if (bits >= 8)\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\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}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * RFC 9380 expects callers to provide `v != 0`; this helper does not enforce it.\n * @param Fp - Field implementation.\n * @param Z - Simplified SWU map parameter.\n * @returns Square-root ratio helper.\n * @example\n * Build the square-root ratio helper used by SWU map implementations.\n *\n * ```ts\n * import { SWUFpSqrtRatio } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrtRatio = SWUFpSqrtRatio(Fp, 3n);\n * const out = sqrtRatio(4n, 1n);\n * ```\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Fail with the usual field-shape error before touching pow/cmov on malformed field shims.\n const F = validateField(Fp);\n // Generic implementation\n const q = F.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = F.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = F.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) only for v != 0.\n // We keep v=0 on the regular result path with isValid=false instead of\n // throwing so the helper stays closer to the RFC's fixed control flow.\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = F.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = F.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = F.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = F.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = F.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = F.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = F.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = F.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = F.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = F.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = F.eql(tv5, F.ONE); // 12. isQR = tv5 == 1\n tv2 = F.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = F.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = F.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = F.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = F.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = F.eql(tvv5, F.ONE); // 21. e1 = tv5 == 1\n tv2 = F.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = F.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = F.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = F.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = F.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) for v != 0.\n // When u = 0 and v != 0, u / v = 0 is square and the computed root is\n // still 0, so widen only the final flag and keep the full control flow.\n return { isValid: !F.is0(v) && (isQR || F.is0(u)), value: tv3 };\n };\n if (F.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (F.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = F.sqrt(F.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = F.sqr(v); // 1. tv1 = v^2\n const tv2 = F.mul(u, v); // 2. tv2 = u * v\n tv1 = F.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = F.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = F.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = F.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = F.mul(F.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = F.eql(tv3, u); // 9. isQR = tv3 == u\n let y = F.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: !F.is0(v) && isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 | RFC 9380 section 6.6.2}.\n * @param Fp - Field implementation.\n * @param opts - SWU parameters:\n * - `A`: Curve parameter `A`.\n * - `B`: Curve parameter `B`.\n * - `Z`: Simplified SWU map parameter.\n * @returns Deterministic map-to-curve function.\n * @throws If the SWU parameters are invalid or the field lacks the required helpers. {@link Error}\n * @example\n * Map one field element to a Weierstrass curve point with the SWU recipe.\n *\n * ```ts\n * import { mapToCurveSimpleSWU } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const map = mapToCurveSimpleSWU(Fp, { A: 1n, B: 2n, Z: 3n });\n * const point = map(5n);\n * ```\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n const F = validateField(Fp);\n const { A, B, Z } = opts;\n if (!F.isValidNot0(A) || !F.isValidNot0(B) || !F.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n // RFC 9380 §6.6.2 and Appendix H.2 require:\n // 1. Z is non-square in F\n // 2. Z != -1 in F\n // 3. g(x) - Z is irreducible over F\n // 4. g(B / (Z * A)) is square in F\n // We can enforce 1, 2, and 4 with the current field API.\n // Criterion 3 is not checked here because generic `IField<T>` does not expose\n // polynomial-ring / irreducibility operations, and this helper is used for\n // both prime and extension fields.\n if (F.eql(Z, F.neg(F.ONE)) || FpIsSquare(F, Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n // RFC 9380 Appendix H.2 criterion 4: g(B / (Z * A)) is square in F.\n // x = B / (Z * A)\n const x = F.mul(B, F.inv(F.mul(Z, A)));\n // g(x) = x^3 + A*x + B\n const gx = F.add(F.add(F.mul(F.sqr(x), x), F.mul(A, x)), B);\n if (!FpIsSquare(F, gx))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(F, Z);\n if (!F.isOdd)\n throw new Error('Field does not have .isOdd()');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = F.sqr(u); // 1. tv1 = u^2\n tv1 = F.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = F.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = F.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = F.add(tv2, F.ONE); // 5. tv3 = tv2 + 1\n tv3 = F.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = F.cmov(Z, F.neg(tv2), !F.eql(tv2, F.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = F.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = F.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = F.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = F.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = F.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = F.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = F.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = F.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = F.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = F.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = F.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = F.mul(y, value); // 20. y = y * y1\n x = F.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = F.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = F.isOdd(u) === F.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = F.cmov(F.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(F, [tv4], true)[0];\n x = F.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\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 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 return !!Point.fromBytes(publicKey);\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 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 // 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 ecdsaOpts = Object.assign({}, ecdsaOpts);\n const randomBytes = ecdsaOpts.randomBytes === undefined ? wcRandomBytes : ecdsaOpts.randomBytes;\n const hmac = ecdsaOpts.hmac === undefined\n ? (key, msg) => nobleHmac(hash_, key, msg)\n : ecdsaOpts.hmac;\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts = {\n prehash: true,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.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 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 const { r, s } = DER.toSig(abytes(bytes));\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.multiplyUnsafe(u1).add(R.multiplyUnsafe(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 = ecdsaOpts.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 : ecdsaOpts.bits2int;\n const bits2int_modN = ecdsaOpts.bits2int_modN === undefined\n ? function bits2int_modN_def(bytes) {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n }\n : ecdsaOpts.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 // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\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 ik = Fn.inv(k); // k^-1 mod n\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 const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // 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 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.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P\n if (R.is0())\n return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\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 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//# sourceMappingURL=weierstrass.js.map","/**\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 } from \"./abstract/hash-to-curve.js\";\nimport { Field, mapHashToField, pow2 } from \"./abstract/modular.js\";\nimport { ecdsa, mapToCurveSimpleSWU, weierstrass, } from \"./abstract/weierstrass.js\";\nimport { abytes, asciiToBytes, bytesToNumberBE, concatBytes, } 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 = 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 = {};\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 hasEven = (y) => y % _2n === _0n;\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(priv);\n const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: pointToBytes(p) };\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.create(x * x);\n const c = Fp.create(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 const m = 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 k = hasEven(p.y) ? k_ : Fn.neg(k_);\n const rx = pointToBytes(p);\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 r = num(sig.subarray(0, 32)); // 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(Fn.toBytes(r), pointToBytes(P), m);\n // R = s⋅G - e⋅P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\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) || 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 });\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(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(PK, nonces) {\n if (hasEven(PK.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 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//# sourceMappingURL=secp256k1.js.map","/**\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 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 * @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/** 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 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, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\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 s = [5, 9, 14, 20];\n }\n else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n }\n else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\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 * @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 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 * @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//# sourceMappingURL=legacy.js.map","/**\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).slice(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\").slice(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.slice(1), signature.slice(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.slice(64), signatureBytes.slice(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.slice(64), signatureBytes.slice(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 */\nexport type NetworkPreference = {\n addressPrefix: string;\n signerType: SignerType;\n /**\n * Wallet signers should check if the wallet is using preferred networks.\n * If not, try to switch to the first preferred network.\n * If non preferred, let users choose what they want.\n * BTC: // They made a mess...\n * btc\n * btcTestnet\n * btcTestnet4 // UTXO Global\n * btcSignet // OKX & UTXO Global\n * fractalBtc // UniSat\n */\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 // Returns the preference if we need to switch network\n // undefined otherwise\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.setWitnessArgsAt(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 { 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 =\n tx.getWitnessArgsAt(info.position) ?? WitnessArgs.from({});\n witness.lock = signature;\n tx.setWitnessArgsAt(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.getWitnessArgsAt(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.getWitnessArgsAt(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.setWitnessArgsAt(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.getWitnessArgsAt(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.setWitnessArgsAt(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()).slice(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.setWitnessArgsAt(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.slice(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.setWitnessArgsAt(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.setWitnessArgsAt(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","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.setWitnessArgsAt(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/index.js\";\n"],"x_google_ignoreList":[0,12,13,14,15,16,17,20,21,22,23,24,25,26,27,28,29,30,31,32,33],"mappings":"+JAmBA,MAAMA,EAAM,OAAO,CAAC,EACdC,EAAM,OAAO,CAAC,EACdC,EAAM,OAAO,CAAC,EACdC,EAAM,OAAO,CAAC,EACd,EAAQ,OAAO,GAAG,EAGlB,EAAS,OAAO,GAAI,EACpB,EAAU,CAAC,EACX,EAAY,CAAC,EACb,EAAa,CAAC,EACpB,IAAK,IAAI,EAAQ,EAAG,EAAIF,EAAK,EAAI,EAAG,EAAI,EAAG,EAAQ,GAAI,IAAS,CAE5D,CAAC,EAAG,GAAK,CAAC,GAAI,EAAI,EAAI,EAAI,GAAK,CAAC,EAChC,EAAQ,KAAK,GAAK,EAAI,EAAI,EAAE,EAE5B,EAAU,MAAQ,EAAQ,IAAM,EAAQ,GAAM,EAAK,EAAE,EAErD,IAAI,EAAID,EACR,IAAK,IAAI,EAAI,EAAG,EAAI,EAAG,IACnB,GAAM,GAAKC,GAAS,GAAKE,GAAO,GAAW,EACvC,EAAID,IACJ,GAAKD,IAASA,GAAO,OAAO,CAAC,GAAKA,GAE1C,EAAW,KAAK,CAAC,CACrB,CACA,MAAM,EAAQG,EAAAA,GAAM,EAAY,EAAI,EAI9B,EAAc,EAAM,GACpB,EAAc,EAAM,GAEpB,GAAS,EAAG,EAAG,IAAO,EAAI,GAAKC,EAAAA,GAAO,EAAG,EAAG,CAAC,EAAIC,EAAAA,GAAO,EAAG,EAAG,CAAC,EAC/D,GAAS,EAAG,EAAG,IAAO,EAAI,GAAKC,EAAAA,GAAO,EAAG,EAAG,CAAC,EAAIC,EAAAA,GAAO,EAAG,EAAG,CAAC,EAarE,SAAgB,EAAQ,EA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