@babylonlabs-io/ts-sdk 2.0.0 → 2.0.2
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/dist/{PayoutManager-CpfQjtL0.cjs → PayoutManager-B6GFbG3X.cjs} +2 -2
- package/dist/{PayoutManager-CpfQjtL0.cjs.map → PayoutManager-B6GFbG3X.cjs.map} +1 -1
- package/dist/{PayoutManager-CHTOwj0E.js → PayoutManager-BSwbUQeF.js} +2 -2
- package/dist/{PayoutManager-CHTOwj0E.js.map → PayoutManager-BSwbUQeF.js.map} +1 -1
- package/dist/{PeginManager-DEldv_Ro.js → PeginManager-CKf7Bjmj.js} +6 -6
- package/dist/{PeginManager-DEldv_Ro.js.map → PeginManager-CKf7Bjmj.js.map} +1 -1
- package/dist/{PeginManager-6tjlGd0t.cjs → PeginManager-Dt2Z5ljw.cjs} +2 -2
- package/dist/{PeginManager-6tjlGd0t.cjs.map → PeginManager-Dt2Z5ljw.cjs.map} +1 -1
- package/dist/{bip322Verify-DSco3Yhl.js → bip322Verify-BXYrHBh8.js} +2 -2
- package/dist/{bip322Verify-DSco3Yhl.js.map → bip322Verify-BXYrHBh8.js.map} +1 -1
- package/dist/{bip322Verify-B7_gIhRk.cjs → bip322Verify-DLxJR9CQ.cjs} +2 -2
- package/dist/{bip322Verify-B7_gIhRk.cjs.map → bip322Verify-DLxJR9CQ.cjs.map} +1 -1
- package/dist/{buildAndBroadcastReclaim-CqO2DoP8.js → buildAndBroadcastReclaim-B19cyK69.js} +952 -724
- package/dist/buildAndBroadcastReclaim-B19cyK69.js.map +1 -0
- package/dist/buildAndBroadcastReclaim-DcbsjJdf.cjs +2 -0
- package/dist/buildAndBroadcastReclaim-DcbsjJdf.cjs.map +1 -0
- package/dist/{deriveVaultRoot-BwbXmN0x.js → deriveVaultRoot-BcvmER1E.js} +2 -2
- package/dist/{deriveVaultRoot-BwbXmN0x.js.map → deriveVaultRoot-BcvmER1E.js.map} +1 -1
- package/dist/{deriveVaultRoot-DvhkHzNb.cjs → deriveVaultRoot-C3uqnJto.cjs} +2 -2
- package/dist/{deriveVaultRoot-DvhkHzNb.cjs.map → deriveVaultRoot-C3uqnJto.cjs.map} +1 -1
- package/dist/{index-DQ5bfoT3.js → index-Bnavi_r3.js} +115 -99
- package/dist/index-Bnavi_r3.js.map +1 -0
- package/dist/index-CcdCNFLM.cjs +2 -0
- package/dist/index-CcdCNFLM.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +159 -154
- package/dist/{json-rpc-client-DuUARJvV.js → json-rpc-client-CQLbpuKK.js} +31 -30
- package/dist/json-rpc-client-CQLbpuKK.js.map +1 -0
- package/dist/json-rpc-client-DbpFfa_o.cjs +2 -0
- package/dist/json-rpc-client-DbpFfa_o.cjs.map +1 -0
- package/dist/{onChainBtcPubkey-BXry_CM4.cjs → onChainBtcPubkey-BlzxYImF.cjs} +2 -2
- package/dist/{onChainBtcPubkey-BXry_CM4.cjs.map → onChainBtcPubkey-BlzxYImF.cjs.map} +1 -1
- package/dist/{onChainBtcPubkey-C1WqyxPM.js → onChainBtcPubkey-CCTdl53s.js} +2 -2
- package/dist/{onChainBtcPubkey-C1WqyxPM.js.map → onChainBtcPubkey-CCTdl53s.js.map} +1 -1
- package/dist/{pegin-registration-client-BNV44jzw.cjs → pegin-registration-client-BdJ6c7si.cjs} +2 -2
- package/dist/{pegin-registration-client-BNV44jzw.cjs.map → pegin-registration-client-BdJ6c7si.cjs.map} +1 -1
- package/dist/{pegin-registration-client-1sZ-74UC.js → pegin-registration-client-C5Hktrja.js} +3 -3
- package/dist/{pegin-registration-client-1sZ-74UC.js.map → pegin-registration-client-C5Hktrja.js.map} +1 -1
- package/dist/peginState-BU2ONFXF.js +68 -0
- package/dist/{peginState-CxDiaKuk.js.map → peginState-BU2ONFXF.js.map} +1 -1
- package/dist/peginState-DUv10EJR.cjs +2 -0
- package/dist/{peginState-eaQ4IO_R.cjs.map → peginState-DUv10EJR.cjs.map} +1 -1
- package/dist/{primeVpAuth-BOGKniTl.cjs → primeVpAuth-D21PXgg2.cjs} +2 -2
- package/dist/{primeVpAuth-BOGKniTl.cjs.map → primeVpAuth-D21PXgg2.cjs.map} +1 -1
- package/dist/{primeVpAuth-DdfHSC53.js → primeVpAuth-PiUJksAq.js} +5 -5
- package/dist/{primeVpAuth-DdfHSC53.js.map → primeVpAuth-PiUJksAq.js.map} +1 -1
- package/dist/{reservation-Cj9F0rP9.js → reservation-DOAHVT3B.js} +2 -2
- package/dist/{reservation-Cj9F0rP9.js.map → reservation-DOAHVT3B.js.map} +1 -1
- package/dist/{reservation-Dr2HLCxx.cjs → reservation-ECxjZi5t.cjs} +2 -2
- package/dist/{reservation-Dr2HLCxx.cjs.map → reservation-ECxjZi5t.cjs.map} +1 -1
- package/dist/sha2-Ce6KewYx.cjs +2 -0
- package/dist/{sha2-DI0-0SHr.cjs.map → sha2-Ce6KewYx.cjs.map} +1 -1
- package/dist/{sha2-CLpQd0Rd.js → sha2-YqVHJiFj.js} +91 -77
- package/dist/{sha2-CLpQd0Rd.js.map → sha2-YqVHJiFj.js.map} +1 -1
- package/dist/tbv/core/clients/eth/index.cjs +1 -1
- package/dist/tbv/core/clients/eth/index.js +3 -3
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +27 -26
- package/dist/tbv/core/clients/vault-provider/index.d.ts +1 -1
- package/dist/tbv/core/clients/vault-provider/index.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.d.ts +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.js +10 -9
- package/dist/tbv/core/clients/vault-provider/types.d.ts +7 -3
- package/dist/tbv/core/clients/vault-provider/types.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/validators.d.ts +8 -0
- package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +158 -153
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +2 -2
- package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/__tests__/graphFingerprint.test.d.ts +2 -0
- package/dist/tbv/core/services/deposit/__tests__/graphFingerprint.test.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/graphFingerprint.d.ts +115 -0
- package/dist/tbv/core/services/deposit/graphFingerprint.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/index.d.ts +2 -1
- package/dist/tbv/core/services/deposit/index.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/peginState.d.ts +23 -0
- package/dist/tbv/core/services/deposit/peginState.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +11 -0
- package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +66 -62
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +1 -1
- package/dist/tbv/core/vault-secrets/index.cjs +1 -1
- package/dist/tbv/core/vault-secrets/index.js +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +158 -153
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/{toRefundInputs-BaN9XluU.cjs → toRefundInputs-B_GlIXjk.cjs} +2 -2
- package/dist/{toRefundInputs-BaN9XluU.cjs.map → toRefundInputs-B_GlIXjk.cjs.map} +1 -1
- package/dist/{toRefundInputs-mtuuYezp.js → toRefundInputs-DIIdhjvu.js} +5 -5
- package/dist/{toRefundInputs-mtuuYezp.js.map → toRefundInputs-DIIdhjvu.js.map} +1 -1
- package/dist/{types-BuxreSq4.cjs → types-DJxOEU3P.cjs} +2 -2
- package/dist/{types-BuxreSq4.cjs.map → types-DJxOEU3P.cjs.map} +1 -1
- package/dist/{types-BdCEoANP.js → types-Dz1kVqn6.js} +2 -2
- package/dist/{types-BdCEoANP.js.map → types-Dz1kVqn6.js.map} +1 -1
- package/dist/verifyKeyPathSchnorrSignature-BQHNhRj6.js.map +1 -1
- package/dist/verifyKeyPathSchnorrSignature-Gm9EmZkx.cjs.map +1 -1
- package/package.json +2 -1
- package/dist/buildAndBroadcastReclaim-BwT6Jxp5.cjs +0 -2
- package/dist/buildAndBroadcastReclaim-BwT6Jxp5.cjs.map +0 -1
- package/dist/buildAndBroadcastReclaim-CqO2DoP8.js.map +0 -1
- package/dist/index-CK1Xvq4K.cjs +0 -2
- package/dist/index-CK1Xvq4K.cjs.map +0 -1
- package/dist/index-DQ5bfoT3.js.map +0 -1
- package/dist/json-rpc-client-BiAmg_ho.cjs +0 -2
- package/dist/json-rpc-client-BiAmg_ho.cjs.map +0 -1
- package/dist/json-rpc-client-DuUARJvV.js.map +0 -1
- package/dist/peginState-CxDiaKuk.js +0 -63
- package/dist/peginState-eaQ4IO_R.cjs +0 -2
- package/dist/sha2-DI0-0SHr.cjs +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifyKeyPathSchnorrSignature-BQHNhRj6.js","sources":["../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/utils/witness/witnessStack.ts","../src/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.ts","../src/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.ts"],"sourcesContent":["/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"../../wasm\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * Vault core (tx-graph) version the Pre-PegIn was built with. Must match\n * the version passed to buildPrePeginPsbt() so the HTLC connector scripts\n * are derived for the same graph.\n */\n vaultCoreVersion: number;\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n // Keep the facade's graph-version and input checks. Do not use its scripts\n // or control block as signing data.\n await getPrePeginHtlcConnectorInfo({\n txGraphVersion: params.vaultCoreVersion,\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n const expectedHtlc = deriveExpectedPrePeginHtlc(params, params.hashlock);\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n if (!expectedHtlc.scriptPubKey.equals(htlcOutput.script)) {\n throw new Error(\n \"PegIn HTLC taptree mismatch: the independent 2-leaf tree does not \" +\n \"reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.\",\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending. bitcoinjs\n // re-verifies leaf-in-tree consistency (control block vs tapMerkleRoot)\n // inside addInput — a second independent check.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.hashlockScript,\n controlBlock: expectedHtlc.hashlockControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(hexToUint8Array(depositorPubkey));\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n","/**\n * Consensus witness-stack decoding, shared by every module that reads a\n * witness we did not build.\n *\n * Two independent decoders drifted apart before this existed: one accepted\n * non-minimal CompactSize encodings, the other rejected them. vaultd decodes\n * with rust-bitcoin, whose `VarInt::consensus_decode`\n * (0.32.8 `consensus/encode.rs:493-522`) returns `NonMinimalVarInt` for a 0xfd\n * carrying < 0xfd and a 0xfe carrying < 0x10000 — so the strict reading is the\n * only one that matches what the network will accept.\n *\n * @module tbv/core/utils/witness/witnessStack\n */\n\n/** CompactSize discriminators; 0xff (u64) is out of range for a witness. */\nconst COMPACT_SIZE_UINT16_PREFIX = 0xfd;\nconst COMPACT_SIZE_UINT32_PREFIX = 0xfe;\nconst COMPACT_SIZE_UINT16_BYTES = 3;\nconst COMPACT_SIZE_UINT32_BYTES = 5;\nconst COMPACT_SIZE_UINT16_MIN_VALUE = 0xfd;\nconst COMPACT_SIZE_UINT32_MIN_VALUE = 0x10000;\n\n/**\n * Decode a consensus-encoded witness stack: item count, then (len, bytes)*.\n *\n * @param witness - The consensus-encoded witness bytes.\n * @param subject - Names the witness in error messages (e.g. \"finalScriptWitness\").\n * @returns The stack items, as views over `witness`.\n * @throws If the encoding is truncated, non-minimal, out of range, or leaves\n * trailing bytes.\n */\nexport function decodeWitnessStack(\n witness: Uint8Array,\n subject: string,\n): Uint8Array[] {\n let offset = 0;\n\n const readCompactSize = (): number => {\n if (offset >= witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const first = witness[offset];\n if (first < COMPACT_SIZE_UINT16_PREFIX) {\n offset += 1;\n return first;\n }\n if (first === COMPACT_SIZE_UINT16_PREFIX) {\n if (offset + COMPACT_SIZE_UINT16_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value = witness[offset + 1] | (witness[offset + 2] << 8);\n if (value < COMPACT_SIZE_UINT16_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT16_BYTES;\n return value;\n }\n if (first === COMPACT_SIZE_UINT32_PREFIX) {\n if (offset + COMPACT_SIZE_UINT32_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value =\n (witness[offset + 1] |\n (witness[offset + 2] << 8) |\n (witness[offset + 3] << 16) |\n (witness[offset + 4] << 24)) >>>\n 0;\n if (value < COMPACT_SIZE_UINT32_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT32_BYTES;\n return value;\n }\n throw new Error(`${subject} carries an out-of-range item length`);\n };\n\n const count = readCompactSize();\n const items: Uint8Array[] = [];\n for (let i = 0; i < count; i++) {\n const len = readCompactSize();\n if (offset + len > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n items.push(witness.subarray(offset, offset + len));\n offset += len;\n }\n if (offset !== witness.length) {\n throw new Error(`${subject} has trailing bytes`);\n }\n return items;\n}\n","/**\n * Far-side verification of P2WPKH ECDSA signatures a wallet returned, over\n * the PSBT we requested (trusted prevouts) — the Native SegWit sibling of\n * `verifyKeyPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs:945-1000\n * verify_finalized_p2wpkh_spend`. The wallet's success/finalization is\n * never trusted on its own (CLAUDE.md §8): prevout script and value come\n * from the PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport {\n crypto as bcrypto,\n script as bscript,\n payments,\n Psbt,\n Transaction,\n} from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\n\n// P2WPKH scriptPubKey is exactly `OP_0 OP_PUSHBYTES_20 <20-byte key hash>`\n// (BIP-141 witness program v0, 20 bytes).\nconst P2WPKH_SCRIPT_LEN = 22;\nconst OP_0 = 0x00;\nconst OP_PUSHBYTES_20 = 0x14;\nconst P2WPKH_PROGRAM_START = 2;\n\n/** SEC1 compressed pubkey (client.rs:959: \"expected a 33-byte compressed key\"). */\nconst COMPRESSED_PUBKEY_BYTES = 33;\n/** Consensus P2WPKH witness: exactly [signature, pubkey] (client.rs:951-957). */\nconst P2WPKH_WITNESS_ITEMS = 2;\n\n/** Only claim P2WPKH: 22-byte scriptPubKey starting `OP_0 PUSH20`. */\nexport function isP2wpkhScript(\n script: Uint8Array | undefined,\n): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2WPKH_SCRIPT_LEN &&\n script[0] === OP_0 &&\n script[1] === OP_PUSHBYTES_20\n );\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\n/** The `[signature, pubkey]` pair of a finalized P2WPKH witness (client.rs:951-957). */\nfunction decodeP2wpkhWitness(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; pubkey: Uint8Array } {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== P2WPKH_WITNESS_ITEMS) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized P2WPKH witness must have ` +\n `exactly 2 items [signature, pubkey], got ${items.length}.`,\n );\n }\n return { signature: items[0], pubkey: items[1] };\n}\n\nexport interface AssertReturnedP2wpkhSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout script/value). NOT the wallet's. */\n requestedPsbtHex: string;\n /** The wallet-returned PSBT input carrying the signature material. */\n returnedInput: {\n partialSig?: Array<{ pubkey: Uint8Array; signature: Uint8Array }>;\n finalScriptWitness?: Uint8Array;\n };\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that the returned input carries a valid P2WPKH ECDSA signature\n * over the BIP-143 sighash of `requestedPsbtHex` input `inputIndex`:\n * `partialSig` (BIP-174: the value is the exact witness-stack signature\n * bytes, the key its pubkey), or the finalized 2-item witness — and when\n * both are present they must be the same bytes.\n *\n * @throws If the requested input is not a P2WPKH spend, no signature was\n * returned, a finalized witness disagrees with its `partialSig`,\n * or any check of `verify_finalized_p2wpkh_spend` fails.\n */\nexport function assertReturnedP2wpkhSignature(\n params: AssertReturnedP2wpkhSignatureParams,\n): void {\n const { requestedPsbtHex, returnedInput, inputIndex } = params;\n\n const partials = returnedInput.partialSig;\n // Consensus allows exactly one signature in a P2WPKH witness, so a second\n // partialSig entry is ambiguous tampering, not a fallback to pick from.\n if (partials !== undefined && partials.length > 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a P2WPKH input must carry at most one ` +\n `partial signature, got ${partials.length}.`,\n );\n }\n const partial = partials?.[0];\n const witness = returnedInput.finalScriptWitness\n ? decodeP2wpkhWitness(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify (same\n // rationale as the tapKeySig/witness agreement check).\n if (\n partial &&\n witness &&\n (!bytesEqual(partial.signature, witness.signature) ||\n !bytesEqual(partial.pubkey, witness.pubkey))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its partialSig.`,\n );\n }\n\n const material = partial ?? witness;\n if (!material) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no P2WPKH signature ` +\n `(no partialSig, not finalized).`,\n );\n }\n\n assertP2wpkhEcdsaSignature(\n requestedPsbtHex,\n material.signature,\n material.pubkey,\n inputIndex,\n );\n}\n\n/**\n * The crypto core, mirroring `verify_finalized_p2wpkh_spend` check by\n * check: pubkey shape and curve membership, hash160(pubkey) == witness\n * program, strict-DER + SIGHASH_ALL-only signature, ECDSA over the\n * BIP-143 sighash recomputed from the REQUESTED prevout.\n */\nfunction assertP2wpkhEcdsaSignature(\n requestedPsbtHex: string,\n encodedSignature: Uint8Array,\n pubkey: Uint8Array,\n inputIndex: number,\n): void {\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n const prevout = psbt.data.inputs[inputIndex].witnessUtxo;\n if (!prevout || !isP2wpkhScript(prevout.script)) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a P2WPKH input.`,\n );\n }\n\n // Pubkey: exactly 33 bytes (client.rs:959-965) and a parseable curve\n // point, as PublicKey::from_slice (client.rs:966-968).\n if (pubkey.length !== COMPRESSED_PUBKEY_BYTES) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey must be 33 bytes, ` +\n `got ${pubkey.length}.`,\n );\n }\n if (!ecc.isPointCompressed(pubkey)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey is not a valid secp256k1 point.`,\n );\n }\n\n // hash160(pubkey) must equal the prevout's witness program — what\n // consensus checks (client.rs:970-977).\n const program = prevout.script.subarray(\n P2WPKH_PROGRAM_START,\n P2WPKH_SCRIPT_LEN,\n );\n if (!bytesEqual(bcrypto.hash160(Buffer.from(pubkey)), program)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey does not hash to the ` +\n `prevout's witness program.`,\n );\n }\n\n // Strict-DER decode with defined-hashtype gate — the accept set of\n // ecdsa::Signature::from_slice / EcdsaSighashType::from_standard\n // (client.rs:978-980) — then SIGHASH_ALL exactly (client.rs:981-987).\n let decoded: { signature: Buffer; hashType: number };\n try {\n decoded = bscript.signature.decode(Buffer.from(encodedSignature));\n } catch (e) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not DER with a ` +\n `defined sighash byte: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that libsecp's strict consensus\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(decoded.signature, decoded.hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not canonical DER.`,\n );\n }\n if (decoded.hashType !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature has sighash type ` +\n `0x${decoded.hashType.toString(16)} (expected SIGHASH_ALL).`,\n );\n }\n\n // BIP-143 sighash over the REQUESTED prevout value with the standard\n // P2WPKH scriptCode built from the witness program (client.rs:988-991;\n // scriptCode template per bitcoinjs-lib's own P2WPKH signer,\n // `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: Buffer.from(program) }).output;\n if (!scriptCode) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: could not build the P2WPKH scriptCode.`,\n );\n }\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV0(\n inputIndex,\n scriptCode,\n prevout.value,\n decoded.hashType,\n );\n\n // strict=true rejects high-S, as libsecp256k1's verify_ecdsa does\n // (client.rs:992-999; secp256k1 crate `ecdsa/mod.rs:194`). ecc.verify\n // throws on out-of-range r/s — that is a failed verification here.\n let verifies = false;\n try {\n verifies = ecc.verify(sighash, pubkey, decoded.signature, true);\n } catch {\n verifies = false;\n }\n if (!verifies) {\n throw new Error(\n `P2WPKH signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout. The wallet may have signed a different ` +\n `transaction or key.`,\n );\n }\n}\n","/**\n * Far-side verification of Taproot KEY-PATH Schnorr signatures a wallet\n * returned, over the PSBT we requested (trusted prevouts) — the key-path twin\n * of `assertScriptPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs check_signatures_valid` (output key taken\n * from the prevout scriptPubKey, all prevouts committed). The wallet's\n * success/finalization is never trusted on its own (CLAUDE.md §8).\n * `assertReturnedKeyPathSignatures` additionally dispatches P2WPKH-funded\n * inputs to `verifyP2wpkhEcdsaSignature` (client.rs's\n * `verify_finalized_p2wpkh_spend` sibling), so a Native SegWit software\n * wallet's signatures no longer pass through unchecked.\n *\n * Why verify against the *requested* PSBT: `assertPsbtUnsignedTxMatches` pins\n * the unsigned transaction but deliberately skips per-input metadata, so a\n * wallet could rewrite `witnessUtxo` in its response and make a wrong-message\n * signature self-validate. Prevout scripts and values therefore come from the\n * PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\nimport { hexToUint8Array, stripHexPrefix } from \"../utils/bitcoin\";\nimport {\n assertReturnedP2wpkhSignature,\n isP2wpkhScript,\n} from \"./verifyP2wpkhEcdsaSignature\";\n\nconst SCHNORR_SIG_BYTES = 64;\nconst SIGHASH_DEFAULT = Transaction.SIGHASH_DEFAULT; // 0x00\nconst SIGHASH_ALL = Transaction.SIGHASH_ALL; // 0x01\n\n// P2TR scriptPubKey is exactly `OP_1 OP_PUSHBYTES_32 <32-byte output key>`.\nconst P2TR_SCRIPT_LEN = 34;\nconst OP_1 = 0x51;\nconst OP_PUSHBYTES_32 = 0x20;\nconst P2TR_OUTPUT_KEY_OFFSET = 2;\n\nfunction isP2trScript(script: Uint8Array | undefined): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2TR_SCRIPT_LEN &&\n script[0] === OP_1 &&\n script[1] === OP_PUSHBYTES_32\n );\n}\n\n/** BIP-341: 64 bytes ⇒ SIGHASH_DEFAULT; 65 bytes ⇒ the trailing byte is the hash type (we accept ALL only). */\nfunction splitHashType(\n sig: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; hashType: number } {\n if (sig.length === SCHNORR_SIG_BYTES) {\n return { signature: sig, hashType: SIGHASH_DEFAULT };\n }\n if (\n sig.length === SCHNORR_SIG_BYTES + 1 &&\n sig[SCHNORR_SIG_BYTES] === SIGHASH_ALL\n ) {\n return {\n signature: sig.subarray(0, SCHNORR_SIG_BYTES),\n hashType: SIGHASH_ALL,\n };\n }\n throw new Error(\n `Key-path signature for input ${inputIndex} must be 64 bytes (SIGHASH_DEFAULT) or ` +\n `65 bytes ending in 0x01 (SIGHASH_ALL), got ${sig.length}.`,\n );\n}\n\nexport interface AssertKeyPathSchnorrSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout scripts/values). NOT the wallet's. */\n requestedPsbtHex: string;\n /** 64- or 65-byte signature, hex. */\n signatureHex: string;\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that `signatureHex` is a valid BIP-340 Schnorr signature over the\n * Taproot key-path sighash of `requestedPsbtHex` input `inputIndex`, under the\n * tweaked output key taken from that input's prevout scriptPubKey.\n *\n * @throws If the input is not a key-path P2TR spend, the requested PSBT lacks\n * the prevout data needed to recompute the sighash, or the signature\n * does not verify.\n */\nexport function assertKeyPathSchnorrSignature(\n params: AssertKeyPathSchnorrSignatureParams,\n): void {\n const { requestedPsbtHex, signatureHex, inputIndex } = params;\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n\n if (!isKeyPathEligible(psbt.data.inputs[inputIndex])) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a key-path P2TR input.`,\n );\n }\n\n // Taproot's sighash commits to every input's prevout (script + value), so all\n // inputs must carry a witnessUtxo. A missing one is a build error, not a\n // value we can default — fail loudly.\n const prevOutScripts: Buffer[] = [];\n const values: number[] = [];\n for (let i = 0; i < psbt.data.inputs.length; i++) {\n const prevout = psbt.data.inputs[i].witnessUtxo;\n if (!prevout) {\n throw new Error(\n `Cannot verify signature: input ${i} of the requested PSBT has no witnessUtxo ` +\n `(required to recompute the Taproot sighash).`,\n );\n }\n prevOutScripts.push(prevout.script);\n values.push(prevout.value);\n }\n\n const { signature, hashType } = splitHashType(\n hexToUint8Array(stripHexPrefix(signatureHex)),\n inputIndex,\n );\n\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV1(\n inputIndex,\n prevOutScripts,\n values,\n hashType,\n );\n\n // Key-path signatures verify against the TWEAKED output key = the prevout's\n // witness program.\n const outputKey = prevOutScripts[inputIndex].subarray(P2TR_OUTPUT_KEY_OFFSET);\n\n if (!ecc.verifySchnorr(sighash, outputKey, signature)) {\n throw new Error(\n `Key-path Schnorr signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout (output key ${Buffer.from(outputKey).toString(\"hex\")}). ` +\n `The wallet may have signed a different transaction or key.`,\n );\n }\n}\n\n/**\n * A key-path P2TR input: an internal key, no script-path material, and a\n * taproot prevout. Script-path inputs are the script-path verifier's job.\n */\nfunction isKeyPathEligible(input: {\n tapInternalKey?: Uint8Array;\n tapLeafScript?: unknown;\n tapMerkleRoot?: Uint8Array;\n witnessUtxo?: { script: Uint8Array };\n}): boolean {\n return (\n input.tapInternalKey !== undefined &&\n input.tapLeafScript === undefined &&\n input.tapMerkleRoot === undefined &&\n isP2trScript(input.witnessUtxo?.script)\n );\n}\n\n/**\n * The lone stack item of a finalized key-path witness. An annex would add a\n * second item, but Bitcoin Core rejects annexes as nonstandard\n * (`src/policy/policy.cpp:327-329`), so such a spend could never broadcast.\n */\nfunction singleWitnessItem(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): Uint8Array {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized key-path witness must have ` +\n `exactly one item, got ${items.length}.`,\n );\n }\n return items[0];\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\nexport interface AssertReturnedKeyPathSignaturesParams {\n /** PSBT we built locally and asked the wallet to sign. */\n requestedPsbtHex: string;\n /** PSBT the wallet returned after signing. */\n returnedPsbtHex: string;\n}\n\n/**\n * Verify every key-path-eligible and P2WPKH input of the REQUESTED PSBT\n * against what the wallet RETURNED. Key-path: `tapKeySig`, or the single\n * finalized witness item for wallets that auto-finalize — and when both are\n * present they must be the same bytes. P2WPKH: `partialSig`, or the finalized\n * 2-item witness, verified as ECDSA over the BIP-143 sighash\n * ({@link assertReturnedP2wpkhSignature}); a failure throws but the input is\n * NOT counted. Any other input type (script-path, P2WSH, ...) throws — no\n * verifier here covers it, so it cannot be treated as verified.\n *\n * @returns How many inputs were verified KEY-PATH. A caller that knows every\n * input is taproot key-path (e.g. an approval wallet) must assert\n * this equals its input count — P2WPKH inputs never count toward it,\n * so that gate stays exact.\n * @throws If the input counts differ, an input is neither key-path P2TR nor\n * P2WPKH, an eligible input carries no signature, a finalized witness\n * disagrees with its `tapKeySig`/`partialSig`, or any signature does\n * not verify.\n */\nexport function assertReturnedKeyPathSignatures(\n params: AssertReturnedKeyPathSignaturesParams,\n): number {\n const { requestedPsbtHex, returnedPsbtHex } = params;\n\n const requested = Psbt.fromHex(requestedPsbtHex);\n const returned = Psbt.fromHex(returnedPsbtHex);\n\n if (returned.data.inputs.length !== requested.data.inputs.length) {\n throw new Error(\n `Returned PSBT input count ${returned.data.inputs.length} differs from the ` +\n `requested ${requested.data.inputs.length}.`,\n );\n }\n\n let verified = 0;\n requested.data.inputs.forEach((input, inputIndex) => {\n const returnedInput = returned.data.inputs[inputIndex];\n\n if (!isKeyPathEligible(input)) {\n // Native SegWit funding inputs get the ECDSA check.\n if (isP2wpkhScript(input.witnessUtxo?.script)) {\n assertReturnedP2wpkhSignature({\n requestedPsbtHex,\n returnedInput,\n inputIndex,\n });\n return;\n }\n // No verifier exists for any other type — fail closed like btc-vault's\n // check_signatures_valid rather than silently reporting it checked.\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is neither key-path P2TR ` +\n `nor P2WPKH; refusing to treat it as verified.`,\n );\n }\n verified++;\n\n const tapKeySig = returnedInput.tapKeySig;\n const witnessSig = returnedInput.finalScriptWitness\n ? singleWitnessItem(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify. Matches\n // btc-vault `crates/btc-wallet-remote/src/client.rs:1053-1072,1102-1121`,\n // which checks each independently.\n if (tapKeySig && witnessSig && !bytesEqual(tapKeySig, witnessSig)) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its tapKeySig.`,\n );\n }\n\n const sig = tapKeySig ?? witnessSig;\n if (!sig) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no key-path signature ` +\n `(no tapKeySig, not finalized).`,\n );\n }\n\n assertKeyPathSchnorrSignature({\n requestedPsbtHex,\n signatureHex: Buffer.from(sig).toString(\"hex\"),\n inputIndex,\n });\n });\n\n return verified;\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","getPrePeginHtlcConnectorInfo","expectedHtlc","deriveExpectedPrePeginHtlc","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","hexToUint8Array","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","COMPACT_SIZE_UINT16_PREFIX","COMPACT_SIZE_UINT32_PREFIX","COMPACT_SIZE_UINT16_BYTES","COMPACT_SIZE_UINT32_BYTES","COMPACT_SIZE_UINT16_MIN_VALUE","COMPACT_SIZE_UINT32_MIN_VALUE","decodeWitnessStack","witness","subject","offset","readCompactSize","first","value","count","items","i","len","P2WPKH_SCRIPT_LEN","OP_0","OP_PUSHBYTES_20","P2WPKH_PROGRAM_START","COMPRESSED_PUBKEY_BYTES","P2WPKH_WITNESS_ITEMS","isP2wpkhScript","script","bytesEqual","a","b","byte","decodeP2wpkhWitness","finalScriptWitness","inputIndex","assertReturnedP2wpkhSignature","requestedPsbtHex","returnedInput","partials","partial","material","assertP2wpkhEcdsaSignature","encodedSignature","pubkey","prevout","ecc","program","bcrypto","decoded","bscript","scriptCode","payments","sighash","verifies","SCHNORR_SIG_BYTES","SIGHASH_DEFAULT","SIGHASH_ALL","P2TR_SCRIPT_LEN","OP_1","OP_PUSHBYTES_32","P2TR_OUTPUT_KEY_OFFSET","isP2trScript","splitHashType","assertKeyPathSchnorrSignature","signatureHex","isKeyPathEligible","prevOutScripts","values","signature","hashType","outputKey","_a","singleWitnessItem","assertReturnedKeyPathSignatures","returnedPsbtHex","requested","returned","verified","tapKeySig","witnessSig"],"mappings":";;;;;;AA4FA,eAAsBA,GACpBC,GACoC;AACpC,QAAMC,IAAaC,EAAeF,EAAO,UAAU,GAC7CG,IAAsBD,EAAeF,EAAO,mBAAmB;AAIrE,QAAMI,EAA6B;AAAA,IACjC,gBAAgBJ,EAAO;AAAA,IACvB,iBAAiBA,EAAO;AAAA,IACxB,qBAAqBA,EAA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IE,EAAS,KAAK,OAAO,WAAWD,EAAU,KAAK,OAAO;AACxD,UAAM,IAAI;AAAA,MACR,6BAA6BC,EAAS,KAAK,OAAO,MAAM,+BACzCD,EAAU,KAAK,OAAO,MAAM;AAAA,IAAA;AAI/C,MAAIE,IAAW;AACf,SAAAF,EAAU,KAAK,OAAO,QAAQ,CAACjF,GAAOwC,MAAe;;AACnD,UAAMG,IAAgBuC,EAAS,KAAK,OAAO1C,CAAU;AAErD,QAAI,CAAC+B,EAAkBvE,CAAK,GAAG;AAE7B,UAAIgC,GAAe6C,IAAA7E,EAAM,gBAAN,gBAAA6E,EAAmB,MAAM,GAAG;AAC7C,QAAApC,EAA8B;AAAA,UAC5B,kBAAAC;AAAA,UACA,eAAAC;AAAA,UACA,YAAAH;AAAA,QAAA,CACD;AACD;AAAA,MACF;AAGA,YAAM,IAAI;AAAA,QACR,SAASA,CAAU;AAAA,MAAA;AAAA,IAGvB;AACA,IAAA2C;AAEA,UAAMC,IAAYzC,EAAc,WAC1B0C,IAAa1C,EAAc,qBAC7BmC,GAAkBnC,EAAc,oBAAoBH,CAAU,IAC9D;AAMJ,QAAI4C,KAAaC,KAAc,CAACnD,GAAWkD,GAAWC,CAAU;AAC9D,YAAM,IAAI;AAAA,QACR,uBAAuB7C,CAAU;AAAA,MAAA;AAIrC,UAAMhC,IAAM4E,KAAaC;AACzB,QAAI,CAAC7E;AACH,YAAM,IAAI;AAAA,QACR,uBAAuBgC,CAAU;AAAA,MAAA;AAKrC,IAAA6B,GAA8B;AAAA,MAC5B,kBAAA3B;AAAA,MACA,cAAchD,EAAO,KAAKc,CAAG,EAAE,SAAS,KAAK;AAAA,MAC7C,YAAAgC;AAAA,IAAA,CACD;AAAA,EACH,CAAC,GAEM2C;AACT;"}
|
|
1
|
+
{"version":3,"file":"verifyKeyPathSchnorrSignature-BQHNhRj6.js","sources":["../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/utils/witness/witnessStack.ts","../src/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.ts","../src/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.ts"],"sourcesContent":["/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"../../wasm\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * Vault core (tx-graph) version the Pre-PegIn was built with. Must match\n * the version passed to buildPrePeginPsbt() so the HTLC connector scripts\n * are derived for the same graph.\n */\n vaultCoreVersion: number;\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n // Keep the facade's graph-version and input checks. Do not use its scripts\n // or control block as signing data.\n await getPrePeginHtlcConnectorInfo({\n txGraphVersion: params.vaultCoreVersion,\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n const expectedHtlc = deriveExpectedPrePeginHtlc(params, params.hashlock);\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n if (!expectedHtlc.scriptPubKey.equals(htlcOutput.script)) {\n throw new Error(\n \"PegIn HTLC taptree mismatch: the independent 2-leaf tree does not \" +\n \"reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.\",\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending. bitcoinjs\n // re-verifies leaf-in-tree consistency (control block vs tapMerkleRoot)\n // inside addInput — a second independent check.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.hashlockScript,\n controlBlock: expectedHtlc.hashlockControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(hexToUint8Array(depositorPubkey));\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // A wallet that ignores `autoFinalized: false` returns already-finalized\n // inputs (OKX's single-PSBT endpoint does; the wallet-connector routes OKX\n // around it). finalizeAllInputs() throws in that case, so fall back to\n // verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n","/**\n * Consensus witness-stack decoding, shared by every module that reads a\n * witness we did not build.\n *\n * Two independent decoders drifted apart before this existed: one accepted\n * non-minimal CompactSize encodings, the other rejected them. vaultd decodes\n * with rust-bitcoin, whose `VarInt::consensus_decode`\n * (0.32.8 `consensus/encode.rs:493-522`) returns `NonMinimalVarInt` for a 0xfd\n * carrying < 0xfd and a 0xfe carrying < 0x10000 — so the strict reading is the\n * only one that matches what the network will accept.\n *\n * @module tbv/core/utils/witness/witnessStack\n */\n\n/** CompactSize discriminators; 0xff (u64) is out of range for a witness. */\nconst COMPACT_SIZE_UINT16_PREFIX = 0xfd;\nconst COMPACT_SIZE_UINT32_PREFIX = 0xfe;\nconst COMPACT_SIZE_UINT16_BYTES = 3;\nconst COMPACT_SIZE_UINT32_BYTES = 5;\nconst COMPACT_SIZE_UINT16_MIN_VALUE = 0xfd;\nconst COMPACT_SIZE_UINT32_MIN_VALUE = 0x10000;\n\n/**\n * Decode a consensus-encoded witness stack: item count, then (len, bytes)*.\n *\n * @param witness - The consensus-encoded witness bytes.\n * @param subject - Names the witness in error messages (e.g. \"finalScriptWitness\").\n * @returns The stack items, as views over `witness`.\n * @throws If the encoding is truncated, non-minimal, out of range, or leaves\n * trailing bytes.\n */\nexport function decodeWitnessStack(\n witness: Uint8Array,\n subject: string,\n): Uint8Array[] {\n let offset = 0;\n\n const readCompactSize = (): number => {\n if (offset >= witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const first = witness[offset];\n if (first < COMPACT_SIZE_UINT16_PREFIX) {\n offset += 1;\n return first;\n }\n if (first === COMPACT_SIZE_UINT16_PREFIX) {\n if (offset + COMPACT_SIZE_UINT16_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value = witness[offset + 1] | (witness[offset + 2] << 8);\n if (value < COMPACT_SIZE_UINT16_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT16_BYTES;\n return value;\n }\n if (first === COMPACT_SIZE_UINT32_PREFIX) {\n if (offset + COMPACT_SIZE_UINT32_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value =\n (witness[offset + 1] |\n (witness[offset + 2] << 8) |\n (witness[offset + 3] << 16) |\n (witness[offset + 4] << 24)) >>>\n 0;\n if (value < COMPACT_SIZE_UINT32_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT32_BYTES;\n return value;\n }\n throw new Error(`${subject} carries an out-of-range item length`);\n };\n\n const count = readCompactSize();\n const items: Uint8Array[] = [];\n for (let i = 0; i < count; i++) {\n const len = readCompactSize();\n if (offset + len > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n items.push(witness.subarray(offset, offset + len));\n offset += len;\n }\n if (offset !== witness.length) {\n throw new Error(`${subject} has trailing bytes`);\n }\n return items;\n}\n","/**\n * Far-side verification of P2WPKH ECDSA signatures a wallet returned, over\n * the PSBT we requested (trusted prevouts) — the Native SegWit sibling of\n * `verifyKeyPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs:945-1000\n * verify_finalized_p2wpkh_spend`. The wallet's success/finalization is\n * never trusted on its own (CLAUDE.md §8): prevout script and value come\n * from the PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport {\n crypto as bcrypto,\n script as bscript,\n payments,\n Psbt,\n Transaction,\n} from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\n\n// P2WPKH scriptPubKey is exactly `OP_0 OP_PUSHBYTES_20 <20-byte key hash>`\n// (BIP-141 witness program v0, 20 bytes).\nconst P2WPKH_SCRIPT_LEN = 22;\nconst OP_0 = 0x00;\nconst OP_PUSHBYTES_20 = 0x14;\nconst P2WPKH_PROGRAM_START = 2;\n\n/** SEC1 compressed pubkey (client.rs:959: \"expected a 33-byte compressed key\"). */\nconst COMPRESSED_PUBKEY_BYTES = 33;\n/** Consensus P2WPKH witness: exactly [signature, pubkey] (client.rs:951-957). */\nconst P2WPKH_WITNESS_ITEMS = 2;\n\n/** Only claim P2WPKH: 22-byte scriptPubKey starting `OP_0 PUSH20`. */\nexport function isP2wpkhScript(\n script: Uint8Array | undefined,\n): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2WPKH_SCRIPT_LEN &&\n script[0] === OP_0 &&\n script[1] === OP_PUSHBYTES_20\n );\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\n/** The `[signature, pubkey]` pair of a finalized P2WPKH witness (client.rs:951-957). */\nfunction decodeP2wpkhWitness(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; pubkey: Uint8Array } {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== P2WPKH_WITNESS_ITEMS) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized P2WPKH witness must have ` +\n `exactly 2 items [signature, pubkey], got ${items.length}.`,\n );\n }\n return { signature: items[0], pubkey: items[1] };\n}\n\nexport interface AssertReturnedP2wpkhSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout script/value). NOT the wallet's. */\n requestedPsbtHex: string;\n /** The wallet-returned PSBT input carrying the signature material. */\n returnedInput: {\n partialSig?: Array<{ pubkey: Uint8Array; signature: Uint8Array }>;\n finalScriptWitness?: Uint8Array;\n };\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that the returned input carries a valid P2WPKH ECDSA signature\n * over the BIP-143 sighash of `requestedPsbtHex` input `inputIndex`:\n * `partialSig` (BIP-174: the value is the exact witness-stack signature\n * bytes, the key its pubkey), or the finalized 2-item witness — and when\n * both are present they must be the same bytes.\n *\n * @throws If the requested input is not a P2WPKH spend, no signature was\n * returned, a finalized witness disagrees with its `partialSig`,\n * or any check of `verify_finalized_p2wpkh_spend` fails.\n */\nexport function assertReturnedP2wpkhSignature(\n params: AssertReturnedP2wpkhSignatureParams,\n): void {\n const { requestedPsbtHex, returnedInput, inputIndex } = params;\n\n const partials = returnedInput.partialSig;\n // Consensus allows exactly one signature in a P2WPKH witness, so a second\n // partialSig entry is ambiguous tampering, not a fallback to pick from.\n if (partials !== undefined && partials.length > 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a P2WPKH input must carry at most one ` +\n `partial signature, got ${partials.length}.`,\n );\n }\n const partial = partials?.[0];\n const witness = returnedInput.finalScriptWitness\n ? decodeP2wpkhWitness(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify (same\n // rationale as the tapKeySig/witness agreement check).\n if (\n partial &&\n witness &&\n (!bytesEqual(partial.signature, witness.signature) ||\n !bytesEqual(partial.pubkey, witness.pubkey))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its partialSig.`,\n );\n }\n\n const material = partial ?? witness;\n if (!material) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no P2WPKH signature ` +\n `(no partialSig, not finalized).`,\n );\n }\n\n assertP2wpkhEcdsaSignature(\n requestedPsbtHex,\n material.signature,\n material.pubkey,\n inputIndex,\n );\n}\n\n/**\n * The crypto core, mirroring `verify_finalized_p2wpkh_spend` check by\n * check: pubkey shape and curve membership, hash160(pubkey) == witness\n * program, strict-DER + SIGHASH_ALL-only signature, ECDSA over the\n * BIP-143 sighash recomputed from the REQUESTED prevout.\n */\nfunction assertP2wpkhEcdsaSignature(\n requestedPsbtHex: string,\n encodedSignature: Uint8Array,\n pubkey: Uint8Array,\n inputIndex: number,\n): void {\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n const prevout = psbt.data.inputs[inputIndex].witnessUtxo;\n if (!prevout || !isP2wpkhScript(prevout.script)) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a P2WPKH input.`,\n );\n }\n\n // Pubkey: exactly 33 bytes (client.rs:959-965) and a parseable curve\n // point, as PublicKey::from_slice (client.rs:966-968).\n if (pubkey.length !== COMPRESSED_PUBKEY_BYTES) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey must be 33 bytes, ` +\n `got ${pubkey.length}.`,\n );\n }\n if (!ecc.isPointCompressed(pubkey)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey is not a valid secp256k1 point.`,\n );\n }\n\n // hash160(pubkey) must equal the prevout's witness program — what\n // consensus checks (client.rs:970-977).\n const program = prevout.script.subarray(\n P2WPKH_PROGRAM_START,\n P2WPKH_SCRIPT_LEN,\n );\n if (!bytesEqual(bcrypto.hash160(Buffer.from(pubkey)), program)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey does not hash to the ` +\n `prevout's witness program.`,\n );\n }\n\n // Strict-DER decode with defined-hashtype gate — the accept set of\n // ecdsa::Signature::from_slice / EcdsaSighashType::from_standard\n // (client.rs:978-980) — then SIGHASH_ALL exactly (client.rs:981-987).\n let decoded: { signature: Buffer; hashType: number };\n try {\n decoded = bscript.signature.decode(Buffer.from(encodedSignature));\n } catch (e) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not DER with a ` +\n `defined sighash byte: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that libsecp's strict consensus\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(decoded.signature, decoded.hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not canonical DER.`,\n );\n }\n if (decoded.hashType !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature has sighash type ` +\n `0x${decoded.hashType.toString(16)} (expected SIGHASH_ALL).`,\n );\n }\n\n // BIP-143 sighash over the REQUESTED prevout value with the standard\n // P2WPKH scriptCode built from the witness program (client.rs:988-991;\n // scriptCode template per bitcoinjs-lib's own P2WPKH signer,\n // `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: Buffer.from(program) }).output;\n if (!scriptCode) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: could not build the P2WPKH scriptCode.`,\n );\n }\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV0(\n inputIndex,\n scriptCode,\n prevout.value,\n decoded.hashType,\n );\n\n // strict=true rejects high-S, as libsecp256k1's verify_ecdsa does\n // (client.rs:992-999; secp256k1 crate `ecdsa/mod.rs:194`). ecc.verify\n // throws on out-of-range r/s — that is a failed verification here.\n let verifies = false;\n try {\n verifies = ecc.verify(sighash, pubkey, decoded.signature, true);\n } catch {\n verifies = false;\n }\n if (!verifies) {\n throw new Error(\n `P2WPKH signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout. The wallet may have signed a different ` +\n `transaction or key.`,\n );\n }\n}\n","/**\n * Far-side verification of Taproot KEY-PATH Schnorr signatures a wallet\n * returned, over the PSBT we requested (trusted prevouts) — the key-path twin\n * of `assertScriptPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs check_signatures_valid` (output key taken\n * from the prevout scriptPubKey, all prevouts committed). The wallet's\n * success/finalization is never trusted on its own (CLAUDE.md §8).\n * `assertReturnedKeyPathSignatures` additionally dispatches P2WPKH-funded\n * inputs to `verifyP2wpkhEcdsaSignature` (client.rs's\n * `verify_finalized_p2wpkh_spend` sibling), so a Native SegWit software\n * wallet's signatures no longer pass through unchecked.\n *\n * Why verify against the *requested* PSBT: `assertPsbtUnsignedTxMatches` pins\n * the unsigned transaction but deliberately skips per-input metadata, so a\n * wallet could rewrite `witnessUtxo` in its response and make a wrong-message\n * signature self-validate. Prevout scripts and values therefore come from the\n * PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\nimport { hexToUint8Array, stripHexPrefix } from \"../utils/bitcoin\";\nimport {\n assertReturnedP2wpkhSignature,\n isP2wpkhScript,\n} from \"./verifyP2wpkhEcdsaSignature\";\n\nconst SCHNORR_SIG_BYTES = 64;\nconst SIGHASH_DEFAULT = Transaction.SIGHASH_DEFAULT; // 0x00\nconst SIGHASH_ALL = Transaction.SIGHASH_ALL; // 0x01\n\n// P2TR scriptPubKey is exactly `OP_1 OP_PUSHBYTES_32 <32-byte output key>`.\nconst P2TR_SCRIPT_LEN = 34;\nconst OP_1 = 0x51;\nconst OP_PUSHBYTES_32 = 0x20;\nconst P2TR_OUTPUT_KEY_OFFSET = 2;\n\nfunction isP2trScript(script: Uint8Array | undefined): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2TR_SCRIPT_LEN &&\n script[0] === OP_1 &&\n script[1] === OP_PUSHBYTES_32\n );\n}\n\n/** BIP-341: 64 bytes ⇒ SIGHASH_DEFAULT; 65 bytes ⇒ the trailing byte is the hash type (we accept ALL only). */\nfunction splitHashType(\n sig: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; hashType: number } {\n if (sig.length === SCHNORR_SIG_BYTES) {\n return { signature: sig, hashType: SIGHASH_DEFAULT };\n }\n if (\n sig.length === SCHNORR_SIG_BYTES + 1 &&\n sig[SCHNORR_SIG_BYTES] === SIGHASH_ALL\n ) {\n return {\n signature: sig.subarray(0, SCHNORR_SIG_BYTES),\n hashType: SIGHASH_ALL,\n };\n }\n throw new Error(\n `Key-path signature for input ${inputIndex} must be 64 bytes (SIGHASH_DEFAULT) or ` +\n `65 bytes ending in 0x01 (SIGHASH_ALL), got ${sig.length}.`,\n );\n}\n\nexport interface AssertKeyPathSchnorrSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout scripts/values). NOT the wallet's. */\n requestedPsbtHex: string;\n /** 64- or 65-byte signature, hex. */\n signatureHex: string;\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that `signatureHex` is a valid BIP-340 Schnorr signature over the\n * Taproot key-path sighash of `requestedPsbtHex` input `inputIndex`, under the\n * tweaked output key taken from that input's prevout scriptPubKey.\n *\n * @throws If the input is not a key-path P2TR spend, the requested PSBT lacks\n * the prevout data needed to recompute the sighash, or the signature\n * does not verify.\n */\nexport function assertKeyPathSchnorrSignature(\n params: AssertKeyPathSchnorrSignatureParams,\n): void {\n const { requestedPsbtHex, signatureHex, inputIndex } = params;\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n\n if (!isKeyPathEligible(psbt.data.inputs[inputIndex])) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a key-path P2TR input.`,\n );\n }\n\n // Taproot's sighash commits to every input's prevout (script + value), so all\n // inputs must carry a witnessUtxo. A missing one is a build error, not a\n // value we can default — fail loudly.\n const prevOutScripts: Buffer[] = [];\n const values: number[] = [];\n for (let i = 0; i < psbt.data.inputs.length; i++) {\n const prevout = psbt.data.inputs[i].witnessUtxo;\n if (!prevout) {\n throw new Error(\n `Cannot verify signature: input ${i} of the requested PSBT has no witnessUtxo ` +\n `(required to recompute the Taproot sighash).`,\n );\n }\n prevOutScripts.push(prevout.script);\n values.push(prevout.value);\n }\n\n const { signature, hashType } = splitHashType(\n hexToUint8Array(stripHexPrefix(signatureHex)),\n inputIndex,\n );\n\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV1(\n inputIndex,\n prevOutScripts,\n values,\n hashType,\n );\n\n // Key-path signatures verify against the TWEAKED output key = the prevout's\n // witness program.\n const outputKey = prevOutScripts[inputIndex].subarray(P2TR_OUTPUT_KEY_OFFSET);\n\n if (!ecc.verifySchnorr(sighash, outputKey, signature)) {\n throw new Error(\n `Key-path Schnorr signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout (output key ${Buffer.from(outputKey).toString(\"hex\")}). ` +\n `The wallet may have signed a different transaction or key.`,\n );\n }\n}\n\n/**\n * A key-path P2TR input: an internal key, no script-path material, and a\n * taproot prevout. Script-path inputs are the script-path verifier's job.\n */\nfunction isKeyPathEligible(input: {\n tapInternalKey?: Uint8Array;\n tapLeafScript?: unknown;\n tapMerkleRoot?: Uint8Array;\n witnessUtxo?: { script: Uint8Array };\n}): boolean {\n return (\n input.tapInternalKey !== undefined &&\n input.tapLeafScript === undefined &&\n input.tapMerkleRoot === undefined &&\n isP2trScript(input.witnessUtxo?.script)\n );\n}\n\n/**\n * The lone stack item of a finalized key-path witness. An annex would add a\n * second item, but Bitcoin Core rejects annexes as nonstandard\n * (`src/policy/policy.cpp:327-329`), so such a spend could never broadcast.\n */\nfunction singleWitnessItem(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): Uint8Array {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized key-path witness must have ` +\n `exactly one item, got ${items.length}.`,\n );\n }\n return items[0];\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\nexport interface AssertReturnedKeyPathSignaturesParams {\n /** PSBT we built locally and asked the wallet to sign. */\n requestedPsbtHex: string;\n /** PSBT the wallet returned after signing. */\n returnedPsbtHex: string;\n}\n\n/**\n * Verify every key-path-eligible and P2WPKH input of the REQUESTED PSBT\n * against what the wallet RETURNED. Key-path: `tapKeySig`, or the single\n * finalized witness item for wallets that auto-finalize — and when both are\n * present they must be the same bytes. P2WPKH: `partialSig`, or the finalized\n * 2-item witness, verified as ECDSA over the BIP-143 sighash\n * ({@link assertReturnedP2wpkhSignature}); a failure throws but the input is\n * NOT counted. Any other input type (script-path, P2WSH, ...) throws — no\n * verifier here covers it, so it cannot be treated as verified.\n *\n * @returns How many inputs were verified KEY-PATH. A caller that knows every\n * input is taproot key-path (e.g. an approval wallet) must assert\n * this equals its input count — P2WPKH inputs never count toward it,\n * so that gate stays exact.\n * @throws If the input counts differ, an input is neither key-path P2TR nor\n * P2WPKH, an eligible input carries no signature, a finalized witness\n * disagrees with its `tapKeySig`/`partialSig`, or any signature does\n * not verify.\n */\nexport function assertReturnedKeyPathSignatures(\n params: AssertReturnedKeyPathSignaturesParams,\n): number {\n const { requestedPsbtHex, returnedPsbtHex } = params;\n\n const requested = Psbt.fromHex(requestedPsbtHex);\n const returned = Psbt.fromHex(returnedPsbtHex);\n\n if (returned.data.inputs.length !== requested.data.inputs.length) {\n throw new Error(\n `Returned PSBT input count ${returned.data.inputs.length} differs from the ` +\n `requested ${requested.data.inputs.length}.`,\n );\n }\n\n let verified = 0;\n requested.data.inputs.forEach((input, inputIndex) => {\n const returnedInput = returned.data.inputs[inputIndex];\n\n if (!isKeyPathEligible(input)) {\n // Native SegWit funding inputs get the ECDSA check.\n if (isP2wpkhScript(input.witnessUtxo?.script)) {\n assertReturnedP2wpkhSignature({\n requestedPsbtHex,\n returnedInput,\n inputIndex,\n });\n return;\n }\n // No verifier exists for any other type — fail closed like btc-vault's\n // check_signatures_valid rather than silently reporting it checked.\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is neither key-path P2TR ` +\n `nor P2WPKH; refusing to treat it as verified.`,\n );\n }\n verified++;\n\n const tapKeySig = returnedInput.tapKeySig;\n const witnessSig = returnedInput.finalScriptWitness\n ? singleWitnessItem(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify. Matches\n // btc-vault `crates/btc-wallet-remote/src/client.rs:1053-1072,1102-1121`,\n // which checks each independently.\n if (tapKeySig && witnessSig && !bytesEqual(tapKeySig, witnessSig)) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its tapKeySig.`,\n );\n }\n\n const sig = tapKeySig ?? witnessSig;\n if (!sig) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no key-path signature ` +\n `(no tapKeySig, not finalized).`,\n );\n }\n\n assertKeyPathSchnorrSignature({\n requestedPsbtHex,\n signatureHex: Buffer.from(sig).toString(\"hex\"),\n inputIndex,\n });\n });\n\n return verified;\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","getPrePeginHtlcConnectorInfo","expectedHtlc","deriveExpectedPrePeginHtlc","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","hexToUint8Array","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","COMPACT_SIZE_UINT16_PREFIX","COMPACT_SIZE_UINT32_PREFIX","COMPACT_SIZE_UINT16_BYTES","COMPACT_SIZE_UINT32_BYTES","COMPACT_SIZE_UINT16_MIN_VALUE","COMPACT_SIZE_UINT32_MIN_VALUE","decodeWitnessStack","witness","subject","offset","readCompactSize","first","value","count","items","i","len","P2WPKH_SCRIPT_LEN","OP_0","OP_PUSHBYTES_20","P2WPKH_PROGRAM_START","COMPRESSED_PUBKEY_BYTES","P2WPKH_WITNESS_ITEMS","isP2wpkhScript","script","bytesEqual","a","b","byte","decodeP2wpkhWitness","finalScriptWitness","inputIndex","assertReturnedP2wpkhSignature","requestedPsbtHex","returnedInput","partials","partial","material","assertP2wpkhEcdsaSignature","encodedSignature","pubkey","prevout","ecc","program","bcrypto","decoded","bscript","scriptCode","payments","sighash","verifies","SCHNORR_SIG_BYTES","SIGHASH_DEFAULT","SIGHASH_ALL","P2TR_SCRIPT_LEN","OP_1","OP_PUSHBYTES_32","P2TR_OUTPUT_KEY_OFFSET","isP2trScript","splitHashType","assertKeyPathSchnorrSignature","signatureHex","isKeyPathEligible","prevOutScripts","values","signature","hashType","outputKey","_a","singleWitnessItem","assertReturnedKeyPathSignatures","returnedPsbtHex","requested","returned","verified","tapKeySig","witnessSig"],"mappings":";;;;;;AA4FA,eAAsBA,GACpBC,GACoC;AACpC,QAAMC,IAAaC,EAAeF,EAAO,UAAU,GAC7CG,IAAsBD,EAAeF,EAAO,mBAAmB;AAIrE,QAAMI,EAA6B;AAAA,IACjC,gBAAgBJ,EAAO;AAAA,IACvB,iBAAiBA,EAAO;AAAA,IACxB,qBAAqBA,EAAO;AAAA,IAC5B,oBAAoBA,EAAO;AAAA,IAC3B,4BAA4BA,EAAO;AAAA,IACnC,UAAUA,EAAO;AAAA,IACjB,gBAAgBA,EAAO;AAAA,IACvB,SAASA,EAAO;AAAA,EAAA,CACjB;AACD,QAAMK,IAAeC,EAA2BN,GAAQA,EAAO,QAAQ,GAEjEO,IAAUC,EAAY,QAAQP,CAAU,GACxCQ,IAAaD,EAAY,QAAQL,CAAmB;AAE1D,MAAII,EAAQ,IAAI,WAAW;AACzB,UAAM,IAAI;AAAA,MACR,oDAAoDA,EAAQ,IAAI,MAAM;AAAA,IAAA;AAI1E,QAAMG,IAAaH,EAAQ,IAAI,CAAC,GAG1BI,IAAeF,EAAW,MAAA,GAC1BG,IAAiBC;AAAA,IACrB,IAAI,WAAWH,EAAW,IAAI,EAAE,MAAA,EAAQ,QAAA;AAAA,EAAQ;AAGlD,MAAIE,MAAmBD;AACrB,UAAM,IAAI;AAAA,MACR,sEACcA,CAAY,SAASC,CAAc;AAAA,IAAA;AAIrD,QAAME,IAAaL,EAAW,KAAKC,EAAW,KAAK;AACnD,MAAI,CAACI;AACH,UAAM,IAAI;AAAA,MACR,oBAAoBJ,EAAW,KAAK,6BAChBD,EAAW,KAAK,MAAM;AAAA,IAAA;AAI9C,MAAI,CAACJ,EAAa,aAAa,OAAOS,EAAW,MAAM;AACrD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AaC;AACzB,QAAI,CAAC7E;AACH,YAAM,IAAI;AAAA,QACR,uBAAuBgC,CAAU;AAAA,MAAA;AAKrC,IAAA6B,GAA8B;AAAA,MAC5B,kBAAA3B;AAAA,MACA,cAAchD,EAAO,KAAKc,CAAG,EAAE,SAAS,KAAK;AAAA,MAC7C,YAAAgC;AAAA,IAAA,CACD;AAAA,EACH,CAAC,GAEM2C;AACT;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifyKeyPathSchnorrSignature-Gm9EmZkx.cjs","sources":["../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/utils/witness/witnessStack.ts","../src/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.ts","../src/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.ts"],"sourcesContent":["/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"../../wasm\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * Vault core (tx-graph) version the Pre-PegIn was built with. Must match\n * the version passed to buildPrePeginPsbt() so the HTLC connector scripts\n * are derived for the same graph.\n */\n vaultCoreVersion: number;\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n // Keep the facade's graph-version and input checks. Do not use its scripts\n // or control block as signing data.\n await getPrePeginHtlcConnectorInfo({\n txGraphVersion: params.vaultCoreVersion,\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n const expectedHtlc = deriveExpectedPrePeginHtlc(params, params.hashlock);\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n if (!expectedHtlc.scriptPubKey.equals(htlcOutput.script)) {\n throw new Error(\n \"PegIn HTLC taptree mismatch: the independent 2-leaf tree does not \" +\n \"reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.\",\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending. bitcoinjs\n // re-verifies leaf-in-tree consistency (control block vs tapMerkleRoot)\n // inside addInput — a second independent check.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.hashlockScript,\n controlBlock: expectedHtlc.hashlockControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(hexToUint8Array(depositorPubkey));\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n","/**\n * Consensus witness-stack decoding, shared by every module that reads a\n * witness we did not build.\n *\n * Two independent decoders drifted apart before this existed: one accepted\n * non-minimal CompactSize encodings, the other rejected them. vaultd decodes\n * with rust-bitcoin, whose `VarInt::consensus_decode`\n * (0.32.8 `consensus/encode.rs:493-522`) returns `NonMinimalVarInt` for a 0xfd\n * carrying < 0xfd and a 0xfe carrying < 0x10000 — so the strict reading is the\n * only one that matches what the network will accept.\n *\n * @module tbv/core/utils/witness/witnessStack\n */\n\n/** CompactSize discriminators; 0xff (u64) is out of range for a witness. */\nconst COMPACT_SIZE_UINT16_PREFIX = 0xfd;\nconst COMPACT_SIZE_UINT32_PREFIX = 0xfe;\nconst COMPACT_SIZE_UINT16_BYTES = 3;\nconst COMPACT_SIZE_UINT32_BYTES = 5;\nconst COMPACT_SIZE_UINT16_MIN_VALUE = 0xfd;\nconst COMPACT_SIZE_UINT32_MIN_VALUE = 0x10000;\n\n/**\n * Decode a consensus-encoded witness stack: item count, then (len, bytes)*.\n *\n * @param witness - The consensus-encoded witness bytes.\n * @param subject - Names the witness in error messages (e.g. \"finalScriptWitness\").\n * @returns The stack items, as views over `witness`.\n * @throws If the encoding is truncated, non-minimal, out of range, or leaves\n * trailing bytes.\n */\nexport function decodeWitnessStack(\n witness: Uint8Array,\n subject: string,\n): Uint8Array[] {\n let offset = 0;\n\n const readCompactSize = (): number => {\n if (offset >= witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const first = witness[offset];\n if (first < COMPACT_SIZE_UINT16_PREFIX) {\n offset += 1;\n return first;\n }\n if (first === COMPACT_SIZE_UINT16_PREFIX) {\n if (offset + COMPACT_SIZE_UINT16_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value = witness[offset + 1] | (witness[offset + 2] << 8);\n if (value < COMPACT_SIZE_UINT16_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT16_BYTES;\n return value;\n }\n if (first === COMPACT_SIZE_UINT32_PREFIX) {\n if (offset + COMPACT_SIZE_UINT32_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value =\n (witness[offset + 1] |\n (witness[offset + 2] << 8) |\n (witness[offset + 3] << 16) |\n (witness[offset + 4] << 24)) >>>\n 0;\n if (value < COMPACT_SIZE_UINT32_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT32_BYTES;\n return value;\n }\n throw new Error(`${subject} carries an out-of-range item length`);\n };\n\n const count = readCompactSize();\n const items: Uint8Array[] = [];\n for (let i = 0; i < count; i++) {\n const len = readCompactSize();\n if (offset + len > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n items.push(witness.subarray(offset, offset + len));\n offset += len;\n }\n if (offset !== witness.length) {\n throw new Error(`${subject} has trailing bytes`);\n }\n return items;\n}\n","/**\n * Far-side verification of P2WPKH ECDSA signatures a wallet returned, over\n * the PSBT we requested (trusted prevouts) — the Native SegWit sibling of\n * `verifyKeyPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs:945-1000\n * verify_finalized_p2wpkh_spend`. The wallet's success/finalization is\n * never trusted on its own (CLAUDE.md §8): prevout script and value come\n * from the PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport {\n crypto as bcrypto,\n script as bscript,\n payments,\n Psbt,\n Transaction,\n} from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\n\n// P2WPKH scriptPubKey is exactly `OP_0 OP_PUSHBYTES_20 <20-byte key hash>`\n// (BIP-141 witness program v0, 20 bytes).\nconst P2WPKH_SCRIPT_LEN = 22;\nconst OP_0 = 0x00;\nconst OP_PUSHBYTES_20 = 0x14;\nconst P2WPKH_PROGRAM_START = 2;\n\n/** SEC1 compressed pubkey (client.rs:959: \"expected a 33-byte compressed key\"). */\nconst COMPRESSED_PUBKEY_BYTES = 33;\n/** Consensus P2WPKH witness: exactly [signature, pubkey] (client.rs:951-957). */\nconst P2WPKH_WITNESS_ITEMS = 2;\n\n/** Only claim P2WPKH: 22-byte scriptPubKey starting `OP_0 PUSH20`. */\nexport function isP2wpkhScript(\n script: Uint8Array | undefined,\n): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2WPKH_SCRIPT_LEN &&\n script[0] === OP_0 &&\n script[1] === OP_PUSHBYTES_20\n );\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\n/** The `[signature, pubkey]` pair of a finalized P2WPKH witness (client.rs:951-957). */\nfunction decodeP2wpkhWitness(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; pubkey: Uint8Array } {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== P2WPKH_WITNESS_ITEMS) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized P2WPKH witness must have ` +\n `exactly 2 items [signature, pubkey], got ${items.length}.`,\n );\n }\n return { signature: items[0], pubkey: items[1] };\n}\n\nexport interface AssertReturnedP2wpkhSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout script/value). NOT the wallet's. */\n requestedPsbtHex: string;\n /** The wallet-returned PSBT input carrying the signature material. */\n returnedInput: {\n partialSig?: Array<{ pubkey: Uint8Array; signature: Uint8Array }>;\n finalScriptWitness?: Uint8Array;\n };\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that the returned input carries a valid P2WPKH ECDSA signature\n * over the BIP-143 sighash of `requestedPsbtHex` input `inputIndex`:\n * `partialSig` (BIP-174: the value is the exact witness-stack signature\n * bytes, the key its pubkey), or the finalized 2-item witness — and when\n * both are present they must be the same bytes.\n *\n * @throws If the requested input is not a P2WPKH spend, no signature was\n * returned, a finalized witness disagrees with its `partialSig`,\n * or any check of `verify_finalized_p2wpkh_spend` fails.\n */\nexport function assertReturnedP2wpkhSignature(\n params: AssertReturnedP2wpkhSignatureParams,\n): void {\n const { requestedPsbtHex, returnedInput, inputIndex } = params;\n\n const partials = returnedInput.partialSig;\n // Consensus allows exactly one signature in a P2WPKH witness, so a second\n // partialSig entry is ambiguous tampering, not a fallback to pick from.\n if (partials !== undefined && partials.length > 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a P2WPKH input must carry at most one ` +\n `partial signature, got ${partials.length}.`,\n );\n }\n const partial = partials?.[0];\n const witness = returnedInput.finalScriptWitness\n ? decodeP2wpkhWitness(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify (same\n // rationale as the tapKeySig/witness agreement check).\n if (\n partial &&\n witness &&\n (!bytesEqual(partial.signature, witness.signature) ||\n !bytesEqual(partial.pubkey, witness.pubkey))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its partialSig.`,\n );\n }\n\n const material = partial ?? witness;\n if (!material) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no P2WPKH signature ` +\n `(no partialSig, not finalized).`,\n );\n }\n\n assertP2wpkhEcdsaSignature(\n requestedPsbtHex,\n material.signature,\n material.pubkey,\n inputIndex,\n );\n}\n\n/**\n * The crypto core, mirroring `verify_finalized_p2wpkh_spend` check by\n * check: pubkey shape and curve membership, hash160(pubkey) == witness\n * program, strict-DER + SIGHASH_ALL-only signature, ECDSA over the\n * BIP-143 sighash recomputed from the REQUESTED prevout.\n */\nfunction assertP2wpkhEcdsaSignature(\n requestedPsbtHex: string,\n encodedSignature: Uint8Array,\n pubkey: Uint8Array,\n inputIndex: number,\n): void {\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n const prevout = psbt.data.inputs[inputIndex].witnessUtxo;\n if (!prevout || !isP2wpkhScript(prevout.script)) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a P2WPKH input.`,\n );\n }\n\n // Pubkey: exactly 33 bytes (client.rs:959-965) and a parseable curve\n // point, as PublicKey::from_slice (client.rs:966-968).\n if (pubkey.length !== COMPRESSED_PUBKEY_BYTES) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey must be 33 bytes, ` +\n `got ${pubkey.length}.`,\n );\n }\n if (!ecc.isPointCompressed(pubkey)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey is not a valid secp256k1 point.`,\n );\n }\n\n // hash160(pubkey) must equal the prevout's witness program — what\n // consensus checks (client.rs:970-977).\n const program = prevout.script.subarray(\n P2WPKH_PROGRAM_START,\n P2WPKH_SCRIPT_LEN,\n );\n if (!bytesEqual(bcrypto.hash160(Buffer.from(pubkey)), program)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey does not hash to the ` +\n `prevout's witness program.`,\n );\n }\n\n // Strict-DER decode with defined-hashtype gate — the accept set of\n // ecdsa::Signature::from_slice / EcdsaSighashType::from_standard\n // (client.rs:978-980) — then SIGHASH_ALL exactly (client.rs:981-987).\n let decoded: { signature: Buffer; hashType: number };\n try {\n decoded = bscript.signature.decode(Buffer.from(encodedSignature));\n } catch (e) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not DER with a ` +\n `defined sighash byte: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that libsecp's strict consensus\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(decoded.signature, decoded.hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not canonical DER.`,\n );\n }\n if (decoded.hashType !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature has sighash type ` +\n `0x${decoded.hashType.toString(16)} (expected SIGHASH_ALL).`,\n );\n }\n\n // BIP-143 sighash over the REQUESTED prevout value with the standard\n // P2WPKH scriptCode built from the witness program (client.rs:988-991;\n // scriptCode template per bitcoinjs-lib's own P2WPKH signer,\n // `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: Buffer.from(program) }).output;\n if (!scriptCode) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: could not build the P2WPKH scriptCode.`,\n );\n }\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV0(\n inputIndex,\n scriptCode,\n prevout.value,\n decoded.hashType,\n );\n\n // strict=true rejects high-S, as libsecp256k1's verify_ecdsa does\n // (client.rs:992-999; secp256k1 crate `ecdsa/mod.rs:194`). ecc.verify\n // throws on out-of-range r/s — that is a failed verification here.\n let verifies = false;\n try {\n verifies = ecc.verify(sighash, pubkey, decoded.signature, true);\n } catch {\n verifies = false;\n }\n if (!verifies) {\n throw new Error(\n `P2WPKH signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout. The wallet may have signed a different ` +\n `transaction or key.`,\n );\n }\n}\n","/**\n * Far-side verification of Taproot KEY-PATH Schnorr signatures a wallet\n * returned, over the PSBT we requested (trusted prevouts) — the key-path twin\n * of `assertScriptPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs check_signatures_valid` (output key taken\n * from the prevout scriptPubKey, all prevouts committed). The wallet's\n * success/finalization is never trusted on its own (CLAUDE.md §8).\n * `assertReturnedKeyPathSignatures` additionally dispatches P2WPKH-funded\n * inputs to `verifyP2wpkhEcdsaSignature` (client.rs's\n * `verify_finalized_p2wpkh_spend` sibling), so a Native SegWit software\n * wallet's signatures no longer pass through unchecked.\n *\n * Why verify against the *requested* PSBT: `assertPsbtUnsignedTxMatches` pins\n * the unsigned transaction but deliberately skips per-input metadata, so a\n * wallet could rewrite `witnessUtxo` in its response and make a wrong-message\n * signature self-validate. Prevout scripts and values therefore come from the\n * PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\nimport { hexToUint8Array, stripHexPrefix } from \"../utils/bitcoin\";\nimport {\n assertReturnedP2wpkhSignature,\n isP2wpkhScript,\n} from \"./verifyP2wpkhEcdsaSignature\";\n\nconst SCHNORR_SIG_BYTES = 64;\nconst SIGHASH_DEFAULT = Transaction.SIGHASH_DEFAULT; // 0x00\nconst SIGHASH_ALL = Transaction.SIGHASH_ALL; // 0x01\n\n// P2TR scriptPubKey is exactly `OP_1 OP_PUSHBYTES_32 <32-byte output key>`.\nconst P2TR_SCRIPT_LEN = 34;\nconst OP_1 = 0x51;\nconst OP_PUSHBYTES_32 = 0x20;\nconst P2TR_OUTPUT_KEY_OFFSET = 2;\n\nfunction isP2trScript(script: Uint8Array | undefined): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2TR_SCRIPT_LEN &&\n script[0] === OP_1 &&\n script[1] === OP_PUSHBYTES_32\n );\n}\n\n/** BIP-341: 64 bytes ⇒ SIGHASH_DEFAULT; 65 bytes ⇒ the trailing byte is the hash type (we accept ALL only). */\nfunction splitHashType(\n sig: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; hashType: number } {\n if (sig.length === SCHNORR_SIG_BYTES) {\n return { signature: sig, hashType: SIGHASH_DEFAULT };\n }\n if (\n sig.length === SCHNORR_SIG_BYTES + 1 &&\n sig[SCHNORR_SIG_BYTES] === SIGHASH_ALL\n ) {\n return {\n signature: sig.subarray(0, SCHNORR_SIG_BYTES),\n hashType: SIGHASH_ALL,\n };\n }\n throw new Error(\n `Key-path signature for input ${inputIndex} must be 64 bytes (SIGHASH_DEFAULT) or ` +\n `65 bytes ending in 0x01 (SIGHASH_ALL), got ${sig.length}.`,\n );\n}\n\nexport interface AssertKeyPathSchnorrSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout scripts/values). NOT the wallet's. */\n requestedPsbtHex: string;\n /** 64- or 65-byte signature, hex. */\n signatureHex: string;\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that `signatureHex` is a valid BIP-340 Schnorr signature over the\n * Taproot key-path sighash of `requestedPsbtHex` input `inputIndex`, under the\n * tweaked output key taken from that input's prevout scriptPubKey.\n *\n * @throws If the input is not a key-path P2TR spend, the requested PSBT lacks\n * the prevout data needed to recompute the sighash, or the signature\n * does not verify.\n */\nexport function assertKeyPathSchnorrSignature(\n params: AssertKeyPathSchnorrSignatureParams,\n): void {\n const { requestedPsbtHex, signatureHex, inputIndex } = params;\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n\n if (!isKeyPathEligible(psbt.data.inputs[inputIndex])) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a key-path P2TR input.`,\n );\n }\n\n // Taproot's sighash commits to every input's prevout (script + value), so all\n // inputs must carry a witnessUtxo. A missing one is a build error, not a\n // value we can default — fail loudly.\n const prevOutScripts: Buffer[] = [];\n const values: number[] = [];\n for (let i = 0; i < psbt.data.inputs.length; i++) {\n const prevout = psbt.data.inputs[i].witnessUtxo;\n if (!prevout) {\n throw new Error(\n `Cannot verify signature: input ${i} of the requested PSBT has no witnessUtxo ` +\n `(required to recompute the Taproot sighash).`,\n );\n }\n prevOutScripts.push(prevout.script);\n values.push(prevout.value);\n }\n\n const { signature, hashType } = splitHashType(\n hexToUint8Array(stripHexPrefix(signatureHex)),\n inputIndex,\n );\n\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV1(\n inputIndex,\n prevOutScripts,\n values,\n hashType,\n );\n\n // Key-path signatures verify against the TWEAKED output key = the prevout's\n // witness program.\n const outputKey = prevOutScripts[inputIndex].subarray(P2TR_OUTPUT_KEY_OFFSET);\n\n if (!ecc.verifySchnorr(sighash, outputKey, signature)) {\n throw new Error(\n `Key-path Schnorr signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout (output key ${Buffer.from(outputKey).toString(\"hex\")}). ` +\n `The wallet may have signed a different transaction or key.`,\n );\n }\n}\n\n/**\n * A key-path P2TR input: an internal key, no script-path material, and a\n * taproot prevout. Script-path inputs are the script-path verifier's job.\n */\nfunction isKeyPathEligible(input: {\n tapInternalKey?: Uint8Array;\n tapLeafScript?: unknown;\n tapMerkleRoot?: Uint8Array;\n witnessUtxo?: { script: Uint8Array };\n}): boolean {\n return (\n input.tapInternalKey !== undefined &&\n input.tapLeafScript === undefined &&\n input.tapMerkleRoot === undefined &&\n isP2trScript(input.witnessUtxo?.script)\n );\n}\n\n/**\n * The lone stack item of a finalized key-path witness. An annex would add a\n * second item, but Bitcoin Core rejects annexes as nonstandard\n * (`src/policy/policy.cpp:327-329`), so such a spend could never broadcast.\n */\nfunction singleWitnessItem(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): Uint8Array {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized key-path witness must have ` +\n `exactly one item, got ${items.length}.`,\n );\n }\n return items[0];\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\nexport interface AssertReturnedKeyPathSignaturesParams {\n /** PSBT we built locally and asked the wallet to sign. */\n requestedPsbtHex: string;\n /** PSBT the wallet returned after signing. */\n returnedPsbtHex: string;\n}\n\n/**\n * Verify every key-path-eligible and P2WPKH input of the REQUESTED PSBT\n * against what the wallet RETURNED. Key-path: `tapKeySig`, or the single\n * finalized witness item for wallets that auto-finalize — and when both are\n * present they must be the same bytes. P2WPKH: `partialSig`, or the finalized\n * 2-item witness, verified as ECDSA over the BIP-143 sighash\n * ({@link assertReturnedP2wpkhSignature}); a failure throws but the input is\n * NOT counted. Any other input type (script-path, P2WSH, ...) throws — no\n * verifier here covers it, so it cannot be treated as verified.\n *\n * @returns How many inputs were verified KEY-PATH. A caller that knows every\n * input is taproot key-path (e.g. an approval wallet) must assert\n * this equals its input count — P2WPKH inputs never count toward it,\n * so that gate stays exact.\n * @throws If the input counts differ, an input is neither key-path P2TR nor\n * P2WPKH, an eligible input carries no signature, a finalized witness\n * disagrees with its `tapKeySig`/`partialSig`, or any signature does\n * not verify.\n */\nexport function assertReturnedKeyPathSignatures(\n params: AssertReturnedKeyPathSignaturesParams,\n): number {\n const { requestedPsbtHex, returnedPsbtHex } = params;\n\n const requested = Psbt.fromHex(requestedPsbtHex);\n const returned = Psbt.fromHex(returnedPsbtHex);\n\n if (returned.data.inputs.length !== requested.data.inputs.length) {\n throw new Error(\n `Returned PSBT input count ${returned.data.inputs.length} differs from the ` +\n `requested ${requested.data.inputs.length}.`,\n );\n }\n\n let verified = 0;\n requested.data.inputs.forEach((input, inputIndex) => {\n const returnedInput = returned.data.inputs[inputIndex];\n\n if (!isKeyPathEligible(input)) {\n // Native SegWit funding inputs get the ECDSA check.\n if (isP2wpkhScript(input.witnessUtxo?.script)) {\n assertReturnedP2wpkhSignature({\n requestedPsbtHex,\n returnedInput,\n inputIndex,\n });\n return;\n }\n // No verifier exists for any other type — fail closed like btc-vault's\n // check_signatures_valid rather than silently reporting it checked.\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is neither key-path P2TR ` +\n `nor P2WPKH; refusing to treat it as verified.`,\n );\n }\n verified++;\n\n const tapKeySig = returnedInput.tapKeySig;\n const witnessSig = returnedInput.finalScriptWitness\n ? singleWitnessItem(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify. Matches\n // btc-vault `crates/btc-wallet-remote/src/client.rs:1053-1072,1102-1121`,\n // which checks each independently.\n if (tapKeySig && witnessSig && !bytesEqual(tapKeySig, witnessSig)) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its tapKeySig.`,\n );\n }\n\n const sig = tapKeySig ?? witnessSig;\n if (!sig) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no key-path signature ` +\n `(no tapKeySig, not finalized).`,\n );\n }\n\n assertKeyPathSchnorrSignature({\n requestedPsbtHex,\n signatureHex: Buffer.from(sig).toString(\"hex\"),\n inputIndex,\n });\n });\n\n return verified;\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","getPrePeginHtlcConnectorInfo","expectedHtlc","deriveExpectedPrePeginHtlc","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","hexToUint8Array","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","COMPACT_SIZE_UINT16_PREFIX","COMPACT_SIZE_UINT32_PREFIX","COMPACT_SIZE_UINT16_BYTES","COMPACT_SIZE_UINT32_BYTES","COMPACT_SIZE_UINT16_MIN_VALUE","COMPACT_SIZE_UINT32_MIN_VALUE","decodeWitnessStack","witness","subject","offset","readCompactSize","first","value","count","items","i","len","P2WPKH_SCRIPT_LEN","OP_0","OP_PUSHBYTES_20","P2WPKH_PROGRAM_START","COMPRESSED_PUBKEY_BYTES","P2WPKH_WITNESS_ITEMS","isP2wpkhScript","script","bytesEqual","a","b","byte","decodeP2wpkhWitness","finalScriptWitness","inputIndex","assertReturnedP2wpkhSignature","requestedPsbtHex","returnedInput","partials","partial","material","assertP2wpkhEcdsaSignature","encodedSignature","pubkey","prevout","ecc","program","bcrypto","decoded","bscript","scriptCode","payments","sighash","verifies","SCHNORR_SIG_BYTES","SIGHASH_DEFAULT","SIGHASH_ALL","P2TR_SCRIPT_LEN","OP_1","OP_PUSHBYTES_32","P2TR_OUTPUT_KEY_OFFSET","isP2trScript","splitHashType","assertKeyPathSchnorrSignature","signatureHex","isKeyPathEligible","prevOutScripts","values","signature","hashType","outputKey","_a","singleWitnessItem","assertReturnedKeyPathSignatures","returnedPsbtHex","requested","returned","verified","tapKeySig","witnessSig"],"mappings":"khBA4FA,eAAsBA,EACpBC,EACoC,CACpC,MAAMC,EAAaC,EAAAA,eAAeF,EAAO,UAAU,EAC7CG,EAAsBD,EAAAA,eAAeF,EAAO,mBAAmB,EAIrE,MAAMI,+BAA6B,CACjC,eAAgBJ,EAAO,iBACvB,gBAAiBA,EAAO,gBACxB,oBAAqBA,EAAO,oBAC5B,mBAAoBA,EAAO,mBAC3B,2BAA4BA,EAAO,2BACnC,SAAUA,EAAO,SACjB,eAAgBA,EAAO,eACvB,QAASA,EAAO,OAAA,CACjB,EACD,MAAMK,EAAeC,EAAAA,2BAA2BN,EAAQA,EAAO,QAAQ,EAEjEO,EAAUC,EAAAA,YAAY,QAAQP,CAAU,EACxCQ,EAAaD,EAAAA,YAAY,QAAQL,CAAmB,EAE1D,GAAII,EAAQ,IAAI,SAAW,EACzB,MAAM,IAAI,MACR,oDAAoDA,EAAQ,IAAI,MAAM,EAAA,EAI1E,MAAMG,EAAaH,EAAQ,IAAI,CAAC,EAG1BI,EAAeF,EAAW,MAAA,EAC1BG,EAAiBC,EAAAA,gBAC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v/core/primitives/psbt/peginInput.ts","../src/tbv/core/utils/witness/witnessStack.ts","../src/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.ts","../src/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.ts"],"sourcesContent":["/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"../../wasm\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * Vault core (tx-graph) version the Pre-PegIn was built with. Must match\n * the version passed to buildPrePeginPsbt() so the HTLC connector scripts\n * are derived for the same graph.\n */\n vaultCoreVersion: number;\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n // Keep the facade's graph-version and input checks. Do not use its scripts\n // or control block as signing data.\n await getPrePeginHtlcConnectorInfo({\n txGraphVersion: params.vaultCoreVersion,\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n const expectedHtlc = deriveExpectedPrePeginHtlc(params, params.hashlock);\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n if (!expectedHtlc.scriptPubKey.equals(htlcOutput.script)) {\n throw new Error(\n \"PegIn HTLC taptree mismatch: the independent 2-leaf tree does not \" +\n \"reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.\",\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending. bitcoinjs\n // re-verifies leaf-in-tree consistency (control block vs tapMerkleRoot)\n // inside addInput — a second independent check.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.hashlockScript,\n controlBlock: expectedHtlc.hashlockControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(hexToUint8Array(depositorPubkey));\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // A wallet that ignores `autoFinalized: false` returns already-finalized\n // inputs (OKX's single-PSBT endpoint does; the wallet-connector routes OKX\n // around it). finalizeAllInputs() throws in that case, so fall back to\n // verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n","/**\n * Consensus witness-stack decoding, shared by every module that reads a\n * witness we did not build.\n *\n * Two independent decoders drifted apart before this existed: one accepted\n * non-minimal CompactSize encodings, the other rejected them. vaultd decodes\n * with rust-bitcoin, whose `VarInt::consensus_decode`\n * (0.32.8 `consensus/encode.rs:493-522`) returns `NonMinimalVarInt` for a 0xfd\n * carrying < 0xfd and a 0xfe carrying < 0x10000 — so the strict reading is the\n * only one that matches what the network will accept.\n *\n * @module tbv/core/utils/witness/witnessStack\n */\n\n/** CompactSize discriminators; 0xff (u64) is out of range for a witness. */\nconst COMPACT_SIZE_UINT16_PREFIX = 0xfd;\nconst COMPACT_SIZE_UINT32_PREFIX = 0xfe;\nconst COMPACT_SIZE_UINT16_BYTES = 3;\nconst COMPACT_SIZE_UINT32_BYTES = 5;\nconst COMPACT_SIZE_UINT16_MIN_VALUE = 0xfd;\nconst COMPACT_SIZE_UINT32_MIN_VALUE = 0x10000;\n\n/**\n * Decode a consensus-encoded witness stack: item count, then (len, bytes)*.\n *\n * @param witness - The consensus-encoded witness bytes.\n * @param subject - Names the witness in error messages (e.g. \"finalScriptWitness\").\n * @returns The stack items, as views over `witness`.\n * @throws If the encoding is truncated, non-minimal, out of range, or leaves\n * trailing bytes.\n */\nexport function decodeWitnessStack(\n witness: Uint8Array,\n subject: string,\n): Uint8Array[] {\n let offset = 0;\n\n const readCompactSize = (): number => {\n if (offset >= witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const first = witness[offset];\n if (first < COMPACT_SIZE_UINT16_PREFIX) {\n offset += 1;\n return first;\n }\n if (first === COMPACT_SIZE_UINT16_PREFIX) {\n if (offset + COMPACT_SIZE_UINT16_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value = witness[offset + 1] | (witness[offset + 2] << 8);\n if (value < COMPACT_SIZE_UINT16_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT16_BYTES;\n return value;\n }\n if (first === COMPACT_SIZE_UINT32_PREFIX) {\n if (offset + COMPACT_SIZE_UINT32_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value =\n (witness[offset + 1] |\n (witness[offset + 2] << 8) |\n (witness[offset + 3] << 16) |\n (witness[offset + 4] << 24)) >>>\n 0;\n if (value < COMPACT_SIZE_UINT32_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT32_BYTES;\n return value;\n }\n throw new Error(`${subject} carries an out-of-range item length`);\n };\n\n const count = readCompactSize();\n const items: Uint8Array[] = [];\n for (let i = 0; i < count; i++) {\n const len = readCompactSize();\n if (offset + len > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n items.push(witness.subarray(offset, offset + len));\n offset += len;\n }\n if (offset !== witness.length) {\n throw new Error(`${subject} has trailing bytes`);\n }\n return items;\n}\n","/**\n * Far-side verification of P2WPKH ECDSA signatures a wallet returned, over\n * the PSBT we requested (trusted prevouts) — the Native SegWit sibling of\n * `verifyKeyPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs:945-1000\n * verify_finalized_p2wpkh_spend`. The wallet's success/finalization is\n * never trusted on its own (CLAUDE.md §8): prevout script and value come\n * from the PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport {\n crypto as bcrypto,\n script as bscript,\n payments,\n Psbt,\n Transaction,\n} from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\n\n// P2WPKH scriptPubKey is exactly `OP_0 OP_PUSHBYTES_20 <20-byte key hash>`\n// (BIP-141 witness program v0, 20 bytes).\nconst P2WPKH_SCRIPT_LEN = 22;\nconst OP_0 = 0x00;\nconst OP_PUSHBYTES_20 = 0x14;\nconst P2WPKH_PROGRAM_START = 2;\n\n/** SEC1 compressed pubkey (client.rs:959: \"expected a 33-byte compressed key\"). */\nconst COMPRESSED_PUBKEY_BYTES = 33;\n/** Consensus P2WPKH witness: exactly [signature, pubkey] (client.rs:951-957). */\nconst P2WPKH_WITNESS_ITEMS = 2;\n\n/** Only claim P2WPKH: 22-byte scriptPubKey starting `OP_0 PUSH20`. */\nexport function isP2wpkhScript(\n script: Uint8Array | undefined,\n): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2WPKH_SCRIPT_LEN &&\n script[0] === OP_0 &&\n script[1] === OP_PUSHBYTES_20\n );\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\n/** The `[signature, pubkey]` pair of a finalized P2WPKH witness (client.rs:951-957). */\nfunction decodeP2wpkhWitness(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; pubkey: Uint8Array } {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== P2WPKH_WITNESS_ITEMS) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized P2WPKH witness must have ` +\n `exactly 2 items [signature, pubkey], got ${items.length}.`,\n );\n }\n return { signature: items[0], pubkey: items[1] };\n}\n\nexport interface AssertReturnedP2wpkhSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout script/value). NOT the wallet's. */\n requestedPsbtHex: string;\n /** The wallet-returned PSBT input carrying the signature material. */\n returnedInput: {\n partialSig?: Array<{ pubkey: Uint8Array; signature: Uint8Array }>;\n finalScriptWitness?: Uint8Array;\n };\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that the returned input carries a valid P2WPKH ECDSA signature\n * over the BIP-143 sighash of `requestedPsbtHex` input `inputIndex`:\n * `partialSig` (BIP-174: the value is the exact witness-stack signature\n * bytes, the key its pubkey), or the finalized 2-item witness — and when\n * both are present they must be the same bytes.\n *\n * @throws If the requested input is not a P2WPKH spend, no signature was\n * returned, a finalized witness disagrees with its `partialSig`,\n * or any check of `verify_finalized_p2wpkh_spend` fails.\n */\nexport function assertReturnedP2wpkhSignature(\n params: AssertReturnedP2wpkhSignatureParams,\n): void {\n const { requestedPsbtHex, returnedInput, inputIndex } = params;\n\n const partials = returnedInput.partialSig;\n // Consensus allows exactly one signature in a P2WPKH witness, so a second\n // partialSig entry is ambiguous tampering, not a fallback to pick from.\n if (partials !== undefined && partials.length > 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a P2WPKH input must carry at most one ` +\n `partial signature, got ${partials.length}.`,\n );\n }\n const partial = partials?.[0];\n const witness = returnedInput.finalScriptWitness\n ? decodeP2wpkhWitness(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify (same\n // rationale as the tapKeySig/witness agreement check).\n if (\n partial &&\n witness &&\n (!bytesEqual(partial.signature, witness.signature) ||\n !bytesEqual(partial.pubkey, witness.pubkey))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its partialSig.`,\n );\n }\n\n const material = partial ?? witness;\n if (!material) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no P2WPKH signature ` +\n `(no partialSig, not finalized).`,\n );\n }\n\n assertP2wpkhEcdsaSignature(\n requestedPsbtHex,\n material.signature,\n material.pubkey,\n inputIndex,\n );\n}\n\n/**\n * The crypto core, mirroring `verify_finalized_p2wpkh_spend` check by\n * check: pubkey shape and curve membership, hash160(pubkey) == witness\n * program, strict-DER + SIGHASH_ALL-only signature, ECDSA over the\n * BIP-143 sighash recomputed from the REQUESTED prevout.\n */\nfunction assertP2wpkhEcdsaSignature(\n requestedPsbtHex: string,\n encodedSignature: Uint8Array,\n pubkey: Uint8Array,\n inputIndex: number,\n): void {\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n const prevout = psbt.data.inputs[inputIndex].witnessUtxo;\n if (!prevout || !isP2wpkhScript(prevout.script)) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a P2WPKH input.`,\n );\n }\n\n // Pubkey: exactly 33 bytes (client.rs:959-965) and a parseable curve\n // point, as PublicKey::from_slice (client.rs:966-968).\n if (pubkey.length !== COMPRESSED_PUBKEY_BYTES) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey must be 33 bytes, ` +\n `got ${pubkey.length}.`,\n );\n }\n if (!ecc.isPointCompressed(pubkey)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey is not a valid secp256k1 point.`,\n );\n }\n\n // hash160(pubkey) must equal the prevout's witness program — what\n // consensus checks (client.rs:970-977).\n const program = prevout.script.subarray(\n P2WPKH_PROGRAM_START,\n P2WPKH_SCRIPT_LEN,\n );\n if (!bytesEqual(bcrypto.hash160(Buffer.from(pubkey)), program)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey does not hash to the ` +\n `prevout's witness program.`,\n );\n }\n\n // Strict-DER decode with defined-hashtype gate — the accept set of\n // ecdsa::Signature::from_slice / EcdsaSighashType::from_standard\n // (client.rs:978-980) — then SIGHASH_ALL exactly (client.rs:981-987).\n let decoded: { signature: Buffer; hashType: number };\n try {\n decoded = bscript.signature.decode(Buffer.from(encodedSignature));\n } catch (e) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not DER with a ` +\n `defined sighash byte: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that libsecp's strict consensus\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(decoded.signature, decoded.hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not canonical DER.`,\n );\n }\n if (decoded.hashType !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature has sighash type ` +\n `0x${decoded.hashType.toString(16)} (expected SIGHASH_ALL).`,\n );\n }\n\n // BIP-143 sighash over the REQUESTED prevout value with the standard\n // P2WPKH scriptCode built from the witness program (client.rs:988-991;\n // scriptCode template per bitcoinjs-lib's own P2WPKH signer,\n // `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: Buffer.from(program) }).output;\n if (!scriptCode) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: could not build the P2WPKH scriptCode.`,\n );\n }\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV0(\n inputIndex,\n scriptCode,\n prevout.value,\n decoded.hashType,\n );\n\n // strict=true rejects high-S, as libsecp256k1's verify_ecdsa does\n // (client.rs:992-999; secp256k1 crate `ecdsa/mod.rs:194`). ecc.verify\n // throws on out-of-range r/s — that is a failed verification here.\n let verifies = false;\n try {\n verifies = ecc.verify(sighash, pubkey, decoded.signature, true);\n } catch {\n verifies = false;\n }\n if (!verifies) {\n throw new Error(\n `P2WPKH signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout. The wallet may have signed a different ` +\n `transaction or key.`,\n );\n }\n}\n","/**\n * Far-side verification of Taproot KEY-PATH Schnorr signatures a wallet\n * returned, over the PSBT we requested (trusted prevouts) — the key-path twin\n * of `assertScriptPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs check_signatures_valid` (output key taken\n * from the prevout scriptPubKey, all prevouts committed). The wallet's\n * success/finalization is never trusted on its own (CLAUDE.md §8).\n * `assertReturnedKeyPathSignatures` additionally dispatches P2WPKH-funded\n * inputs to `verifyP2wpkhEcdsaSignature` (client.rs's\n * `verify_finalized_p2wpkh_spend` sibling), so a Native SegWit software\n * wallet's signatures no longer pass through unchecked.\n *\n * Why verify against the *requested* PSBT: `assertPsbtUnsignedTxMatches` pins\n * the unsigned transaction but deliberately skips per-input metadata, so a\n * wallet could rewrite `witnessUtxo` in its response and make a wrong-message\n * signature self-validate. Prevout scripts and values therefore come from the\n * PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\nimport { hexToUint8Array, stripHexPrefix } from \"../utils/bitcoin\";\nimport {\n assertReturnedP2wpkhSignature,\n isP2wpkhScript,\n} from \"./verifyP2wpkhEcdsaSignature\";\n\nconst SCHNORR_SIG_BYTES = 64;\nconst SIGHASH_DEFAULT = Transaction.SIGHASH_DEFAULT; // 0x00\nconst SIGHASH_ALL = Transaction.SIGHASH_ALL; // 0x01\n\n// P2TR scriptPubKey is exactly `OP_1 OP_PUSHBYTES_32 <32-byte output key>`.\nconst P2TR_SCRIPT_LEN = 34;\nconst OP_1 = 0x51;\nconst OP_PUSHBYTES_32 = 0x20;\nconst P2TR_OUTPUT_KEY_OFFSET = 2;\n\nfunction isP2trScript(script: Uint8Array | undefined): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2TR_SCRIPT_LEN &&\n script[0] === OP_1 &&\n script[1] === OP_PUSHBYTES_32\n );\n}\n\n/** BIP-341: 64 bytes ⇒ SIGHASH_DEFAULT; 65 bytes ⇒ the trailing byte is the hash type (we accept ALL only). */\nfunction splitHashType(\n sig: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; hashType: number } {\n if (sig.length === SCHNORR_SIG_BYTES) {\n return { signature: sig, hashType: SIGHASH_DEFAULT };\n }\n if (\n sig.length === SCHNORR_SIG_BYTES + 1 &&\n sig[SCHNORR_SIG_BYTES] === SIGHASH_ALL\n ) {\n return {\n signature: sig.subarray(0, SCHNORR_SIG_BYTES),\n hashType: SIGHASH_ALL,\n };\n }\n throw new Error(\n `Key-path signature for input ${inputIndex} must be 64 bytes (SIGHASH_DEFAULT) or ` +\n `65 bytes ending in 0x01 (SIGHASH_ALL), got ${sig.length}.`,\n );\n}\n\nexport interface AssertKeyPathSchnorrSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout scripts/values). NOT the wallet's. */\n requestedPsbtHex: string;\n /** 64- or 65-byte signature, hex. */\n signatureHex: string;\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that `signatureHex` is a valid BIP-340 Schnorr signature over the\n * Taproot key-path sighash of `requestedPsbtHex` input `inputIndex`, under the\n * tweaked output key taken from that input's prevout scriptPubKey.\n *\n * @throws If the input is not a key-path P2TR spend, the requested PSBT lacks\n * the prevout data needed to recompute the sighash, or the signature\n * does not verify.\n */\nexport function assertKeyPathSchnorrSignature(\n params: AssertKeyPathSchnorrSignatureParams,\n): void {\n const { requestedPsbtHex, signatureHex, inputIndex } = params;\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n\n if (!isKeyPathEligible(psbt.data.inputs[inputIndex])) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a key-path P2TR input.`,\n );\n }\n\n // Taproot's sighash commits to every input's prevout (script + value), so all\n // inputs must carry a witnessUtxo. A missing one is a build error, not a\n // value we can default — fail loudly.\n const prevOutScripts: Buffer[] = [];\n const values: number[] = [];\n for (let i = 0; i < psbt.data.inputs.length; i++) {\n const prevout = psbt.data.inputs[i].witnessUtxo;\n if (!prevout) {\n throw new Error(\n `Cannot verify signature: input ${i} of the requested PSBT has no witnessUtxo ` +\n `(required to recompute the Taproot sighash).`,\n );\n }\n prevOutScripts.push(prevout.script);\n values.push(prevout.value);\n }\n\n const { signature, hashType } = splitHashType(\n hexToUint8Array(stripHexPrefix(signatureHex)),\n inputIndex,\n );\n\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV1(\n inputIndex,\n prevOutScripts,\n values,\n hashType,\n );\n\n // Key-path signatures verify against the TWEAKED output key = the prevout's\n // witness program.\n const outputKey = prevOutScripts[inputIndex].subarray(P2TR_OUTPUT_KEY_OFFSET);\n\n if (!ecc.verifySchnorr(sighash, outputKey, signature)) {\n throw new Error(\n `Key-path Schnorr signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout (output key ${Buffer.from(outputKey).toString(\"hex\")}). ` +\n `The wallet may have signed a different transaction or key.`,\n );\n }\n}\n\n/**\n * A key-path P2TR input: an internal key, no script-path material, and a\n * taproot prevout. Script-path inputs are the script-path verifier's job.\n */\nfunction isKeyPathEligible(input: {\n tapInternalKey?: Uint8Array;\n tapLeafScript?: unknown;\n tapMerkleRoot?: Uint8Array;\n witnessUtxo?: { script: Uint8Array };\n}): boolean {\n return (\n input.tapInternalKey !== undefined &&\n input.tapLeafScript === undefined &&\n input.tapMerkleRoot === undefined &&\n isP2trScript(input.witnessUtxo?.script)\n );\n}\n\n/**\n * The lone stack item of a finalized key-path witness. An annex would add a\n * second item, but Bitcoin Core rejects annexes as nonstandard\n * (`src/policy/policy.cpp:327-329`), so such a spend could never broadcast.\n */\nfunction singleWitnessItem(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): Uint8Array {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized key-path witness must have ` +\n `exactly one item, got ${items.length}.`,\n );\n }\n return items[0];\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\nexport interface AssertReturnedKeyPathSignaturesParams {\n /** PSBT we built locally and asked the wallet to sign. */\n requestedPsbtHex: string;\n /** PSBT the wallet returned after signing. */\n returnedPsbtHex: string;\n}\n\n/**\n * Verify every key-path-eligible and P2WPKH input of the REQUESTED PSBT\n * against what the wallet RETURNED. Key-path: `tapKeySig`, or the single\n * finalized witness item for wallets that auto-finalize — and when both are\n * present they must be the same bytes. P2WPKH: `partialSig`, or the finalized\n * 2-item witness, verified as ECDSA over the BIP-143 sighash\n * ({@link assertReturnedP2wpkhSignature}); a failure throws but the input is\n * NOT counted. Any other input type (script-path, P2WSH, ...) throws — no\n * verifier here covers it, so it cannot be treated as verified.\n *\n * @returns How many inputs were verified KEY-PATH. A caller that knows every\n * input is taproot key-path (e.g. an approval wallet) must assert\n * this equals its input count — P2WPKH inputs never count toward it,\n * so that gate stays exact.\n * @throws If the input counts differ, an input is neither key-path P2TR nor\n * P2WPKH, an eligible input carries no signature, a finalized witness\n * disagrees with its `tapKeySig`/`partialSig`, or any signature does\n * not verify.\n */\nexport function assertReturnedKeyPathSignatures(\n params: AssertReturnedKeyPathSignaturesParams,\n): number {\n const { requestedPsbtHex, returnedPsbtHex } = params;\n\n const requested = Psbt.fromHex(requestedPsbtHex);\n const returned = Psbt.fromHex(returnedPsbtHex);\n\n if (returned.data.inputs.length !== requested.data.inputs.length) {\n throw new Error(\n `Returned PSBT input count ${returned.data.inputs.length} differs from the ` +\n `requested ${requested.data.inputs.length}.`,\n );\n }\n\n let verified = 0;\n requested.data.inputs.forEach((input, inputIndex) => {\n const returnedInput = returned.data.inputs[inputIndex];\n\n if (!isKeyPathEligible(input)) {\n // Native SegWit funding inputs get the ECDSA check.\n if (isP2wpkhScript(input.witnessUtxo?.script)) {\n assertReturnedP2wpkhSignature({\n requestedPsbtHex,\n returnedInput,\n inputIndex,\n });\n return;\n }\n // No verifier exists for any other type — fail closed like btc-vault's\n // check_signatures_valid rather than silently reporting it checked.\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is neither key-path P2TR ` +\n `nor P2WPKH; refusing to treat it as verified.`,\n );\n }\n verified++;\n\n const tapKeySig = returnedInput.tapKeySig;\n const witnessSig = returnedInput.finalScriptWitness\n ? singleWitnessItem(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify. Matches\n // btc-vault `crates/btc-wallet-remote/src/client.rs:1053-1072,1102-1121`,\n // which checks each independently.\n if (tapKeySig && witnessSig && !bytesEqual(tapKeySig, witnessSig)) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its tapKeySig.`,\n );\n }\n\n const sig = tapKeySig ?? witnessSig;\n if (!sig) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no key-path signature ` +\n `(no tapKeySig, not finalized).`,\n );\n }\n\n assertKeyPathSchnorrSignature({\n requestedPsbtHex,\n signatureHex: Buffer.from(sig).toString(\"hex\"),\n inputIndex,\n });\n });\n\n return verified;\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","getPrePeginHtlcConnectorInfo","expectedHtlc","deriveExpectedPrePeginHtlc","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","hexToUint8Array","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","COMPACT_SIZE_UINT16_PREFIX","COMPACT_SIZE_UINT32_PREFIX","COMPACT_SIZE_UINT16_BYTES","COMPACT_SIZE_UINT32_BYTES","COMPACT_SIZE_UINT16_MIN_VALUE","COMPACT_SIZE_UINT32_MIN_VALUE","decodeWitnessStack","witness","subject","offset","readCompactSize","first","value","count","items","i","len","P2WPKH_SCRIPT_LEN","OP_0","OP_PUSHBYTES_20","P2WPKH_PROGRAM_START","COMPRESSED_PUBKEY_BYTES","P2WPKH_WITNESS_ITEMS","isP2wpkhScript","script","bytesEqual","a","b","byte","decodeP2wpkhWitness","finalScriptWitness","inputIndex","assertReturnedP2wpkhSignature","requestedPsbtHex","returnedInput","partials","partial","material","assertP2wpkhEcdsaSignature","encodedSignature","pubkey","prevout","ecc","program","bcrypto","decoded","bscript","scriptCode","payments","sighash","verifies","SCHNORR_SIG_BYTES","SIGHASH_DEFAULT","SIGHASH_ALL","P2TR_SCRIPT_LEN","OP_1","OP_PUSHBYTES_32","P2TR_OUTPUT_KEY_OFFSET","isP2trScript","splitHashType","assertKeyPathSchnorrSignature","signatureHex","isKeyPathEligible","prevOutScripts","values","signature","hashType","outputKey","_a","singleWitnessItem","assertReturnedKeyPathSignatures","returnedPsbtHex","requested","returned","verified","tapKeySig","witnessSig"],"mappings":"khBA4FA,eAAsBA,EACpBC,EACoC,CACpC,MAAMC,EAAaC,EAAAA,eAAeF,EAAO,UAAU,EAC7CG,EAAsBD,EAAAA,eAAeF,EAAO,mBAAmB,EAIrE,MAAMI,+BAA6B,CACjC,eAAgBJ,EAAO,iBACvB,gBAAiBA,EAAO,gBACxB,oBAAqBA,EAAO,oBAC5B,mBAAoBA,EAAO,mBAC3B,2BAA4BA,EAAO,2BACnC,SAAUA,EAAO,SACjB,eAAgBA,EAAO,eACvB,QAASA,EAAO,OAAA,CACjB,EACD,MAAMK,EAAeC,EAAAA,2BAA2BN,EAAQA,EAAO,QAAQ,EAEjEO,EAAUC,EAAAA,YAAY,QAAQP,CAAU,EACxCQ,EAAaD,EAAAA,YAAY,QAAQL,CAAmB,EAE1D,GAAII,EAAQ,IAAI,SAAW,EACzB,MAAM,IAAI,MACR,oDAAoDA,EAAQ,IAAI,MAAM,EAAA,EAI1E,MAAMG,EAAaH,EAAQ,IAAI,CAAC,EAG1BI,EAAeF,EAAW,MAAA,EAC1BG,EAAiBC,EAAAA,gBACrB,IAAI,WAAWH,EAAW,IAAI,EAAE,MAAA,EAAQ,QAAA,CAAQ,EAGlD,GAAIE,IAAmBD,EACrB,MAAM,IAAI,MACR,sEACcA,CAAY,SAASC,CAAc,EAAA,EAIrD,MAAME,EAAaL,EAAW,KAAKC,EAAW,KAAK,EACnD,GAAI,CAACI,EACH,MAAM,IAAI,MACR,oBAAoBJ,EAAW,KAAK,6BAChBD,EAAW,KAAK,MAAM,WAAA,EAI9C,GAAI,CAACJ,EAAa,aAAa,OAAOS,E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AO,MAAM,GAAA,EAI/C,IAAIE,EAAW,EACf,OAAAF,EAAU,KAAK,OAAO,QAAQ,CAACjF,EAAOwC,IAAe,OACnD,MAAMG,EAAgBuC,EAAS,KAAK,OAAO1C,CAAU,EAErD,GAAI,CAAC+B,EAAkBvE,CAAK,EAAG,CAE7B,GAAIgC,GAAe6C,EAAA7E,EAAM,cAAN,YAAA6E,EAAmB,MAAM,EAAG,CAC7CpC,EAA8B,CAC5B,iBAAAC,EACA,cAAAC,EACA,WAAAH,CAAA,CACD,EACD,MACF,CAGA,MAAM,IAAI,MACR,SAASA,CAAU,+FAAA,CAGvB,CACA2C,IAEA,MAAMC,EAAYzC,EAAc,UAC1B0C,EAAa1C,EAAc,mBAC7BmC,GAAkBnC,EAAc,mBAAoBH,CAAU,EAC9D,OAMJ,GAAI4C,GAAaC,GAAc,CAACnD,GAAWkD,EAAWC,CAAU,EAC9D,MAAM,IAAI,MACR,uBAAuB7C,CAAU,kDAAA,EAIrC,MAAMhC,EAAM4E,GAAaC,EACzB,GAAI,CAAC7E,EACH,MAAM,IAAI,MACR,uBAAuBgC,CAAU,+DAAA,EAKrC6B,EAA8B,CAC5B,iBAAA3B,EACA,aAAchD,EAAAA,OAAO,KAAKc,CAAG,EAAE,SAAS,KAAK,EAC7C,WAAAgC,CAAA,CACD,CACH,CAAC,EAEM2C,CACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@babylonlabs-io/ts-sdk",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -167,6 +167,7 @@
|
|
|
167
167
|
},
|
|
168
168
|
"scripts": {
|
|
169
169
|
"build": "tsc -b --noEmit tsconfig.lib.json && vite build && node scripts/check-eth-build.js",
|
|
170
|
+
"typecheck": "tsc -b --noEmit tsconfig.lib.json",
|
|
170
171
|
"check:packed-consumer": "node scripts/check-packed-consumer.js",
|
|
171
172
|
"format": "prettier --check \"src/**/*.ts\"",
|
|
172
173
|
"format:fix": "prettier --write \"src/**/*.ts\"",
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var Qe=Object.defineProperty;var Je=(e,t,r)=>t in e?Qe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var N=(e,t,r)=>Je(e,typeof t!="symbol"?t+"":t,r);const ke=require("./BTCVaultRegistry.abi-BQ5tFNSu.cjs"),p=require("./bitcoin-D-O2GjbC.cjs"),O=require("./PayoutManager-CpfQjtL0.cjs"),$=require("buffer"),V=require("./signing-3l5Aqd-H.cjs"),x=require("./tbv/core/wasm/index.cjs"),E=require("./verifyScriptPathSchnorrSignature-BKZihCjk.cjs"),B=require("bitcoinjs-lib"),S=require("./constants-BTZdyOuk.cjs"),Ze=require("./deriveVaultRoot-DvhkHzNb.cjs"),G=require("./onChainBtcPubkey-BXry_CM4.cjs"),W=require("viem"),T=require("./json-rpc-client-BiAmg_ho.cjs"),I=require("./noPayout-DAWBQ0eG.cjs"),et=require("./secp256k1-DDHQ1_za.cjs"),tt=/^0x[0-9a-fA-F]{64}$/,rt=/^0x[0-9a-fA-F]{40}$/,ot=/^0x([0-9a-fA-F]{2})*$/;function F(e,t){if(e.length!==66)throw new Error(`${t} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`);if(!tt.test(e))throw new Error(`${t} must contain only hex characters after the 0x prefix`)}function nt(e,t){if(!rt.test(e))throw new Error(`${t} must be a 20-byte 0x-prefixed hex address (42 chars)`)}function it(e,t){if(!ot.test(e))throw new Error(`${t} must be a 0x-prefixed hex string with an even number of hex chars`)}function _e(e){nt(e.btcVaultRegistryAddress,"btcVaultRegistryAddress"),F(e.vaultId,"vaultId");const t=p.ensureHexPrefix(e.secret);if(F(t,"secret"),e.hashlock!==void 0&&(F(e.hashlock,"hashlock"),!O.validateSecretAgainstHashlock(t,e.hashlock)))throw new Error("Invalid secret: SHA256(secret) does not match the provided hashlock");return t}async function st(e){const{btcVaultRegistryAddress:t,vaultId:r,hashlock:o,activationMetadata:n,writeContract:u,signal:i}=e;i==null||i.throwIfAborted();const a=_e({btcVaultRegistryAddress:t,vaultId:r,secret:e.secret,hashlock:o});return it(n,"activationMetadata"),u({address:t,abi:ke.BTCVaultRegistryABI,functionName:"activateVaultWithSecret",args:[r,a,n]})}async function at(e){const{btcVaultRegistryAddress:t,vaultId:r,hashlock:o,writeContract:n,signal:u}=e;u==null||u.throwIfAborted();const i=_e({btcVaultRegistryAddress:t,vaultId:r,secret:e.secret,hashlock:o});return n({address:t,abi:ke.BTCVaultRegistryABI,functionName:"activateVaultWithSecretAndRedeem",args:[r,i]})}class Ae extends Error{constructor(t,r){super("Transaction graph's challenger set does not match the vault's (local ∪ universal)"+(t.length>0?` (missing: ${t.join(", ")})`:"")+(r.length>0?` (unexpected: ${r.join(", ")})`:"")+". Refusing to sign an incomplete or padded challenger set."),this.missing=t,this.unexpected=r,this.name="ChallengerSetMismatchError"}}function Se(e){const t=E.deriveLocalChallengers({claimerBtcPubkey:e.depositorBtcPubkey,depositorBtcPubkey:e.depositorBtcPubkey,vaultProviderBtcPubkey:e.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:e.vaultKeeperBtcPubkeys}),r=e.universalChallengerBtcPubkeys.map(ye),o=t.filter(h=>r.includes(h));if(o.length>0)throw new Error(`Cannot check the challenger set: vault keepers and universal challengers overlap (${o.join(", ")}).`);const n=e.graphChallengerPubkeys.map(ye),u=new Set(n);if(u.size!==n.length)throw new Error("Transaction graph lists the same challenger more than once.");const i=[...t,...r],a=new Set(i),s=i.filter(h=>!u.has(h)),c=n.filter(h=>!a.has(h));if(s.length>0||c.length>0)throw new Ae(s,c)}function ye(e){return p.stripHexPrefix(e).toLowerCase()}const Ce=0;class Re extends Error{constructor(t,r){super(`Payout transaction output ${Ce} pays ${r}, not the vault's registered payout script ${t}. Refusing to sign a payout to another destination.`),this.expectedScriptHex=t,this.actualScriptHex=r,this.name="PayoutDestinationError"}}function Be(e){let t;try{t=B.Psbt.fromBase64(e.payoutPsbtBase64)}catch(s){throw new Error("Payout PSBT cannot be parsed.",{cause:s})}const{version:r,locktime:o,outs:n}=ut(t);if(r!==S.PAYOUT_TX_VERSION||o!==S.PAYOUT_TX_LOCKTIME)throw new Error(`Payout transaction has version ${r} and locktime ${o}, expected ${S.PAYOUT_TX_VERSION} and ${S.PAYOUT_TX_LOCKTIME}.`);if(n.length!==S.NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT)throw new Error(`Payout transaction has ${n.length} output(s), expected exactly ${S.NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT} for a depositor-as-claimer payout.`);const u=p.stripHexPrefix(e.registeredPayoutScriptPubKey).toLowerCase();if(u.length===0)throw new Error("registeredPayoutScriptPubKey is empty; the vault's on-chain payout script is required to check the Payout destination.");const i=n[Ce].script.toString("hex").toLowerCase();if(!$.Buffer.from(i,"hex").equals($.Buffer.from(u,"hex")))throw new Re(u,i);const a=n[S.NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT-1];if(a.value!==S.PAYOUT_ANCHOR_DUST_SATS)throw new Error(`Payout CPFP anchor value ${a.value} sats must equal ${S.PAYOUT_ANCHOR_DUST_SATS} sats.`)}function ut(e){return{version:e.version,locktime:e.locktime,outs:e.txOutputs.map(t=>({script:$.Buffer.from(t.script),value:t.value}))}}const Ie=0;class $e extends Error{constructor(t,r,o){super(`Transaction graph does not belong to vault ${t}: its Claim spends PegIn ${o}, which derives vault ${r}. Refusing to sign for a graph served for another vault.`),this.expectedVaultId=t,this.derivedVaultId=r,this.peginTxid=o,this.name="VaultIdBindingError"}}function ct(e){let t;try{t=B.Psbt.fromBase64(e)}catch(o){throw new Error("Claim PSBT cannot be parsed.",{cause:o})}const r=t.txInputs[Ie];if(!r)throw new Error("Claim PSBT carries no PegIn input to bind the vault to.");return Ve(r.hash)}function lt(e){const t=e.ins[Ie];if(!t)throw new Error("Artifacts file's claim_tx carries no PegIn input to bind the vault to.");return Ve(t.hash)}function ne(e){const t=M(G.derivePeginVaultId(e.peginTxid,e.depositorEthAddress)),r=M(e.expectedVaultId);if(t!==r)throw new $e(r,t,e.peginTxid)}function M(e){return`0x${(e.startsWith("0x")?e.slice(2):e).toLowerCase()}`}function Ve(e){return $.Buffer.from(e).reverse().toString("hex")}const ht=0,dt=0,pt=1,gt=0,ft=0;async function Pt(e){const{txGraphVersion:t}=e.vault,r=e.source.txGraphJson,[o,n,u,i]=await Promise.all([x.buildClaimPsbt(t,r),x.buildAssertClaimerPsbt(t,r),x.buildPayoutClaimerPsbt(t,r),x.buildWronglyChallengedPsbts(t,r)]);ne({peginTxid:ct(o),depositorEthAddress:e.vault.depositorEthAddress,expectedVaultId:e.vault.vaultId});const a=await x.buildPayoutDepositorPsbt(t,r);for(const m of[u,a])Be({payoutPsbtBase64:m,registeredPayoutScriptPubKey:e.vault.registeredPayoutScriptPubKey});Se({graphChallengerPubkeys:Object.keys(i),depositorBtcPubkey:e.depositorPublicKey,vaultProviderBtcPubkey:e.vault.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:e.vault.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:e.vault.universalChallengerBtcPubkeys});const s=[{psbtBase64:o,inputIndex:ht},{psbtBase64:n,inputIndex:dt},{psbtBase64:u,inputIndex:pt},{psbtBase64:a,inputIndex:gt}],c=Object.keys(i);for(const m of c)for(const w of i[m])s.push({psbtBase64:w,inputIndex:ft});const h=await bt(e.btcWallet,e.depositorPublicKey,e.btcNetwork,s);let l=0;const d=h[l++],g=h[l++],f=h[l++],b=h[l++],P={};for(const m of c){const w=i[m].length;P[m]=h.slice(l,l+w),l+=w}const y=await x.finalizeClaimTx(t,r,d);return x.buildWatchtowerArtifacts({txGraphVersion:t,graphJson:r,signedClaimTxHex:y,assertClaimerSigHex:g,payoutClaimerSigHex:f,wronglyChallengedSigs:P,depositorPayoutSigHex:b,verifyingKeyHex:e.source.verifyingKeyHex,claimableEventBlockNumber:e.vault.claimableEventBlockNumber,proverCircuitVersion:e.vault.proverCircuitVersion,vaultIdHex:e.vault.vaultId,babeSessionsJson:e.babeSessionsJson,expectedVaultCoreVersion:e.vault.vaultCoreVersion})}function be(e){const t=e.replace(/^0x/,"").toLowerCase();if(t.length===66)return t.slice(2);if(t.length===64)return t;throw new Error(`Public key must be 33-byte compressed or 32-byte x-only hex, got ${t.length/2} bytes.`)}async function yt(e,t,r){const o=await e.getPublicKeyHex();if(be(o)!==be(t))throw new Error("Connected wallet does not hold the vault's depositor key. Select the account that made the deposit, then try again.");const n=await e.getAddress();if(!p.isAddressFromPublicKey(n,t,r))throw new Error(`Connected wallet reports address "${n}", which is not derived from the vault's depositor key. Select the account that made the deposit, then try again.`);return n}async function bt(e,t,r,o){const n=await yt(e,t,r),u=await O.signPsbtsWithFallback(e,o.map(i=>vt(i.psbtBase64)),o.map(i=>V.createTaprootScriptPathSignOptionsForInput(t,i.inputIndex,n)));return Promise.all(u.map((i,a)=>x.extractTapScriptSig(mt(i),o[a].inputIndex)))}function vt(e){return $.Buffer.from(e,"base64").toString("hex")}function mt(e){return $.Buffer.from(e,"hex").toString("base64")}async function wt(e){const t=await Ze.deriveVaultRoot(e.btcWallet,e.vaultContext);let r;try{r=await x.expandWotsSeed(t,e.htlcVout)}finally{t.fill(0)}let o;try{o=await x.wotsKeypairFromSeed(r)}finally{r.fill(0)}return Et(o.pk_hash,e.expectedWotsPkHash),await x.validateWotsKeypairAgainstGraph(e.txGraphVersion,o.keypair,e.txGraphJson),{wotsKeypairJson:JSON.stringify(o.keypair),pkHash:o.pk_hash}}function Et(e,t){if(H(e)!==H(t))throw new Error(`Derived WOTS public-key hash ${H(e)} does not match the vault's on-chain depositorWotsPkHash ${H(t)}. The wallet, the HTLC output index, or the derivation itself is not the one this vault was created with.`)}function H(e){return`0x${(e.startsWith("0x")?e.slice(2):e).toLowerCase()}`}const Oe=3;class Ne extends Error{constructor(t,r){super(`Artifacts belong to vault ${r}, not ${t}. Select the artifacts file saved for this vault.`),this.expectedVaultId=t,this.actualVaultId=r,this.name="ArtifactsVaultMismatchError"}}function He(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error("Artifacts file is not valid JSON.",{cause:i})}const r=ve(t.vault_id,"vault_id"),o=Tt(ve(t.claim_tx,"claim_tx")),n=U(t.prover_circuit_version,"prover_circuit_version"),u=t.claimable_event_block_number===void 0?0n:BigInt(U(t.claimable_event_block_number,"claimable_event_block_number"));return{vaultCoreVersion:t.vault_core_version===void 0?void 0:U(t.vault_core_version,"vault_core_version"),vaultId:r,claimTxid:o.getId(),peginTxid:lt(o),proverCircuitVersion:n,claimableEventBlockNumber:u,babeSessionChallengerPubkeys:Object.keys(kt(t.babe_sessions,"babe_sessions"))}}async function xt(e){const t=He(e.artifactsJson),r=M(e.expectedVaultId),o=M(t.vaultId);if(r!==o)throw new Ne(r,o);ne({peginTxid:t.peginTxid,depositorEthAddress:e.depositorEthAddress,expectedVaultId:r});const n=e.txGraphVersion??Oe;if(t.vaultCoreVersion!==void 0&&t.vaultCoreVersion!==n)throw new Error(`Artifacts record vault core version ${t.vaultCoreVersion}, but verification was asked for version ${n}.`);if(t.claimableEventBlockNumber===0n)throw new Error("Artifacts carry no claimable event block number. They were assembled before the Ethereum withdrawal was initiated; assemble them again.");return await x.verifyWatchtowerArtifacts(n,e.artifactsJson),t}function Tt(e){try{return B.Transaction.fromHex(e)}catch(t){throw new Error("Artifacts file carries an unparseable claim_tx.",{cause:t})}}function ve(e,t){if(typeof e!="string"||e.length===0)throw new Error(`Artifacts file is missing a usable "${t}".`);return e}function U(e,t){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`Artifacts file is missing a usable "${t}".`);return e}function kt(e,t){if(e===void 0)return{};if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`Artifacts file is missing a usable "${t}".`);return e}const Ke=8,_t=6e3,At=10*6e4,St=10;class ie extends Error{constructor(t){super(t),this.name="PeginRegistrationMissingError"}}class se extends Error{constructor(t){super(t),this.name="PeginRegistrationNotFinalError"}}function Me(e){return e instanceof ie||e instanceof Error&&e.name==="PeginRegistrationMissingError"}function Ct(e){return e instanceof se||e instanceof Error&&e.name==="PeginRegistrationNotFinalError"}function me(e){const{currentBlock:t,createdAtBlock:r}=e,o=t-r+1n;return o<0n?0:Number(o)}async function Rt(e){const{vaultRegistryReader:t,getBlockNumber:r,vaultIds:o,required:n=Ke,pollIntervalMs:u=_t,timeoutMs:i=At,signal:a,onProgress:s}=e;if(o.length===0)throw new Error("waitForPeginRegistrationDepth requires at least one vault ID");const c=Date.now();let h=!1,l=0,d;for(;;){if(a!=null&&a.aborted)throw new Error(`Aborted while waiting for peg-in registration depth (${o.length} vault(s))`);if(Date.now()-c>=i)throw new se(`Peg-in registration did not reach ${n} Ethereum confirmations within ${i}ms. The registration transaction was submitted but is not yet final, so the Pre-PegIn Bitcoin transaction was never sent and no funds are at risk. Resume this deposit from the dashboard once the network settles.`+(d instanceof Error?` Last read error: ${d.message}`:""));try{const g=await r(),f=await Promise.all(o.map(P=>t.getVaultBasicInfo(P))),b=f.findIndex(P=>P.depositor===W.zeroAddress||P.createdAt===0n);if(b!==-1){if(l+=1,!h&&l>St)throw new ie(`Vault ${o[b]} is still not visible on-chain after ${l} reads — the registration does not exist.`);console.warn(`Peg-in registration for vault ${o[b]} is not visible in chain state at block ${g} — a lagging RPC backend or an Ethereum reorg. Still polling.`),s==null||s({confirmations:0,required:n})}else{h=!0,l=0,d=void 0;let P=f[0],y=me({currentBlock:g,createdAtBlock:f[0].createdAt});for(const m of f.slice(1)){const w=me({currentBlock:g,createdAtBlock:m.createdAt});w<y&&(y=w,P=m)}if(s==null||s({confirmations:y,required:n}),y>=n)return{confirmations:y,basicInfo:P}}}catch(g){if(Me(g))throw g;console.warn(`Registration-depth read failed (retrying in ${u}ms): `+(g instanceof Error?g.message:String(g))),d=g}await new Promise((g,f)=>{const b=()=>{clearTimeout(P),f(new Error(`Aborted while waiting for peg-in registration depth (${o.length} vault(s))`))},P=setTimeout(()=>{a==null||a.removeEventListener("abort",b),g()},u);a==null||a.addEventListener("abort",b,{once:!0})})}}const Bt=1;function It(e,t,r){const o=r.map(l=>p.stripHexPrefix(l).toLowerCase()),n=t.filter(l=>o.includes(l));if(n.length>0)throw new Error(`Cannot validate challenger set: vault keepers and universal challengers overlap (${n.join(", ")})`);const u=[...t,...o],i=e.map(l=>p.stripHexPrefix(l.challenger_pubkey).toLowerCase()),a=new Set(i);if(a.size!==i.length)throw new Error("Depositor graph contains duplicate challenger entries in challenger_presign_data");const s=new Set(u),c=u.filter(l=>!a.has(l)),h=i.filter(l=>!s.has(l));if(c.length>0||h.length>0)throw new Error("Depositor graph challenger set does not match expected (local ∪ universal)"+(c.length>0?` (missing: ${c.join(", ")})`:"")+(h.length>0?` (unexpected: ${h.join(", ")})`:""))}function $t(e,t){const r=e.ins[t];return p.uint8ArrayToHex(new Uint8Array(r.hash).slice().reverse())}function L(e,t,r,o,n){const u=e.ins[t];if(u.index!==0)throw new Error(`NoPayout (challenger ${n}) input ${t} expected to spend ${o} vout 0, got vout ${u.index}`);const i=r.getId(),a=$t(e,t);if(a!==i)throw new Error(`NoPayout (challenger ${n}) input ${t} does not reference ${o} (expected txid ${i}, got ${a})`)}async function Vt(e,t,r){const o=[],n=[],u=[],i=E.deriveLocalChallengers({claimerBtcPubkey:r.depositorBtcPubkey,depositorBtcPubkey:r.depositorBtcPubkey,vaultProviderBtcPubkey:r.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:r.vaultKeeperBtcPubkeys});It(e.challenger_presign_data,i,r.universalChallengerBtcPubkeys);const a=await E.buildPayoutPsbt({vaultCoreVersion:r.vaultCoreVersion,vkClaimerPayoutScriptPubKeys:r.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:r.vpCommissionScriptPubKey,payoutTxHex:e.payout_tx.tx_hex,peginTxHex:r.peginTxHex,assertTxHex:e.assert_tx.tx_hex,timelockAssert:r.timelockAssert,depositorBtcPubkey:r.depositorBtcPubkey,vaultProviderBtcPubkey:r.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:r.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:r.universalChallengerBtcPubkeys,timelockPegin:r.timelockPegin,network:r.network,claimerBtcPubkey:r.depositorBtcPubkey,registeredPayoutScriptPubKey:r.registeredPayoutScriptPubKey,commissionBps:Bt,protocolFeeRate:r.protocolFeeRate,councilMembers:r.councilMembers,councilQuorum:r.councilQuorum});o.push(a.psbtHex),n.push(V.createTaprootScriptPathSignOptions(t,S.DEPOSITOR_SIGNED_INPUT_COUNT));const s=p.stripHexPrefix(r.depositorBtcPubkey),c=B.Transaction.fromHex(p.stripHexPrefix(e.assert_tx.tx_hex));for(const h of e.challenger_presign_data){const l=p.stripHexPrefix(h.challenger_pubkey),d=o.length,g=await Ot({challenger:h,challengerPubkey:l,claimerPubkey:s,localChallengers:i,assertTxParsed:c,ctx:r});o.push(g),n.push(V.createTaprootScriptPathSignOptions(t,S.DEPOSITOR_SIGNED_INPUT_COUNT)),u.push({challengerPubkey:l,noPayoutIdx:d})}return{psbtHexes:o,signOptions:n,challengerEntries:u}}async function Ot(e){const{challenger:t,challengerPubkey:r,claimerPubkey:o,localChallengers:n,assertTxParsed:u,ctx:i}=e;I.assertNoPayoutOutputMatchesChallenger(t.nopayout_tx.tx_hex,r,i.network);const a=B.Transaction.fromHex(p.stripHexPrefix(t.nopayout_tx.tx_hex)),s=B.Transaction.fromHex(p.stripHexPrefix(t.challenge_assert_x_tx.tx_hex)),c=B.Transaction.fromHex(p.stripHexPrefix(t.challenge_assert_y_tx.tx_hex));if(a.ins.length!==3)throw new Error(`NoPayout (challenger ${r}) must have exactly 3 inputs, got ${a.ins.length}`);L(a,0,u,"Assert",r),L(a,1,s,"ChallengeAssertX",r),L(a,2,c,"ChallengeAssertY",r);const h=[u.outs[0],s.outs[0],c.outs[0]].map(l=>({script_pubkey:p.uint8ArrayToHex(new Uint8Array(l.script)),value:l.value}));return I.buildNoPayoutPsbt({noPayoutTxHex:t.nopayout_tx.tx_hex,challengerPubkey:r,prevouts:h,connectorParams:{txGraphVersion:i.vaultCoreVersion,claimer:o,localChallengers:n,universalChallengers:i.universalChallengerBtcPubkeys,timelockAssert:i.timelockAssert,councilMembers:i.councilMembers,councilQuorum:i.councilQuorum}})}function Nt(e,t,r){E.assertPsbtUnsignedTxMatches(e[0]);const n=E.extractPayoutSignature(e[0].returnedPsbtHex,r);E.assertScriptPathSchnorrSignature({requestedPsbtHex:e[0].requestedPsbtHex,signatureHex:n,signerXOnlyPubkeyHex:r,inputIndex:0});const u={};for(const i of t){E.assertPsbtUnsignedTxMatches(e[i.noPayoutIdx]);const a=E.extractPayoutSignature(e[i.noPayoutIdx].returnedPsbtHex,r);E.assertScriptPathSchnorrSignature({requestedPsbtHex:e[i.noPayoutIdx].requestedPsbtHex,signatureHex:a,signerXOnlyPubkeyHex:r,inputIndex:0}),u[i.challengerPubkey]={nopayout_signature:a}}return{payout_signatures:{payout_signature:n},per_challenger:u}}async function De(e){const{depositorGraph:t,btcWallet:r,signingContext:o}=e,n=await r.getPublicKeyHex(),{depositorPubkey:u}=p.validateWalletPubkey(n,p.stripHexPrefix(o.depositorBtcPubkey)),{psbtHexes:i,signOptions:a,challengerEntries:s}=await Vt(t,n,o),c=await O.signPsbtsWithFallback(r,i,a),h=i.map((l,d)=>({requestedPsbtHex:l,returnedPsbtHex:c[d]}));return Nt(h,s,u)}const Ht=1e4;async function ae(e){const{statusReader:t,peginTxid:r,targetStatuses:o,timeoutMs:n,pollIntervalMs:u=Ht,signal:i}=e,a=Date.now();for(;;){if(i!=null&&i.aborted)throw new Error(`Polling aborted for pegin ${r.slice(0,8)}… (target: ${[...o].join(", ")})`);if(Date.now()-a>=n)throw new Error(`Polling timeout after ${n}ms for pegin ${r.slice(0,8)}… (target: ${[...o].join(", ")})`);try{const s=await t.getPeginStatus({pegin_txid:r},i);if(s.pegin_txid.toLowerCase()!==r.toLowerCase())throw new Error(`getPeginStatus returned status for pegin ${s.pegin_txid.slice(0,8)}…, requested ${r.slice(0,8)}…`);const c=s.status;if(o.has(c)||c===T.DaemonStatus.ACTIVATED)return c;if(c===T.DaemonStatus.EXPIRED||T.VP_TERMINAL_FAILURE_STATUSES.has(c))throw new Error(`Pegin ${r.slice(0,8)}… reached terminal status "${c}" while waiting for ${[...o].join(", ")}`)}catch(s){if(!(s instanceof T.JsonRpcError&&s.code===T.RpcErrorCode.PEGIN_NOT_FOUND))throw s}await new Promise((s,c)=>{const h=()=>{clearTimeout(l),c(new Error(`Polling aborted for pegin ${r.slice(0,8)}… (target: ${[...o].join(", ")})`))},l=setTimeout(()=>{i==null||i.removeEventListener("abort",h),s()},u);i==null||i.addEventListener("abort",h,{once:!0})})}}const Kt=1200*1e3,Fe=new Set([T.DaemonStatus.PENDING_ACKS,T.DaemonStatus.PENDING_ACTIVATION,T.DaemonStatus.ACTIVATED_PENDING_BROADCAST,T.DaemonStatus.ACTIVATED]),Mt=new Set([T.DaemonStatus.PENDING_DEPOSITOR_SIGNATURES,...Fe]);function Dt(e){return e.map(t=>({claimerPubkeyXOnly:p.processPublicKeyToXOnly(t.claimer_pubkey),payoutTxHex:t.payout_tx.tx_hex,assertTxHex:t.assert_tx.tx_hex}))}function R(e){return p.processPublicKeyToXOnly(e).toLowerCase()}function Ft(e,t){const r=(s,c,h)=>{throw new Error(`Deposit terms ${s} (${String(c)}) does not match the vault's version-locked signing context (${String(h)}); refusing to sign payouts against terms that describe a different graph.`)},o=[["protocolFeeRate",e.protocolFeeRate,t.protocolFeeRate],["vaultCoreVersion",e.vaultCoreVersion,t.vaultCoreVersion],["timelockPegin",e.timelockPegin,t.timelockPegin],["timelockAssert",e.timelockAssert,t.timelockAssert]];for(const[s,c,h]of o)c!==h&&r(s,c,h);const n=s=>s.map(R).sort(),u=(s,c)=>{const h=n(s),l=n(c);return h.length===l.length&&h.every((d,g)=>d===l[g])};u(e.vaultKeeperBtcPubkeys,t.vaultKeeperBtcPubkeys)||r("vaultKeeperBtcPubkeys",e.vaultKeeperBtcPubkeys.join(","),t.vaultKeeperBtcPubkeys.join(",")),u(e.universalChallengerBtcPubkeys,t.universalChallengerBtcPubkeys)||r("universalChallengerBtcPubkeys",e.universalChallengerBtcPubkeys.join(","),t.universalChallengerBtcPubkeys.join(","));const i=R(t.vaultProviderBtcPubkey),a=e.vaults.map(s=>R(s.vaultProviderBtcPubkey));a.includes(i)||r("vaults[].vaultProviderBtcPubkey",a.join(",")||"<no vaults>",t.vaultProviderBtcPubkey)}function Ut(e,t,r,o){const n=R(o),u=[R(t),...r.map(R)],i=new Set(u);if(i.size!==u.length)throw new Error("Cannot validate claimer set: signing context contains duplicate vault provider or vault keeper key");if(i.has(n))throw new Error("Cannot validate claimer set: depositor key overlaps with vault provider or vault keeper set");const a=e.map(d=>R(d.claimer_pubkey));if(new Set(a).size!==a.length)throw new Error("Presign response contains duplicate claimer entries");const s=a.filter(d=>d!==n),c=new Set(s),h=u.filter(d=>!c.has(d)),l=s.filter(d=>!i.has(d));if(h.length>0||l.length>0)throw new Error("Presign response claimer set does not match expected (vault provider ∪ vault keepers)"+(h.length>0?` (missing: ${h.join(", ")})`:"")+(l.length>0?` (unexpected: ${l.join(", ")})`:""))}function we(e,t){return{vaultCoreVersion:t.vaultCoreVersion,payoutTxHex:e.payoutTxHex,peginTxHex:t.peginTxHex,assertTxHex:e.assertTxHex,vaultProviderBtcPubkey:t.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:t.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:t.universalChallengerBtcPubkeys,depositorBtcPubkey:t.depositorBtcPubkey,timelockPegin:t.timelockPegin,timelockAssert:t.timelockAssert,registeredPayoutScriptPubKey:t.registeredPayoutScriptPubKey,claimerBtcPubkey:e.claimerPubkeyXOnly,commissionBps:t.commissionBps,protocolFeeRate:t.protocolFeeRate,councilMembers:t.councilMembers,councilQuorum:t.councilQuorum,vkClaimerPayoutScriptPubKeys:t.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:t.vpCommissionScriptPubKey}}async function Lt(e,t,r,o){const n=new O.PayoutManager({network:t.network,btcWallet:e}),u=r.length;o==null||o(0,u);let i;if(n.supportsBatchSigning())i=(await n.signPayoutTransactionsBatch(r.map(c=>we(c,t)))).map(c=>c.payoutSignature);else{i=[];for(let s=0;s<r.length;s++){o==null||o(s,u);const c=await n.signPayoutTransaction(we(r[s],t));i.push(c.signature)}}const a={};for(let s=0;s<r.length;s++)a[r[s].claimerPubkeyXOnly]={payout_signature:i[s]};return o==null||o(u,u),a}async function Xt(e){const{statusReader:t,presignClient:r,btcWallet:o,peginTxid:n,depositorPk:u,signingContext:i,depositTerms:a,timeoutMs:s=Kt,signal:c,onProgress:h}=e,l=await ae({statusReader:t,peginTxid:n,targetStatuses:Mt,timeoutMs:s,signal:c});if(Fe.has(l))return;if(c==null||c.throwIfAborted(),a!==void 0&&Ft(a,i),O.supportsDepositApproval(o)){if(!a)throw new Error("runDepositorPresignFlow: this wallet requires approved deposit terms but none were provided. Fresh deposits must pass PreparePeginResult.depositTerms; resume flows must rebuild them from on-chain state (the vault app's rebuildDepositTerms).");typeof o.validateDepositTerms=="function"&&await o.validateDepositTerms(a),await o.approveDepositTerms(a)}const d=await r.requestDepositorPresignTransactions({pegin_txid:n,depositor_pk:u},c);c==null||c.throwIfAborted();const g=R(u);Ut(d.txs,i.vaultProviderBtcPubkey,i.vaultKeeperBtcPubkeys,u);const f=d.txs.filter(w=>R(w.claimer_pubkey)!==g),b=Dt(f),P=await Lt(o,i,b,h);c==null||c.throwIfAborted();const y=await De({depositorGraph:d.depositor_graph,btcWallet:o,signingContext:{vaultCoreVersion:i.vaultCoreVersion,peginTxHex:i.peginTxHex,depositorBtcPubkey:u,vaultProviderBtcPubkey:i.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:i.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:i.universalChallengerBtcPubkeys,timelockPegin:i.timelockPegin,timelockAssert:i.timelockAssert,councilMembers:i.councilMembers,councilQuorum:i.councilQuorum,network:i.network,registeredPayoutScriptPubKey:i.registeredPayoutScriptPubKey,protocolFeeRate:i.protocolFeeRate,vkClaimerPayoutScriptPubKeys:i.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:i.vpCommissionScriptPubKey}});c==null||c.throwIfAborted();const m={...P};m[p.stripHexPrefix(u)]=y.payout_signatures,await r.submitDepositorPresignatures({pegin_txid:n,depositor_pk:u,signatures:m,depositor_claimer_presignatures:y},c)}const qt=300*1e3,zt=new Set([T.DaemonStatus.PENDING_DEPOSITOR_WOTS_PK,...T.POST_WOTS_STATUSES]);async function Gt(e){const{statusReader:t,wotsSubmitter:r,peginTxid:o,depositorPk:n,wotsPublicKeys:u,timeoutMs:i=qt,signal:a}=e;a==null||a.throwIfAborted();const s=await ae({statusReader:t,peginTxid:o,targetStatuses:zt,timeoutMs:i,signal:a});T.POST_WOTS_STATUSES.has(s)||(a==null||a.throwIfAborted(),await r.submitDepositorWotsKey({pegin_txid:o,depositor_pk:n,wots_public_keys:u},a))}function K(e){return e.registration||e.operation}function Ue(e,t,r){const o=p.canonicalizeBtcPubkey(e);return{registration:o===p.canonicalizeBtcPubkey(t),operation:o===p.canonicalizeBtcPubkey(r)}}function j(e,t,r){const o=X(e);return{registration:Ee(o,X(t)),operation:Ee(o,X(r))}}function X(e){return e.map(p.canonicalizeBtcPubkey).sort()}function Ee(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}async function Wt(e){const{vaultProviderEthAddress:t,hintBtcPubkey:r,registrationBtcPubkey:o,readCurrentOperationBtcPubkey:n,context:u}=e;if(!r)return;const i=p.canonicalizeBtcPubkey(r);if(i===p.canonicalizeBtcPubkey(o))return;const a=p.canonicalizeBtcPubkey(await n());if(i!==a)throw new Error(`Vault provider BTC pubkey mismatch for ${t}: indexer hint matches neither the registration key nor the current operation key on-chain.${u?` ${u}`:""}`)}function q(e,t,r){const o=`${e} operation key (admin=${t.ethAddress})`,n=G.assertOnChainBtcPubkey(t.btcPubKey,`${e} roster key (admin=${t.ethAddress})`),u=G.assertOnChainBtcPubkey(r,o);return{adminAddress:t.ethAddress,genesisBtcPubkey:n,operationBtcPubkey:u,rotated:u!==n}}function jt(e){const t=new Map;for(const r of e){const o=t.get(r.operationBtcPubkey);if(o)throw new Error(`Participant operation key collision: ${o} and ${r.adminAddress} both resolve to operation key ${r.operationBtcPubkey}`);t.set(r.operationBtcPubkey,r.adminAddress)}}function Le(e,t,r){if(t.vaultKeepers.length!==e.vaultKeepers.length||t.universalChallengers.length!==e.universalChallengers.length)throw new Error(`Operation-key resolution returned ${t.vaultKeepers.length} keeper and ${t.universalChallengers.length} challenger keys for a roster of ${e.vaultKeepers.length} keepers and ${e.universalChallengers.length} challengers`);const o=q("vault provider",{ethAddress:e.vaultProviderEthAddress,btcPubKey:e.vaultProviderGenesisBtcPubkey},t.vaultProvider),n=e.vaultKeepers.map((i,a)=>q("vault keeper",i,t.vaultKeepers[a])),u=e.universalChallengers.map((i,a)=>q("universal challenger",i,t.universalChallengers[a]));return jt([o,...n,...u]),{vaultProvider:o,vaultKeepers:n,universalChallengers:u,vaultKeeperOperationKeysSorted:n.map(i=>i.operationBtcPubkey).sort(),universalChallengerOperationKeysSorted:u.map(i=>i.operationBtcPubkey).sort(),resolvedAt:r,query:e}}async function Xe(e){const t=await e.operationKeyReader.getCurrentOperationKeys(e.query,e.blockNumber);return Le(e.query,t,{mode:"current"})}async function qe(e){const t=await e.operationKeyReader.getOperationKeysAtEpochs(e.query,e.epochs);return Le(e.query,t,{mode:"epochs",epochs:e.epochs})}class D extends Error{constructor(t){super(t),this.name="ApplicationEntryPointMismatchError"}}function Yt(e){return e instanceof D||e instanceof Error&&e.name==="ApplicationEntryPointMismatchError"}const xe=e=>e.map(p.canonicalizeBtcPubkey).sort();async function Qt(e){const{vaultRegistryReader:t,vaultKeeperReader:r,universalChallengerReader:o,vaultProviderEthAddress:n,applicationEntryPoint:u,expectedVaultProviderBtcPubkey:i,expectedVaultKeeperBtcPubkeys:a,expectedUniversalChallengerBtcPubkeys:s,operationKeyReader:c,onIndexerServingOperationKeys:h,onIndexerHintsInconsistent:l,blockNumber:d}=e,[g,f,b,P]=await Promise.all([t.getVaultProviderApplication(n,d),t.getVaultProviderGenesisBtcPubKey(n,d),o.getLatestUniversalChallengersVersion(d),o.getCurrentUcKeyEpoch(d)]);if(!W.isAddress(u,{strict:!1}))throw new D(`The application entry point this deposit was prepared for is not a valid address: ${u}`);if(!W.isAddressEqual(g,u))throw new D(`Vault provider ${n} is registered to application ${g}, but this deposit was prepared for ${u}. Refusing to build: the vault keeper roster, its version, and the keeper key epoch would all resolve against a different application than the one selected.`);const[y,m]=await Promise.all([r.getCurrentVaultKeepersVersion(g,d),r.getCurrentAppKeeperKeyEpoch(g,d)]),[w,k]=await Promise.all([r.getVaultKeepersByVersion(g,y,d),o.getUniversalChallengersByVersion(b,d)]),_={vaultProvider:p.canonicalizeBtcPubkey(f),vaultKeepers:xe(w.map(A=>A.btcPubKey)),universalChallengers:xe(k.map(A=>A.btcPubKey))},C=await Xe({operationKeyReader:c,query:{vaultProviderEthAddress:n,vaultProviderGenesisBtcPubkey:`0x${f}`,applicationEntryPoint:g,vaultKeepers:w,universalChallengers:k},blockNumber:d}),v={vaultProvider:C.vaultProvider.operationBtcPubkey,vaultKeepers:[...C.vaultKeeperOperationKeysSorted],universalChallengers:[...C.universalChallengerOperationKeysSorted]},de=Ue(i,_.vaultProvider,v.vaultProvider),pe=j(a,_.vaultKeepers,v.vaultKeepers),ge=j(s,_.universalChallengers,v.universalChallengers);if(!K(de))throw new Error(`Vault provider BTC pubkey indexer hint does not match BTCVaultRegistry for ${n}. Refresh and try again.`);if(!K(pe))throw new Error(`Vault keeper BTC pubkeys (v${y}) indexer set does not match ApplicationRegistry on-chain set. Refresh and try again.`);if(!K(ge))throw new Error(`Universal challenger BTC pubkeys (v${b}) indexer set does not match ProtocolParams on-chain set. Refresh and try again.`);const fe=[de,pe,ge],Ye=fe.some(A=>A.registration&&!A.operation),Pe=fe.some(A=>A.operation&&!A.registration);if(Ye&&Pe){const A=`Indexer participant hints are internally inconsistent for vault provider ${n}: some roles match the registration keys while others match the rotated operation keys.`;throw l==null||l(A),new Error(`${A} Refresh and try again.`)}return Pe&&(h==null||h(`Indexer is serving rotated operation keys for vault provider ${n}`)),{vaultProviderBtcPubkeyXOnly:v.vaultProvider,vaultKeeperBtcPubkeysSorted:v.vaultKeepers,universalChallengerBtcPubkeysSorted:v.universalChallengers,expectedAppVaultKeepersVersion:y,expectedUniversalChallengersVersion:b,appKeeperKeyEpoch:m,ucKeyEpoch:P,registrationKeys:_,participantKeys:C}}function Jt(e){return/^[0-9a-fA-F]{64}$/.test(e)}function Zt(e){const{amountSats:t,minDeposit:r,maxDeposit:o,btcBalance:n,estimatedFeeSats:u,depositorClaimValue:i}=e;return!(t<=0n||t<r||o&&o>0n&&t>o||u==null||i==null||t+u+i>n)}function er(e,t,r){return e<=0n?{valid:!1,error:"Deposit amount must be greater than zero"}:e<t?{valid:!1,error:`Minimum deposit is ${p.formatSatoshisToBtc(t)} BTC`}:r&&r>0n&&e>r?{valid:!1,error:`Maximum deposit is ${p.formatSatoshisToBtc(r)} BTC`}:{valid:!0}}function tr(e){const{amount:t,effectiveRemaining:r}=e;return r===null?{valid:!0}:r===0n?{valid:!1,error:"Supply cap reached — deposits temporarily paused"}:t>r?{valid:!1,error:`Vault size exceeds remaining capacity (${p.formatSatoshisToBtc(r)} BTC)`}:{valid:!0}}function rr(e,t){if(!e||e.length===0)return{valid:!1,error:"At least one vault provider must be selected"};const r=t.map(n=>n.toLowerCase());return e.filter(n=>!r.includes(n.toLowerCase())).length>0?{valid:!1,error:"Invalid vault provider selected"}:{valid:!0}}function ze(e,t,r){if(!e||e.length===0)return{valid:!1,error:"At least one vault amount required"};for(let o=0;o<e.length;o++){const n=e[o];if(n<=0n)return{valid:!1,error:`Vault ${o+1} amount must be positive`};if(t&&n<t)return{valid:!1,error:`Vault ${o+1} amount ${p.formatSatoshisToBtc(n)} BTC is below minimum deposit ${p.formatSatoshisToBtc(t)} BTC`};if(r&&n>r)return{valid:!1,error:`Vault ${o+1} amount ${p.formatSatoshisToBtc(n)} BTC exceeds maximum deposit ${p.formatSatoshisToBtc(r)} BTC`}}return{valid:!0}}function Ge(e){const t=p.stripHexPrefix(e);return Jt(t)?{valid:!0}:{valid:!1,error:"Invalid pubkey format: must be 64 hex characters (32-byte x-only public key, no 0x prefix)"}}function or(e){if(!e||e.length===0)throw new Error("No vault keepers available. The system requires at least one vault keeper to create a deposit.")}function nr(e){if(!e||e.length===0)throw new Error("No universal challengers available. The system requires at least one universal challenger to create a deposit.")}function ir(e){if(e.length===0)throw new Error("No spendable UTXOs available")}function sr(e){const{vaultAmounts:t,confirmedUTXOs:r,vaultProviderBtcPubkey:o,vaultKeeperBtcPubkeys:n,universalChallengerBtcPubkeys:u,minDeposit:i,maxDeposit:a}=e,s=ze(t,i,a);if(!s.valid)throw new Error(s.error);const c=Ge(o);if(!c.valid)throw new Error(c.error);or(n),nr(u),ir(r)}class ue extends Error{constructor(t){super(t),this.name="ParticipantKeyDriftError"}}function ar(e){return e instanceof ue||e instanceof Error&&e.name==="ParticipantKeyDriftError"}function Te(e,t,r){return t.length===r.length&&t.every((o,n)=>o===r[n])?null:`${e} expected [${t.join(", ")}], got [${r.join(", ")}]`}async function ur(e){const{vaultRegistryReader:t,operationKeyReader:r,vaultIds:o,expected:n}=e,u=n.query;if(o.length===0)return;const i=await t.getVaultKeyEpochsBatch(o),a=[];for(const[s,c]of i.entries()){const h=o[s];let l;try{l=await qe({operationKeyReader:r,query:u,epochs:c})}catch(f){a.push(`vault ${h}: could not resolve participants at frozen epochs (vp=${c.vpKeyEpoch}, keeper=${c.appKeeperKeyEpoch}, uc=${c.ucKeyEpoch}): ${f.message}`);continue}l.vaultProvider.operationBtcPubkey!==n.vaultProvider.operationBtcPubkey&&a.push(`vault ${h}: vault provider key expected ${n.vaultProvider.operationBtcPubkey}, got ${l.vaultProvider.operationBtcPubkey}`);const d=Te(`vault ${h}: vault keeper keys`,n.vaultKeeperOperationKeysSorted,l.vaultKeeperOperationKeysSorted);d&&a.push(d);const g=Te(`vault ${h}: universal challenger keys`,n.universalChallengerOperationKeysSorted,l.universalChallengerOperationKeysSorted);g&&a.push(g)}if(a.length>0)throw new ue(`Aborting BTC broadcast: participant operation keys changed during registration (${a.join("; ")}). The Pre-PegIn was not broadcast; the registered ETH vault will time out per protocol rules.`)}class ce extends Error{constructor(t){super(t),this.name="RegisteredVaultVersionMismatchError"}}function cr(e){return e instanceof ce||e instanceof Error&&e.name==="RegisteredVaultVersionMismatchError"}async function lr(e){const{vaultRegistryReader:t,vaultIds:r,expectedOffchainParamsVersion:o,expectedAppVaultKeepersVersion:n,expectedUniversalChallengersVersion:u,expectedVaultCoreVersion:i}=e,a=await t.getProtocolInfoBatch(r),s=[];if(a.forEach((c,h)=>{const l=r[h];c.offchainParamsVersion!==o&&s.push(`vault ${l}: offchainParams expected v${o}, got v${c.offchainParamsVersion}`),c.appVaultKeepersVersion!==n&&s.push(`vault ${l}: appVaultKeepers expected v${n}, got v${c.appVaultKeepersVersion}`),c.universalChallengersVersion!==u&&s.push(`vault ${l}: universalChallengers expected v${u}, got v${c.universalChallengersVersion}`),c.vaultCoreVersion!==i&&s.push(`vault ${l}: vaultCoreVersion expected v${i} (build-time active), got v${c.vaultCoreVersion}`)}),s.length>0)throw new ce(`Aborting BTC broadcast: signer-set or offchain-params versions changed during registration (${s.join("; ")}). The Pre-PegIn was not broadcast; the registered ETH vault will time out per protocol rules.`)}var le=(e=>(e.CLAIM_EVENT_RECEIVED="ClaimEventReceived",e.CLAIM_BROADCAST="ClaimBroadcast",e.ASSERT_BROADCAST="AssertBroadcast",e.PAYOUT_BROADCAST="PayoutBroadcast",e.PAYOUT_BLOCKED="PayoutBlocked",e))(le||{});const hr=new Set(["PayoutBroadcast","PayoutBlocked"]);function dr(e){return Object.values(le).includes(e)}function pr(e){return!!e&&hr.has(e)}class We extends Error{constructor(r,o){super(`Refund not yet mature (BIP68 not final): ${o.message}`);N(this,"vaultId");N(this,"cause");this.name="BIP68NotMatureError",this.vaultId=r,this.cause=o}}const gr=/^0x[0-9a-fA-F]{64}$/,fr=/^(?:0x)?(?:[0-9a-fA-F]{2})+$/,je=/^(?:0x)?(?:[0-9a-fA-F]{64}|[0-9a-fA-F]{66})$/,he=160,Y=2e3,Q=10n,J=100n;function Pr(e){if(!Number.isFinite(e)||e<=0)throw new Error(`feeRateSatsVb must be a positive finite number, got ${e}`);return BigInt(Math.ceil(e*he))}const yr=1,br=/non-BIP68-final/i;function Z(e,t){if(e.length!==66)throw new Error(`${t} must be 32 bytes (66 hex chars with 0x prefix), got length ${e.length}`);if(!gr.test(e))throw new Error(`${t} must contain only hex characters after the 0x prefix`)}function z(e,t){if(!Number.isInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer, got ${e}`)}function vr(e){if(Z(e.hashlock,"hashlock"),!Number.isInteger(e.htlcVout)||e.htlcVout<0)throw new Error(`htlcVout must be a non-negative integer, got ${e.htlcVout}`);if(!Array.isArray(e.batch)||e.batch.length===0)throw new Error("batch must be a non-empty array of HTLC entries");if(e.htlcVout>=e.batch.length)throw new Error(`htlcVout ${e.htlcVout} is out of range for batch of size ${e.batch.length}`);for(let r=0;r<e.batch.length;r++){const o=e.batch[r];if(Z(o.hashlock,`batch[${r}].hashlock`),!Number.isInteger(o.htlcVout)||o.htlcVout!==r)throw new Error(`batch[${r}].htlcVout must equal ${r} (contiguous vout-ordered vector), got ${o.htlcVout}`);if(typeof o.amount!="bigint"||o.amount<=0n)throw new Error(`batch[${r}].amount must be a positive bigint, got ${o.amount}`)}const t=e.batch[e.htlcVout];if(t.hashlock.toLowerCase()!==e.hashlock.toLowerCase())throw new Error(`batch[${e.htlcVout}].hashlock (${t.hashlock}) does not match target hashlock (${e.hashlock})`);if(t.amount!==e.amount)throw new Error(`batch[${e.htlcVout}].amount (${t.amount}) does not match target amount (${e.amount})`);if(z(e.offchainParamsVersion,"offchainParamsVersion"),z(e.appVaultKeepersVersion,"appVaultKeepersVersion"),z(e.universalChallengersVersion,"universalChallengersVersion"),et.assertValidVaultCoreVersion(e.vaultCoreVersion,"VaultRefundData.vaultCoreVersion"),typeof e.unsignedPrePeginTxHex!="string"||e.unsignedPrePeginTxHex.length===0)throw new Error("unsignedPrePeginTxHex must be a non-empty hex string");if(!fr.test(e.unsignedPrePeginTxHex))throw new Error("unsignedPrePeginTxHex must be a hex byte string (optional 0x prefix, even length)");if(!e.depositorBtcPubkey||!je.test(e.depositorBtcPubkey))throw new Error("depositorBtcPubkey must be 32 or 33 bytes of hex (optional 0x prefix)");if(typeof e.amount!="bigint"||e.amount<=0n)throw new Error(`amount must be a positive bigint, got ${e.amount}`)}function mr(e){if(!e.vaultProviderPubkey||!je.test(e.vaultProviderPubkey))throw new Error("vaultProviderPubkey must be 32 or 33 bytes of hex");if(e.vaultKeeperPubkeys.length===0)throw new Error("vaultKeeperPubkeys must be non-empty");if(e.universalChallengerPubkeys.length===0)throw new Error("universalChallengerPubkeys must be non-empty");if(!Number.isInteger(e.timelockRefund)||e.timelockRefund<=0)throw new Error(`timelockRefund must be a positive integer, got ${e.timelockRefund}`);if(typeof e.feeRate!="bigint"||e.feeRate<=0n)throw new Error(`protocol feeRate must be a positive bigint, got ${e.feeRate}`);if(typeof e.minPeginFeeRate!="bigint"||e.minPeginFeeRate<=0n)throw new Error(`minPeginFeeRate must be a positive bigint, got ${e.minPeginFeeRate}`);if(!Number.isInteger(e.numLocalChallengers)||e.numLocalChallengers<0)throw new Error("numLocalChallengers must be a non-negative integer");if(!Number.isInteger(e.councilQuorum)||!Number.isInteger(e.councilSize)||e.councilQuorum<=0||e.councilSize<=0||e.councilQuorum>e.councilSize)throw new Error(`councilQuorum (${e.councilQuorum}) must be in [1, councilSize=${e.councilSize}]`)}async function wr(e){const{vaultId:t,readVault:r,readPrePeginContext:o,feeRate:n,signPsbt:u,broadcastTx:i,signal:a}=e;a==null||a.throwIfAborted(),Z(t,"vaultId");const s=await r();vr(s),a==null||a.throwIfAborted();const c=await o(s);if(mr(c),a==null||a.throwIfAborted(),!Number.isFinite(n)||n<=0)throw new Error(`feeRate must be a positive number, got ${n}`);if(n>Y)throw new Error(`feeRate ${n} sat/vB exceeds refund safety cap ${Y} sat/vB; refusing to sign refund.`);const h=BigInt(Math.ceil(n*he)),l=s.amount*Q/J;if(h>l)throw new Error(`Refund fee ${h} sats exceeds the per-vault safety cap of ${l} sats (${Q}/${J} of vault.amount=${s.amount}); refusing to sign refund.`);a==null||a.throwIfAborted();const d=p.processPublicKeyToXOnly(s.depositorBtcPubkey),g=p.stripHexPrefix(s.unsignedPrePeginTxHex),f=O.findAuthAnchorOpReturn(g);if(f!==void 0&&f.vout!==s.batch.length)throw new Error(`Auth-anchor OP_RETURN at vout ${f.vout} does not match batch size (${s.batch.length} HTLC outputs expect the anchor at vout ${s.batch.length}). Refund refused — sibling HTLC vector is incomplete.`);const b=f==null?void 0:f.hash;let P;try{P=B.Transaction.fromHex(g)}catch(v){throw new Error(`Failed to parse funded Pre-PegIn transaction hex: ${v instanceof Error?v.message:String(v)}`)}if(P.outs.length<s.batch.length)throw new Error(`Funded Pre-PegIn tx has ${P.outs.length} outputs but batch requires at least ${s.batch.length} HTLC outputs. Refund refused — funded tx shape disagrees with sibling vector.`);const{psbtHex:y}=await I.buildRefundPsbt({prePeginParams:{vaultCoreVersion:s.vaultCoreVersion,depositorPubkey:d,vaultProviderPubkey:p.stripHexPrefix(c.vaultProviderPubkey),vaultKeeperPubkeys:c.vaultKeeperPubkeys.map(p.stripHexPrefix),universalChallengerPubkeys:c.universalChallengerPubkeys.map(p.stripHexPrefix),hashlocks:s.batch.map(v=>p.stripHexPrefix(v.hashlock)),timelockRefund:c.timelockRefund,pegInAmounts:s.batch.map(v=>v.amount),feeRate:c.feeRate,minPeginFeeRate:c.minPeginFeeRate,numLocalChallengers:c.numLocalChallengers,councilQuorum:c.councilQuorum,councilSize:c.councilSize,network:c.network,authAnchorHash:b},fundedPrePeginTxHex:g,htlcVout:s.htlcVout,refundFee:h,hashlock:p.stripHexPrefix(s.hashlock)});a==null||a.throwIfAborted();const m=V.createTaprootScriptPathSignOptions(s.depositorBtcPubkey,yr),w=await u(y,m);E.assertPsbtUnsignedTxMatches({requestedPsbtHex:y,returnedPsbtHex:w});const k=0,_=E.extractPayoutSignature(w,d,k);E.assertScriptPathSchnorrSignature({requestedPsbtHex:y,signatureHex:_,signerXOnlyPubkeyHex:d,inputIndex:k});const C=I.finalizeScriptPathWithSignatures({requestedPsbtHex:y,signaturesHex:[_],signerXOnlyPubkeyHex:d});a==null||a.throwIfAborted();try{return await i(C)}catch(v){throw v instanceof Error&&br.test(v.message)?new We(t,v):v}}class ee extends Error{constructor(r,o,n){super(r);N(this,"feeSats");N(this,"sweptTotalSats");this.name="ReclaimUneconomicalError",this.feeSats=o,this.sweptTotalSats=n}}const te=2e3,re=25n,oe=100n,Er=10n;async function xr(e,t,r){for(let o=0;o<e.length;o++){const n=V.calculateBtcTxHash(e[o].depositorSignedPeginTxHex),u=p.ensureHexPrefix(await x.deriveVaultId(p.stripHexPrefix(n),p.stripHexPrefix(r))).toLowerCase();if(u!==t[o].toLowerCase())throw new Error(`Reserve ${o} belongs to vault ${u}, not the requested ${t[o].toLowerCase()}. Refusing to sweep a reserve whose vault is not the one the caller asked for — the reserve funds that vault's claim transaction and cannot be replaced.`)}}async function Tr(e){const{vaultIds:t,depositorEthAddress:r,depositorBtcPubkey:o,readVaults:n,feeRate:u,signPsbt:i,broadcastTx:a,signal:s}=e;if(s==null||s.throwIfAborted(),t.length===0)throw new Error("Reclaim requires at least one vault id; got none.");if(!Number.isFinite(u)||u<=0)throw new Error(`feeRate must be a positive number, got ${u}`);if(u>te)throw new ee(`Fee rate ${u} sat/vB exceeds the reclaim safety cap of ${te} sat/vB; refusing to sign.`,0n,0n);const c=await n();if(s==null||s.throwIfAborted(),c.length!==t.length)throw new Error(`readVaults returned ${c.length} reserves for ${t.length} vault id(s); refusing to sweep a set that does not match the request.`);await xr(c,t,r),s==null||s.throwIfAborted();const h=p.processPublicKeyToXOnly(o),l=c.map(k=>({depositorSignedPeginTxHex:k.depositorSignedPeginTxHex,observed:k.observed,expectedValue:k.expectedClaimValue})),d=I.estimateReclaimFeeSats(u,l.length),g=l.reduce((k,_)=>k+_.expectedValue,0n),f=g*re/oe;if(d>f)throw new ee(`Reclaim fee ${d} sats exceeds ${re}/${oe} of the swept total (${g} sats, cap ${f} sats). The reserve is not at risk — it stays where it is until fee rates fall.`,d,g);s==null||s.throwIfAborted();const{psbtHex:b}=I.buildReclaimPsbt({depositorPubkey:h,inputs:l,feeSats:d});s==null||s.throwIfAborted();const P=V.createTaprootScriptPathSignOptions(o,l.length),y=await i(b,P);E.assertPsbtUnsignedTxMatches({requestedPsbtHex:b,returnedPsbtHex:y});const m=l.map((k,_)=>{const C=E.extractPayoutSignature(y,h,_);return E.assertScriptPathSchnorrSignature({requestedPsbtHex:b,signatureHex:C,signerXOnlyPubkeyHex:h,inputIndex:_}),C}),w=I.finalizeScriptPathWithSignatures({requestedPsbtHex:b,signaturesHex:m,signerXOnlyPubkeyHex:h});return s==null||s.throwIfAborted(),a(w)}exports.ApplicationEntryPointMismatchError=D;exports.ArtifactsVaultMismatchError=Ne;exports.BIP68NotMatureError=We;exports.ChallengerSetMismatchError=Ae;exports.ClaimerPegoutStatusValue=le;exports.DELEGATED_CLAIM_TX_GRAPH_VERSION=Oe;exports.PEGIN_ETH_CONFIRMATIONS=Ke;exports.ParticipantKeyDriftError=ue;exports.PayoutDestinationError=Re;exports.PeginRegistrationMissingError=ie;exports.PeginRegistrationNotFinalError=se;exports.RECLAIM_MAX_FEE_FRACTION_DENOMINATOR=oe;exports.RECLAIM_MAX_FEE_FRACTION_NUMERATOR=re;exports.RECLAIM_MAX_FEE_RATE_SATS_VB=te;exports.RECLAIM_WARN_FEE_FRACTION_NUMERATOR=Er;exports.REFUND_MAX_FEE_FRACTION_DENOMINATOR=J;exports.REFUND_MAX_FEE_FRACTION_NUMERATOR=Q;exports.REFUND_MAX_FEE_RATE_SATS_VB=Y;exports.REFUND_VSIZE=he;exports.ReclaimUneconomicalError=ee;exports.RegisteredVaultVersionMismatchError=ce;exports.VaultIdBindingError=$e;exports.activateVault=st;exports.activateVaultAndRedeem=at;exports.assembleWatchtowerArtifacts=Pt;exports.assertArtifactsUsableForVault=xt;exports.assertChallengerSetMatchesVault=Se;exports.assertClaimSpendsVault=ne;exports.assertPayoutPaysRegisteredScript=Be;exports.assertVaultProviderHintAccepted=Wt;exports.buildAndBroadcastReclaim=Tr;exports.buildAndBroadcastRefund=wr;exports.deriveClaimerWotsKeypair=wt;exports.estimateRefundFeeSats=Pr;exports.isApplicationEntryPointMismatchError=Yt;exports.isDepositAmountValid=Zt;exports.isHintAccepted=K;exports.isParticipantKeyDriftError=ar;exports.isPeginRegistrationMissingError=Me;exports.isPeginRegistrationNotFinalError=Ct;exports.isPegoutTerminalStatus=pr;exports.isRecognizedPegoutStatus=dr;exports.isRegisteredVaultVersionMismatchError=cr;exports.matchKeyHint=Ue;exports.matchKeySetHint=j;exports.resolveCurrentParticipantKeys=Xe;exports.resolveParticipantKeysAtEpochs=qe;exports.runDepositorPresignFlow=Xt;exports.signDepositorGraph=De;exports.submitWotsPublicKey=Gt;exports.summarizeWatchtowerArtifacts=He;exports.validateDepositAmount=er;exports.validateMultiVaultDepositInputs=sr;exports.validateOnChainParticipantKeys=Qt;exports.validateProviderSelection=rr;exports.validateRemainingCapacity=tr;exports.validateVaultAmounts=ze;exports.validateVaultProviderPubkey=Ge;exports.verifyRegisteredParticipantKeys=ur;exports.verifyRegisteredVaultVersions=lr;exports.waitForPeginRegistrationDepth=Rt;exports.waitForPeginStatus=ae;
|
|
2
|
-
//# sourceMappingURL=buildAndBroadcastReclaim-BwT6Jxp5.cjs.map
|