@qntx/wallet-chains 0.0.0-stage → 0.4.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bitcoin.mjs","names":["isRecord","isRecord"],"sources":["../src/bitcoin/psbt.ts","../src/bitcoin/account.ts","../src/bitcoin/decode.ts","../../../node_modules/.bun/@scure+base@2.4.0/node_modules/@scure/base/index.js","../src/bitcoin/verify.ts","../src/bitcoin/index.ts"],"sourcesContent":["import { Transaction, getInputType } from \"@scure/btc-signer/transaction.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\n/**\n * BIP-32 derivation paths carry a coin type: 0 for mainnet, 1 for every test network. This is what\n * binds PSBT metadata to the requested network — the raw output scripts themselves carry no network\n * marker.\n */\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Bip32Derivation values are [pubkey, { fingerprint, path }] tuples; tapBip32Derivation values are\n * { hashes, der: { fingerprint, path } }.\n */\nconst derivationPaths = (map: unknown): ReadonlyArray<ReadonlyArray<number>> => {\n const entries =\n map instanceof Map\n ? [...map.values()]\n : Array.isArray(map)\n ? map\n : isRecord(map)\n ? Object.values(map)\n : [];\n const paths: number[][] = [];\n for (const entry of entries) {\n const value: unknown = Array.isArray(entry) ? entry[1] : entry;\n if (!isRecord(value)) {\n continue;\n }\n const der = isRecord(value[\"der\"]) ? value[\"der\"] : value;\n const { path } = der;\n if (Array.isArray(path) && path.every((p) => typeof p === \"number\")) {\n paths.push(path);\n }\n }\n return paths;\n};\n\nconst checkPaths = (\n paths: ReadonlyArray<ReadonlyArray<number>>,\n where: string,\n coinType: number,\n): void => {\n for (const path of paths) {\n if (path.length >= 2 && (path[1] ?? -1) - 0x80000000 !== coinType) {\n throw new ChainError(\n \"chain-id-mismatch\",\n `${where} derivation coin type is not this network's`,\n );\n }\n }\n};\n\nconst checkDerivations = (tx: Transaction, coinType: number): void => {\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n checkPaths(derivationPaths(input.bip32Derivation), `input ${i}`, coinType);\n checkPaths(derivationPaths(input.tapBip32Derivation), `input ${i}`, coinType);\n }\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n checkPaths(derivationPaths(output.bip32Derivation), `output ${i}`, coinType);\n checkPaths(derivationPaths(output.tapBip32Derivation), `output ${i}`, coinType);\n }\n};\n\nconst DEFAULT_SIGHASH = 0;\nconst SIGHASH_ALL = 1;\n\nconst isTaprootInput = (input: ReturnType<Transaction[\"getInput\"]>): boolean =>\n input.tapInternalKey !== undefined || getInputType(input).type === \"taproot\";\n\n/**\n * Validates and canonicalizes a bitcoin.psbt request (network already checked by the caller).\n * `strictPrevoutValidation` makes btc-signer verify every `nonWitnessUtxo`'s txid against its\n * outpoint.\n */\nexport const normalizeBitcoinPsbt = (\n psbt: Uint8Array,\n sign: unknown,\n network: string,\n): { psbt: Uint8Array; sign: ReadonlyArray<number> } => {\n const net = bitcoinNetwork(network);\n let tx: Transaction;\n try {\n tx = Transaction.fromPSBT(psbt, { strictPrevoutValidation: true });\n } catch {\n throw new ChainError(\"invalid-request\", \"PSBT failed to decode\");\n }\n if (\n !Array.isArray(sign) ||\n sign.length === 0 ||\n !sign.every((i) => Number.isSafeInteger(i) && i >= 0)\n ) {\n throw new ChainError(\"invalid-request\", \"sign must be a non-empty array of input indices\");\n }\n const unique = [...new Set(sign.map(Number))].sort((a, b) => a - b);\n const last = unique.at(-1);\n if (unique.length !== sign.length || last === undefined || last >= tx.inputsLength) {\n throw new ChainError(\"invalid-request\", \"sign must be unique, ascending, and in range\");\n }\n checkDerivations(tx, net.coinType);\n for (const idx of unique) {\n const input = tx.getInput(idx);\n if (input.witnessUtxo === undefined) {\n throw new ChainError(\"invalid-request\", `input ${idx} is missing witnessUtxo`);\n }\n if (input.bip32Derivation === undefined && input.tapBip32Derivation === undefined) {\n throw new ChainError(\"invalid-request\", `input ${idx} is missing a bip32 derivation`);\n }\n const { type } = getInputType(input);\n if ((type === \"legacy\" || type === \"nonwitness-script\") && input.nonWitnessUtxo === undefined) {\n throw new ChainError(\"invalid-request\", `input ${idx} is missing nonWitnessUtxo`);\n }\n const sighash = input.sighashType;\n const allowed =\n sighash === undefined ||\n sighash === SIGHASH_ALL ||\n (isTaprootInput(input) && sighash === DEFAULT_SIGHASH);\n if (!allowed) {\n throw new ChainError(\"unsupported\", `input ${idx} uses a non-default sighash`);\n }\n }\n return { psbt: tx.toPSBT(0), sign: unique };\n};\n","/** Public-derivation helpers for account-level extended keys — no secrets involved. */\nimport { HDKey } from \"@scure/bip32\";\nimport { p2tr, p2wpkh } from \"@scure/btc-signer/payment.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nexport type BitcoinAccountTemplate = \"btc.bip84\" | \"btc.bip86\";\n\n/**\n * Derive the address at `change`/`index` under an account-level xpub (`m/84'/c'/i'` or\n * `m/86'/c'/i'`) — P2WPKH for `btc.bip84`, P2TR key-path for `btc.bip86`.\n */\nexport function bitcoinAddressFromXpub(\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n change: 0 | 1,\n index: number,\n): string {\n if (!Number.isInteger(index) || index < 0) {\n throw new ChainError(\"invalid-request\", \"index must be a non-negative integer\");\n }\n const net = bitcoinNetwork(network);\n let node: HDKey;\n try {\n node = HDKey.fromExtendedKey(xpub, net.bip32);\n } catch (error) {\n throw new ChainError(\n \"invalid-request\",\n `xpub: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const child = node.derive(`m/${change}/${index}`);\n const pub = child.publicKey;\n if (pub === null) {\n throw new ChainError(\"invalid-request\", \"xpub carries no public key\");\n }\n const address =\n template === \"btc.bip84\"\n ? p2wpkh(pub, net.params).address\n : p2tr(pub.subarray(1), undefined, net.params).address;\n if (address === undefined) {\n throw new ChainError(\"invalid-request\", \"could not encode the derived address\");\n }\n return address;\n}\n","import { Address, OutScript } from \"@scure/btc-signer/payment.js\";\nimport { Transaction } from \"@scure/btc-signer/transaction.js\";\n\nimport type { AssetFlow, DisplayIntent, SignRequest, Verifiability } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst SATS = \"sats\";\nconst OP_RETURN = 0x6a;\n\nconst bytesToHex = (bytes: Uint8Array): string => {\n let out = \"\";\n for (const b of bytes) {\n out += b.toString(16).padStart(2, \"0\");\n }\n return out;\n};\n\ntype DecodedOutput = {\n readonly amount: bigint;\n readonly script: string;\n readonly opReturn: boolean;\n};\n\n/** Decodes an output scriptPubKey; OP_RETURN gets an amount-0 display row. */\nconst decodeOutput = (script: Uint8Array, amount: bigint): DecodedOutput => {\n const hex = bytesToHex(script);\n if (script[0] === OP_RETURN) {\n return { amount, script: hex, opReturn: true };\n }\n return { amount, script: hex, opReturn: false };\n};\n\nexport type BitcoinDisplay = {\n readonly intent: DisplayIntent;\n};\n\n/**\n * Decodes a normalized bitcoin.psbt request for display. `ownScripts` is the set of output script\n * hexes the caller has independently verified as this account's (e.g. the kernel re-deriving\n * change) — not a display hint.\n */\nexport const decodeBitcoinPsbt = (\n request: Extract<SignRequest, { kind: \"bitcoin.psbt\" }>,\n ownScripts: ReadonlySet<string> = new Set(),\n): DisplayIntent => {\n const tx = Transaction.fromPSBT(request.psbt);\n const coder = Address(bitcoinNetwork(request.network).params);\n const signed = new Set(request.sign);\n const outflows: AssetFlow[] = [];\n let canFee = true;\n let outSum = 0n;\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n const { script } = output;\n const { amount } = output;\n if (script === undefined || amount === undefined) {\n continue;\n }\n const decoded = decodeOutput(script, amount);\n outSum += amount;\n if (decoded.opReturn || ownScripts.has(decoded.script)) {\n continue;\n }\n let addr: string | undefined;\n try {\n const out = OutScript.decode(script);\n addr = out === undefined ? undefined : coder.encode(out);\n } catch {\n addr = undefined;\n }\n outflows.push({\n to: addr ?? decoded.script,\n amount: { asset: SATS, amount: amount.toString(10) },\n verified: addr !== undefined,\n });\n }\n let inSum = 0n;\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n if (input.witnessUtxo === undefined) {\n canFee = false;\n } else {\n inSum += input.witnessUtxo.amount;\n }\n }\n const external = tx.inputsLength - signed.size > 0;\n const undecodable = outflows.some((o) => !o.verified);\n const verifiability: Verifiability = external ? \"opaque\" : undecodable ? \"partial\" : \"full\";\n return {\n family: \"bitcoin\",\n network: request.network,\n summary: outflows.length > 0 ? \"transfer\" : \"contract-call\",\n outflows,\n approvals: [],\n fee: canFee ? { max: { asset: SATS, amount: (inSum - outSum).toString(10) } } : undefined,\n warnings: [],\n verifiability,\n };\n};\n\nexport const verifiabilityBitcoin = (\n request: Extract<SignRequest, { kind: \"bitcoin.psbt\" }>,\n ownScripts: ReadonlySet<string> = new Set(),\n): Verifiability => decodeBitcoinPsbt(request, ownScripts).verifiability;\n","/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Freeze the result of a thunk. `/* @__PURE__ */ freeze(() => expr)` keeps the whole\n// initializer tree-shakable: the annotated call's only argument is a function literal,\n// so bundlers drop everything (inner chain()/alphabet() calls included) when unused.\nconst freeze = (fn) => Object.freeze(fn());\nfunction isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The\n // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized\n // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the\n // 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/** Asserts something is Uint8Array. */\nfunction abytes(b) {\n if (!isBytes(b))\n throw new TypeError('Uint8Array expected');\n}\nfunction isArrayOf(isString, arr) {\n if (!Array.isArray(arr))\n return false;\n if (arr.length === 0)\n return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n }\n else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\nfunction afn(input) {\n if (typeof input !== 'function')\n throw new TypeError('function expected');\n return true;\n}\nfunction astr(label, input) {\n if (typeof input !== 'string')\n throw new TypeError(`${label}: string expected`);\n return true;\n}\nfunction anumber(n, title = 'number') {\n if (typeof n !== 'number')\n throw new TypeError(`${title}: expected number, got ${typeof n}`);\n if (!Number.isSafeInteger(n))\n throw new RangeError(`${title}: expected safe integer, got ${n}`);\n}\nfunction anumArr(label, input) {\n if (!isArrayOf(false, input))\n throw new TypeError(`${label}: array of numbers expected`);\n}\nfunction chain(...args) {\n const id = (a) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a, b) => (c) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\nfunction normalize(fn) {\n afn(fn);\n return { encode: (from) => from, decode: (to) => fn(to) };\n}\nconst powers = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++)\n res.push(2 ** i);\n return res;\n})();\n// Indexed copy loops instead of Array.from / Uint8Array.from: those go through the\n// iterator protocol on typed arrays, which is ~10x slower and would swamp the fast\n// links' gains on the conversion boundaries.\nfunction u8ToNumArr(u8, len = u8.length) {\n const res = new Array(len);\n for (let i = 0; i < len; i++)\n res[i] = u8[i];\n return res;\n}\n// UTF-8 TextDecoder builds a string from ASCII codes 2x faster than `TextDecoder('latin1')`\n// (4x on freshly allocated, our exact case).\n// All codes here are < 128 (range is validated elsewhere): UTF-8 agrees with ASCII byte-for-byte.\n// UTF-8 needs no ICU, so the probe only guards runtimes without TextDecoder at all (Hermes).\nconst asciiDecoder = /* @__PURE__ */ (() => {\n try {\n const decoder = new TextDecoder();\n // Self-check on the domain we use (codes < 128): reject broken polyfills at\n // probe time instead of producing corrupted codec output later.\n return decoder.decode(Uint8Array.of(0x41, 0x30, 0x2b, 0x7f)) === 'A0+\\x7f'\n ? decoder\n : undefined;\n }\n catch (e) {\n return undefined;\n }\n})();\nconst B2S_CHUNK = 8192; // char codes per String.fromCharCode call, avoids arg-count limits\nfunction charcodesToString(codes) {\n const len = codes.length;\n // Measured crossover: the TextDecoder's per-call setup dominates below ~12 chars,\n // where String.fromCharCode wins (bech32 checksums, base58xmr blocks).\n if (asciiDecoder !== undefined && len >= 12)\n return asciiDecoder.decode(codes);\n if (len <= B2S_CHUNK)\n return String.fromCharCode.apply(null, codes);\n let res = '';\n for (let i = 0; i < len; i += B2S_CHUNK)\n res += String.fromCharCode.apply(null, codes.subarray(i, i + B2S_CHUNK));\n return res;\n}\n/**\n * Linear 8 <-> bits regrouping (radix2Slow semantics), with Uint8Array digits and\n * preallocated output.\n */\nfunction radix2(bits) {\n anumber(bits);\n if (bits <= 0 || bits > 8)\n throw new RangeError('radix2: bits should be in (0..8]');\n const mask = powers[bits] - 1;\n return {\n encode: (bytes) => {\n abytes(bytes);\n const len = bytes.length;\n // 8->bits with zero-bit padding of the last digit, like convertRadix2(padding=true)\n const res = new Uint8Array(Math.ceil((len * 8) / bits));\n let carry = 0;\n let pos = 0;\n let j = 0;\n for (let i = 0; i < len;) {\n // At most 7 residual bits plus 24 new bits fit in the signed 32-bit carry.\n if (i + 2 < len) {\n carry = (carry << 24) | (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n pos += 24;\n i += 3;\n }\n else {\n // Constant mask instead of convertRadix2's exact powers[pos]-1 cleanup: with\n // bits <= 8 the residual is pos <= 7 bits, so carry needs at most pos + 8 <= 15\n // meaningful bits. Stale bits in [pos, 16) shift to >= bits on extraction and\n // are removed by `& mask` there and in the tail below.\n carry = ((carry << 8) | bytes[i]) & 0xffff;\n pos += 8;\n i++;\n }\n // Each input adds at least `bits`, so the first extraction is unconditional.\n for (;;) {\n pos -= bits;\n res[j++] = (carry >> pos) & mask;\n if (pos < bits)\n break;\n }\n }\n if (pos > 0)\n res[j] = (carry << (bits - pos)) & mask;\n return res;\n },\n decode: (digits) => {\n // bits->8, strict canonical form, like convertRadix2(padding=false):\n // rejects leftover whole input words and non-zero pad bits.\n const len = digits.length;\n const res = new Uint8Array(Math.floor((len * bits) / 8));\n let carry = 0;\n let pos = 0;\n let j = 0;\n for (let i = 0; i < len; i++) {\n // Same constant-mask carry bound as encode: pos <= 7 residual plus bits <= 8\n // incoming keeps meaningful carry within 15 bits; stale bits above pos are\n // masked out on extraction and in the tail check below.\n carry = ((carry << bits) | digits[i]) & 0xffff;\n pos += bits;\n for (; pos >= 8; pos -= 8)\n res[j++] = (carry >> (pos - 8)) & 0xff;\n }\n carry = (carry << (8 - pos)) & 0xff;\n if (pos >= bits)\n throw new Error('Excess padding');\n if (carry > 0)\n throw new Error(`Non-zero padding: ${carry}`);\n return res;\n },\n };\n}\n/**\n * Digit <-> letter mapping fused with string join (chain(alphabetSlow(letters), join(''))\n * semantics), via char-code lookup tables.\n */\nfunction alphabet(letters, aliases) {\n const len = letters.length;\n // Larger indexes would wrap in the Int8Array reverse table and decode to wrong digits.\n if (len > 128)\n throw new Error('alphabet: max 128 letters');\n const encTable = new Uint8Array(len);\n const decTable = new Int8Array(128).fill(-1);\n for (let i = 0; i < len; i++) {\n const code = letters.charCodeAt(i);\n if (letters.codePointAt(i) !== code || code > 127)\n throw new Error('alphabet: single-char ASCII letters only');\n encTable[i] = code;\n decTable[code] = i;\n }\n // Aliases decode like their canonical letter (e.g. hex case-folding), without a\n // separate normalization pass over the input string.\n if (aliases !== undefined) {\n for (const alias of Object.keys(aliases)) {\n const code = alias.charCodeAt(0);\n const target = decTable[aliases[alias].charCodeAt(0)];\n if (alias.length !== 1 || code > 127 || target === undefined || target === -1)\n throw new Error(`alphabet: invalid alias ${alias}`);\n decTable[code] = target;\n }\n }\n return {\n encode: (digits) => {\n const codes = new Uint8Array(digits.length);\n for (let i = 0; i < digits.length; i++) {\n const d = digits[i];\n const code = encTable[d];\n // Reuse the table lookup's bounds result for the required per-digit range check.\n // Chained radix2 always emits digits < 2**bits === len; check anyway so a\n // mismatched chain throws (like alphabetSlow) instead of silently emitting letter 0.\n if (code === undefined)\n throw new Error(`alphabet.encode: invalid digit ${d}`);\n codes[i] = code;\n }\n return charcodesToString(codes);\n },\n decode: (input) => {\n // Uniform label: this is the decode entry link for nopad codecs, padding for padded\n // ones. Keeps \"decode: string expected\" identical across all built-in codecs\n // (released 2.x said \"join.decode: string expected\").\n astr('decode', input);\n const slen = input.length;\n const digits = new Uint8Array(slen);\n for (let i = 0; i < slen; i++) {\n const code = input.charCodeAt(i);\n const digit = code < 128 ? decTable[code] : -1;\n if (digit === -1)\n throw new Error(`Unknown letter \"${input[i]}\". Allowed: ${letters}`);\n digits[i] = digit;\n }\n return digits;\n },\n };\n}\n/**\n * Pad / unpad (paddingSlow semantics), on the joined string.\n */\nfunction padding(bits, chr = '=') {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data) {\n while ((data.length * bits) % 8)\n data += chr;\n return data;\n },\n decode(input) {\n // Uniform label, see alphabet.decode above.\n astr('decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid length');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const byte = (end - 1) * bits;\n if (byte % 8 === 0)\n throw new Error('padding: excess padding');\n }\n return input.slice(0, end);\n },\n };\n}\nfunction unsafeWrapper(fn) {\n afn(fn);\n return function (...args) {\n // Only for *Unsafe APIs that intentionally collapse validation failures to `undefined`.\n // Do not wrap code that needs to preserve exception details.\n try {\n return fn.apply(null, args);\n }\n catch (e) { }\n };\n}\nfunction checksum(len, fn) {\n anumber(len);\n // Reject degenerate zero-byte checksums up front so callers don't accidentally\n // build a no-op checksum stage.\n if (len <= 0)\n throw new RangeError(`checksum length must be positive: ${len}`);\n afn(fn);\n const _fn = fn;\n // Uses the first `len` bytes of fn(data) in both directions.\n // Current call sites rely on `len > 0` and checksum functions that return at least that many bytes.\n return {\n encode(data) {\n abytes(data);\n const sum = _fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data) {\n abytes(data);\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = _fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i])\n throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n// RFC 4648 aka RFC 3548\n// ---------------------\n/**\n * base16 encoding from RFC 4648.\n * This codec uses RFC 4648 Table 5's uppercase alphabet directly.\n * RFC 4648 §8 calls base16 \"case-insensitive hex encoding\", but we intentionally do not case-fold decode input here.\n * Use `hex` for case-insensitive hex decoding.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16 = /* @__PURE__ */ freeze(() => chain(radix2(4), alphabet('0123456789ABCDEF')));\n/**\n * base32 encoding from RFC 4648. Has padding.\n * RFC 4648 §6 Table 3 uses uppercase letters, and RFC 4648 §3.4 allows applications to choose\n * upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32 = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5)));\n/**\n * base32 encoding from RFC 4648. No padding.\n * This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567')));\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * RFC 4648 §7 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5)));\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV')));\nconst BASE32_CROCKFORD_ASCII = /^[\\x00-\\x7f]*$/;\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}.\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), normalize((s) => {\n astr('base32crockford.decode', s);\n const upper = s.toUpperCase();\n if (s !== upper && !BASE32_CROCKFORD_ASCII.test(s))\n throw new Error('base32crockford.decode: ASCII expected');\n return upper.replace(/O/g, '0').replace(/[IL]/g, '1');\n})));\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// Require both directions before taking the native fast path, so base64/base64url don't mix native and JS behavior.\n// prettier-ignore\nconst hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === 'function' &&\n typeof Uint8Array.fromBase64 === 'function')();\n// Native `Uint8Array.fromBase64()` accepts these ASCII whitespace chars.\n// Reject them first so the native base64 path still follows RFC 4648 §3.3.\n// ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE\nconst ASCII_WHITESPACE = /[\\t\\n\\f\\r ]/;\nconst decodeBase64Builtin = (s, isUrl) => {\n astr('base64', s);\n const alphabet = isUrl ? 'base64url' : 'base64';\n // Per spec, .fromBase64 already throws on any other non-alphabet symbols except ASCII whitespace\n // And checking just for whitespace makes decoding about 3x faster than a full range check.\n // lastChunkHandling: 'strict' rejects loose tails and non-zero pad bits so native decoding stays canonical.\n if (s.length > 0 && ASCII_WHITESPACE.test(s))\n throw new Error('invalid base64');\n return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n/** base64 from RFC 4648. Padded. Pure JS version */\nconst base64Fallback = /* @__PURE__ */ freeze(() => chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6)));\n/** base64url from RFC 4648. Padded. Pure JS version */\nconst base64urlFallback = /* @__PURE__ */ freeze(() => chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6)));\n/**\n * base64 from RFC 4648. Padded.\n * Alternative variants: `base64nopad`, `base64url`, `base64urlnopad`.\n * Utilizes native `Uint8Array.fromBase64` builtin, otherwise falls back to `base64fallback` when it's unavailable.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64 = /* @__PURE__ */ freeze(() => hasBase64Builtin ? {\n encode(b) { abytes(b); return b.toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : base64Fallback);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad = /* @__PURE__ */ freeze(() => chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/')));\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url = /* @__PURE__ */ freeze(() => hasBase64Builtin ? {\n encode(b) { abytes(b); return b.toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : base64urlFallback);\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad = /* @__PURE__ */ freeze(() => chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_')));\n// baseN radix code (base58, base36)\n// ---------------------------------\n// Base conversion 256 <-> BASE done on 16-bit limbs, five baseN digits (one divmod by\n// BASE**5) per pass, ~10x fewer inner-loop iterations than digit-at-a-time conversion.\n// Exactness: every intermediate is a non-negative integer below 2**53, so float64\n// arithmetic (including Math.floor of the quotients) is exact for any GROUP = BASE**5 < 2**30:\n// - encode: carry * 2**16 + limb < BASE**5 * 2**16 < 2**46\n// - decode: limb * BASE**5 + carry < 2**16 * BASE**5 + 2**30 < 2**46\n// Still O(n^2) overall like any positional-base conversion — see the base58 DoS note.\n// GROUP literals (not `BASE ** 5`) so bundlers can drop unused coders as dead code.\nconst B58_GROUP = 656356768; // 58**5 < 2**30\nconst B36_GROUP = 60466176; // 36**5 < 2**26\nconst RADIX_BASE_N_MAX_LENGTH = 65536;\nconst BASE_N_MAX_BYTES = 2048;\nconst BASE_N_MAX_CHARS = 4096;\nconst radixBaseN = (BASE, GROUP) => ({\n encode: (bytes) => {\n abytes(bytes);\n const blen = bytes.length;\n if (blen === 0)\n return new Uint8Array(0);\n if (blen >= RADIX_BASE_N_MAX_LENGTH)\n throw new Error('invalid length');\n // Leading zero bytes map 1:1 to leading zero digits (at most blen-1 explicit zeros;\n // an all-zero value still contributes one digit below).\n let zeros = 0;\n while (zeros < blen - 1 && bytes[zeros] === 0)\n zeros++;\n // Pack big-endian 16-bit limbs; odd length makes the top limb a single byte.\n const nlimbs = Math.ceil(blen / 2);\n const limbs = new Uint16Array(nlimbs);\n const odd = blen & 1;\n if (odd)\n limbs[0] = bytes[0];\n for (let i = odd, j = odd; i < blen; i += 2, j++)\n limbs[j] = (bytes[i] << 8) | bytes[i + 1];\n // Repeated divmod by BASE**5; each pass emits one 5-digit group, least significant\n // first. No carry-overflow guard like convertRadix had: that one faced arbitrary\n // caller-chosen bases, while these bounds are static and proven exact above.\n const groups = [];\n let pos = 0; // limbs before pos are known zero\n while (pos < nlimbs) {\n let carry = 0;\n for (let i = pos; i < nlimbs; i++) {\n const cur = carry * 0x10000 + limbs[i];\n const q = Math.floor(cur / GROUP);\n carry = cur - q * GROUP;\n limbs[i] = q;\n if (q === 0 && i === pos)\n pos++;\n }\n groups.push(carry);\n }\n // The top group is nonzero unless the whole value is zero, so total significant\n // digit count is 5 per full group plus the top group's own width. (Writing 5 digits\n // per group and trimming via subarray is smaller code, but the offset view slows\n // encode ~25% and base58xmr 2x — measured.)\n const top = groups.length - 1;\n let sig = top * 5;\n for (let v = groups[top];; v = Math.floor(v / BASE)) {\n sig++;\n if (v < BASE)\n break;\n }\n const res = new Uint8Array(zeros + sig); // leading zero digits are already 0\n let j = res.length - 1;\n for (let g = 0; g < top; g++) {\n let v = groups[g];\n for (let k = 0; k < 5; k++) {\n res[j--] = v % BASE;\n v = Math.floor(v / BASE);\n }\n }\n for (let v = groups[top]; j >= zeros; v = Math.floor(v / BASE))\n res[j--] = v % BASE;\n return res;\n },\n decode: (digits) => {\n abytes(digits);\n const dlen = digits.length;\n if (dlen === 0)\n return new Uint8Array(0);\n if (dlen >= RADIX_BASE_N_MAX_LENGTH)\n throw new Error('invalid length');\n let zeros = 0;\n while (zeros < dlen - 1 && digits[zeros] === 0)\n zeros++;\n // Multiply-accumulate 16-bit limbs (little-endian, `used` live) group by group,\n // most significant group first; the first group may be shorter than 5 digits, and\n // its BASE**group factor falls out of the digit fold.\n const limbs = new Uint16Array(Math.ceil((dlen * 6) / 16) + 1);\n let used = 0;\n let i = 0;\n let group = dlen % 5 || 5;\n while (i < dlen) {\n let gval = 0;\n let factor = 1;\n for (const end = i + group; i < end; i++) {\n const d = digits[i];\n // Unreachable through the public chain (alphabet emits digits < BASE); guards\n // internal misuse from silently corrupting output.\n if (d >= BASE)\n throw new Error(`invalid integer: ${d}`);\n gval = gval * BASE + d;\n factor *= BASE;\n }\n group = 5;\n let carry = gval;\n for (let k = 0; k < used; k++) {\n const cur = limbs[k] * factor + carry;\n carry = Math.floor(cur / 0x10000);\n limbs[k] = cur - carry * 0x10000;\n }\n for (; carry > 0; carry = Math.floor(carry / 0x10000))\n limbs[used++] = carry % 0x10000;\n }\n // used === 0 means the value is zero: it still contributes one byte, like a lone\n // zero digit does.\n const valueBytes = used === 0 ? 1 : used * 2 - (limbs[used - 1] < 256 ? 1 : 0);\n const res = new Uint8Array(zeros + valueBytes); // leading zero bytes are already 0\n let j = res.length - 1;\n for (let k = 0; k < used; k++) {\n const limb = limbs[k];\n res[j--] = limb & 0xff;\n if (j >= zeros)\n res[j--] = limb >> 8;\n }\n return res;\n },\n});\nconst genBaseN = (radix, abc) => {\n const letters = alphabet(abc);\n return {\n encode(bytes) {\n abytes(bytes);\n if (bytes.length > BASE_N_MAX_BYTES)\n throw new Error('invalid length');\n return letters.encode(radix.encode(bytes));\n },\n decode(str) {\n astr('baseN.decode', str);\n if (str.length > BASE_N_MAX_CHARS)\n throw new Error('invalid length');\n return radix.decode(letters.decode(str));\n },\n };\n};\nconst radix58 = /* @__PURE__ */ radixBaseN(58, B58_GROUP);\n/**\n * base36: lowercase alphanumeric, big-endian positional (multibase `k` payload,\n * used by e.g. IPNS/CID addresses). Leading zero bytes map to leading `0` digits.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * const text = base36.encode(Uint8Array.from([0, 1, 2]));\n * base36.decode(text);\n * // => Uint8Array.from([0, 1, 2])\n * ```\n */\nexport const base36 = /* @__PURE__ */ freeze(() => genBaseN(radixBaseN(36, B36_GROUP), '0123456789abcdefghijklmnopqrstuvwxyz'));\nconst genBase58 = (abc) => genBaseN(radix58, abc);\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * const text = base58.encode(Uint8Array.from([0, 1, 2]));\n * base58.decode(text);\n * // => Uint8Array.from([0, 1, 2])\n * ```\n */\nexport const base58 = /* @__PURE__ */ freeze(() => genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'));\n/**\n * base58: flickr version. Check out `base58`.\n * @example\n * Round-trip bytes with the Flickr alphabet.\n * ```ts\n * const text = base58flickr.encode(Uint8Array.from([0, 1, 2]));\n * base58flickr.decode(text);\n * ```\n */\nexport const base58flickr = /* @__PURE__ */ freeze(() => genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'));\n/**\n * base58: XRP version. Check out `base58`.\n * @example\n * Round-trip bytes with the XRP alphabet.\n * ```ts\n * const text = base58xrp.encode(Uint8Array.from([0, 1, 2]));\n * base58xrp.decode(text);\n * ```\n */\nexport const base58xrp = /* @__PURE__ */ freeze(() => genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'));\n// Data len (index) -> encoded block len.\n// Monero pads each 1..8-byte block to this fixed base58 width so decode can recover the tail length.\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n * @example\n * Round-trip bytes with the Monero block codec.\n * ```ts\n * const text = base58xmr.encode(Uint8Array.from([0, 1, 2]));\n * base58xmr.decode(text);\n * ```\n */\nexport const base58xmr = /* @__PURE__ */ freeze(() => ({\n encode(data) {\n abytes(data);\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');\n }\n return res;\n },\n decode(str) {\n astr('base58xmr.decode', str);\n const strLen = str.length;\n // Only the last block may be short, and only to one of the XMR_BLOCK_LEN widths —\n // so the output length is known up front and blocks write into place. Growing a\n // number[] via concat per block was quadratic; this keeps decode linear like the\n // block encoding always intended.\n const tailChars = strLen % 11;\n const tailBytes = tailChars === 0 ? 0 : XMR_BLOCK_LEN.indexOf(tailChars);\n if (tailBytes === -1)\n throw new Error(`base58xmr: invalid block length ${tailChars}`);\n const res = new Uint8Array(Math.floor(strLen / 11) * 8 + tailBytes);\n let w = 0;\n for (let i = 0; i < strLen; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = slice.length === 11 ? 8 : tailBytes;\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0)\n throw new Error('base58xmr: wrong padding');\n }\n for (let j = block.length - blockLen; j < block.length; j++)\n res[w++] = block[j];\n }\n return res;\n },\n}));\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n * Callers must include any version bytes in `data`; this helper only applies the\n * 4-byte double-SHA256 checksum used by Bitcoin Base58Check.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Create a base58check codec from a SHA-256 implementation.\n * ```ts\n * import { createBase58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = createBase58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const createBase58check = (sha256) => {\n // Validate the hash function at construction time so wrong inputs fail before returning a coder.\n afn(sha256);\n const _sha256 = sha256;\n return chain(checksum(4, (data) => _sha256(_sha256(data))), base58);\n};\n/**\n * Use `createBase58check` instead.\n * @deprecated Use {@link createBase58check} instead.\n * Callers must include any version bytes in `data`; this alias keeps the same\n * 4-byte double-SHA256 checksum behavior as `createBase58check`.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @example\n * Create a base58check codec with the deprecated alias.\n * ```ts\n * import { base58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = base58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const base58check = createBase58check;\n// BIP 173 character table.\n// Callers adapt the public number[] words API to Uint8Array at the edges (wordsToU8 below):\n// feeding number[] into alphabet.encode would work at runtime, but it turns the shared\n// hot loop polymorphic and measurably slows the RFC 4648 codecs using the same literal.\nconst BECH_ALPHABET = /* @__PURE__ */ alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l');\nconst BECH_UPPERCASE_PRINTABLE = /^[\\x21-\\x60\\x7b-\\x7e]+$/;\nfunction assertBech32Printable(label, value) {\n for (let i = 0; i < value.length; i++) {\n const c = value.charCodeAt(i);\n if (c < 33 || c > 126)\n throw new Error(`${label}: printable ASCII expected`);\n }\n}\n// Range-checks while packing: a plain copy would silently wrap out-of-range words\n// (256 -> 0 would encode to a valid letter). Same message the old slow alphabet threw.\nfunction wordsToU8(words) {\n const len = words.length;\n const res = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n const w = words[i];\n if (w < 0 || w >= 32)\n throw new Error(`alphabet.encode: invalid digit ${w}`);\n res[i] = w;\n }\n return res;\n}\n// BIP 173 `bech32_polymod` GEN coefficients.\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n// BIP 173 step split: this applies the polymod state transition before callers xor in the next 5-bit value.\nfunction bech32Polymod(pre) {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1)\n chk ^= POLYMOD_GENERATORS[i];\n }\n return chk;\n}\nfunction bechChecksum(prefix, words, encodingConst = 1) {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126)\n throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++)\n chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words)\n chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++)\n chk = bech32Polymod(chk);\n // BIP 173/BIP 350: xor the final checksum constant, then emit the 30-bit state as six 5-bit symbols.\n chk ^= encodingConst;\n const sum = new Uint8Array(6);\n for (let i = 0; i < 6; i++)\n sum[i] = (chk >>> (5 * (5 - i))) & 31;\n return BECH_ALPHABET.encode(sum);\n}\nfunction genBech32(encoding) {\n // BIP 173 uses final xor constant 1; BIP 350 swaps in 0x2bc830a3 for Bech32m.\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n // Public API words are number[], so adapt the fast radix2's Uint8Array protocol at the edge.\n const _words = radix2(5);\n const toWords = (from) => {\n abytes(from);\n // Dedicated 8->5 regrouping (radix2(5).encode semantics) writing the public number[]\n // directly; encode-into-Uint8Array plus a copy loop measurably regressed this hot path.\n const len = from.length;\n const res = new Array(Math.ceil((len * 8) / 5));\n let carry = 0;\n let pos = 0;\n let j = 0;\n for (let i = 0; i < len; i++) {\n // No carry cleanup needed: stale bits sit above pos and every extraction (including\n // the tail below) masks with `& 31`, so they never reach the output. Masking carry\n // here measurably slowed the loop.\n carry = (carry << 8) | from[i];\n pos += 8;\n for (; pos >= 5; pos -= 5)\n res[j++] = (carry >> (pos - 5)) & 31;\n }\n if (pos > 0)\n res[j] = (carry << (5 - pos)) & 31;\n return res;\n };\n const fromWords = (to) => {\n anumArr('radix2.decode', to);\n // Range-check while packing into the byte buffer: a plain copy would silently\n // truncate out-of-range words. Rejecting negatives is a deliberate fix — the old\n // convertRadix2 path silently corrupted output for them.\n const len = to.length;\n const digits = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n const w = to[i];\n if (w < 0 || w >= 32)\n throw new Error(`convertRadix2: invalid word=${w}`);\n digits[i] = w;\n }\n return _words.decode(digits);\n };\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n function encode(prefix, words, limit = 90) {\n astr('bech32.encode prefix', prefix);\n if (limit !== false)\n anumber(limit, 'limit');\n if (isBytes(words))\n words = u8ToNumArr(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0)\n throw new TypeError(`Invalid prefix length ${plen}`);\n // Total output is hrp + `1` separator + payload words + 6 checksum chars.\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n assertBech32Printable('bech32.encode prefix', prefix);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(wordsToU8(words))}${sum}`;\n }\n function decode(str, limit = 90) {\n astr('bech32.decode input', str);\n if (limit !== false)\n anumber(limit, 'limit');\n const slen = str.length;\n // Minimum length is 1-char hrp + `1` separator + 6-char checksum.\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length ${slen}, expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered) {\n // Case folding is the only way a non-ASCII input can become valid: unchanged\n // characters are rejected by the prefix and alphabet checks below.\n if (!BECH_UPPERCASE_PRINTABLE.test(str)) {\n assertBech32Printable('bech32.decode input', str);\n throw new Error(`mixed-case string not allowed`);\n }\n }\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`invalid separator \"1\"`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6)\n throw new Error('invalid data length');\n const digits = BECH_ALPHABET.decode(data);\n const words = u8ToNumArr(digits, digits.length - 6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum))\n throw new Error(`Invalid checksum in ${str}`);\n return { prefix, words };\n }\n const decodeUnsafe = unsafeWrapper(decode);\n function decodeToBytes(str, limit = 90) {\n const { prefix, words } = decode(str, limit);\n return {\n prefix,\n words,\n bytes: fromWords(words),\n };\n }\n function encodeFromBytes(prefix, bytes) {\n // Keep the convenience wrapper on encode()'s default 90-char cap; custom limits should call encode(prefix, toWords(bytes), limit).\n return encode(prefix, toWords(bytes));\n }\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them, then decode back.\n * ```ts\n * const words = bech32.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32.encode('bc', words);\n * bech32.decode(text);\n * ```\n */\nexport const bech32 = /* @__PURE__ */ freeze(() => genBech32('bech32'));\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them with bech32m, then decode back.\n * ```ts\n * const words = bech32m.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32m.encode('bc', words);\n * bech32m.decode(text);\n * ```\n */\nexport const bech32m = /* @__PURE__ */ freeze(() => genBech32('bech32m'));\n/**\n * ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes.\n * @example\n * ```js\n * const b = ascii.decode(\"ABC\"); // => new Uint8Array([ 65, 66, 67 ])\n * const str = ascii.encode(b); // \"ABC\"\n * ```\n */\nexport const ascii = /* @__PURE__ */ freeze(() => ({\n encode(data) {\n abytes(data);\n for (let i = 0; i < data.length; i++) {\n const byte = data[i];\n // ASCII is 7-bit; reject bytes outside 0x00..0x7f instead of silently widening to\n // Latin-1/UTF-8. Validating up front keeps the error position exact while the\n // string itself is built in bulk (~3x faster at 1KB than per-char concat).\n if (byte > 127)\n throw new RangeError(`non-ASCII byte ${byte} at ${i}`);\n }\n return charcodesToString(data);\n },\n decode(str) {\n if (typeof str !== 'string')\n throw new TypeError('ascii string expected, got ' + typeof str);\n const res = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n // Indexed access is much faster than Uint8Array.from(str, mapFn) here and keeps\n // exact error positions.\n const charCode = str.charCodeAt(i);\n if (charCode > 127)\n throw new RangeError(`non-ASCII char \"${str[i]}\" (${charCode}) at ${i}`);\n res[i] = charCode;\n }\n return res;\n },\n}));\nconst _isWellFormedShim = (str) => {\n // encodeURI rejects malformed UTF-16, giving a compact fallback that matches native\n // isWellFormed on our tests/fuzz corpus.\n try {\n return encodeURI(str) !== null;\n }\n catch {\n return false;\n }\n};\nconst _isWellFormed = /* @__PURE__ */ (() => \n// Pick the native check once so utf8.decode doesn't re-probe String.prototype on every call.\ntypeof ''.isWellFormed === 'function'\n ? (str) => str.isWellFormed()\n : _isWellFormedShim)();\n// This fallback stays small because strict UTF-8 only needs fatal decoding plus well-formed\n// UTF-16 checks, not the replacement, streaming, or legacy-encoding behavior of full platform\n// text codecs.\nconst utf8err = (i) => new TypeError(`invalid utf8 at byte ${i}`);\nconst utf8Fallback = /* @__PURE__ */ freeze(() => ({\n encode(data) {\n abytes(data);\n let res = '';\n for (let i = 0; i < data.length;) {\n const a = data[i++];\n if (a < 0b1000_0000) {\n res += String.fromCharCode(a);\n continue;\n }\n if (a < 0b1100_0010 || i >= data.length)\n throw utf8err(i - 1);\n const b = data[i++];\n if ((b & 0b1100_0000) !== 0b1000_0000)\n throw utf8err(i - 1);\n let cp = ((a & 0b0001_1111) << 6) | (b & 0b0011_1111);\n if (a >= 0b1110_0000) {\n if (i >= data.length)\n throw utf8err(i - 1);\n const c = data[i++];\n if ((c & 0b1100_0000) !== 0b1000_0000 ||\n (a === 0b1110_0000 && b < 0b1010_0000) ||\n (a === 0xed && b >= 0b1010_0000))\n throw utf8err(i - 1);\n cp = ((a & 0b0000_1111) << 12) | ((b & 0b0011_1111) << 6) | (c & 0b0011_1111);\n if (a >= 0b1111_0000) {\n if (i >= data.length)\n throw utf8err(i - 1);\n const d = data[i++];\n if (a > 0b1111_0100 ||\n (d & 0b1100_0000) !== 0b1000_0000 ||\n (a === 0b1111_0000 && b < 0b1001_0000) ||\n (a === 0b1111_0100 && b >= 0b1001_0000))\n throw utf8err(i - 1);\n cp =\n ((a & 7) << 18) |\n ((b & 0b0011_1111) << 12) |\n ((c & 0b0011_1111) << 6) |\n (d & 0b0011_1111);\n }\n }\n if (cp < 0x10000)\n res += String.fromCharCode(cp);\n else {\n cp -= 0x10000;\n res += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00);\n }\n }\n return res;\n },\n decode(str) {\n astr('utf8', str);\n if (!_isWellFormed(str))\n throw new TypeError('utf8 expected well-formed string');\n // Direct Uint8Array writes are much faster than number[] + Uint8Array.from on Hermes and\n // large Node inputs.\n const res = new Uint8Array(str.length * 3);\n let pos = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 0b1000_0000) {\n res[pos++] = c;\n continue;\n }\n if (c >= 0xd800 && c <= 0xdfff) {\n const d = str.charCodeAt(++i);\n c = 0x10000 + ((c - 0xd800) << 10) + d - 0xdc00;\n }\n if (c >= 0x10000) {\n res[pos++] = (c >> 18) | 0b1111_0000;\n res[pos++] = ((c >> 12) & 0b0011_1111) | 0b1000_0000;\n }\n else if (c >= 0x800)\n res[pos++] = (c >> 12) | 0b1110_0000;\n else\n res[pos++] = (c >> 6) | 0b1100_0000;\n if (c >= 0x800)\n res[pos++] = ((c >> 6) & 0b0011_1111) | 0b1000_0000;\n res[pos++] = (c & 0b0011_1111) | 0b1000_0000;\n }\n return res.subarray(0, pos);\n },\n}));\n/**\n * Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and\n * `decode(string)` returns bytes.\n * `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and\n * throws on invalid UTF-8 bytes.\n * `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with\n * lone surrogates.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8 = /* @__PURE__ */ freeze(() => {\n let _utf8Encoder;\n let _utf8Decoder;\n const utf8Builtin = {\n // ignoreBOM preserves an explicit leading U+FEFF;\n // fatal rejects invalid UTF-8 bytes instead of replacing them.\n encode(data) {\n abytes(data);\n return (_utf8Decoder || (_utf8Decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }))).decode(data);\n },\n decode(str) {\n astr('utf8', str);\n if (!_isWellFormed(str))\n throw new TypeError('utf8 expected well-formed string');\n return (_utf8Encoder || (_utf8Encoder = new TextEncoder())).encode(str);\n },\n };\n return {\n // Select each direction once at module init, since\n // TextEncoder and TextDecoder can exist independently.\n encode: typeof TextDecoder === 'function' ? utf8Builtin.encode : utf8Fallback.encode,\n decode: typeof TextEncoder === 'function' ? utf8Builtin.decode : utf8Fallback.decode,\n };\n});\n/** Lowercase hex with case-insensitive decoding. Pure JS version. */\nconst hexFallback = /* @__PURE__ */ freeze(() => chain(radix2(4), \n// Case-insensitive decode via table aliases instead of a toLowerCase pass.\nalphabet('0123456789abcdef', { A: 'a', B: 'b', C: 'c', D: 'd', E: 'e', F: 'f' }), normalize((s) => {\n // astr first: same non-string message as the native path, and no `s.length`\n // access on null / undefined while building the error.\n astr('hex', s);\n if (s.length % 2 !== 0)\n throw new TypeError(`hex.decode: odd-length string (${s.length})`);\n return s;\n})));\n// Keep internal parity probes behind a test-only export.\nexport const __TESTS = /* @__PURE__ */ freeze(() => ({\n alphabet: alphabet,\n base64Fallback: base64Fallback,\n base64urlFallback: base64urlFallback,\n hexFallback: hexFallback,\n radix2: radix2,\n radix58: radix58,\n checksum: checksum,\n utf8Fallback: utf8Fallback,\n _isWellFormedShim: _isWellFormedShim,\n}));\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// Require both directions before enabling the native hex path so encode/decode stay symmetric.\ntypeof Uint8Array.from([]).toHex === 'function' &&\n typeof Uint8Array.fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin = {\n // Keep local type guards so the native path preserves library-level input errors.\n // Native toHex emits lowercase hex, matching the fallback alphabet and Node's hex strings.\n encode(data) { abytes(data); return data.toHex(); },\n // Native fromHex accepts either hex case and rejects odd-length / non-hex syntax.\n decode(s) { astr('hex', s); return Uint8Array.fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex = /* @__PURE__ */ freeze(() => hasHexBuiltin ? hexBuiltin : hexFallback);\n","/**\n * Result verification for `chain.sign`: the host re-checks the kernel's Bitcoin work against the\n * account's xpub — a kernel returning someone else's signature fails closed with `integrity`.\n * `/bitcoin` entry only — no private key material.\n */\nimport { secp256k1, schnorr } from \"@noble/curves/secp256k1.js\";\nimport { base64 } from \"@scure/base\";\nimport { HDKey } from \"@scure/bip32\";\nimport { Address, OutScript } from \"@scure/btc-signer/payment.js\";\nimport { SigHash, Transaction } from \"@scure/btc-signer/transaction.js\";\n\nimport type { BitcoinAccountTemplate } from \"./account.ts\";\nimport { bip322ToSpendTxid } from \"./message.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v) && !(v instanceof Uint8Array);\n\n/** Derive the child's public key from the account xpub at `change/index` (non-hardened). */\nconst childPub = (xpub: string, network: string, change: number, index: number): Uint8Array => {\n const child = HDKey.fromExtendedKey(xpub, bitcoinNetwork(network).bip32)\n .deriveChild(change)\n .deriveChild(index);\n if (child.publicKey === null || child.publicKey === undefined) {\n throw new Error(\"xpub cannot derive this child\");\n }\n return child.publicKey;\n};\n\n/** Extract `[pubkey, {fingerprint, path}]`-shaped entries from either PSBT derivation map. */\nconst derivationOf = (\n map: unknown,\n): ReadonlyArray<{ pubkey: Uint8Array; path: ReadonlyArray<number> }> => {\n const out: Array<{ pubkey: Uint8Array; path: ReadonlyArray<number> }> = [];\n const readEntry = (key: unknown, value: unknown): void => {\n const der = isRecord(value) && isRecord(value[\"der\"]) ? value[\"der\"] : value;\n const { path } = isRecord(der) ? der : {};\n if (\n key instanceof Uint8Array &&\n Array.isArray(path) &&\n path.every((p) => typeof p === \"number\")\n ) {\n out.push({ pubkey: key, path });\n }\n };\n if (map instanceof Map) {\n for (const [key, value] of map) {\n readEntry(key, value);\n }\n } else if (Array.isArray(map)) {\n for (const entry of map) {\n if (Array.isArray(entry) && entry.length === 2) {\n readEntry(entry[0], entry[1]);\n }\n }\n }\n return out;\n};\n\n/** The non-hardened `{change, index}` tail of a derivation path, if present and valid. */\nconst tailOf = (path: ReadonlyArray<number>): { change: 0 | 1; index: number } | undefined => {\n const change = path.at(-2);\n const index = path.at(-1);\n if ((change !== 0 && change !== 1) || index === undefined || index < 0 || index >= 0x80000000) {\n return undefined;\n }\n return { change, index };\n};\n\nconst eq = (a: Uint8Array, b: Uint8Array): boolean =>\n a.length === b.length && a.every((v, i) => v === b[i]);\n\n/**\n * Verify every signature on the inputs listed in `sign` against the account's xpub: the input's\n * derivation entry must claim the child pubkey re-derived from the xpub, and the signature must\n * verify over the input's sighash (BIP-143 partialSig for P2WPKH, tapKeySig for P2TR key path).\n */\nexport const verifyBitcoinPsbtSignatures = (\n signedPsbt: Uint8Array,\n sign: ReadonlyArray<number>,\n xpub: string,\n template: BitcoinAccountTemplate,\n network: string,\n): boolean => {\n try {\n const tx = Transaction.fromPSBT(signedPsbt);\n const taproot = template === \"btc.bip86\";\n for (const idx of sign) {\n const input = tx.getInput(idx);\n const claimed = derivationOf(taproot ? input.tapBip32Derivation : input.bip32Derivation).find(\n ({ path }) => tailOf(path) !== undefined,\n );\n const tail = claimed === undefined ? undefined : tailOf(claimed.path);\n if (claimed === undefined || tail === undefined) {\n return false;\n }\n const prevout = input.witnessUtxo;\n if (prevout === undefined) {\n return false;\n }\n const pub = childPub(xpub, network, tail.change, tail.index);\n if (taproot) {\n const xonly = pub.slice(1);\n const rawSig = input.tapKeySig;\n if (\n !eq(claimed.pubkey, xonly) ||\n !(rawSig instanceof Uint8Array) ||\n (rawSig.length !== 64 && rawSig.length !== 65)\n ) {\n return false;\n }\n const sighashType =\n rawSig.length === 65 ? (rawSig[64] ?? SigHash.DEFAULT) : SigHash.DEFAULT;\n const sig = rawSig.slice(0, 64);\n const scripts: Uint8Array[] = [];\n const amounts: bigint[] = [];\n let complete = true;\n for (let i = 0; i < tx.inputsLength; i++) {\n const w = tx.getInput(i).witnessUtxo;\n if (w === undefined) {\n complete = false;\n break;\n }\n scripts.push(w.script);\n amounts.push(w.amount);\n }\n if (\n !complete ||\n !schnorr.verify(sig, tx.preimageWitnessV1(idx, scripts, sighashType, amounts), xonly)\n ) {\n return false;\n }\n } else {\n const partial = input.partialSig;\n const found = Array.isArray(partial)\n ? partial.find(([p]) => p instanceof Uint8Array && eq(p, pub))\n : undefined;\n const rawSig =\n Array.isArray(found) && found[1] instanceof Uint8Array ? found[1] : undefined;\n if (!eq(claimed.pubkey, pub) || rawSig === undefined || rawSig.length === 0) {\n return false;\n }\n const sighashType = input.sighashType ?? rawSig.at(-1) ?? SigHash.ALL;\n const decoded = OutScript.decode(prevout.script);\n const scriptCode =\n decoded !== undefined && decoded.type === \"wpkh\"\n ? OutScript.encode({ type: \"pkh\", hash: decoded.hash })\n : prevout.script;\n const hash = tx.preimageWitnessV0(idx, scriptCode, sighashType, prevout.amount);\n if (\n !secp256k1.verify(\n secp256k1.Signature.fromBytes(rawSig.slice(0, -1), \"der\").toBytes(),\n hash,\n pub,\n { prehash: false },\n )\n ) {\n return false;\n }\n }\n }\n return true;\n } catch {\n return false;\n }\n};\n\n/** Deserialize the `smp`-prefixed base64 witness: count + pushData items. */\nconst witnessOf = (sig: string): ReadonlyArray<Uint8Array> | undefined => {\n if (!sig.startsWith(\"smp\")) {\n return undefined;\n }\n const raw = base64.decode(sig.slice(3));\n if (raw === undefined || raw.length === 0) {\n return undefined;\n }\n const items: Uint8Array[] = [];\n let off = 1;\n for (let i = 0; i < (raw[0] ?? 0); i++) {\n const len = raw[off];\n if (len === undefined || off + 1 + len > raw.length) {\n return undefined;\n }\n items.push(raw.slice(off + 1, off + 1 + len));\n off += 1 + len;\n }\n return off === raw.length ? items : undefined;\n};\n\n/**\n * BIP-322 simple verification against an address: rebuild to_spend/to_sign exactly as the signer\n * does, then verify the witness signature (P2WPKH ECDSA / P2TR schnorr) over the input preimage.\n */\nexport const verifyBitcoinMessage = (\n address: string,\n message: string,\n signatureBase64: string,\n network: string,\n): boolean => {\n try {\n const net = bitcoinNetwork(network);\n const scriptPubKey = OutScript.encode(Address(net.params).decode(address));\n const witness = witnessOf(signatureBase64);\n if (witness === undefined || witness.length === 0) {\n return false;\n }\n const tx = new Transaction({ version: 0, lockTime: 0, allowUnknownOutputs: true });\n tx.addInput({\n txid: Uint8Array.from([...bip322ToSpendTxid(scriptPubKey, message)].reverse()),\n index: 0,\n sequence: 0,\n witnessUtxo: { script: scriptPubKey, amount: 0n },\n });\n tx.addOutput({ script: Uint8Array.of(0x6a), amount: 0n });\n if (scriptPubKey.at(0) === 0x51) {\n const [rawSig] = witness;\n const xonly = scriptPubKey.slice(2);\n if (\n rawSig === undefined ||\n xonly.length !== 32 ||\n (rawSig.length !== 64 && rawSig.length !== 65)\n ) {\n return false;\n }\n const sighashType =\n rawSig.length === 65 ? (rawSig.at(64) ?? SigHash.DEFAULT) : SigHash.DEFAULT;\n return schnorr.verify(\n rawSig.slice(0, 64),\n tx.preimageWitnessV1(0, [scriptPubKey], sighashType, [0n]),\n xonly,\n );\n }\n const [rawSig, pub] = witness;\n if (rawSig === undefined || pub === undefined || pub.length !== 33 || rawSig.length === 0) {\n return false;\n }\n const sighashType = rawSig.at(-1) ?? SigHash.ALL;\n const decoded = OutScript.decode(scriptPubKey);\n const scriptCode =\n decoded !== undefined && decoded.type === \"wpkh\"\n ? OutScript.encode({ type: \"pkh\", hash: decoded.hash })\n : scriptPubKey;\n return secp256k1.verify(\n secp256k1.Signature.fromBytes(rawSig.slice(0, -1), \"der\").toBytes(),\n tx.preimageWitnessV0(0, scriptCode, sighashType, 0n),\n pub,\n { prehash: false },\n );\n } catch {\n return false;\n }\n};\n","import { Address, OutScript } from \"@scure/btc-signer/payment.js\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { AccountRef, SignRequest } from \"../index.ts\";\nimport { bitcoinNetwork } from \"./networks.ts\";\nimport { normalizeBitcoinPsbt } from \"./psbt.ts\";\n\nexport { BITCOIN_NETWORKS, bitcoinNetwork } from \"./networks.ts\";\nexport type { BitcoinAccountTemplate } from \"./account.ts\";\nexport { bitcoinAddressFromXpub } from \"./account.ts\";\nexport { decodeBitcoinPsbt, verifiabilityBitcoin } from \"./decode.ts\";\nexport { verifyBitcoinMessage, verifyBitcoinPsbtSignatures } from \"./verify.ts\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isAccountRef = (value: unknown): value is AccountRef => {\n if (!isRecord(value) || typeof value[\"kind\"] !== \"string\") {\n return false;\n }\n if (value[\"kind\"] === \"hd\") {\n return (\n typeof value[\"walletId\"] === \"string\" &&\n typeof value[\"groupIndex\"] === \"number\" &&\n typeof value[\"template\"] === \"string\"\n );\n }\n return (\n value[\"kind\"] === \"imported\" &&\n typeof value[\"keyId\"] === \"string\" &&\n typeof value[\"family\"] === \"string\"\n );\n};\n\nconst common = (request: Record<string, unknown>): { network: string; account: AccountRef } => {\n const { network } = request;\n const { account } = request;\n if (typeof network !== \"string\") {\n throw new ChainError(\"invalid-request\", \"request.network must be a string\");\n }\n if (!isAccountRef(account)) {\n throw new ChainError(\"invalid-request\", \"request.account must be an AccountRef\");\n }\n bitcoinNetwork(network);\n return { network, account };\n};\n\n/** The decoded `address` fields needed by message signers. */\nexport type MessageTarget = {\n readonly type: string;\n readonly address: string;\n readonly format: \"bip322-simple\" | \"legacy\";\n readonly scriptPubKey: Uint8Array;\n};\n\nconst messageTarget = (address: unknown, network: string, format: unknown): MessageTarget => {\n if (typeof address !== \"string\") {\n throw new ChainError(\"invalid-request\", \"address must be a string\");\n }\n const net = bitcoinNetwork(network);\n let decoded: ReturnType<ReturnType<typeof Address>[\"decode\"]>;\n try {\n decoded = Address(net.params).decode(address);\n } catch {\n throw new ChainError(\"invalid-address\", \"address does not belong to this network\");\n }\n if (format === \"bip322-simple\") {\n if (decoded.type !== \"wpkh\" && decoded.type !== \"tr\") {\n throw new ChainError(\"unsupported\", \"bip322-simple is only for P2WPKH/P2TR addresses\");\n }\n } else if (format === \"legacy\") {\n if (decoded.type !== \"pkh\") {\n throw new ChainError(\"unsupported\", \"legacy signing is only for P2PKH addresses\");\n }\n } else {\n throw new ChainError(\"unsupported\", `unsupported message format: ${String(format)}`);\n }\n const scriptPubKey = OutScript.encode(decoded);\n return { type: decoded.type, address, format, scriptPubKey };\n};\n\n/**\n * Normalizes a bitcoin sign request. Idempotent: the returned PSBT is the canonical\n * re-serialization.\n */\nexport const normalizeBitcoin = (request: unknown): SignRequest => {\n if (!isRecord(request) || typeof request[\"kind\"] !== \"string\") {\n throw new ChainError(\"invalid-request\", \"request must be an object with a kind\");\n }\n const { network, account } = common(request);\n if (request[\"kind\"] === \"bitcoin.psbt\") {\n const { psbt } = request;\n if (!(psbt instanceof Uint8Array)) {\n throw new ChainError(\"invalid-request\", \"psbt must be bytes\");\n }\n const normalized = normalizeBitcoinPsbt(psbt, request[\"sign\"], network);\n return { kind: \"bitcoin.psbt\", network, account, psbt: normalized.psbt, sign: normalized.sign };\n }\n if (request[\"kind\"] === \"bitcoin.message\") {\n const { format } = request;\n const target = messageTarget(request[\"address\"], network, format);\n void target;\n const { message, change, index } = request;\n if (typeof message !== \"string\") {\n throw new ChainError(\"invalid-request\", \"message must be a string\");\n }\n if (change !== 0 && change !== 1) {\n throw new ChainError(\"invalid-request\", \"change must be 0 or 1\");\n }\n if (\n typeof index !== \"number\" ||\n !Number.isSafeInteger(index) ||\n index < 0 ||\n index >= 0x80000000\n ) {\n throw new ChainError(\"invalid-request\", \"index must be a non-hardened path index\");\n }\n return {\n kind: \"bitcoin.message\",\n network,\n account,\n address: target.address,\n message,\n format: target.format,\n change,\n index,\n };\n }\n throw new ChainError(\"unsupported\", `unsupported sign request kind: ${request[\"kind\"]}`);\n};\n\n/** Decodes the message `address` into the scriptPubKey the signer needs. */\nexport const decodeMessageTarget = (\n request: Extract<SignRequest, { kind: \"bitcoin.message\" }>,\n): MessageTarget => messageTarget(request.address, request.network, request.format);\n"],"ignoreList":[3],"mappings":";;;;;;;;;;;;AAUA,MAAMA,cAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;;;AAMrE,MAAM,mBAAmB,QAAuD;CAC9E,MAAM,UACJ,eAAe,MACX,CAAC,GAAG,IAAI,OAAO,CAAC,IAChB,MAAM,QAAQ,GAAG,IACf,MACAA,WAAS,GAAG,IACV,OAAO,OAAO,GAAG,IACjB,CAAC;CACX,MAAM,QAAoB,CAAC;CAC3B,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,QAAiB,MAAM,QAAQ,KAAK,IAAI,MAAM,KAAK;EACzD,IAAI,CAACA,WAAS,KAAK,GACjB;EAGF,MAAM,EAAE,SADIA,WAAS,MAAM,MAAM,IAAI,MAAM,SAAS;EAEpD,IAAI,MAAM,QAAQ,IAAI,KAAK,KAAK,OAAO,MAAM,OAAO,MAAM,QAAQ,GAChE,MAAM,KAAK,IAAI;CAEnB;CACA,OAAO;AACT;AAEA,MAAM,cACJ,OACA,OACA,aACS;CACT,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,UAAU,MAAM,KAAK,MAAM,MAAM,eAAe,UACvD,MAAM,IAAI,WACR,qBACA,GAAG,MAAM,4CACX;AAGN;AAEA,MAAM,oBAAoB,IAAiB,aAA2B;CACpE,KAAK,IAAI,IAAI,GAAG,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