@babylonlabs-io/ts-sdk 0.57.2 → 0.58.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/{PeginManager-DbMFLh-1.js → PeginManager-C8ixWlUM.js} +319 -298
  2. package/dist/PeginManager-C8ixWlUM.js.map +1 -0
  3. package/dist/PeginManager-CogqZaa2.cjs +2 -0
  4. package/dist/PeginManager-CogqZaa2.cjs.map +1 -0
  5. package/dist/{batchPoll-X7D7OIcu.js → batchPoll-B0VxT62K.js} +4 -4
  6. package/dist/{batchPoll-X7D7OIcu.js.map → batchPoll-B0VxT62K.js.map} +1 -1
  7. package/dist/{batchPoll-D2OuUee1.cjs → batchPoll-D5IDDOa8.cjs} +2 -2
  8. package/dist/{batchPoll-D2OuUee1.cjs.map → batchPoll-D5IDDOa8.cjs.map} +1 -1
  9. package/dist/{bitcoin-CHzNE-rS.js → bitcoin-d9eaaZB_.js} +13 -14
  10. package/dist/bitcoin-d9eaaZB_.js.map +1 -0
  11. package/dist/{bitcoin-Dpcfff7b.cjs → bitcoin-m84N5a8o.cjs} +2 -2
  12. package/dist/bitcoin-m84N5a8o.cjs.map +1 -0
  13. package/dist/buildAndBroadcastRefund-BL8u-Ti4.cjs +2 -0
  14. package/dist/buildAndBroadcastRefund-BL8u-Ti4.cjs.map +1 -0
  15. package/dist/{buildAndBroadcastRefund-D_l93Gln.js → buildAndBroadcastRefund-DBA-Mp4I.js} +406 -376
  16. package/dist/buildAndBroadcastRefund-DBA-Mp4I.js.map +1 -0
  17. package/dist/{challengeAssert-CIHykYs3.cjs → challengeAssert-BFRE2DM-.cjs} +2 -2
  18. package/dist/{challengeAssert-CIHykYs3.cjs.map → challengeAssert-BFRE2DM-.cjs.map} +1 -1
  19. package/dist/{challengeAssert-XeAql2fF.js → challengeAssert-C7PzyJ7g.js} +2 -2
  20. package/dist/{challengeAssert-XeAql2fF.js.map → challengeAssert-C7PzyJ7g.js.map} +1 -1
  21. package/dist/constants-DU5CGcqO.cjs +2 -0
  22. package/dist/{constants-BqU1Uz15.cjs.map → constants-DU5CGcqO.cjs.map} +1 -1
  23. package/dist/constants-GjWXdaqV.js +23 -0
  24. package/dist/{constants-CDQE812z.js.map → constants-GjWXdaqV.js.map} +1 -1
  25. package/dist/{deriveVaultRoot-B5G8y6HJ.js → deriveVaultRoot-D0RY5GJc.js} +2 -2
  26. package/dist/{deriveVaultRoot-B5G8y6HJ.js.map → deriveVaultRoot-D0RY5GJc.js.map} +1 -1
  27. package/dist/{deriveVaultRoot-DH0kEyaS.cjs → deriveVaultRoot-p4uGsM7w.cjs} +2 -2
  28. package/dist/{deriveVaultRoot-DH0kEyaS.cjs.map → deriveVaultRoot-p4uGsM7w.cjs.map} +1 -1
  29. package/dist/errors-2aF9oRwM.cjs +2 -0
  30. package/dist/errors-2aF9oRwM.cjs.map +1 -0
  31. package/dist/errors-kXGQXKxZ.js +28 -0
  32. package/dist/errors-kXGQXKxZ.js.map +1 -0
  33. package/dist/index.cjs +1 -1
  34. package/dist/index.js +108 -105
  35. package/dist/{mempoolApi-4T6J5oxg.js → mempoolApi-CMHEz4ez.js} +3 -3
  36. package/dist/{mempoolApi-4T6J5oxg.js.map → mempoolApi-CMHEz4ez.js.map} +1 -1
  37. package/dist/{mempoolApi-BtIABIAQ.cjs → mempoolApi-DfD3_Y6v.cjs} +2 -2
  38. package/dist/{mempoolApi-BtIABIAQ.cjs.map → mempoolApi-DfD3_Y6v.cjs.map} +1 -1
  39. package/dist/{noPayout-DCf1xoJn.js → noPayout-DuE-UyhQ.js} +3 -3
  40. package/dist/{noPayout-DCf1xoJn.js.map → noPayout-DuE-UyhQ.js.map} +1 -1
  41. package/dist/{noPayout-BkXzkhU1.cjs → noPayout-qUEtRKc_.cjs} +2 -2
  42. package/dist/{noPayout-BkXzkhU1.cjs.map → noPayout-qUEtRKc_.cjs.map} +1 -1
  43. package/dist/{onChainBtcPubkey-DqYufM7j.cjs → onChainBtcPubkey-C_a2L3kL.cjs} +2 -2
  44. package/dist/{onChainBtcPubkey-DqYufM7j.cjs.map → onChainBtcPubkey-C_a2L3kL.cjs.map} +1 -1
  45. package/dist/{onChainBtcPubkey-mP95j21Z.js → onChainBtcPubkey-DeF4cKoO.js} +2 -2
  46. package/dist/{onChainBtcPubkey-mP95j21Z.js.map → onChainBtcPubkey-DeF4cKoO.js.map} +1 -1
  47. package/dist/peginInput-Ci921gTl.cjs +2 -0
  48. package/dist/peginInput-Ci921gTl.cjs.map +1 -0
  49. package/dist/peginInput-HQPWZfly.js +123 -0
  50. package/dist/peginInput-HQPWZfly.js.map +1 -0
  51. package/dist/{reservation-4F9XCk0v.js → reservation-CbAXa7VG.js} +2 -2
  52. package/dist/{reservation-4F9XCk0v.js.map → reservation-CbAXa7VG.js.map} +1 -1
  53. package/dist/{reservation-B_7tzSwY.cjs → reservation-RGKvg2x6.cjs} +2 -2
  54. package/dist/{reservation-B_7tzSwY.cjs.map → reservation-RGKvg2x6.cjs.map} +1 -1
  55. package/dist/signPsbtsWithFallback-Xs4jZw5z.cjs +2 -0
  56. package/dist/signPsbtsWithFallback-Xs4jZw5z.cjs.map +1 -0
  57. package/dist/{signPsbtsWithFallback-DxG_APbS.js → signPsbtsWithFallback-eY1YgV13.js} +69 -67
  58. package/dist/signPsbtsWithFallback-eY1YgV13.js.map +1 -0
  59. package/dist/tbv/core/clients/index.cjs +1 -1
  60. package/dist/tbv/core/clients/index.js +3 -3
  61. package/dist/tbv/core/deposit-terms/__tests__/depositTermsErrors.test.d.ts +2 -0
  62. package/dist/tbv/core/deposit-terms/__tests__/depositTermsErrors.test.d.ts.map +1 -0
  63. package/dist/tbv/core/deposit-terms/buildDepositTerms.d.ts.map +1 -1
  64. package/dist/tbv/core/deposit-terms/depositTerms.d.ts +72 -25
  65. package/dist/tbv/core/deposit-terms/depositTerms.d.ts.map +1 -1
  66. package/dist/tbv/core/deposit-terms/depositTermsErrors.d.ts +24 -0
  67. package/dist/tbv/core/deposit-terms/depositTermsErrors.d.ts.map +1 -0
  68. package/dist/tbv/core/deposit-terms/index.d.ts +2 -1
  69. package/dist/tbv/core/deposit-terms/index.d.ts.map +1 -1
  70. package/dist/tbv/core/index.cjs +1 -1
  71. package/dist/tbv/core/index.js +108 -105
  72. package/dist/tbv/core/managers/PayoutManager.d.ts +2 -0
  73. package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -1
  74. package/dist/tbv/core/managers/PeginManager.d.ts +16 -3
  75. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  76. package/dist/tbv/core/managers/index.cjs +1 -1
  77. package/dist/tbv/core/managers/index.js +2 -2
  78. package/dist/tbv/core/primitives/index.cjs +1 -1
  79. package/dist/tbv/core/primitives/index.js +6 -6
  80. package/dist/tbv/core/primitives/psbt/assertPayoutFeeBand.d.ts +14 -32
  81. package/dist/tbv/core/primitives/psbt/assertPayoutFeeBand.d.ts.map +1 -1
  82. package/dist/tbv/core/primitives/psbt/constants.d.ts +10 -1
  83. package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
  84. package/dist/tbv/core/primitives/psbt/payout.d.ts +8 -2
  85. package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
  86. package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
  87. package/dist/tbv/core/primitives/utils/bitcoin.d.ts +11 -1
  88. package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
  89. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +1 -1
  90. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  91. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts +1 -1
  92. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  93. package/dist/tbv/core/services/index.cjs +1 -1
  94. package/dist/tbv/core/services/index.js +2 -2
  95. package/dist/tbv/core/utils/index.cjs +1 -1
  96. package/dist/tbv/core/utils/index.js +2 -2
  97. package/dist/tbv/core/vault-secrets/index.cjs +1 -1
  98. package/dist/tbv/core/vault-secrets/index.js +1 -1
  99. package/dist/tbv/index.cjs +1 -1
  100. package/dist/tbv/index.js +108 -105
  101. package/dist/tbv/integrations/aave/index.cjs +1 -1
  102. package/dist/tbv/integrations/aave/index.cjs.map +1 -1
  103. package/dist/tbv/integrations/aave/index.d.ts +2 -0
  104. package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
  105. package/dist/tbv/integrations/aave/index.js +2 -0
  106. package/dist/testing/index.cjs +1 -1
  107. package/dist/testing/index.js +1 -1
  108. package/dist/{verifyScriptPathSchnorrSignature-wwa1JhiB.js → verifyScriptPathSchnorrSignature-Bav08_7R.js} +268 -240
  109. package/dist/verifyScriptPathSchnorrSignature-Bav08_7R.js.map +1 -0
  110. package/dist/verifyScriptPathSchnorrSignature-CYjK4IP_.cjs +2 -0
  111. package/dist/verifyScriptPathSchnorrSignature-CYjK4IP_.cjs.map +1 -0
  112. package/package.json +1 -1
  113. package/dist/PeginManager-DOmyNYT-.cjs +0 -2
  114. package/dist/PeginManager-DOmyNYT-.cjs.map +0 -1
  115. package/dist/PeginManager-DbMFLh-1.js.map +0 -1
  116. package/dist/bitcoin-CHzNE-rS.js.map +0 -1
  117. package/dist/bitcoin-Dpcfff7b.cjs.map +0 -1
  118. package/dist/buildAndBroadcastRefund-COinY4dk.cjs +0 -2
  119. package/dist/buildAndBroadcastRefund-COinY4dk.cjs.map +0 -1
  120. package/dist/buildAndBroadcastRefund-D_l93Gln.js.map +0 -1
  121. package/dist/constants-BqU1Uz15.cjs +0 -2
  122. package/dist/constants-CDQE812z.js +0 -21
  123. package/dist/errors-B-H0seUG.js +0 -8
  124. package/dist/errors-B-H0seUG.js.map +0 -1
  125. package/dist/errors-Bfjxg_iJ.cjs +0 -2
  126. package/dist/errors-Bfjxg_iJ.cjs.map +0 -1
  127. package/dist/peginInput-CAYuE_5F.cjs +0 -2
  128. package/dist/peginInput-CAYuE_5F.cjs.map +0 -1
  129. package/dist/peginInput-DRUm164W.js +0 -105
  130. package/dist/peginInput-DRUm164W.js.map +0 -1
  131. package/dist/signPsbtsWithFallback-DxG_APbS.js.map +0 -1
  132. package/dist/signPsbtsWithFallback-r3bC-CfM.cjs +0 -2
  133. package/dist/signPsbtsWithFallback-r3bC-CfM.cjs.map +0 -1
  134. package/dist/verifyScriptPathSchnorrSignature-fhjfNoHK.cjs +0 -2
  135. package/dist/verifyScriptPathSchnorrSignature-fhjfNoHK.cjs.map +0 -1
  136. package/dist/verifyScriptPathSchnorrSignature-wwa1JhiB.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"peginInput-DRUm164W.js","sources":["../src/tbv/core/primitives/psbt/peginInput.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 {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, stripHexPrefix, uint8ArrayToHex } from \"../utils/bitcoin\";\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 const htlcConnector = 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\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 const hashlockScript = hexToUint8Array(htlcConnector.hashlockScript);\n const hashlockControlBlock = hexToUint8Array(htlcConnector.hashlockControlBlock);\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.\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: Buffer.from(hashlockScript),\n controlBlock: Buffer.from(hashlockControlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\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(\n hexToUint8Array(depositorPubkey),\n );\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"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","hashlockScript","hexToUint8Array","hashlockControlBlock","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex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GAAG;AAIV,QAAI,CAHiBd,EAAK,KAAK,OAAO;AAAA,MACpC,CAACe,MAAQA,EAAI,sBAAsBA,EAAI;AAAA,IAAA;AAGvC,YAAM,IAAI;AAAA,QACR,8DAA8DD,CAAC;AAAA,MAAA;AAAA,EAGrE;AAEA,SAAOd,EAAK,mBAAA,EAAqB,MAAA;AACnC;AASO,SAASY,EAAkBI,GAAyB;AACzD,MAAIA,EAAI,WAAW;AACjB,WAAOrB,EAAgB,IAAI,WAAWqB,CAAG,CAAC;AAE5C,QAAIA,EAAI,WAAW,KACX,IAAI;AAAA,IACR,6BAA6BA,EAAI,EAAE,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC;AAAA,EAAA,IAIhE,IAAI,MAAM,4CAA4CA,EAAI,MAAM,EAAE;AAC1E;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"signPsbtsWithFallback-DxG_APbS.js","sources":["../src/tbv/core/managers/pegin/assertAuthAnchorOpReturn.ts","../src/tbv/core/services/htlc/index.ts","../src/tbv/core/deposit-terms/depositTerms.ts","../src/tbv/core/managers/PayoutManager.ts","../src/tbv/core/managers/pegin/signPsbtsWithFallback.ts"],"sourcesContent":["/**\n * Structural verifier for the auth-anchor OP_RETURN in a funded\n * Pre-PegIn transaction.\n *\n * @module managers/pegin/assertAuthAnchorOpReturn\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\n\n/** OP_RETURN opcode. */\nconst OP_RETURN = 0x6a;\n/** Push-32-bytes opcode (raw push, not OP_PUSHDATA1). */\nconst OP_PUSH32 = 0x20;\n/** Encoded length of a standard OP_RETURN script with a 32-byte payload. */\nconst OP_RETURN_PUSH32_SCRIPT_LEN = 1 + 1 + 32;\n\n/**\n * Verify the broadcast Pre-PegIn carries the expected OP_RETURN\n * commitment to the auth anchor.\n *\n * The OP_RETURN sits at `vout = vaultCount` (right after the per-vault\n * HTLC outputs and before the depositor-claim/change outputs) and\n * pushes the 32-byte `SHA256(authAnchor)`. The script encoding is\n * exactly `OP_RETURN || PUSH32 || <32 bytes>` (34 bytes). A\n * non-conformant WASM build that omitted the OP_RETURN, swapped its\n * position, or changed its push payload would let the depositor\n * obtain a valid bearer token for a Pre-PegIn whose on-chain\n * commitment doesn't actually bind the anchor — degrading the auth\n * from on-chain-bound to a shared secret. Fail closed.\n *\n * @throws If the OP_RETURN is missing, mis-located, mis-encoded, or\n * pushes a payload other than `expectedAuthAnchorHashHex`.\n */\nexport function assertAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n vaultCount: number,\n expectedAuthAnchorHashHex: string,\n): void {\n const cleanHex = stripHexPrefix(fundedPrePeginTxHex);\n const tx = bitcoin.Transaction.fromHex(cleanHex);\n\n if (tx.outs.length <= vaultCount) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN missing: tx has ${tx.outs.length} ` +\n `outputs, expected at least ${vaultCount + 1} (vault outputs + OP_RETURN)`,\n );\n }\n\n const opReturnOutput = tx.outs[vaultCount];\n const script = opReturnOutput.script;\n if (\n script.length !== OP_RETURN_PUSH32_SCRIPT_LEN ||\n script[0] !== OP_RETURN ||\n script[1] !== OP_PUSH32\n ) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has unexpected ` +\n `script encoding (got ${script.length}-byte script with prefix ` +\n `0x${script.slice(0, Math.min(2, script.length)).toString(\"hex\")}; ` +\n `expected ${OP_RETURN_PUSH32_SCRIPT_LEN}-byte OP_RETURN + PUSH32 layout)`,\n );\n }\n\n const pushedHex = script.slice(2).toString(\"hex\").toLowerCase();\n if (pushedHex !== expectedAuthAnchorHashHex.toLowerCase()) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${vaultCount}: ` +\n `tx pushes ${pushedHex}, expected ${expectedAuthAnchorHashHex}`,\n );\n }\n\n if (opReturnOutput.value !== 0) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has non-zero ` +\n `value ${opReturnOutput.value}; OP_RETURN outputs must be 0-value`,\n );\n }\n}\n\n/**\n * Scan a funded Pre-PegIn transaction for its auth-anchor commitment\n * (an `OP_RETURN || PUSH32 || <32 bytes>` output with value 0).\n *\n * Returns `{ vout, hash }` when exactly one such output is found.\n * Returns `undefined` when:\n * - the hex is unparseable,\n * - no matching output exists (legacy non-auth-anchored Pre-PegIn),\n * - more than one matching output exists (ambiguous / malformed).\n *\n * Used by the refund orchestrator to (a) locate the on-chain anchor\n * regardless of how many HTLCs preceded it and (b) detect multi-vault\n * funded transactions structurally: the single-vault refund path\n * reconstructs only one hashlock and expects the anchor at vout 1, so\n * any other vout signals a layout this call cannot safely refund.\n */\nexport function findAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n): { vout: number; hash: string } | undefined {\n let tx: bitcoin.Transaction;\n try {\n tx = bitcoin.Transaction.fromHex(stripHexPrefix(fundedPrePeginTxHex));\n } catch {\n return undefined;\n }\n\n const hits: { vout: number; hash: string }[] = [];\n for (let i = 0; i < tx.outs.length; i++) {\n const output = tx.outs[i];\n const script = output.script;\n if (\n script.length === OP_RETURN_PUSH32_SCRIPT_LEN &&\n script[0] === OP_RETURN &&\n script[1] === OP_PUSH32 &&\n output.value === 0\n ) {\n hits.push({\n vout: i,\n hash: script.slice(2).toString(\"hex\").toLowerCase(),\n });\n }\n }\n\n return hits.length === 1 ? hits[0] : undefined;\n}\n","/**\n * HTLC Secret / Hashlock Utilities\n *\n * Pure functions for computing and validating SHA-256 hashlocks used in the\n * vault deposit protocol's HTLC (Hash Time Lock Contract).\n *\n * The SDK does NOT generate secrets — that is the caller's responsibility.\n * Today callers use `crypto.getRandomValues(32)`; when the `deriveContextHash`\n * wallet API ships, callers will use `wallet.deriveContextHash(\"babylon-btc-vault\", ctx)`.\n * These utilities work identically regardless of how the secret was produced.\n *\n * On-chain contract validation (BTCVaultRegistry.activateVaultWithSecret):\n * if (sha256(abi.encodePacked(s)) != hashlock) revert InvalidSecret();\n *\n * @module htlc\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport type { Hex } from \"viem\";\n\n/** Expected hex length for a 0x-prefixed bytes32 value. */\nconst HEX_BYTES32_LENGTH = 66; // \"0x\" + 64 hex chars\n\n/**\n * Decode a 0x-prefixed hex string to bytes, with strict validation.\n * @throws if the input is not a valid 0x-prefixed hex string\n */\nfunction hexToBytes(hex: Hex): Uint8Array {\n if (!hex.startsWith(\"0x\") && !hex.startsWith(\"0X\")) {\n throw new Error(\"Expected 0x-prefixed hex string\");\n }\n const clean = hex.slice(2);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has odd length: ${clean.length}`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error(\"Hex string contains non-hex characters\");\n }\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Encode a Uint8Array as a 0x-prefixed lowercase hex string.\n */\nfunction bytesToHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\n/**\n * Validate that a value is a 0x-prefixed bytes32 (exactly 32 bytes).\n * @throws if the value is not exactly 32 bytes\n */\nfunction assertBytes32(value: Hex, label: string): void {\n if (value.length !== HEX_BYTES32_LENGTH) {\n throw new Error(\n `${label} must be exactly 32 bytes (${HEX_BYTES32_LENGTH} hex chars with 0x prefix), got ${value.length}`,\n );\n }\n}\n\n/**\n * Compute the SHA-256 hashlock from a secret preimage.\n *\n * Matches the on-chain validation: `sha256(abi.encodePacked(s))` where `s` is a `bytes32`.\n * `abi.encodePacked(bytes32)` is just the raw 32 bytes — no ABI padding.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @returns 0x-prefixed bytes32 SHA-256 hash\n * @throws if secret is not exactly 32 bytes\n */\nexport function computeHashlock(secret: Hex): Hex {\n assertBytes32(secret, \"Secret\");\n const secretBytes = hexToBytes(secret);\n const hash = sha256(secretBytes);\n return bytesToHex(hash);\n}\n\n/**\n * Validate that a secret's SHA-256 hash matches the expected hashlock.\n *\n * Use this for client-side pre-validation before sending the activation\n * transaction to avoid wasting gas on a contract revert.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @param hashlock - 0x-prefixed bytes32 expected hashlock from the vault\n * @returns true if SHA-256(secret) matches the hashlock\n * @throws if secret or hashlock is not exactly 32 bytes\n */\nexport function validateSecretAgainstHashlock(\n secret: Hex,\n hashlock: Hex,\n): boolean {\n assertBytes32(secret, \"Secret\");\n assertBytes32(hashlock, \"Hashlock\");\n // Validate hashlock is valid hex (secret is validated inside computeHashlock)\n hexToBytes(hashlock);\n\n const computed = computeHashlock(secret);\n return computed.toLowerCase() === hashlock.toLowerCase();\n}\n","import type { BitcoinWallet } from \"../../../shared/wallets/interfaces\";\n\n// Field docs use /** */ so they survive into the emitted .d.ts — the published\n// package is the only contract the external provider author (#2109) sees.\n\nexport interface DepositTermsVaultGroup {\n /** 0-based; equals the group's position (groups are ascending by vout). */\n readonly htlcVout: number;\n /** x-only hex (64 chars), as validated on-chain upstream. */\n readonly vaultProviderPk: string;\n /** sats */\n readonly vaultAmount: bigint;\n /** sats; floor(vaultAmount * commissionBps / 10_000). */\n readonly commissionFee: bigint;\n /** sats; the same value for every vault. */\n readonly depositorClaimValue: bigint;\n /** sats; the minimum PegIn fee for this graph version. */\n readonly peginMaxFee: bigint;\n}\n\nexport interface DepositTerms {\n /**\n * sat/vB; the tx-graph fee rate (protocolFeeRate), NOT the mempool funding\n * rate. An approving wallet bounds each payout's fee at baseFeeRate x a\n * conservative vsize estimate (v22 §4.9.7.1) — pass the exact graph rate,\n * not an inflated ceiling.\n */\n baseFeeRate: bigint;\n /** Vault-UTXO CSV timelock (blocks). */\n peginCsvTimelock: number;\n /**\n * Payout timelock on the Assert transaction's output 0; comes from the same\n * protocol param (timelockAssert) as peginCsvTimelock.\n */\n payoutTimelock: number;\n /** HTLC refund CSV timelock (blocks). */\n htlcRefundTimelock: number;\n /**\n * 64-char hex in display order. A device-wire encoder must byte-reverse it to\n * the little-endian form the device recomputes and compares against.\n */\n prepeginTxid: string;\n /** sats; the funded Pre-PegIn fee (an approving wallet caps the signed fee at this). */\n prepeginMaxFee: bigint;\n /**\n * x-only hex. Sorted ascending by the upstream on-chain validation\n * (validateOnChainParticipantKeys); the builder passes them through\n * unasserted — the device rejects unsorted lists at intent load.\n */\n keeperPks: readonly string[];\n /**\n * x-only hex, sorted ascending upstream independently of keeperPks (same\n * pass-through contract). Universal challengers only — the full graph\n * challenger set is keeperPks ∪ challengerPks (vault keepers are the local\n * challengers).\n */\n challengerPks: readonly string[];\n /** Per-vault groups, ordered by ascending htlcVout. */\n vaults: readonly DepositTermsVaultGroup[];\n}\n\n/**\n * Implemented only by depositor-approval wallets (e.g. a Ledger vault provider).\n * Either a class field or a prototype method works — the deposit flow spreads\n * the wallet object but forwards this method explicitly at every wrapper site.\n *\n * Seam invariant: never call deriveContextHash between approveDepositTerms and\n * the last terms-bound signature of a connection — deriving while an intent is\n * loaded nullifies it on-device. Design: the SDK owns approval (mirrors its\n * deriveContextHash/signPsbts orchestration); provider-internal and app-driven\n * placements were rejected.\n */\nexport interface DepositTermsApprover {\n approveDepositTerms(terms: DepositTerms): Promise<void>;\n}\n\n/** True when the wallet implements {@link DepositTermsApprover.approveDepositTerms}. */\nexport function supportsDepositApproval(\n wallet: BitcoinWallet,\n): wallet is BitcoinWallet & DepositTermsApprover {\n return typeof (wallet as Partial<DepositTermsApprover>).approveDepositTerms === \"function\";\n}\n\n/**\n * Spreadable forward of `approveDepositTerms` for wallet-wrapper objects.\n * Object spread drops prototype methods, so every `{...wallet}` wrapper site\n * must re-attach the capability explicitly: `...forwardDepositApproval(wallet)`.\n */\nexport function forwardDepositApproval(\n wallet: BitcoinWallet,\n): Partial<DepositTermsApprover> {\n return supportsDepositApproval(wallet)\n ? { approveDepositTerms: (terms) => wallet.approveDepositTerms(terms) }\n : {};\n}\n\nexport interface BuildDepositTermsInputs {\n protocolFeeRate: bigint;\n timelockPegin: number;\n timelockRefund: number;\n prepeginTxid: string;\n prepeginMaxFee: bigint;\n vaultProviderPk: string;\n keeperPks: readonly string[];\n challengerPks: readonly string[];\n commissionBps: number;\n vaultAmounts: readonly bigint[];\n depositorClaimValue: bigint;\n peginMaxFee: bigint;\n}\n","/**\n * Payout Manager\n *\n * High-level manager that orchestrates the payout signing flow by coordinating\n * SDK primitives ({@link buildPayoutPsbt}, {@link extractPayoutSignature})\n * with a user-provided Bitcoin wallet.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @see {@link PeginManager} - For Steps 1–4 of the peg-in flow\n * @see {@link buildPayoutPsbt} - Lower-level primitive for custom implementations\n * @see {@link extractPayoutSignature} - Extract signatures from signed PSBTs\n *\n * @module managers/PayoutManager\n */\n\nimport type { BitcoinWallet, SignPsbtOptions } from \"../../../shared/wallets\";\nimport {\n assertPsbtUnsignedTxMatches,\n assertScriptPathSchnorrSignature,\n buildPayoutPsbt,\n extractPayoutSignature,\n validateWalletPubkey,\n type Network,\n} from \"../primitives\";\nimport { createTaprootScriptPathSignOptions } from \"../utils/signing\";\n\n/** Payout PSBTs are signed by the depositor on input 0 (Taproot script-path). */\nconst PAYOUT_SIGNED_INPUT_INDEX = 0;\n\n/**\n * Configuration for the PayoutManager.\n */\nexport interface PayoutManagerConfig {\n /**\n * Bitcoin network to use for transactions.\n */\n network: Network;\n\n /**\n * Bitcoin wallet for signing payout transactions.\n */\n btcWallet: BitcoinWallet;\n}\n\n/**\n * Base parameters shared by both payout transaction types.\n */\ninterface SignPayoutBaseParams {\n /**\n * Vault core (tx-graph) version the vault was registered under — the\n * vault's stamped on-chain `vaultCoreVersion`. Forwarded to\n * {@link buildPayoutPsbt} to derive the matching graph's payout scripts.\n */\n vaultCoreVersion: number;\n\n /**\n * Peg-in transaction hex.\n * The original transaction that created the vault output being spent.\n */\n peginTxHex: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex).\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex).\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex).\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex). This MUST be the\n * key registered on-chain for the vault — typically read from\n * `BTCVaultRegistry.getBtcVaultBasicInfo(...).depositorBtcPubKey`.\n *\n * Required: omitting it would degrade `validateWalletPubkey` to a\n * self-comparison, allowing the wrong wallet to produce a signature\n * over a script tree that doesn't match the on-chain UTXO.\n */\n depositorBtcPubkey: string;\n\n /**\n * The on-chain registered depositor payout scriptPubKey (hex, with or without 0x prefix).\n * Used to validate that the VP-provided payout transaction actually pays to the\n * correct depositor payout address before signing.\n */\n registeredPayoutScriptPubKey: string;\n\n /**\n * The claimer's x-only BTC public key for this payout (64-char hex, no prefix).\n * Forwarded to {@link buildPayoutPsbt} for per-role output validation.\n */\n claimerBtcPubkey: string;\n\n /**\n * VP commission in basis points (`1..=9999`). Forwarded to {@link buildPayoutPsbt}.\n */\n commissionBps: number;\n\n /**\n * Version-locked tx-graph fee rate (sat/vB) the graph was built with.\n * Forwarded to {@link buildPayoutPsbt} for the fee band.\n */\n protocolFeeRate: bigint;\n\n /** Security council member count; forwarded to the fee floor (see PayoutParams). */\n councilSize: number;\n\n /**\n * RFC-006 resolved payout destinations, keyed by lowercased x-only operation\n * pubkey. Forwarded verbatim to {@link buildPayoutPsbt}; every VK claimer\n * must be present.\n */\n vkClaimerPayoutScriptPubKeys: Readonly<Record<string, string>>;\n /** RFC-006 VP commission destination. Forwarded to {@link buildPayoutPsbt}. */\n vpCommissionScriptPubKey: string;\n}\n\n/**\n * Parameters for signing a Payout transaction.\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface SignPayoutParams extends SignPayoutBaseParams {\n /**\n * Payout transaction hex (unsigned).\n * This is the transaction from the vault provider that needs depositor signature.\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex.\n * Payout input 1 references Assert output 0.\n */\n assertTxHex: string;\n}\n\n/**\n * Result of signing a payout transaction.\n */\nexport interface PayoutSignatureResult {\n /**\n * 64-byte Schnorr signature (128 hex characters).\n */\n signature: string;\n\n /**\n * Depositor's BTC public key used for signing.\n */\n depositorBtcPubkey: string;\n}\n\n/**\n * High-level manager for payout transaction signing.\n *\n * @remarks\n * After registering your peg-in on Ethereum (Step 3), the vault provider prepares\n * claim/payout transaction pairs. You must sign each payout transaction using this\n * manager and submit the signatures to the vault provider's RPC API.\n *\n * **What happens internally:**\n * 1. Validates your wallet's public key matches the vault's depositor\n * 2. Builds an unsigned PSBT with taproot script path spend info\n * 3. Signs input 0 (the vault UTXO) with your wallet\n * 4. Extracts the 64-byte Schnorr signature\n *\n * **Note:** The payout transaction has 2 inputs. PayoutManager only signs input 0\n * (from the peg-in tx). Input 1 (from the assert tx) is signed by the vault provider.\n *\n * @see {@link PeginManager} - For the complete peg-in flow context\n * @see {@link buildPayoutPsbt} - Lower-level primitive used internally\n * @see {@link extractPayoutSignature} - Signature extraction primitive\n */\nexport class PayoutManager {\n private readonly config: PayoutManagerConfig;\n\n /**\n * Creates a new PayoutManager instance.\n *\n * @param config - Manager configuration including wallet\n */\n constructor(config: PayoutManagerConfig) {\n this.config = config;\n }\n\n /**\n * Signs a Payout transaction and extracts the Schnorr signature.\n *\n * Flow:\n * 1. Vault provider submits Claim transaction\n * 2. Claimer submits Assert transaction to prove validity\n * 3. Payout can be executed (references Assert tx)\n *\n * This method orchestrates the following steps:\n * 1. Get wallet's public key and convert to x-only format\n * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)\n * 3. Build unsigned PSBT using primitives\n * 4. Sign PSBT via btcWallet.signPsbt()\n * 5. Extract 64-byte Schnorr signature using primitives\n *\n * The returned signature can be submitted to the vault provider API.\n *\n * @param params - Payout signing parameters\n * @returns Signature result with 64-byte Schnorr signature and depositor pubkey\n * @throws Error if wallet pubkey doesn't match depositor pubkey\n * @throws Error if wallet operations fail or signature extraction fails\n */\n async signPayoutTransaction(\n params: SignPayoutParams,\n ): Promise<PayoutSignatureResult> {\n // Validate wallet pubkey matches depositor and get both formats\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n params.depositorBtcPubkey,\n );\n\n // Build unsigned PSBT for Payout (uses Assert tx). Per-role output\n // validation happens inside buildPayoutPsbt against the resolved input\n // values.\n const payoutPsbt = await buildPayoutPsbt({\n vaultCoreVersion: params.vaultCoreVersion,\n payoutTxHex: params.payoutTxHex,\n peginTxHex: params.peginTxHex,\n assertTxHex: params.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: params.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: params.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: this.config.network,\n claimerBtcPubkey: params.claimerBtcPubkey,\n registeredPayoutScriptPubKey: params.registeredPayoutScriptPubKey,\n commissionBps: params.commissionBps,\n protocolFeeRate: params.protocolFeeRate,\n councilSize: params.councilSize,\n vkClaimerPayoutScriptPubKeys: params.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: params.vpCommissionScriptPubKey,\n });\n\n // Sign PSBT via wallet (Taproot script-path spend, input 0 only)\n const signedPsbtHex = await this.config.btcWallet.signPsbt(\n payoutPsbt.psbtHex,\n createTaprootScriptPathSignOptions(walletPubkeyRaw, 1),\n );\n\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: payoutPsbt.psbtHex,\n returnedPsbtHex: signedPsbtHex,\n });\n\n // Extract Schnorr signature\n const signature = extractPayoutSignature(signedPsbtHex, depositorPubkey);\n // Critical Path #7: verify the signature against a sighash recomputed from\n // the PSBT we built, not the wallet-returned one.\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: payoutPsbt.psbtHex,\n signatureHex: signature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: PAYOUT_SIGNED_INPUT_INDEX,\n });\n\n return {\n signature,\n depositorBtcPubkey: depositorPubkey,\n };\n }\n\n /**\n * Gets the configured Bitcoin network.\n *\n * @returns The Bitcoin network (mainnet, testnet, signet, regtest)\n */\n getNetwork(): Network {\n return this.config.network;\n }\n\n /**\n * Checks if the wallet supports batch signing (signPsbts).\n *\n * @returns true if batch signing is supported\n */\n supportsBatchSigning(): boolean {\n return typeof this.config.btcWallet.signPsbts === \"function\";\n }\n\n /**\n * Batch signs multiple payout transactions (1 per claimer).\n * This allows signing all transactions with a single wallet interaction.\n *\n * @param transactions - Array of payout params to sign\n * @returns Array of signature results matching input order\n * @throws Error if wallet doesn't support batch signing\n * @throws Error if any signing operation fails\n */\n async signPayoutTransactionsBatch(transactions: SignPayoutParams[]): Promise<\n Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }>\n > {\n if (!this.supportsBatchSigning()) {\n throw new Error(\n \"Wallet does not support batch signing (signPsbts method not available)\",\n );\n }\n\n // Get wallet pubkey once\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n\n // Build all PSBTs (1 per claimer)\n const psbtsToSign: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n const depositorPubkeys: string[] = [];\n\n for (const tx of transactions) {\n // Validate wallet pubkey matches depositor\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n tx.depositorBtcPubkey,\n );\n depositorPubkeys.push(depositorPubkey);\n\n // Build Payout PSBT (output validation runs inside buildPayoutPsbt\n // against resolved input values).\n const payoutPsbt = await buildPayoutPsbt({\n vaultCoreVersion: tx.vaultCoreVersion,\n payoutTxHex: tx.payoutTxHex,\n peginTxHex: tx.peginTxHex,\n assertTxHex: tx.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: tx.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: tx.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: tx.universalChallengerBtcPubkeys,\n timelockPegin: tx.timelockPegin,\n network: this.config.network,\n claimerBtcPubkey: tx.claimerBtcPubkey,\n registeredPayoutScriptPubKey: tx.registeredPayoutScriptPubKey,\n commissionBps: tx.commissionBps,\n protocolFeeRate: tx.protocolFeeRate,\n councilSize: tx.councilSize,\n vkClaimerPayoutScriptPubKeys: tx.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: tx.vpCommissionScriptPubKey,\n });\n psbtsToSign.push(payoutPsbt.psbtHex);\n signOptions.push(createTaprootScriptPathSignOptions(walletPubkeyRaw, 1));\n }\n\n // Batch sign all PSBTs with single wallet interaction\n const signedPsbts = await this.config.btcWallet.signPsbts!(\n psbtsToSign,\n signOptions,\n );\n\n // Validate that wallet returned the expected number of signed PSBTs\n if (signedPsbts.length !== transactions.length) {\n throw new Error(\n `Expected ${transactions.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n\n // Extract signatures from signed PSBTs\n const results: Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }> = [];\n\n for (let i = 0; i < transactions.length; i++) {\n const depositorPubkey = depositorPubkeys[i];\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: psbtsToSign[i],\n returnedPsbtHex: signedPsbts[i],\n });\n const payoutSignature = extractPayoutSignature(\n signedPsbts[i],\n depositorPubkey,\n );\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: psbtsToSign[i],\n signatureHex: payoutSignature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: PAYOUT_SIGNED_INPUT_INDEX,\n });\n\n results.push({\n payoutSignature,\n depositorBtcPubkey: depositorPubkey,\n });\n }\n\n return results;\n }\n}\n","/**\n * Wallet-signing helper that routes a lone PSBT to `signPsbt`, prefers native\n * `signPsbts` for real batches, and falls back to sequential `signPsbt` for\n * wallets that don't implement batch signing.\n *\n * @module managers/pegin/signPsbtsWithFallback\n */\n\nimport type {\n BitcoinWallet,\n SignPsbtOptions,\n} from \"../../../../shared/wallets\";\n\n/**\n * Sign one or more PSBTs against a wallet.\n *\n * A single PSBT is always signed via `signPsbt`, never the batch endpoint: it's\n * one wallet interaction either way, and `signPsbt` is the universally-required\n * wallet method (batch `signPsbts` is optional), so single-sign is the portable\n * choice — some integrations (notably MPC / institutional wallets) prefer it.\n * For a real batch (>1), wallets exposing native `signPsbts` (e.g. UniSat) sign\n * in one interaction; others loop `signPsbt`.\n *\n * @throws If native `signPsbts` returns a different number of signed PSBTs\n * than were submitted.\n */\nexport async function signPsbtsWithFallback(\n wallet: BitcoinWallet,\n psbtsHexes: string[],\n options?: SignPsbtOptions[],\n): Promise<string[]> {\n if (psbtsHexes.length === 1) {\n return [await wallet.signPsbt(psbtsHexes[0], options?.[0])];\n }\n\n if (typeof wallet.signPsbts === \"function\") {\n const signedPsbts = await wallet.signPsbts(psbtsHexes, options);\n if (signedPsbts.length !== psbtsHexes.length) {\n throw new Error(\n `Expected ${psbtsHexes.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n return signedPsbts;\n }\n\n const signedPsbts: string[] = [];\n for (let i = 0; i < psbtsHexes.length; i++) {\n signedPsbts.push(await wallet.signPsbt(psbtsHexes[i], options?.[i]));\n }\n return signedPsbts;\n}\n"],"names":["OP_RETURN","OP_PUSH32","OP_RETURN_PUSH32_SCRIPT_LEN","assertAuthAnchorOpReturn","fundedPrePeginTxHex","vaultCount","expectedAuthAnchorHashHex","cleanHex","stripHexPrefix","tx","bitcoin","opReturnOutput","script","pushedHex","findAuthAnchorOpReturn","hits","i","output","HEX_BYTES32_LENGTH","hexToBytes","hex","clean","bytes","bytesToHex","b","assertBytes32","value","label","computeHashlock","secret","secretBytes","hash","sha256","validateSecretAgainstHashlock","hashlock","supportsDepositApproval","wallet","forwardDepositApproval","terms","PAYOUT_SIGNED_INPUT_INDEX","PayoutManager","config","__publicField","params","walletPubkeyRaw","depositorPubkey","validateWalletPubkey","payoutPsbt","buildPayoutPsbt","signedPsbtHex","createTaprootScriptPathSignOptions","assertPsbtUnsignedTxMatches","signature","extractPayoutSignature","assertScriptPathSchnorrSignature","transactions","psbtsToSign","signOptions","depositorPubkeys","signedPsbts","results","payoutSignature","signPsbtsWithFallback","psbtsHexes","options"],"mappings":";;;;;;;;;AAYA,MAAMA,IAAY,KAEZC,IAAY,IAEZC,IAA8B;AAmB7B,SAASC,EACdC,GACAC,GACAC,GACM;AACN,QAAMC,IAAWC,EAAeJ,CAAmB,GAC7CK,IAAKC,EAAQ,YAAY,QAAQH,CAAQ;AAE/C,MAAIE,EAAG,KAAK,UAAUJ;AACpB,UAAM,IAAI;AAAA,MACR,mDAAmDI,EAAG,KAAK,MAAM,+BACjCJ,IAAa,CAAC;AAAA,IAAA;AAIlD,QAAMM,IAAiBF,EAAG,KAAKJ,CAAU,GACnCO,IAASD,EAAe;AAC9B,MACEC,EAAO,WAAWV,KAClBU,EAAO,CAAC,MAAMZ,KACdY,EAAO,CAAC,MAAMX;AAEd,UAAM,IAAI;AAAA,MACR,2CAA2CI,CAAU,wCAC3BO,EAAO,MAAM,8BAChCA,EAAO,MAAM,GAAG,KAAK,IAAI,GAAGA,EAAO,MAAM,CAAC,EAAE,SAAS,KAAK,CAAC,cACpDV,CAA2B;AAAA,IAAA;AAI7C,QAAMW,IAAYD,EAAO,MAAM,CAAC,EAAE,SAAS,KAAK,EAAE,YAAA;AAClD,MAAIC,MAAcP,EAA0B;AAC1C,UAAM,IAAI;AAAA,MACR,4DAA4DD,CAAU,eACvDQ,CAAS,cAAcP,CAAyB;AAAA,IAAA;AAInE,MAAIK,EAAe,UAAU;AAC3B,UAAM,IAAI;AAAA,MACR,2CAA2CN,CAAU,uBAC1CM,EAAe,KAAK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1C,CAAC;AAC1C,MAAAmC,EAA4B;AAAA,QAC1B,kBAAkBK,EAAYxC,CAAC;AAAA,QAC/B,iBAAiB2C,EAAY3C,CAAC;AAAA,MAAA,CAC/B;AACD,YAAM6C,IAAkBR;AAAA,QACtBM,EAAY3C,CAAC;AAAA,QACb6B;AAAA,MAAA;AAEF,MAAAS,EAAiC;AAAA,QAC/B,kBAAkBE,EAAYxC,CAAC;AAAA,QAC/B,cAAc6C;AAAA,QACd,sBAAsBhB;AAAA,QACtB,YAAYN;AAAA,MAAA,CACb,GAEDqB,EAAQ,KAAK;AAAA,QACX,iBAAAC;AAAA,QACA,oBAAoBhB;AAAA,MAAA,CACrB;AAAA,IACH;AAEA,WAAOe;AAAA,EACT;AACF;AC3XA,eAAsBE,EACpB1B,GACA2B,GACAC,GACmB;AACnB,MAAID,EAAW,WAAW;AACxB,WAAO,CAAC,MAAM3B,EAAO,SAAS2B,EAAW,CAAC,GAAGC,KAAA,gBAAAA,EAAU,EAAE,CAAC;AAG5D,MAAI,OAAO5B,EAAO,aAAc,YAAY;AAC1C,UAAMuB,IAAc,MAAMvB,EAAO,UAAU2B,GAAYC,CAAO;AAC9D,QAAIL,EAAY,WAAWI,EAAW;AACpC,YAAM,IAAI;AAAA,QACR,YAAYA,EAAW,MAAM,8BAA8BJ,EAAY,MAAM;AAAA,MAAA;AAGjF,WAAOA;AAAAA,EACT;AAEA,QAAMA,IAAwB,CAAA;AAC9B,WAAS3C,IAAI,GAAGA,IAAI+C,EAAW,QAAQ/C;AACrC,IAAA2C,EAAY,KAAK,MAAMvB,EAAO,SAAS2B,EAAW/C,CAAC,GAAGgD,KAAA,gBAAAA,EAAUhD,EAAE,CAAC;AAErE,SAAO2C;AACT;"}
@@ -1,2 +0,0 @@
1
- "use strict";var H=Object.defineProperty;var m=(e,t,r)=>t in e?H(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var b=(e,t,r)=>m(e,typeof t!="symbol"?t+"":t,r);const B=require("bitcoinjs-lib"),g=require("./bitcoin-Dpcfff7b.cjs"),R=require("./sha2-DsrLC4NM.cjs");require("@babylonlabs-io/babylon-tbv-rust-wasm");const u=require("./verifyScriptPathSchnorrSignature-fhjfNoHK.cjs"),y=require("./signing-Bnsro0hE.cjs");function E(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const f=E(B),S=106,k=32,p=34;function O(e,t,r){const n=g.stripHexPrefix(e),s=f.Transaction.fromHex(n);if(s.outs.length<=t)throw new Error(`Pre-PegIn auth-anchor OP_RETURN missing: tx has ${s.outs.length} outputs, expected at least ${t+1} (vault outputs + OP_RETURN)`);const c=s.outs[t],i=c.script;if(i.length!==p||i[0]!==S||i[1]!==k)throw new Error(`Pre-PegIn auth-anchor OP_RETURN at vout ${t} has unexpected script encoding (got ${i.length}-byte script with prefix 0x${i.slice(0,Math.min(2,i.length)).toString("hex")}; expected ${p}-byte OP_RETURN + PUSH32 layout)`);const l=i.slice(2).toString("hex").toLowerCase();if(l!==r.toLowerCase())throw new Error(`Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${t}: tx pushes ${l}, expected ${r}`);if(c.value!==0)throw new Error(`Pre-PegIn auth-anchor OP_RETURN at vout ${t} has non-zero value ${c.value}; OP_RETURN outputs must be 0-value`)}function $(e){let t;try{t=f.Transaction.fromHex(g.stripHexPrefix(e))}catch{return}const r=[];for(let n=0;n<t.outs.length;n++){const s=t.outs[n],c=s.script;c.length===p&&c[0]===S&&c[1]===k&&s.value===0&&r.push({vout:n,hash:c.slice(2).toString("hex").toLowerCase()})}return r.length===1?r[0]:void 0}const x=66;function v(e){if(!e.startsWith("0x")&&!e.startsWith("0X"))throw new Error("Expected 0x-prefixed hex string");const t=e.slice(2);if(t.length%2!==0)throw new Error(`Hex string has odd length: ${t.length}`);if(!/^[0-9a-fA-F]*$/.test(t))throw new Error("Hex string contains non-hex characters");const r=new Uint8Array(t.length/2);for(let n=0;n<r.length;n++)r[n]=parseInt(t.slice(n*2,n*2+2),16);return r}function _(e){return`0x${Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}`}function h(e,t){if(e.length!==x)throw new Error(`${t} must be exactly 32 bytes (${x} hex chars with 0x prefix), got ${e.length}`)}function w(e){h(e,"Secret");const t=v(e),r=R.sha256(t);return _(r)}function K(e,t){return h(e,"Secret"),h(t,"Hashlock"),v(t),w(e).toLowerCase()===t.toLowerCase()}function T(e){return typeof e.approveDepositTerms=="function"}function C(e){return T(e)?{approveDepositTerms:t=>e.approveDepositTerms(t)}:{}}const d=0;class U{constructor(t){b(this,"config");this.config=t}async signPayoutTransaction(t){const r=await this.config.btcWallet.getPublicKeyHex(),{depositorPubkey:n}=g.validateWalletPubkey(r,t.depositorBtcPubkey),s=await u.buildPayoutPsbt({vaultCoreVersion:t.vaultCoreVersion,payoutTxHex:t.payoutTxHex,peginTxHex:t.peginTxHex,assertTxHex:t.assertTxHex,depositorBtcPubkey:n,vaultProviderBtcPubkey:t.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:t.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:t.universalChallengerBtcPubkeys,timelockPegin:t.timelockPegin,network:this.config.network,claimerBtcPubkey:t.claimerBtcPubkey,registeredPayoutScriptPubKey:t.registeredPayoutScriptPubKey,commissionBps:t.commissionBps,protocolFeeRate:t.protocolFeeRate,councilSize:t.councilSize,vkClaimerPayoutScriptPubKeys:t.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:t.vpCommissionScriptPubKey}),c=await this.config.btcWallet.signPsbt(s.psbtHex,y.createTaprootScriptPathSignOptions(r,1));u.assertPsbtUnsignedTxMatches({requestedPsbtHex:s.psbtHex,returnedPsbtHex:c});const i=u.extractPayoutSignature(c,n);return u.assertScriptPathSchnorrSignature({requestedPsbtHex:s.psbtHex,signatureHex:i,signerXOnlyPubkeyHex:n,inputIndex:d}),{signature:i,depositorBtcPubkey:n}}getNetwork(){return this.config.network}supportsBatchSigning(){return typeof this.config.btcWallet.signPsbts=="function"}async signPayoutTransactionsBatch(t){if(!this.supportsBatchSigning())throw new Error("Wallet does not support batch signing (signPsbts method not available)");const r=await this.config.btcWallet.getPublicKeyHex(),n=[],s=[],c=[];for(const o of t){const{depositorPubkey:a}=g.validateWalletPubkey(r,o.depositorBtcPubkey);c.push(a);const P=await u.buildPayoutPsbt({vaultCoreVersion:o.vaultCoreVersion,payoutTxHex:o.payoutTxHex,peginTxHex:o.peginTxHex,assertTxHex:o.assertTxHex,depositorBtcPubkey:a,vaultProviderBtcPubkey:o.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:o.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:o.universalChallengerBtcPubkeys,timelockPegin:o.timelockPegin,network:this.config.network,claimerBtcPubkey:o.claimerBtcPubkey,registeredPayoutScriptPubKey:o.registeredPayoutScriptPubKey,commissionBps:o.commissionBps,protocolFeeRate:o.protocolFeeRate,councilSize:o.councilSize,vkClaimerPayoutScriptPubKeys:o.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:o.vpCommissionScriptPubKey});n.push(P.psbtHex),s.push(y.createTaprootScriptPathSignOptions(r,1))}const i=await this.config.btcWallet.signPsbts(n,s);if(i.length!==t.length)throw new Error(`Expected ${t.length} signed PSBTs but received ${i.length}`);const l=[];for(let o=0;o<t.length;o++){const a=c[o];u.assertPsbtUnsignedTxMatches({requestedPsbtHex:n[o],returnedPsbtHex:i[o]});const P=u.extractPayoutSignature(i[o],a);u.assertScriptPathSchnorrSignature({requestedPsbtHex:n[o],signatureHex:P,signerXOnlyPubkeyHex:a,inputIndex:d}),l.push({payoutSignature:P,depositorBtcPubkey:a})}return l}}async function A(e,t,r){if(t.length===1)return[await e.signPsbt(t[0],r==null?void 0:r[0])];if(typeof e.signPsbts=="function"){const s=await e.signPsbts(t,r);if(s.length!==t.length)throw new Error(`Expected ${t.length} signed PSBTs but received ${s.length}`);return s}const n=[];for(let s=0;s<t.length;s++)n.push(await e.signPsbt(t[s],r==null?void 0:r[s]));return n}exports.PayoutManager=U;exports.assertAuthAnchorOpReturn=O;exports.computeHashlock=w;exports.findAuthAnchorOpReturn=$;exports.forwardDepositApproval=C;exports.signPsbtsWithFallback=A;exports.supportsDepositApproval=T;exports.validateSecretAgainstHashlock=K;
2
- //# sourceMappingURL=signPsbtsWithFallback-r3bC-CfM.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"signPsbtsWithFallback-r3bC-CfM.cjs","sources":["../src/tbv/core/managers/pegin/assertAuthAnchorOpReturn.ts","../src/tbv/core/services/htlc/index.ts","../src/tbv/core/deposit-terms/depositTerms.ts","../src/tbv/core/managers/PayoutManager.ts","../src/tbv/core/managers/pegin/signPsbtsWithFallback.ts"],"sourcesContent":["/**\n * Structural verifier for the auth-anchor OP_RETURN in a funded\n * Pre-PegIn transaction.\n *\n * @module managers/pegin/assertAuthAnchorOpReturn\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\n\n/** OP_RETURN opcode. */\nconst OP_RETURN = 0x6a;\n/** Push-32-bytes opcode (raw push, not OP_PUSHDATA1). */\nconst OP_PUSH32 = 0x20;\n/** Encoded length of a standard OP_RETURN script with a 32-byte payload. */\nconst OP_RETURN_PUSH32_SCRIPT_LEN = 1 + 1 + 32;\n\n/**\n * Verify the broadcast Pre-PegIn carries the expected OP_RETURN\n * commitment to the auth anchor.\n *\n * The OP_RETURN sits at `vout = vaultCount` (right after the per-vault\n * HTLC outputs and before the depositor-claim/change outputs) and\n * pushes the 32-byte `SHA256(authAnchor)`. The script encoding is\n * exactly `OP_RETURN || PUSH32 || <32 bytes>` (34 bytes). A\n * non-conformant WASM build that omitted the OP_RETURN, swapped its\n * position, or changed its push payload would let the depositor\n * obtain a valid bearer token for a Pre-PegIn whose on-chain\n * commitment doesn't actually bind the anchor — degrading the auth\n * from on-chain-bound to a shared secret. Fail closed.\n *\n * @throws If the OP_RETURN is missing, mis-located, mis-encoded, or\n * pushes a payload other than `expectedAuthAnchorHashHex`.\n */\nexport function assertAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n vaultCount: number,\n expectedAuthAnchorHashHex: string,\n): void {\n const cleanHex = stripHexPrefix(fundedPrePeginTxHex);\n const tx = bitcoin.Transaction.fromHex(cleanHex);\n\n if (tx.outs.length <= vaultCount) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN missing: tx has ${tx.outs.length} ` +\n `outputs, expected at least ${vaultCount + 1} (vault outputs + OP_RETURN)`,\n );\n }\n\n const opReturnOutput = tx.outs[vaultCount];\n const script = opReturnOutput.script;\n if (\n script.length !== OP_RETURN_PUSH32_SCRIPT_LEN ||\n script[0] !== OP_RETURN ||\n script[1] !== OP_PUSH32\n ) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has unexpected ` +\n `script encoding (got ${script.length}-byte script with prefix ` +\n `0x${script.slice(0, Math.min(2, script.length)).toString(\"hex\")}; ` +\n `expected ${OP_RETURN_PUSH32_SCRIPT_LEN}-byte OP_RETURN + PUSH32 layout)`,\n );\n }\n\n const pushedHex = script.slice(2).toString(\"hex\").toLowerCase();\n if (pushedHex !== expectedAuthAnchorHashHex.toLowerCase()) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${vaultCount}: ` +\n `tx pushes ${pushedHex}, expected ${expectedAuthAnchorHashHex}`,\n );\n }\n\n if (opReturnOutput.value !== 0) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has non-zero ` +\n `value ${opReturnOutput.value}; OP_RETURN outputs must be 0-value`,\n );\n }\n}\n\n/**\n * Scan a funded Pre-PegIn transaction for its auth-anchor commitment\n * (an `OP_RETURN || PUSH32 || <32 bytes>` output with value 0).\n *\n * Returns `{ vout, hash }` when exactly one such output is found.\n * Returns `undefined` when:\n * - the hex is unparseable,\n * - no matching output exists (legacy non-auth-anchored Pre-PegIn),\n * - more than one matching output exists (ambiguous / malformed).\n *\n * Used by the refund orchestrator to (a) locate the on-chain anchor\n * regardless of how many HTLCs preceded it and (b) detect multi-vault\n * funded transactions structurally: the single-vault refund path\n * reconstructs only one hashlock and expects the anchor at vout 1, so\n * any other vout signals a layout this call cannot safely refund.\n */\nexport function findAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n): { vout: number; hash: string } | undefined {\n let tx: bitcoin.Transaction;\n try {\n tx = bitcoin.Transaction.fromHex(stripHexPrefix(fundedPrePeginTxHex));\n } catch {\n return undefined;\n }\n\n const hits: { vout: number; hash: string }[] = [];\n for (let i = 0; i < tx.outs.length; i++) {\n const output = tx.outs[i];\n const script = output.script;\n if (\n script.length === OP_RETURN_PUSH32_SCRIPT_LEN &&\n script[0] === OP_RETURN &&\n script[1] === OP_PUSH32 &&\n output.value === 0\n ) {\n hits.push({\n vout: i,\n hash: script.slice(2).toString(\"hex\").toLowerCase(),\n });\n }\n }\n\n return hits.length === 1 ? hits[0] : undefined;\n}\n","/**\n * HTLC Secret / Hashlock Utilities\n *\n * Pure functions for computing and validating SHA-256 hashlocks used in the\n * vault deposit protocol's HTLC (Hash Time Lock Contract).\n *\n * The SDK does NOT generate secrets — that is the caller's responsibility.\n * Today callers use `crypto.getRandomValues(32)`; when the `deriveContextHash`\n * wallet API ships, callers will use `wallet.deriveContextHash(\"babylon-btc-vault\", ctx)`.\n * These utilities work identically regardless of how the secret was produced.\n *\n * On-chain contract validation (BTCVaultRegistry.activateVaultWithSecret):\n * if (sha256(abi.encodePacked(s)) != hashlock) revert InvalidSecret();\n *\n * @module htlc\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport type { Hex } from \"viem\";\n\n/** Expected hex length for a 0x-prefixed bytes32 value. */\nconst HEX_BYTES32_LENGTH = 66; // \"0x\" + 64 hex chars\n\n/**\n * Decode a 0x-prefixed hex string to bytes, with strict validation.\n * @throws if the input is not a valid 0x-prefixed hex string\n */\nfunction hexToBytes(hex: Hex): Uint8Array {\n if (!hex.startsWith(\"0x\") && !hex.startsWith(\"0X\")) {\n throw new Error(\"Expected 0x-prefixed hex string\");\n }\n const clean = hex.slice(2);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has odd length: ${clean.length}`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error(\"Hex string contains non-hex characters\");\n }\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Encode a Uint8Array as a 0x-prefixed lowercase hex string.\n */\nfunction bytesToHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\n/**\n * Validate that a value is a 0x-prefixed bytes32 (exactly 32 bytes).\n * @throws if the value is not exactly 32 bytes\n */\nfunction assertBytes32(value: Hex, label: string): void {\n if (value.length !== HEX_BYTES32_LENGTH) {\n throw new Error(\n `${label} must be exactly 32 bytes (${HEX_BYTES32_LENGTH} hex chars with 0x prefix), got ${value.length}`,\n );\n }\n}\n\n/**\n * Compute the SHA-256 hashlock from a secret preimage.\n *\n * Matches the on-chain validation: `sha256(abi.encodePacked(s))` where `s` is a `bytes32`.\n * `abi.encodePacked(bytes32)` is just the raw 32 bytes — no ABI padding.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @returns 0x-prefixed bytes32 SHA-256 hash\n * @throws if secret is not exactly 32 bytes\n */\nexport function computeHashlock(secret: Hex): Hex {\n assertBytes32(secret, \"Secret\");\n const secretBytes = hexToBytes(secret);\n const hash = sha256(secretBytes);\n return bytesToHex(hash);\n}\n\n/**\n * Validate that a secret's SHA-256 hash matches the expected hashlock.\n *\n * Use this for client-side pre-validation before sending the activation\n * transaction to avoid wasting gas on a contract revert.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @param hashlock - 0x-prefixed bytes32 expected hashlock from the vault\n * @returns true if SHA-256(secret) matches the hashlock\n * @throws if secret or hashlock is not exactly 32 bytes\n */\nexport function validateSecretAgainstHashlock(\n secret: Hex,\n hashlock: Hex,\n): boolean {\n assertBytes32(secret, \"Secret\");\n assertBytes32(hashlock, \"Hashlock\");\n // Validate hashlock is valid hex (secret is validated inside computeHashlock)\n hexToBytes(hashlock);\n\n const computed = computeHashlock(secret);\n return computed.toLowerCase() === hashlock.toLowerCase();\n}\n","import type { BitcoinWallet } from \"../../../shared/wallets/interfaces\";\n\n// Field docs use /** */ so they survive into the emitted .d.ts — the published\n// package is the only contract the external provider author (#2109) sees.\n\nexport interface DepositTermsVaultGroup {\n /** 0-based; equals the group's position (groups are ascending by vout). */\n readonly htlcVout: number;\n /** x-only hex (64 chars), as validated on-chain upstream. */\n readonly vaultProviderPk: string;\n /** sats */\n readonly vaultAmount: bigint;\n /** sats; floor(vaultAmount * commissionBps / 10_000). */\n readonly commissionFee: bigint;\n /** sats; the same value for every vault. */\n readonly depositorClaimValue: bigint;\n /** sats; the minimum PegIn fee for this graph version. */\n readonly peginMaxFee: bigint;\n}\n\nexport interface DepositTerms {\n /**\n * sat/vB; the tx-graph fee rate (protocolFeeRate), NOT the mempool funding\n * rate. An approving wallet bounds each payout's fee at baseFeeRate x a\n * conservative vsize estimate (v22 §4.9.7.1) — pass the exact graph rate,\n * not an inflated ceiling.\n */\n baseFeeRate: bigint;\n /** Vault-UTXO CSV timelock (blocks). */\n peginCsvTimelock: number;\n /**\n * Payout timelock on the Assert transaction's output 0; comes from the same\n * protocol param (timelockAssert) as peginCsvTimelock.\n */\n payoutTimelock: number;\n /** HTLC refund CSV timelock (blocks). */\n htlcRefundTimelock: number;\n /**\n * 64-char hex in display order. A device-wire encoder must byte-reverse it to\n * the little-endian form the device recomputes and compares against.\n */\n prepeginTxid: string;\n /** sats; the funded Pre-PegIn fee (an approving wallet caps the signed fee at this). */\n prepeginMaxFee: bigint;\n /**\n * x-only hex. Sorted ascending by the upstream on-chain validation\n * (validateOnChainParticipantKeys); the builder passes them through\n * unasserted — the device rejects unsorted lists at intent load.\n */\n keeperPks: readonly string[];\n /**\n * x-only hex, sorted ascending upstream independently of keeperPks (same\n * pass-through contract). Universal challengers only — the full graph\n * challenger set is keeperPks ∪ challengerPks (vault keepers are the local\n * challengers).\n */\n challengerPks: readonly string[];\n /** Per-vault groups, ordered by ascending htlcVout. */\n vaults: readonly DepositTermsVaultGroup[];\n}\n\n/**\n * Implemented only by depositor-approval wallets (e.g. a Ledger vault provider).\n * Either a class field or a prototype method works — the deposit flow spreads\n * the wallet object but forwards this method explicitly at every wrapper site.\n *\n * Seam invariant: never call deriveContextHash between approveDepositTerms and\n * the last terms-bound signature of a connection — deriving while an intent is\n * loaded nullifies it on-device. Design: the SDK owns approval (mirrors its\n * deriveContextHash/signPsbts orchestration); provider-internal and app-driven\n * placements were rejected.\n */\nexport interface DepositTermsApprover {\n approveDepositTerms(terms: DepositTerms): Promise<void>;\n}\n\n/** True when the wallet implements {@link DepositTermsApprover.approveDepositTerms}. */\nexport function supportsDepositApproval(\n wallet: BitcoinWallet,\n): wallet is BitcoinWallet & DepositTermsApprover {\n return typeof (wallet as Partial<DepositTermsApprover>).approveDepositTerms === \"function\";\n}\n\n/**\n * Spreadable forward of `approveDepositTerms` for wallet-wrapper objects.\n * Object spread drops prototype methods, so every `{...wallet}` wrapper site\n * must re-attach the capability explicitly: `...forwardDepositApproval(wallet)`.\n */\nexport function forwardDepositApproval(\n wallet: BitcoinWallet,\n): Partial<DepositTermsApprover> {\n return supportsDepositApproval(wallet)\n ? { approveDepositTerms: (terms) => wallet.approveDepositTerms(terms) }\n : {};\n}\n\nexport interface BuildDepositTermsInputs {\n protocolFeeRate: bigint;\n timelockPegin: number;\n timelockRefund: number;\n prepeginTxid: string;\n prepeginMaxFee: bigint;\n vaultProviderPk: string;\n keeperPks: readonly string[];\n challengerPks: readonly string[];\n commissionBps: number;\n vaultAmounts: readonly bigint[];\n depositorClaimValue: bigint;\n peginMaxFee: bigint;\n}\n","/**\n * Payout Manager\n *\n * High-level manager that orchestrates the payout signing flow by coordinating\n * SDK primitives ({@link buildPayoutPsbt}, {@link extractPayoutSignature})\n * with a user-provided Bitcoin wallet.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @see {@link PeginManager} - For Steps 1–4 of the peg-in flow\n * @see {@link buildPayoutPsbt} - Lower-level primitive for custom implementations\n * @see {@link extractPayoutSignature} - Extract signatures from signed PSBTs\n *\n * @module managers/PayoutManager\n */\n\nimport type { BitcoinWallet, SignPsbtOptions } from \"../../../shared/wallets\";\nimport {\n assertPsbtUnsignedTxMatches,\n assertScriptPathSchnorrSignature,\n buildPayoutPsbt,\n extractPayoutSignature,\n validateWalletPubkey,\n type Network,\n} from \"../primitives\";\nimport { createTaprootScriptPathSignOptions } from \"../utils/signing\";\n\n/** Payout PSBTs are signed by the depositor on input 0 (Taproot script-path). */\nconst PAYOUT_SIGNED_INPUT_INDEX = 0;\n\n/**\n * Configuration for the PayoutManager.\n */\nexport interface PayoutManagerConfig {\n /**\n * Bitcoin network to use for transactions.\n */\n network: Network;\n\n /**\n * Bitcoin wallet for signing payout transactions.\n */\n btcWallet: BitcoinWallet;\n}\n\n/**\n * Base parameters shared by both payout transaction types.\n */\ninterface SignPayoutBaseParams {\n /**\n * Vault core (tx-graph) version the vault was registered under — the\n * vault's stamped on-chain `vaultCoreVersion`. Forwarded to\n * {@link buildPayoutPsbt} to derive the matching graph's payout scripts.\n */\n vaultCoreVersion: number;\n\n /**\n * Peg-in transaction hex.\n * The original transaction that created the vault output being spent.\n */\n peginTxHex: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex).\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex).\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex).\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex). This MUST be the\n * key registered on-chain for the vault — typically read from\n * `BTCVaultRegistry.getBtcVaultBasicInfo(...).depositorBtcPubKey`.\n *\n * Required: omitting it would degrade `validateWalletPubkey` to a\n * self-comparison, allowing the wrong wallet to produce a signature\n * over a script tree that doesn't match the on-chain UTXO.\n */\n depositorBtcPubkey: string;\n\n /**\n * The on-chain registered depositor payout scriptPubKey (hex, with or without 0x prefix).\n * Used to validate that the VP-provided payout transaction actually pays to the\n * correct depositor payout address before signing.\n */\n registeredPayoutScriptPubKey: string;\n\n /**\n * The claimer's x-only BTC public key for this payout (64-char hex, no prefix).\n * Forwarded to {@link buildPayoutPsbt} for per-role output validation.\n */\n claimerBtcPubkey: string;\n\n /**\n * VP commission in basis points (`1..=9999`). Forwarded to {@link buildPayoutPsbt}.\n */\n commissionBps: number;\n\n /**\n * Version-locked tx-graph fee rate (sat/vB) the graph was built with.\n * Forwarded to {@link buildPayoutPsbt} for the fee band.\n */\n protocolFeeRate: bigint;\n\n /** Security council member count; forwarded to the fee floor (see PayoutParams). */\n councilSize: number;\n\n /**\n * RFC-006 resolved payout destinations, keyed by lowercased x-only operation\n * pubkey. Forwarded verbatim to {@link buildPayoutPsbt}; every VK claimer\n * must be present.\n */\n vkClaimerPayoutScriptPubKeys: Readonly<Record<string, string>>;\n /** RFC-006 VP commission destination. Forwarded to {@link buildPayoutPsbt}. */\n vpCommissionScriptPubKey: string;\n}\n\n/**\n * Parameters for signing a Payout transaction.\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface SignPayoutParams extends SignPayoutBaseParams {\n /**\n * Payout transaction hex (unsigned).\n * This is the transaction from the vault provider that needs depositor signature.\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex.\n * Payout input 1 references Assert output 0.\n */\n assertTxHex: string;\n}\n\n/**\n * Result of signing a payout transaction.\n */\nexport interface PayoutSignatureResult {\n /**\n * 64-byte Schnorr signature (128 hex characters).\n */\n signature: string;\n\n /**\n * Depositor's BTC public key used for signing.\n */\n depositorBtcPubkey: string;\n}\n\n/**\n * High-level manager for payout transaction signing.\n *\n * @remarks\n * After registering your peg-in on Ethereum (Step 3), the vault provider prepares\n * claim/payout transaction pairs. You must sign each payout transaction using this\n * manager and submit the signatures to the vault provider's RPC API.\n *\n * **What happens internally:**\n * 1. Validates your wallet's public key matches the vault's depositor\n * 2. Builds an unsigned PSBT with taproot script path spend info\n * 3. Signs input 0 (the vault UTXO) with your wallet\n * 4. Extracts the 64-byte Schnorr signature\n *\n * **Note:** The payout transaction has 2 inputs. PayoutManager only signs input 0\n * (from the peg-in tx). Input 1 (from the assert tx) is signed by the vault provider.\n *\n * @see {@link PeginManager} - For the complete peg-in flow context\n * @see {@link buildPayoutPsbt} - Lower-level primitive used internally\n * @see {@link extractPayoutSignature} - Signature extraction primitive\n */\nexport class PayoutManager {\n private readonly config: PayoutManagerConfig;\n\n /**\n * Creates a new PayoutManager instance.\n *\n * @param config - Manager configuration including wallet\n */\n constructor(config: PayoutManagerConfig) {\n this.config = config;\n }\n\n /**\n * Signs a Payout transaction and extracts the Schnorr signature.\n *\n * Flow:\n * 1. Vault provider submits Claim transaction\n * 2. Claimer submits Assert transaction to prove validity\n * 3. Payout can be executed (references Assert tx)\n *\n * This method orchestrates the following steps:\n * 1. Get wallet's public key and convert to x-only format\n * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)\n * 3. Build unsigned PSBT using primitives\n * 4. Sign PSBT via btcWallet.signPsbt()\n * 5. Extract 64-byte Schnorr signature using primitives\n *\n * The returned signature can be submitted to the vault provider API.\n *\n * @param params - Payout signing parameters\n * @returns Signature result with 64-byte Schnorr signature and depositor pubkey\n * @throws Error if wallet pubkey doesn't match depositor pubkey\n * @throws Error if wallet operations fail or signature extraction fails\n */\n async signPayoutTransaction(\n params: SignPayoutParams,\n ): Promise<PayoutSignatureResult> {\n // Validate wallet pubkey matches depositor and get both formats\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n params.depositorBtcPubkey,\n );\n\n // Build unsigned PSBT for Payout (uses Assert tx). Per-role output\n // validation happens inside buildPayoutPsbt against the resolved input\n // values.\n const payoutPsbt = await buildPayoutPsbt({\n vaultCoreVersion: params.vaultCoreVersion,\n payoutTxHex: params.payoutTxHex,\n peginTxHex: params.peginTxHex,\n assertTxHex: params.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: params.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: params.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: this.config.network,\n claimerBtcPubkey: params.claimerBtcPubkey,\n registeredPayoutScriptPubKey: params.registeredPayoutScriptPubKey,\n commissionBps: params.commissionBps,\n protocolFeeRate: params.protocolFeeRate,\n councilSize: params.councilSize,\n vkClaimerPayoutScriptPubKeys: params.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: params.vpCommissionScriptPubKey,\n });\n\n // Sign PSBT via wallet (Taproot script-path spend, input 0 only)\n const signedPsbtHex = await this.config.btcWallet.signPsbt(\n payoutPsbt.psbtHex,\n createTaprootScriptPathSignOptions(walletPubkeyRaw, 1),\n );\n\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: payoutPsbt.psbtHex,\n returnedPsbtHex: signedPsbtHex,\n });\n\n // Extract Schnorr signature\n const signature = extractPayoutSignature(signedPsbtHex, depositorPubkey);\n // Critical Path #7: verify the signature against a sighash recomputed from\n // the PSBT we built, not the wallet-returned one.\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: payoutPsbt.psbtHex,\n signatureHex: signature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: PAYOUT_SIGNED_INPUT_INDEX,\n });\n\n return {\n signature,\n depositorBtcPubkey: depositorPubkey,\n };\n }\n\n /**\n * Gets the configured Bitcoin network.\n *\n * @returns The Bitcoin network (mainnet, testnet, signet, regtest)\n */\n getNetwork(): Network {\n return this.config.network;\n }\n\n /**\n * Checks if the wallet supports batch signing (signPsbts).\n *\n * @returns true if batch signing is supported\n */\n supportsBatchSigning(): boolean {\n return typeof this.config.btcWallet.signPsbts === \"function\";\n }\n\n /**\n * Batch signs multiple payout transactions (1 per claimer).\n * This allows signing all transactions with a single wallet interaction.\n *\n * @param transactions - Array of payout params to sign\n * @returns Array of signature results matching input order\n * @throws Error if wallet doesn't support batch signing\n * @throws Error if any signing operation fails\n */\n async signPayoutTransactionsBatch(transactions: SignPayoutParams[]): Promise<\n Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }>\n > {\n if (!this.supportsBatchSigning()) {\n throw new Error(\n \"Wallet does not support batch signing (signPsbts method not available)\",\n );\n }\n\n // Get wallet pubkey once\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n\n // Build all PSBTs (1 per claimer)\n const psbtsToSign: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n const depositorPubkeys: string[] = [];\n\n for (const tx of transactions) {\n // Validate wallet pubkey matches depositor\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n tx.depositorBtcPubkey,\n );\n depositorPubkeys.push(depositorPubkey);\n\n // Build Payout PSBT (output validation runs inside buildPayoutPsbt\n // against resolved input values).\n const payoutPsbt = await buildPayoutPsbt({\n vaultCoreVersion: tx.vaultCoreVersion,\n payoutTxHex: tx.payoutTxHex,\n peginTxHex: tx.peginTxHex,\n assertTxHex: tx.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: tx.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: tx.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: tx.universalChallengerBtcPubkeys,\n timelockPegin: tx.timelockPegin,\n network: this.config.network,\n claimerBtcPubkey: tx.claimerBtcPubkey,\n registeredPayoutScriptPubKey: tx.registeredPayoutScriptPubKey,\n commissionBps: tx.commissionBps,\n protocolFeeRate: tx.protocolFeeRate,\n councilSize: tx.councilSize,\n vkClaimerPayoutScriptPubKeys: tx.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: tx.vpCommissionScriptPubKey,\n });\n psbtsToSign.push(payoutPsbt.psbtHex);\n signOptions.push(createTaprootScriptPathSignOptions(walletPubkeyRaw, 1));\n }\n\n // Batch sign all PSBTs with single wallet interaction\n const signedPsbts = await this.config.btcWallet.signPsbts!(\n psbtsToSign,\n signOptions,\n );\n\n // Validate that wallet returned the expected number of signed PSBTs\n if (signedPsbts.length !== transactions.length) {\n throw new Error(\n `Expected ${transactions.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n\n // Extract signatures from signed PSBTs\n const results: Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }> = [];\n\n for (let i = 0; i < transactions.length; i++) {\n const depositorPubkey = depositorPubkeys[i];\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: psbtsToSign[i],\n returnedPsbtHex: signedPsbts[i],\n });\n const payoutSignature = extractPayoutSignature(\n signedPsbts[i],\n depositorPubkey,\n );\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: psbtsToSign[i],\n signatureHex: payoutSignature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: PAYOUT_SIGNED_INPUT_INDEX,\n });\n\n results.push({\n payoutSignature,\n depositorBtcPubkey: depositorPubkey,\n });\n }\n\n return results;\n }\n}\n","/**\n * Wallet-signing helper that routes a lone PSBT to `signPsbt`, prefers native\n * `signPsbts` for real batches, and falls back to sequential `signPsbt` for\n * wallets that don't implement batch signing.\n *\n * @module managers/pegin/signPsbtsWithFallback\n */\n\nimport type {\n BitcoinWallet,\n SignPsbtOptions,\n} from \"../../../../shared/wallets\";\n\n/**\n * Sign one or more PSBTs against a wallet.\n *\n * A single PSBT is always signed via `signPsbt`, never the batch endpoint: it's\n * one wallet interaction either way, and `signPsbt` is the universally-required\n * wallet method (batch `signPsbts` is optional), so single-sign is the portable\n * choice — some integrations (notably MPC / institutional wallets) prefer it.\n * For a real batch (>1), wallets exposing native `signPsbts` (e.g. UniSat) sign\n * in one interaction; others loop `signPsbt`.\n *\n * @throws If native `signPsbts` returns a different number of signed PSBTs\n * than were submitted.\n */\nexport async function signPsbtsWithFallback(\n wallet: BitcoinWallet,\n psbtsHexes: string[],\n options?: SignPsbtOptions[],\n): Promise<string[]> {\n if (psbtsHexes.length === 1) {\n return [await wallet.signPsbt(psbtsHexes[0], options?.[0])];\n }\n\n if (typeof wallet.signPsbts === \"function\") {\n const signedPsbts = await wallet.signPsbts(psbtsHexes, options);\n if (signedPsbts.length !== psbtsHexes.length) {\n throw new Error(\n `Expected ${psbtsHexes.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n return signedPsbts;\n }\n\n const signedPsbts: string[] = [];\n for (let i = 0; i < psbtsHexes.length; i++) {\n signedPsbts.push(await wallet.signPsbt(psbtsHexes[i], options?.[i]));\n }\n return signedPsbts;\n}\n"],"names":["OP_RETURN","OP_PUSH32","OP_RETURN_PUSH32_SCRIPT_LEN","assertAuthAnchorOpReturn","fundedPrePeginTxHex","vaultCount","expectedAuthAnchorHashHex","cleanHex","stripHexPrefix","tx","bitcoin","opReturnOutput","script","pushedHex","findAuthAnchorOpReturn","hits","i","output","HEX_BYTES32_LENGTH","hexToBytes","hex","clean","bytes","bytesToHex","b","assertBytes32","value","label","computeHashlock","secret","secretBytes","hash","sha256","validateSecretAgainstHashlock","hashlock","supportsDepositApproval","wallet","forwardDepositApproval","terms","PAYOUT_SIGNED_INPUT_INDEX","PayoutManager","config","__publicField","params","walletPubkeyRaw","depositorPubkey","validateWalletPubkey","payoutPsbt","buildPayoutPsbt","signedPsbtHex","createTaprootScriptPathSignOptions","assertPsbtUnsignedTxMatches","signature","extractPayoutSignature","assertScriptPathSchnorrSignature","transactions","psbtsToSign","signOptions","depositorPubkeys","signedPsbts","results","payoutSignature","signPsbtsWithFallback","psbtsHexes","options"],"mappings":"ysBAYMA,EAAY,IAEZC,EAAY,GAEZC,EAA8B,GAmB7B,SAASC,EACdC,EACAC,EACAC,EACM,CACN,MAAMC,EAAWC,EAAAA,eAAeJ,CAAmB,EAC7CK,EAAKC,EAAQ,YAAY,QAAQH,CAAQ,EAE/C,GAAIE,EAAG,KAAK,QAAUJ,EACpB,MAAM,IAAI,MACR,mDAAmDI,EAAG,KAAK,MAAM,+BACjCJ,EAAa,CAAC,8BAAA,EAIlD,MAAMM,EAAiBF,EAAG,KAAKJ,CAAU,EACnCO,EAASD,EAAe,OAC9B,GACEC,EAAO,SAAWV,GAClBU,EAAO,CAAC,IAAMZ,GACdY,EAAO,CAAC,IAAMX,EAEd,MAAM,IAAI,MACR,2CAA2CI,CAAU,wCAC3BO,EAAO,MAAM,8BAChCA,EAAO,MAAM,EAAG,KAAK,IAAI,EAAGA,EAAO,MAAM,CAAC,EAAE,SAAS,KAAK,CAAC,cACpDV,CAA2B,kCAAA,EAI7C,MAAMW,EAAYD,EAAO,MAAM,CAAC,EAAE,SAAS,KAAK,EAAE,YAAA,EAClD,GAAIC,IAAcP,EAA0B,cAC1C,MAAM,IAAI,MACR,4DAA4DD,CAAU,eACvDQ,CAAS,cAAcP,CAAyB,EAAA,EAInE,GAAIK,EAAe,QAAU,EAC3B,MAAM,IAAI,MACR,2CAA2CN,CAAU,uBAC1CM,EAAe,KAAK,qCAAA,CAGrC,CAkBO,SAASG,EACdV,EAC4C,CAC5C,IAAIK,EACJ,GAAI,CACFA,EAAKC,EAAQ,YAAY,QAAQF,EAAAA,eAAeJ,CAAmB,CAAC,CACtE,MAAQ,CACN,MACF,CAEA,MAAMW,EAAyC,CAAA,EAC/C,QAASC,EAAI,EAAGA,EAAIP,EA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0,0 @@
1
- "use strict";const w=require("@babylonlabs-io/babylon-tbv-rust-wasm"),p=require("buffer"),x=require("bitcoinjs-lib"),C=require("./fundPeginTransaction-BLD8FRL9.cjs"),c=require("./bitcoin-Dpcfff7b.cjs"),v=require("./constants-BqU1Uz15.cjs"),X=require("@bitcoin-js/tiny-secp256k1-asmjs");function z(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Y=z(X);async function D(e,t){const n=t.pegInAmounts.length;if(e.htlcValues.length!==n)throw new Error(`WASM Pre-PegIn returned ${e.htlcValues.length} HTLC value(s), expected ${n} (one per requested deposit).`);if(e.peginAmounts.length!==n||e.htlcScriptPubKeys.length!==n||e.htlcAddresses.length!==n)throw new Error(`WASM Pre-PegIn returned mismatched array lengths (htlcValues=${e.htlcValues.length}, peginAmounts=${e.peginAmounts.length}, htlcScriptPubKeys=${e.htlcScriptPubKeys.length}, htlcAddresses=${e.htlcAddresses.length}); expected ${n} each.`);if(e.depositorClaimValue<=0n)throw new Error(`WASM Pre-PegIn returned non-positive depositorClaimValue ${e.depositorClaimValue}; expected > 0.`);const r=await w.computeMinClaimValue(t.vaultCoreVersion,t.numLocalChallengers,t.universalChallengerPubkeys.length,t.councilQuorum,t.councilSize,t.feeRate);if(e.depositorClaimValue!==r)throw new Error(`WASM Pre-PegIn depositorClaimValue ${e.depositorClaimValue} does not match the independently computed minimum claim value ${r} (vaultCoreVersion=${t.vaultCoreVersion}, numLocalChallengers=${t.numLocalChallengers}, numUniversalChallengers=${t.universalChallengerPubkeys.length}, councilQuorum=${t.councilQuorum}, councilSize=${t.councilSize}, feeRate=${t.feeRate}).`);const o=await w.peginP2aAnchorOutput(t.vaultCoreVersion),i=(o==null?void 0:o.value)??0n,s=await w.computeMinPeginFee(t.vaultCoreVersion,t.vaultKeeperPubkeys.length,t.universalChallengerPubkeys.length,t.minPeginFeeRate),u=s+i,P=t.minPeginFeeRate*C.MAX_REASONABLE_PEGIN_VBYTES;for(let a=0;a<n;a++){const h=t.pegInAmounts[a],l=e.peginAmounts[a],g=e.htlcValues[a];if(l!==h)throw new Error(`WASM Pre-PegIn peginAmount[${a}] ${l} does not match the requested amount ${h}; refusing to build a tx whose recorded amount differs from the depositor's request.`);if(l<=0n)throw new Error(`WASM Pre-PegIn peginAmount[${a}] is non-positive (${l}); expected > 0.`);if(g<=0n)throw new Error(`WASM Pre-PegIn htlcValue[${a}] is non-positive (${g}); expected > 0.`);const d=g-l-e.depositorClaimValue;if(d<=0n)throw new Error(`WASM Pre-PegIn htlcValue[${a}] ${g} does not strictly cover peginAmount ${l} + depositorClaimValue ${e.depositorClaimValue} + a PegIn reserve (implied reserve ${d}).`);if(d>P)throw new Error(`WASM Pre-PegIn implied reserve for HTLC[${a}] (${d} sat) exceeds the plausibility cap ${P} sat (minPeginFeeRate=${t.minPeginFeeRate} × ${C.MAX_REASONABLE_PEGIN_VBYTES} vbytes); htlcValue ${g} appears grossly inflated.`);if(d!==u)throw new Error(`WASM Pre-PegIn htlcValue[${a}] ${g} implies a PegIn fee+anchor reserve of ${d} sat, expected exactly ${u} sat (minPeginFee ${s} + p2aAnchor ${i} for vaultCoreVersion ${t.vaultCoreVersion}, vaultKeepers=${t.vaultKeeperPubkeys.length}, universalChallengers=${t.universalChallengerPubkeys.length}, minPeginFeeRate=${t.minPeginFeeRate}).`)}return s}function G(e,t,n){if(e.length<t.length)throw new Error(`Encoded Pre-PegIn tx has ${e.length} output(s), fewer than the ${t.length} HTLC output(s) the cross-check validated.`);for(let r=0;r<t.length;r++){const o=BigInt(e[r].value);if(o!==t[r])throw new Error(`Encoded Pre-PegIn HTLC output[${r}] value ${o} does not match the cross-checked htlcValue ${t[r]}; the funded/signed tx would not pay the validated amount.`);const i=e[r].script.toString("hex").toLowerCase(),s=n[r].toLowerCase();if(i!==s)throw new Error(`Encoded Pre-PegIn HTLC output[${r}] scriptPubKey ${i} does not match the cross-checked htlcScriptPubKey ${s}.`)}}const H=64,Q=/^[0-9a-fA-F]+$/;async function Z(e){const t=T(e.authAnchorHash),n=await w.createPrePeginTransaction({txGraphVersion:e.vaultCoreVersion,depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlocks:[...e.hashlocks],timelockRefund:e.timelockRefund,pegInAmounts:[...e.pegInAmounts],feeRate:e.feeRate,minPeginFeeRate:e.minPeginFeeRate,numLocalChallengers:e.numLocalChallengers,councilQuorum:e.councilQuorum,councilSize:e.councilSize,network:e.network,authAnchorHash:t}),r=await D(n,e),o=C.parseUnfundedWasmTransaction(n.txHex);G(o.outputs,n.htlcValues,n.htlcScriptPubKeys);const i=o.outputs.reduce((u,P)=>u+BigInt(P.value),0n),s=t!==void 0?n.htlcValues.length:null;return{psbtHex:n.txHex,totalOutputValue:i,htlcValues:n.htlcValues,htlcScriptPubKeys:n.htlcScriptPubKeys,htlcAddresses:n.htlcAddresses,peginAmounts:n.peginAmounts,depositorClaimValue:n.depositorClaimValue,authAnchorVout:s,minPeginFee:r}}function T(e){if(e===void 0)return;const t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length!==H||!Q.test(t))throw new Error(`authAnchorHash must be 32-byte hex (${H} chars, no 0x prefix); got length ${t.length}`);return t.toLowerCase()}async function j(e){const t=await w.buildPeginTxFromPrePegin({txGraphVersion:e.prePeginParams.vaultCoreVersion,depositorPubkey:e.prePeginParams.depositorPubkey,vaultProviderPubkey:e.prePeginParams.vaultProviderPubkey,vaultKeeperPubkeys:e.prePeginParams.vaultKeeperPubkeys,universalChallengerPubkeys:e.prePeginParams.universalChallengerPubkeys,hashlocks:[...e.prePeginParams.hashlocks],timelockRefund:e.prePeginParams.timelockRefund,pegInAmounts:[...e.prePeginParams.pegInAmounts],feeRate:e.prePeginParams.feeRate,minPeginFeeRate:e.prePeginParams.minPeginFeeRate,numLocalChallengers:e.prePeginParams.numLocalChallengers,councilQuorum:e.prePeginParams.councilQuorum,councilSize:e.prePeginParams.councilSize,network:e.prePeginParams.network,authAnchorHash:T(e.prePeginParams.authAnchorHash)},e.timelockPegin,e.fundedPrePeginTxHex,e.htlcVout);return await te(t,e),{txHex:t.txHex,txid:t.txid,vaultScriptPubKey:t.vaultScriptPubKey,vaultValue:t.vaultValue}}const J=2,ee=1;async function te(e,t){const n=t.prePeginParams.vaultCoreVersion;await w.validatePeginP2aAnchor(n,e.txHex);const r=await w.peginP2aAnchorOutput(n),o=J+(r?1:0),i=x.Transaction.fromHex(c.stripHexPrefix(e.txHex));if(i.ins.length!==1)throw new Error(`PegIn tx has ${i.ins.length} input(s), expected exactly 1 (the Pre-PegIn HTLC outpoint).`);const s=x.Transaction.fromHex(c.stripHexPrefix(t.fundedPrePeginTxHex)).getId(),u=c.uint8ArrayToHex(new Uint8Array(i.ins[0].hash).slice().reverse());if(u!==s)throw new Error(`PegIn input spends txid ${u}, expected the funded Pre-PegIn ${s}.`);if(i.ins[0].index!==t.htlcVout)throw new Error(`PegIn input spends Pre-PegIn output ${i.ins[0].index}, expected the requested HTLC vout ${t.htlcVout}.`);if(i.outs.length!==o)throw new Error(`PegIn tx has ${i.outs.length} output(s), expected exactly ${o} for vaultCoreVersion ${n} (vault + depositor claim${r?" + P2A anchor":""}).`);const P=t.prePeginParams.pegInAmounts[t.htlcVout];if(e.vaultValue!==P)throw new Error(`PegIn vault output value ${e.vaultValue} does not match the requested peg-in amount ${P} for HTLC ${t.htlcVout}; refusing to sign a vault that locks a different amount than requested.`);const a=i.outs[0];if(BigInt(a.value)!==e.vaultValue)throw new Error(`Encoded PegIn vault output value ${a.value} does not match the WASM-reported vaultValue ${e.vaultValue}.`);const h=a.script.toString("hex"),l=c.stripHexPrefix(e.vaultScriptPubKey).toLowerCase();if(h.toLowerCase()!==l)throw new Error(`Encoded PegIn vault output scriptPubKey ${h} does not match the WASM-reported vaultScriptPubKey ${e.vaultScriptPubKey}.`);const g=i.getId();if(g!==c.stripHexPrefix(e.txid).toLowerCase())throw new Error(`Encoded PegIn txid ${g} does not match the WASM-reported txid ${e.txid}.`);const d=await w.computeMinClaimValue(n,t.prePeginParams.numLocalChallengers,t.prePeginParams.universalChallengerPubkeys.length,t.prePeginParams.councilQuorum,t.prePeginParams.councilSize,t.prePeginParams.feeRate),E=i.outs[ee];if(BigInt(E.value)!==d)throw new Error(`Encoded PegIn depositor-claim output value ${E.value} does not match the independently computed claim value ${d} for vaultCoreVersion ${n}.`);const $=ne(t.prePeginParams.depositorPubkey);if(!E.script.equals($))throw new Error(`Encoded PegIn depositor-claim output scriptPubKey ${E.script.toString("hex")} does not pay to the depositor's claim script (expected ${$.toString("hex")}).`)}function ne(e){const t=x.script.compile([p.Buffer.from(c.hexToUint8Array(e)),x.opcodes.OP_CHECKSIG]),{output:n}=x.payments.p2tr({internalPubkey:p.Buffer.from(w.tapInternalPubkey),scriptTree:{output:t}});if(!n)throw new Error("Failed to derive the depositor-claim P2TR scriptPubKey for PegIn output validation");return n}async function q(e){const t=await w.createPayoutConnector({txGraphVersion:e.vaultCoreVersion,depositor:e.depositor,vaultProvider:e.vaultProvider,vaultKeepers:e.vaultKeepers,universalChallengers:e.universalChallengers,timelockPegin:e.timelockPegin},e.network);return{payoutScript:t.payoutScript,taprootScriptHash:t.taprootScriptHash,scriptPubKey:t.scriptPubKey,address:t.address,payoutControlBlock:t.payoutControlBlock}}const re=500,oe=55,V=0xffffffffn,k=32,ie=34;function se(e){if(typeof e.protocolFeeRate!="bigint"||e.protocolFeeRate<=0n||e.protocolFeeRate>V)throw new Error(`protocolFeeRate must be in [1, ${V}] sat/vB, got ${e.protocolFeeRate}`);for(const[t,n]of[["keepers",e.numVaultKeepers],["challengers",e.numUniversalChallengers]])if(!Number.isInteger(n)||n<1||n>k)throw new Error(`Participant count for ${t} (${n}) is outside the device range [1, ${k}].`);if(!Number.isInteger(e.councilSize)||e.councilSize<1)throw new Error(`councilSize must be an integer >= 1, got ${e.councilSize}`)}async function ue(e,t){const{implicitFeeSats:n,out0Len:r,out1Len:o}=t,i=e.numVaultKeepers+e.numUniversalChallengers,s=BigInt(n),u=Math.max(0,r-ie),P=re+oe*i+u,a=e.protocolFeeRate*BigInt(P);if(s>a)throw new Error(`Payout implicit fee ${n} sats exceeds the safety cap of ${a} sats (${e.protocolFeeRate} sat/vB x ${P} vB for ${i} participants); refusing to sign payout.`);const h=await w.computePayoutFeeFloor(e.vaultCoreVersion,e.numVaultKeepers,e.numUniversalChallengers,e.numVaultKeepers,e.councilSize,r,o,e.protocolFeeRate);if(s<h)throw new Error(`Payout implicit fee ${n} sats is below the floor of ${h} sats (the smallest fee any known vault-provider build produces for this shape); refusing to sign payout.`)}const ce=22,ae=34,le=34,he=25,Pe=23;function de(e){return e.length===ce*2&&e.startsWith("0014")}function pe(e){return e.length===ae*2&&e.startsWith("0020")}function fe(e){return e.length===le*2&&e.startsWith("5120")}function ge(e){return e.length===he*2&&e.startsWith("76a914")&&e.endsWith("88ac")}function xe(e){return e.length===Pe*2&&e.startsWith("a914")&&e.endsWith("87")}function O(e,t){const n=c.stripHexPrefix(e).toLowerCase();if(n.length===0)throw new Error(`${t} is empty`);if(!/^[0-9a-f]+$/.test(n)||n.length%2!==0)throw new Error(`${t} is not valid hex`);if(n.startsWith("6a"))throw new Error(`${t} is an OP_RETURN output, which is provably unspendable`);if(!fe(n)&&!de(n)&&!pe(n)&&!ge(n)&&!xe(n))throw new Error(`${t} is not a standard scriptPubKey (expected P2TR, P2WPKH, P2WSH, P2PKH, or P2SH; got ${n.length/2} bytes: ${n})`)}const R=3;async function ve(e){const t={vaultCoreVersion:e.vaultCoreVersion,numVaultKeepers:e.vaultKeeperBtcPubkeys.length,numUniversalChallengers:e.universalChallengerBtcPubkeys.length,councilSize:e.councilSize,protocolFeeRate:e.protocolFeeRate};se(t);const n=x.Transaction.fromHex(c.stripHexPrefix(e.payoutTxHex)),r=x.Transaction.fromHex(c.stripHexPrefix(e.peginTxHex)),o=x.Transaction.fromHex(c.stripHexPrefix(e.assertTxHex));if(n.ins.length!==v.DEPOSITOR_PAYOUT_INPUT_COUNT)throw new Error(`Payout transaction must have exactly ${v.DEPOSITOR_PAYOUT_INPUT_COUNT} inputs, got ${n.ins.length}`);const i=U(n.ins[0],0,r,"PegIn",v.PEGIN_VAULT_OUTPUT_INDEX),s=U(n.ins[1],1,o,"Assert",v.ASSERT_PAYOUT_OUTPUT_INDEX),{out0Len:u,out1Len:P}=$e(n,i.value,e),a=i.value+s.value;let h=0;for(const d of n.outs)h+=d.value;if(h>a)throw new Error(`Payout outputs (${h} sats) exceed inputs (${a} sats); invalid transaction.`);const l=a-h;await ue(t,{implicitFeeSats:l,out0Len:u,out1Len:P});const g=await q({vaultCoreVersion:e.vaultCoreVersion,depositor:e.depositorBtcPubkey,vaultProvider:e.vaultProviderBtcPubkey,vaultKeepers:e.vaultKeeperBtcPubkeys,universalChallengers:e.universalChallengerBtcPubkeys,timelockPegin:e.timelockPegin,network:e.network});return{psbtHex:we(n,i,s,g)}}function U(e,t,n,r,o){const i=c.uint8ArrayToHex(new Uint8Array(e.hash).slice().reverse()),s=n.getId();if(i!==s||e.index!==o)throw new Error(`Input ${t} must spend ${r}:${o}. Expected ${s}:${o}, got ${i}:${e.index}`);const u=n.outs[e.index];if(!u)throw new Error(`Previous output not found for input ${t} (txid: ${i}, index: ${e.index})`);return u}function we(e,t,n,r){const o=new x.Psbt;o.setVersion(e.version),o.setLocktime(e.locktime);const[i,s]=e.ins;o.addInput({hash:i.hash,index:i.index,sequence:i.sequence,witnessUtxo:{script:t.script,value:t.value},tapLeafScript:[{leafVersion:c.TAPSCRIPT_LEAF_VERSION,script:p.Buffer.from(c.hexToUint8Array(r.payoutScript)),controlBlock:p.Buffer.from(c.hexToUint8Array(r.payoutControlBlock))}],tapInternalKey:p.Buffer.from(w.tapInternalPubkey)}),o.addInput({hash:s.hash,index:s.index,sequence:s.sequence,witnessUtxo:{script:n.script,value:n.value}});for(const u of e.outs)o.addOutput({script:u.script,value:u.value});return o.toHex()}function L(e,t){const n=c.stripHexPrefix(e).toLowerCase(),r=c.stripHexPrefix(c.deriveBip86ScriptPubKeyHex(t)).toLowerCase();return n===r?[n]:[n,r]}function B(e,t){return t.some(n=>e.equals(p.Buffer.from(n,"hex")))}function $e(e,t,n){const{claimerBtcPubkey:r,vaultProviderBtcPubkey:o,depositorBtcPubkey:i,vaultKeeperBtcPubkeys:s,registeredPayoutScriptPubKey:u,commissionBps:P,vkClaimerPayoutScriptPubKeys:a,vpCommissionScriptPubKey:h}=n;if(!c.isValidHex(u))throw new Error("Invalid registeredPayoutScriptPubKey: not valid hex");const l=c.stripHexPrefix(r).toLowerCase(),g=c.stripHexPrefix(o).toLowerCase(),d=c.stripHexPrefix(i).toLowerCase(),E=s.map(m=>c.stripHexPrefix(m).toLowerCase());let $,f,y;if(l===g)$="vp-claimer",f=v.VP_CLAIMER_PAYOUT_OUTPUT_COUNT,y=[c.stripHexPrefix(u)];else if(l===d)$="depositor-as-claimer",f=v.NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT,y=[c.stripHexPrefix(u)];else if(E.includes(l)){$="vk-claimer",f=v.NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT;const m=a[l];if(m===void 0)throw new Error(`No registered payout script resolved for vault keeper claimer ${l}`);O(m,`Vault keeper payout script for claimer ${l}`),y=L(m,l)}else throw new Error(`Unknown claimer pubkey ${l}: not VP, depositor, or a registered vault keeper`);if(e.outs.length!==f)throw new Error(`Payout transaction has ${e.outs.length} output(s), expected exactly ${f} for role ${$}.`);if(!B(e.outs[0].script,y))throw new Error(`Payout transaction output 0 does not pay the expected scriptPubKey for role ${$}. Accepted: ${y.join(" or ")}; got ${e.outs[0].script.toString("hex")}`);const A=f-1;if(e.outs[A].value!==v.PAYOUT_ANCHOR_DUST_SATS)throw new Error(`Payout CPFP anchor (out ${A}) value ${e.outs[A].value} sats must equal ${v.PAYOUT_ANCHOR_DUST_SATS} sats`);if($==="vp-claimer"){O(h,"Vault provider commission payout script");const m=L(h,g);if(!B(e.outs[1].script,m))throw new Error(`Payout transaction output 1 does not pay the vault provider's commission scriptPubKey. Accepted: ${m.join(" or ")}; got ${e.outs[1].script.toString("hex")}`);if(!Number.isInteger(P)||P<0||P>=v.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`commissionBps must be an integer in [0, ${v.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${P}`);const I=Math.floor(t*P/v.BPS_DENOMINATOR);if(e.outs[1].value>I)throw new Error(`Payout VP commission (out 1) value ${e.outs[1].value} sats exceeds cap ${I} sats (${P} bps of peginValue=${t})`)}const b=e.outs[0].script.length;if(b===0||b>v.MAX_PAYOUT_SCRIPT_LEN)throw new Error(`Payout receiver scriptPubKey length ${b} is outside the contract's registration cap [1, ${v.MAX_PAYOUT_SCRIPT_LEN}]; refusing to sign payout.`);const W=$==="vp-claimer"?e.outs[1].script.length:void 0;return{out0Len:b,out1Len:W}}function Se(e,t,n=0){const r=x.Psbt.fromHex(e);if(n>=r.data.inputs.length)throw new Error(`Input index ${n} out of range (${r.data.inputs.length} inputs)`);const o=r.data.inputs[n];if(o.tapScriptSig&&o.tapScriptSig.length>0){const i=c.hexToUint8Array(t);for(const s of o.tapScriptSig)if(s.pubkey.equals(p.Buffer.from(i)))return N(s.signature,n);throw new Error(`No signature found for depositor pubkey: ${t} at input ${n}`)}if(o.finalScriptWitness&&o.finalScriptWitness.length>0){const i=ye(o.finalScriptWitness);if(i.length!==R)throw new Error(`Unexpected finalized witness stack size at input ${n}: expected ${R} items (signature, script, controlBlock), got ${i.length}`);return N(i[0],n)}throw new Error(`No tapScriptSig or finalScriptWitness found in signed PSBT at input ${n}`)}function N(e,t){if(e.length===64)return c.uint8ArrayToHex(new Uint8Array(e));throw e.length===65?new Error(`Unexpected sighash byte 0x${e[64].toString(16).padStart(2,"0")} at input ${t}. Expected implicit SIGHASH_DEFAULT as a 64-byte signature.`):new Error(`Unexpected signature length at input ${t}: ${e.length}`)}function ye(e){const t=[];let n=0;const r=s=>{if(n+s>e.length)throw new Error(`Malformed witness data: need ${s} byte(s) at offset ${n}, only ${e.length-n} remaining`)},o=()=>{r(1);const s=e[n++];if(s<253)return s;if(s===253){r(2);const u=(e[n]|e[n+1]<<8)>>>0;return n+=2,u}if(s===254){r(4);const u=(e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24)>>>0;return n+=4,u}throw new Error(`Malformed witness data: 8-byte varint (0xff) not supported at offset ${n-1}`)},i=o();for(let s=0;s<i;s++){const u=o();r(u),t.push(p.Buffer.from(e.subarray(n,n+u))),n+=u}if(n!==e.length)throw new Error(`Malformed witness data: ${e.length-n} trailing byte(s) after parsing ${i} item(s)`);return t}class S extends Error{constructor(t){super(`Wallet returned a PSBT for a different transaction: ${t}`),this.name="PsbtSubstitutionError"}}function K(e,t){try{return x.Psbt.fromHex(t)}catch(n){const r=n instanceof Error?n.message:String(n);throw new Error(`Failed to parse ${e} PSBT: ${r}`)}}const Ee=8;function _(e){return`${e.toString("hex").slice(0,Ee)}…`}function F(e){const t=p.Buffer.from(e).reverse();return _(t)}function me(e){const t=K("requested",e.requestedPsbtHex),n=K("returned",e.returnedPsbtHex);if(t.version!==n.version)throw new S(`tx version differs (requested=${t.version}, returned=${n.version})`);if(t.locktime!==n.locktime)throw new S(`tx locktime differs (requested=${t.locktime}, returned=${n.locktime})`);if(t.txInputs.length!==n.txInputs.length)throw new S(`input count differs (requested=${t.txInputs.length}, returned=${n.txInputs.length})`);if(t.txOutputs.length!==n.txOutputs.length)throw new S(`output count differs (requested=${t.txOutputs.length}, returned=${n.txOutputs.length})`);for(let r=0;r<t.txInputs.length;r++){const o=t.txInputs[r],i=n.txInputs[r];if(!o.hash.equals(i.hash))throw new S(`input ${r} prevout txid differs (requested=${F(o.hash)}, returned=${F(i.hash)})`);if(o.index!==i.index)throw new S(`input ${r} prevout vout differs (requested=${o.index}, returned=${i.index})`);if(o.sequence!==i.sequence)throw new S(`input ${r} sequence differs (requested=${o.sequence}, returned=${i.sequence})`)}for(let r=0;r<t.txOutputs.length;r++){const o=t.txOutputs[r],i=n.txOutputs[r];if(!o.script.equals(i.script))throw new S(`output ${r} scriptPubKey differs (requested=${_(o.script)}, returned=${_(i.script)})`);if(o.value!==i.value)throw new S(`output ${r} value differs (requested=${o.value}, returned=${i.value})`)}}const M=253,be=254,Ae=65535,Ce=4294967295;function _e(e){if(e<M)return p.Buffer.from([e]);if(e<=Ae){const t=p.Buffer.alloc(2);return t.writeUInt16LE(e),p.Buffer.concat([p.Buffer.from([M]),t])}if(e<=Ce){const t=p.Buffer.alloc(4);return t.writeUInt32LE(e),p.Buffer.concat([p.Buffer.from([be]),t])}throw new Error(`Script too large to encode as CompactSize: ${e} bytes`)}const Te="TapLeaf";function Ie(e,t){const n=p.Buffer.concat([p.Buffer.from([e]),_e(t.length),p.Buffer.from(t)]);return x.crypto.taggedHash(Te,n)}function He(e){const{requestedPsbtHex:t,signatureHex:n,signerXOnlyPubkeyHex:r,inputIndex:o}=e,i=c.stripHexPrefix(n);if(i.length!==c.SCHNORR_SIG_HEX_LEN)throw new Error(`Schnorr signature for input ${o} must be ${c.SCHNORR_SIG_HEX_LEN} hex chars (64 bytes), got ${i.length}.`);const s=c.stripHexPrefix(r);if(s.length!==c.X_ONLY_PUBKEY_HEX_LEN)throw new Error(`Signer x-only pubkey for input ${o} must be ${c.X_ONLY_PUBKEY_HEX_LEN} hex chars (32 bytes), got ${s.length}.`);const u=x.Psbt.fromHex(t);if(o<0||o>=u.data.inputs.length)throw new Error(`Input index ${o} out of range (${u.data.inputs.length} inputs).`);const P=[],a=[];for(let f=0;f<u.data.inputs.length;f++){const y=u.data.inputs[f].witnessUtxo;if(!y)throw new Error(`Cannot verify signature: input ${f} of the requested PSBT has no witnessUtxo (required to recompute the Taproot sighash).`);P.push(y.script),a.push(y.value)}const h=u.data.inputs[o].tapLeafScript;if(!h||h.length!==1)throw new Error(`Cannot verify signature: input ${o} of the requested PSBT must have exactly one tapLeafScript, got ${(h==null?void 0:h.length)??0}.`);const l=h[0];if(l.leafVersion!==c.TAPSCRIPT_LEAF_VERSION)throw new Error(`Cannot verify signature: input ${o} tapLeafScript has leaf version 0x${l.leafVersion.toString(16)}, expected 0x${c.TAPSCRIPT_LEAF_VERSION.toString(16)}.`);const g=Ie(l.leafVersion,l.script),d=new x.Transaction;d.version=u.version,d.locktime=u.locktime;for(const f of u.txInputs)d.addInput(f.hash,f.index,f.sequence);for(const f of u.txOutputs)d.addOutput(f.script,f.value);const E=d.hashForWitnessV1(o,P,a,x.Transaction.SIGHASH_DEFAULT,g);if(!Y.verifySchnorr(E,c.hexToUint8Array(s),c.hexToUint8Array(i)))throw new Error(`Schnorr signature for input ${o} (signer ${s}) does not verify against the expected Taproot script-path sighash. The wallet may have signed with the tweaked key, signed a different transaction, or returned an invalid signature.`)}exports.PsbtSubstitutionError=S;exports.assertPsbtUnsignedTxMatches=me;exports.assertScriptPathSchnorrSignature=He;exports.buildPayoutPsbt=ve;exports.buildPeginTxFromFundedPrePegin=j;exports.buildPrePeginPsbt=Z;exports.createPayoutScript=q;exports.extractPayoutSignature=Se;exports.normalizeAuthAnchorHash=T;
2
- //# sourceMappingURL=verifyScriptPathSchnorrSignature-fhjfNoHK.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"verifyScriptPathSchnorrSignature-fhjfNoHK.cjs","sources":["../src/tbv/core/primitives/psbt/assertWasmPeginSizing.ts","../src/tbv/core/primitives/psbt/pegin.ts","../src/tbv/core/primitives/scripts/payout.ts","../src/tbv/core/primitives/psbt/assertPayoutFeeBand.ts","../src/tbv/core/primitives/psbt/standardPayoutScript.ts","../src/tbv/core/primitives/psbt/payout.ts","../src/tbv/core/primitives/psbt/assertPsbtUnsignedTxMatches.ts","../src/tbv/core/primitives/psbt/verifyScriptPathSchnorrSignature.ts"],"sourcesContent":["/**\n * Cross-check the values WASM returns from `createPrePeginTransaction`\n * against independently-known expectations before they feed a signed\n * Bitcoin transaction or the on-chain PegIn registration.\n *\n * CLAUDE.md critical path #1: the Rust/WASM layer computes\n * `htlcValue = peginAmount + depositorClaimValue + p2aAnchorValue +\n * minPeginFee` internally (the anchor term is 0 for graph versions without a\n * P2A anchor, 240 sats for v2) and JS receives the outputs with no runtime\n * validation. A doctored or buggy binary that returns a different\n * `peginAmount`, an out-of-formula `htlcValue`, or a wrong\n * `depositorClaimValue` would otherwise be committed verbatim — taxing the\n * depositor or starving the downstream tx graph of fees.\n *\n * @module primitives/psbt/assertWasmPeginSizing\n */\n\nimport {\n computeMinClaimValue,\n computeMinPeginFee,\n peginP2aAnchorOutput,\n type PrePeginResult,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\nimport { MAX_REASONABLE_PEGIN_VBYTES } from \"../../utils/fee/constants\";\nimport type { ParsedOutput } from \"../../utils/transaction/fundPeginTransaction\";\n\nimport type { PrePeginParams } from \"./pegin\";\n\n/**\n * Assert the WASM Pre-PegIn sizing result is internally consistent and\n * matches what the caller requested.\n *\n * Two layers of checks. Pure-JS, binary-INDEPENDENT: the per-HTLC\n * `peginAmount` must echo the requested amount, array lengths must match,\n * every value must be positive, and the implied per-HTLC reserve\n * (`htlcValue - peginAmount - depositorClaimValue`) must be strictly\n * positive and under the plausibility cap\n * ({@link MAX_REASONABLE_PEGIN_VBYTES}). WASM-vs-WASM consistency: the\n * reserve must also EXACTLY equal `computeMinPeginFee(version, …) +\n * p2aAnchorValue(version)` (like the `computeMinClaimValue` check) —\n * exact, but both sides come from the same binary, which is why the\n * independent bounds above are kept alongside it.\n *\n * @param result - The result returned by `createPrePeginTransaction`.\n * @param params - The parameters that were passed to build it.\n * @returns The independently computed `minPeginFee` this function already\n * asserted against `result`'s implied reserve — callers that need the\n * value should reuse this instead of recomputing it.\n * @throws If any value is missing, non-positive, mismatched against the\n * request, or outside the protocol formula.\n */\nexport async function assertWasmPeginSizing(\n result: PrePeginResult,\n params: PrePeginParams,\n): Promise<bigint> {\n const expectedCount = params.pegInAmounts.length;\n\n // Count: every parallel array must carry exactly one entry per requested\n // deposit, otherwise the per-HTLC indexing downstream is meaningless.\n if (result.htlcValues.length !== expectedCount) {\n throw new Error(\n `WASM Pre-PegIn returned ${result.htlcValues.length} HTLC value(s), ` +\n `expected ${expectedCount} (one per requested deposit).`,\n );\n }\n if (\n result.peginAmounts.length !== expectedCount ||\n result.htlcScriptPubKeys.length !== expectedCount ||\n result.htlcAddresses.length !== expectedCount\n ) {\n throw new Error(\n `WASM Pre-PegIn returned mismatched array lengths ` +\n `(htlcValues=${result.htlcValues.length}, ` +\n `peginAmounts=${result.peginAmounts.length}, ` +\n `htlcScriptPubKeys=${result.htlcScriptPubKeys.length}, ` +\n `htlcAddresses=${result.htlcAddresses.length}); ` +\n `expected ${expectedCount} each.`,\n );\n }\n\n // depositorClaimValue: positivity + WASM-vs-WASM consistency. Sized by the\n // tx-graph `feeRate` (see PrePeginParams.feeRate), so the standalone\n // `computeMinClaimValue` must reproduce the constructor's internal value.\n if (result.depositorClaimValue <= 0n) {\n throw new Error(\n `WASM Pre-PegIn returned non-positive depositorClaimValue ` +\n `${result.depositorClaimValue}; expected > 0.`,\n );\n }\n const expectedClaimValue = await computeMinClaimValue(\n // Must price the same graph version the builder constructed.\n params.vaultCoreVersion,\n params.numLocalChallengers,\n params.universalChallengerPubkeys.length,\n params.councilQuorum,\n params.councilSize,\n params.feeRate,\n );\n if (result.depositorClaimValue !== expectedClaimValue) {\n throw new Error(\n `WASM Pre-PegIn depositorClaimValue ${result.depositorClaimValue} does ` +\n `not match the independently computed minimum claim value ` +\n `${expectedClaimValue} (vaultCoreVersion=${params.vaultCoreVersion}, ` +\n `numLocalChallengers=${params.numLocalChallengers}, ` +\n `numUniversalChallengers=${params.universalChallengerPubkeys.length}, ` +\n `councilQuorum=${params.councilQuorum}, councilSize=${params.councilSize}, ` +\n `feeRate=${params.feeRate}).`,\n );\n }\n\n // The per-HTLC reserve above pegin+claim decomposes into the version's\n // P2A anchor value (0 when the version has no anchor) plus the exact\n // minimum PegIn fee. Both terms are Rust-model values fetched through\n // independent WASM entry points; the builder must reproduce their sum.\n // The Rust fee model sizes the PegIn input witness from the vault keeper\n // and universal challenger counts (btc-vault `PegInTx::estimate_vsize`).\n const anchor = await peginP2aAnchorOutput(params.vaultCoreVersion);\n const anchorValue = anchor?.value ?? 0n;\n const expectedPeginFee = await computeMinPeginFee(\n params.vaultCoreVersion,\n params.vaultKeeperPubkeys.length,\n params.universalChallengerPubkeys.length,\n params.minPeginFeeRate,\n );\n const expectedReserve = expectedPeginFee + anchorValue;\n // Binary-INDEPENDENT plausibility cap: the exact identity below compares\n // WASM against WASM, so a consistently doctored binary could satisfy it\n // with an inflated reserve. This pure-JS bound (max standard-relay tx\n // vbytes × the caller's fee rate) caps how much a compromised binary can\n // burn.\n const maxImpliedReserve =\n params.minPeginFeeRate * MAX_REASONABLE_PEGIN_VBYTES;\n\n for (let i = 0; i < expectedCount; i++) {\n const requested = params.pegInAmounts[i];\n const peginAmount = result.peginAmounts[i];\n const htlcValue = result.htlcValues[i];\n\n // Amount echo (strongest, fully independent): the recorded pegin amount\n // must equal exactly what the caller requested. A mismatch is the\n // WASM-tax attack — the contract would record a doctored amount while the\n // depositor's wallet funds the original, and the difference is a\n // WASM-controlled tax.\n if (peginAmount !== requested) {\n throw new Error(\n `WASM Pre-PegIn peginAmount[${i}] ${peginAmount} does not match the ` +\n `requested amount ${requested}; refusing to build a tx whose ` +\n `recorded amount differs from the depositor's request.`,\n );\n }\n if (peginAmount <= 0n) {\n throw new Error(\n `WASM Pre-PegIn peginAmount[${i}] is non-positive (${peginAmount}); ` +\n `expected > 0.`,\n );\n }\n if (htlcValue <= 0n) {\n throw new Error(\n `WASM Pre-PegIn htlcValue[${i}] is non-positive (${htlcValue}); ` +\n `expected > 0.`,\n );\n }\n\n // Formula: htlcValue = peginAmount + depositorClaimValue +\n // p2aAnchorValue + minPeginFee. The reserve must match exactly — a\n // shortfall starves the PegIn's fee/anchor, an excess locks sats\n // irrecoverably in the HTLC.\n const impliedReserve = htlcValue - peginAmount - result.depositorClaimValue;\n // Independent JS-side bounds first (see maxImpliedReserve above): the\n // reserve must be strictly positive (a zero reserve starves the PegIn\n // of its fee) and plausibly sized, regardless of what the binary's own\n // reference entry points claim.\n if (impliedReserve <= 0n) {\n throw new Error(\n `WASM Pre-PegIn htlcValue[${i}] ${htlcValue} does not strictly ` +\n `cover peginAmount ${peginAmount} + depositorClaimValue ` +\n `${result.depositorClaimValue} + a PegIn reserve (implied ` +\n `reserve ${impliedReserve}).`,\n );\n }\n if (impliedReserve > maxImpliedReserve) {\n throw new Error(\n `WASM Pre-PegIn implied reserve for HTLC[${i}] (${impliedReserve} ` +\n `sat) exceeds the plausibility cap ${maxImpliedReserve} sat ` +\n `(minPeginFeeRate=${params.minPeginFeeRate} × ` +\n `${MAX_REASONABLE_PEGIN_VBYTES} vbytes); htlcValue ${htlcValue} ` +\n `appears grossly inflated.`,\n );\n }\n if (impliedReserve !== expectedReserve) {\n throw new Error(\n `WASM Pre-PegIn htlcValue[${i}] ${htlcValue} implies a PegIn ` +\n `fee+anchor reserve of ${impliedReserve} sat, expected exactly ` +\n `${expectedReserve} sat (minPeginFee ${expectedPeginFee} + ` +\n `p2aAnchor ${anchorValue} for vaultCoreVersion ` +\n `${params.vaultCoreVersion}, vaultKeepers=` +\n `${params.vaultKeeperPubkeys.length}, universalChallengers=` +\n `${params.universalChallengerPubkeys.length}, minPeginFeeRate=` +\n `${params.minPeginFeeRate}).`,\n );\n }\n }\n\n return expectedPeginFee;\n}\n\n/**\n * Bind the validated metadata to the bytes that actually get funded and\n * signed.\n *\n * `assertWasmPeginSizing` proves the WASM *metadata* (`htlcValues`,\n * `htlcScriptPubKeys`) matches the request and the protocol formula — but the\n * transaction the depositor funds and signs is `result.txHex`. If the encoded\n * tx carried a different HTLC output value or script than the metadata, the\n * depositor would fund a transaction whose real outputs differ from the values\n * that were cross-checked. This closes that final link: the encoded HTLC\n * outputs must equal the validated metadata.\n *\n * The WASM lays out HTLC outputs first (vouts `0..N-1`), then the optional\n * auth-anchor OP_RETURN, then the CPFP anchor — so we only compare the first\n * `htlcValues.length` outputs.\n *\n * @param outputs - Outputs parsed from the unfunded Pre-PegIn tx hex.\n * @param htlcValues - The (already value-validated) per-HTLC values.\n * @param htlcScriptPubKeys - The per-HTLC scriptPubKeys (hex).\n * @throws If the encoded outputs are too few, or any HTLC output's value or\n * scriptPubKey disagrees with the validated metadata.\n */\nexport function assertEncodedHtlcOutputsMatch(\n outputs: readonly ParsedOutput[],\n htlcValues: readonly bigint[],\n htlcScriptPubKeys: readonly string[],\n): void {\n if (outputs.length < htlcValues.length) {\n throw new Error(\n `Encoded Pre-PegIn tx has ${outputs.length} output(s), fewer than the ` +\n `${htlcValues.length} HTLC output(s) the cross-check validated.`,\n );\n }\n\n for (let i = 0; i < htlcValues.length; i++) {\n const encodedValue = BigInt(outputs[i].value);\n if (encodedValue !== htlcValues[i]) {\n throw new Error(\n `Encoded Pre-PegIn HTLC output[${i}] value ${encodedValue} does not ` +\n `match the cross-checked htlcValue ${htlcValues[i]}; the funded/signed ` +\n `tx would not pay the validated amount.`,\n );\n }\n\n const encodedScript = outputs[i].script.toString(\"hex\").toLowerCase();\n const expectedScript = htlcScriptPubKeys[i].toLowerCase();\n if (encodedScript !== expectedScript) {\n throw new Error(\n `Encoded Pre-PegIn HTLC output[${i}] scriptPubKey ${encodedScript} does ` +\n `not match the cross-checked htlcScriptPubKey ${expectedScript}.`,\n );\n }\n }\n}\n","/**\n * Pre-PegIn PSBT Builder Primitive\n *\n * This module provides pure functions for building unfunded Pre-PegIn transactions\n * and deriving PegIn transactions from them, using the WASM implementation from\n * @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * Pre-PegIn Flow:\n * 1. buildPrePeginPsbt() — creates unfunded Pre-PegIn tx (HTLC output)\n * 2. [caller funds Pre-PegIn tx and computes txid]\n * 3. buildPeginTxFromFundedPrePegin() — derives PegIn tx spending the HTLC\n * 4. buildPeginInputPsbt() — PSBT for depositor to sign PegIn HTLC leaf 0 input\n *\n * @module primitives/psbt/pegin\n */\n\nimport {\n buildPeginTxFromPrePegin,\n computeMinClaimValue,\n createPrePeginTransaction,\n peginP2aAnchorOutput,\n tapInternalPubkey,\n validatePeginP2aAnchor,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { payments, script as bscript, Transaction, opcodes } from \"bitcoinjs-lib\";\n\nimport { parseUnfundedWasmTransaction } from \"../../utils/transaction/fundPeginTransaction\";\nimport {\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\nimport {\n assertEncodedHtlcOutputsMatch,\n assertWasmPeginSizing,\n} from \"./assertWasmPeginSizing\";\n\n/**\n * Parameters for building an unfunded Pre-PegIn PSBT\n */\nexport interface PrePeginParams {\n /**\n * Vault core (tx-graph) version to build. Fresh deposits use the contract's\n * `ProtocolParams.activeVaultCoreVersion()`; resumed vaults use their\n * stamped on-chain `vaultCoreVersion`. The WASM facade fails closed on\n * versions it wasn't compiled with.\n */\n vaultCoreVersion: number;\n /** Depositor's BTC public key (x-only, 64-char hex without 0x prefix) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Array of vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Array of universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment(s) (64 hex chars = 32 bytes each) */\n hashlocks: readonly string[];\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Amounts to peg in (satoshis), one per deposit */\n pegInAmounts: readonly bigint[];\n /** TX-graph fee rate in sat/vB from contract offchain params; sizes the depositor claim value */\n feeRate: bigint;\n /** Minimum PegIn fee rate in sat/vB from contract offchain params; sizes the PegIn tx fee */\n minPeginFeeRate: bigint;\n /** Number of local challengers (from contract params) */\n numLocalChallengers: number;\n /** M in M-of-N council multisig (from contract params) */\n councilQuorum: number;\n /** N in M-of-N council multisig (from contract params) */\n councilSize: number;\n /** Bitcoin network */\n network: Network;\n /**\n * Optional 32-byte `SHA256(auth_anchor)` commitment (64-char hex, no\n * `0x` prefix). If provided, the Pre-PegIn tx will include an\n * `OP_RETURN <PUSH32 authAnchorHash>` output at vout =\n * `hashlocks.length`, binding the depositor's bearer-token\n * `auth_anchor` preimage to this Pre-PegIn.\n */\n authAnchorHash?: string;\n}\n\n/**\n * Byte length of an `auth_anchor_hash` commitment when encoded as a\n * lowercase hex string (32 bytes → 64 hex chars).\n */\nconst AUTH_ANCHOR_HASH_HEX_LEN = 64;\n\nconst HEX_PATTERN = /^[0-9a-fA-F]+$/;\n\n/**\n * Result of building an unfunded Pre-PegIn transaction\n */\nexport interface PrePeginPsbtResult {\n /**\n * Unfunded transaction hex (no inputs, HTLC outputs + optional\n * auth-anchor OP_RETURN + CPFP anchor).\n *\n * The caller is responsible for:\n * - Selecting UTXOs covering totalOutputValue + network fees\n * - Funding the transaction (add inputs and change output)\n * - Calling buildPeginTxFromFundedPrePegin() with the funded tx hex\n */\n psbtHex: string;\n /** Sum of all unfunded outputs — use this for UTXO selection */\n totalOutputValue: bigint;\n /**\n * HTLC output values in satoshis, one per deposit. Each includes\n * peginAmount + depositorClaimValue + p2aAnchorValue + minPeginFee (the\n * anchor term is 0 for graph versions without a P2A anchor, 240 for v2).\n */\n htlcValues: readonly bigint[];\n /** HTLC output scriptPubKeys (hex encoded), one per deposit */\n htlcScriptPubKeys: readonly string[];\n /** HTLC Taproot addresses, one per deposit */\n htlcAddresses: readonly string[];\n /** Pegin amounts in satoshis, one per deposit */\n peginAmounts: readonly bigint[];\n /** Depositor claim value computed by WASM from contract parameters */\n depositorClaimValue: bigint;\n /**\n * Vout index of the auth-anchor `OP_RETURN` output if one was\n * included (i.e. `authAnchorHash` was provided), or `null` if not.\n * Always equals `htlcValues.length` when present.\n */\n authAnchorVout: number | null;\n /**\n * Minimum PegIn fee (sats), independently computed and asserted against\n * `htlcValues`' implied reserve by {@link assertWasmPeginSizing}. Reuse\n * this instead of recomputing — it is already the cross-checked value.\n */\n minPeginFee: bigint;\n}\n\n/**\n * Parameters for building the PegIn transaction from a funded Pre-PegIn tx\n */\nexport interface BuildPeginTxParams {\n /** Same PrePeginParams used to create the Pre-PegIn transaction */\n prePeginParams: PrePeginParams;\n /** CSV timelock in blocks for the PegIn vault output */\n timelockPegin: number;\n /** Hex-encoded funded Pre-PegIn transaction */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output to spend */\n htlcVout: number;\n}\n\n/**\n * Result of building the PegIn transaction\n */\nexport interface PeginTxResult {\n /**\n * PegIn transaction hex. 1 input spending the HTLC; outputs are\n * version-shaped: v1 = vault + depositor claim, v2 = vault + depositor\n * claim + P2A anchor at vout 2 (nVersion 3 / TRUC).\n */\n txHex: string;\n /** PegIn transaction ID */\n txid: string;\n /** Vault output scriptPubKey (hex encoded) */\n vaultScriptPubKey: string;\n /** Vault output value in satoshis */\n vaultValue: bigint;\n}\n\n/**\n * Build unfunded Pre-PegIn transaction using WASM.\n *\n * Creates a Bitcoin transaction template with no inputs, an HTLC output, and a\n * CPFP anchor output. The HTLC value is computed internally from the contract\n * parameters — the caller does not need to compute depositorClaimValue separately.\n *\n * @param params - Pre-PegIn parameters\n * @returns Unfunded Pre-PegIn transaction details with HTLC output information\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPrePeginPsbt(\n params: PrePeginParams,\n): Promise<PrePeginPsbtResult> {\n const authAnchorHash = normalizeAuthAnchorHash(params.authAnchorHash);\n\n const result = await createPrePeginTransaction({\n txGraphVersion: params.vaultCoreVersion,\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlocks: [...params.hashlocks],\n timelockRefund: params.timelockRefund,\n pegInAmounts: [...params.pegInAmounts],\n feeRate: params.feeRate,\n minPeginFeeRate: params.minPeginFeeRate,\n numLocalChallengers: params.numLocalChallengers,\n councilQuorum: params.councilQuorum,\n councilSize: params.councilSize,\n network: params.network,\n authAnchorHash,\n });\n\n // CLAUDE.md critical path #1: the WASM outputs reach JS with no runtime\n // validation. Cross-check every value-bearing field against the request\n // and the protocol formula before it can feed a signed tx or the on-chain\n // PegIn registration. Both the sizing and commit passes route through here.\n const minPeginFee = await assertWasmPeginSizing(result, params);\n\n // Parse the unfunded tx to sum all output values\n // (HTLCs + optional OP_RETURN + CPFP anchor). This is the amount\n // UTXOs must cover before adding network fees.\n const parsed = parseUnfundedWasmTransaction(result.txHex);\n\n // Bind the validated metadata to the bytes that get funded and signed:\n // the encoded HTLC outputs must carry exactly the values/scripts the\n // cross-check above validated. Otherwise a tx whose real outputs differ\n // from the checked metadata could still be funded and signed.\n assertEncodedHtlcOutputsMatch(\n parsed.outputs,\n result.htlcValues,\n result.htlcScriptPubKeys,\n );\n\n const totalOutputValue = parsed.outputs.reduce(\n (sum, o) => sum + BigInt(o.value),\n 0n,\n );\n\n // The WASM places the OP_RETURN commitment immediately after the\n // HTLC outputs when authAnchorHash is provided.\n const authAnchorVout =\n authAnchorHash !== undefined ? result.htlcValues.length : null;\n\n return {\n psbtHex: result.txHex,\n totalOutputValue,\n htlcValues: result.htlcValues,\n htlcScriptPubKeys: result.htlcScriptPubKeys,\n htlcAddresses: result.htlcAddresses,\n peginAmounts: result.peginAmounts,\n depositorClaimValue: result.depositorClaimValue,\n authAnchorVout,\n minPeginFee,\n };\n}\n\n/**\n * Validate and normalize an `authAnchorHash` hex string before passing\n * it to the WASM boundary. WASM expects exactly 64 lowercase hex chars.\n */\nexport function normalizeAuthAnchorHash(\n value: string | undefined,\n): string | undefined {\n if (value === undefined) return undefined;\n const cleaned =\n value.startsWith(\"0x\") || value.startsWith(\"0X\") ? value.slice(2) : value;\n if (\n cleaned.length !== AUTH_ANCHOR_HASH_HEX_LEN ||\n !HEX_PATTERN.test(cleaned)\n ) {\n throw new Error(\n `authAnchorHash must be 32-byte hex (${AUTH_ANCHOR_HASH_HEX_LEN} chars, no 0x prefix); got length ${cleaned.length}`,\n );\n }\n return cleaned.toLowerCase();\n}\n\n/**\n * Build the PegIn transaction from a funded Pre-PegIn transaction.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output at htlcVout via the\n * hashlock + all-party script (leaf 0).\n *\n * @param params - Build parameters including Pre-PegIn params and funded tx hex\n * @returns PegIn transaction details\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPeginTxFromFundedPrePegin(\n params: BuildPeginTxParams,\n): Promise<PeginTxResult> {\n // WASM reconstructs the Pre-PegIn template from these params to\n // decode the funded tx. Must pass `authAnchorHash` (normalized\n // identically to buildPrePeginPsbt) so the reconstruction matches\n // the original outputs, including the OP_RETURN at vout =\n // hashlocks.length.\n const result = await buildPeginTxFromPrePegin(\n {\n txGraphVersion: params.prePeginParams.vaultCoreVersion,\n depositorPubkey: params.prePeginParams.depositorPubkey,\n vaultProviderPubkey: params.prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: params.prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys:\n params.prePeginParams.universalChallengerPubkeys,\n hashlocks: [...params.prePeginParams.hashlocks],\n timelockRefund: params.prePeginParams.timelockRefund,\n pegInAmounts: [...params.prePeginParams.pegInAmounts],\n feeRate: params.prePeginParams.feeRate,\n minPeginFeeRate: params.prePeginParams.minPeginFeeRate,\n numLocalChallengers: params.prePeginParams.numLocalChallengers,\n councilQuorum: params.prePeginParams.councilQuorum,\n councilSize: params.prePeginParams.councilSize,\n network: params.prePeginParams.network,\n authAnchorHash: normalizeAuthAnchorHash(\n params.prePeginParams.authAnchorHash,\n ),\n },\n params.timelockPegin,\n params.fundedPrePeginTxHex,\n params.htlcVout,\n );\n\n await assertPeginTxShape(result, params);\n\n return {\n txHex: result.txHex,\n txid: result.txid,\n vaultScriptPubKey: result.vaultScriptPubKey,\n vaultValue: result.vaultValue,\n };\n}\n\n/**\n * PegIn outputs common to every graph version: the vault output (vout 0)\n * and the depositor claim output (vout 1). Versions with a P2A anchor (v2)\n * append it after these.\n */\nconst PEGIN_BASE_OUTPUT_COUNT = 2;\n\n/**\n * Vout of the depositor-claim output in every PegIn version (btc-vault:\n * vault at 0, depositor claim at 1, optional P2A anchor appended after).\n */\nconst PEGIN_DEPOSITOR_CLAIM_VOUT = 1;\n\n/**\n * Cross-check the WASM-built PegIn transaction's bytes against the request\n * and the version's expected output layout before the depositor signs it.\n *\n * CLAUDE.md critical path #1: the metadata (`vaultValue`, `txid`,\n * `vaultScriptPubKey`) and the tx bytes both come from WASM — bind them to\n * each other and to the caller's requested amount so a doctored binary\n * can't commit one thing and encode another. The vault output value is the\n * exact on-chain vault amount, so it must equal the requested peg-in amount\n * (btc-vault: PegIn vout 0 carries `pegin_amount` verbatim). The P2A anchor\n * (exact value/vout/script for v2; complete absence for v1) is enforced by\n * the version-dispatched `validatePeginP2aAnchor`.\n *\n * @throws If the encoded outputs disagree with the metadata, the requested\n * amount, or the version's anchor rules.\n */\nasync function assertPeginTxShape(\n result: {\n txHex: string;\n txid: string;\n vaultScriptPubKey: string;\n vaultValue: bigint;\n },\n params: BuildPeginTxParams,\n): Promise<void> {\n const version = params.prePeginParams.vaultCoreVersion;\n\n await validatePeginP2aAnchor(version, result.txHex);\n\n const anchor = await peginP2aAnchorOutput(version);\n const expectedOutputCount = PEGIN_BASE_OUTPUT_COUNT + (anchor ? 1 : 0);\n\n const peginTx = Transaction.fromHex(stripHexPrefix(result.txHex));\n\n // Input bind: the PegIn must spend EXACTLY the requested HTLC outpoint\n // (fundedPrePeginTxid, htlcVout). Without this, a doctored tx could spend\n // a sibling HTLC while the caller registers it under `htlcVout` — in a\n // multi-HTLC batch that both double-spends the sibling and strands the\n // registered vault. The downstream PSBT builder follows the tx's own\n // input index, so this is the only place the requested vout is enforced.\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn tx has ${peginTx.ins.length} input(s), expected exactly 1 ` +\n `(the Pre-PegIn HTLC outpoint).`,\n );\n }\n const fundedPrePeginTxid = Transaction.fromHex(\n stripHexPrefix(params.fundedPrePeginTxHex),\n ).getId();\n const inputTxid = uint8ArrayToHex(\n new Uint8Array(peginTx.ins[0].hash).slice().reverse(),\n );\n if (inputTxid !== fundedPrePeginTxid) {\n throw new Error(\n `PegIn input spends txid ${inputTxid}, expected the funded Pre-PegIn ` +\n `${fundedPrePeginTxid}.`,\n );\n }\n if (peginTx.ins[0].index !== params.htlcVout) {\n throw new Error(\n `PegIn input spends Pre-PegIn output ${peginTx.ins[0].index}, ` +\n `expected the requested HTLC vout ${params.htlcVout}.`,\n );\n }\n\n if (peginTx.outs.length !== expectedOutputCount) {\n throw new Error(\n `PegIn tx has ${peginTx.outs.length} output(s), expected exactly ` +\n `${expectedOutputCount} for vaultCoreVersion ${version} (vault + ` +\n `depositor claim${anchor ? \" + P2A anchor\" : \"\"}).`,\n );\n }\n\n const requestedAmount =\n params.prePeginParams.pegInAmounts[params.htlcVout];\n if (result.vaultValue !== requestedAmount) {\n throw new Error(\n `PegIn vault output value ${result.vaultValue} does not match the ` +\n `requested peg-in amount ${requestedAmount} for HTLC ` +\n `${params.htlcVout}; refusing to sign a vault that locks a ` +\n `different amount than requested.`,\n );\n }\n\n const encodedVaultOut = peginTx.outs[0];\n if (BigInt(encodedVaultOut.value) !== result.vaultValue) {\n throw new Error(\n `Encoded PegIn vault output value ${encodedVaultOut.value} does not ` +\n `match the WASM-reported vaultValue ${result.vaultValue}.`,\n );\n }\n const encodedVaultScript = encodedVaultOut.script.toString(\"hex\");\n const expectedVaultScript = stripHexPrefix(\n result.vaultScriptPubKey,\n ).toLowerCase();\n if (encodedVaultScript.toLowerCase() !== expectedVaultScript) {\n throw new Error(\n `Encoded PegIn vault output scriptPubKey ${encodedVaultScript} does ` +\n `not match the WASM-reported vaultScriptPubKey ` +\n `${result.vaultScriptPubKey}.`,\n );\n }\n\n const encodedTxid = peginTx.getId();\n if (encodedTxid !== stripHexPrefix(result.txid).toLowerCase()) {\n throw new Error(\n `Encoded PegIn txid ${encodedTxid} does not match the WASM-reported ` +\n `txid ${result.txid}.`,\n );\n }\n\n // Depositor-claim output (vout 1): a doctored binary could burn the claim\n // into miner fee or redirect it while the vault, anchor, and txid binds\n // all pass. Bind its value to the independently recomputed minimum claim\n // value (the same WASM-vs-WASM identity `assertWasmPeginSizing` uses) and\n // its script to a fully JS-derived expectation. With the vault bind, the\n // output count, and value conservation against the validated HTLC input,\n // the implied fee is bound too.\n const expectedClaimValue = await computeMinClaimValue(\n version,\n params.prePeginParams.numLocalChallengers,\n params.prePeginParams.universalChallengerPubkeys.length,\n params.prePeginParams.councilQuorum,\n params.prePeginParams.councilSize,\n params.prePeginParams.feeRate,\n );\n const encodedClaimOut = peginTx.outs[PEGIN_DEPOSITOR_CLAIM_VOUT];\n if (BigInt(encodedClaimOut.value) !== expectedClaimValue) {\n throw new Error(\n `Encoded PegIn depositor-claim output value ${encodedClaimOut.value} ` +\n `does not match the independently computed claim value ` +\n `${expectedClaimValue} for vaultCoreVersion ${version}.`,\n );\n }\n\n const expectedClaimScript = deriveDepositorClaimScriptPubKey(\n params.prePeginParams.depositorPubkey,\n );\n if (!encodedClaimOut.script.equals(expectedClaimScript)) {\n throw new Error(\n `Encoded PegIn depositor-claim output scriptPubKey ` +\n `${encodedClaimOut.script.toString(\"hex\")} does not pay to the ` +\n `depositor's claim script (expected ` +\n `${expectedClaimScript.toString(\"hex\")}).`,\n );\n }\n}\n\n/**\n * Independently derive the PegIn depositor-claim output's scriptPubKey in\n * JS: a Taproot output with the NUMS internal key and a single\n * `<depositor> OP_CHECKSIG` leaf — btc-vault's `SingleKeyConnector`\n * (`crates/vault/src/connectors/mod.rs`, identical across graph versions).\n * Uses the same `tapInternalPubkey` NUMS constant the HTLC connector pins.\n */\nfunction deriveDepositorClaimScriptPubKey(depositorPubkey: string): Buffer {\n const claimLeafScript = bscript.compile([\n Buffer.from(hexToUint8Array(depositorPubkey)),\n opcodes.OP_CHECKSIG,\n ]);\n const { output } = payments.p2tr({\n internalPubkey: Buffer.from(tapInternalPubkey),\n scriptTree: { output: claimLeafScript },\n });\n if (!output) {\n throw new Error(\n \"Failed to derive the depositor-claim P2TR scriptPubKey for PegIn output validation\",\n );\n }\n return output;\n}\n","/**\n * Payout Script Generator Primitive\n *\n * This module provides pure functions for generating payout scripts and taproot information\n * by wrapping the WASM implementation from @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * The payout script is used for signing payout transactions in the vault system.\n * It defines the spending conditions for the vault output, enabling the depositor\n * to authorize payouts during the peg-in flow (Step 3).\n *\n * @remarks\n * This is a low-level primitive. For most use cases, prefer using {@link buildPayoutPsbt}\n * which handles script creation internally. For high-level wallet orchestration, use\n * PayoutManager from the managers module.\n *\n * @see {@link buildPayoutPsbt} - Higher-level function that uses this internally\n *\n * @module primitives/scripts/payout\n */\n\nimport {\n createPayoutConnector,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\n/**\n * Parameters for creating a payout script.\n *\n * These parameters define the participants in a vault and are used to generate\n * the taproot script that controls how funds can be spent from the vault.\n */\nexport interface PayoutScriptParams {\n /**\n * Vault core (tx-graph) version the vault was registered under — the\n * vault's stamped on-chain `vaultCoreVersion`. Selects which graph's\n * payout connector the WASM derives.\n */\n vaultCoreVersion: number;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * This is the user depositing BTC into the vault. The depositor must sign\n * payout transactions to authorize fund distribution.\n */\n depositor: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * The service provider managing vault operations. Also referred to as\n * \"claimer\" in the WASM layer.\n */\n vaultProvider: string;\n\n /**\n * Array of vault keeper BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * Vault keepers participate in vault operations and script spending conditions.\n */\n vaultKeepers: string[];\n\n /**\n * Array of universal challenger BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * These parties can challenge the vault under certain conditions.\n */\n universalChallengers: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network for script generation.\n *\n * Must match the network used for all other vault operations to ensure\n * address encoding compatibility.\n */\n network: Network;\n}\n\n/**\n * Result of creating a payout script.\n *\n * Contains all the taproot-related data needed for constructing and signing\n * payout transactions from the vault.\n */\nexport interface PayoutScriptResult {\n /**\n * The payout script hex used in taproot script path spending.\n *\n * This is the raw script bytes that define the spending conditions,\n * encoded as a hexadecimal string. Used when constructing the\n * tapLeafScript for PSBT signing.\n */\n payoutScript: string;\n\n /**\n * The taproot script hash (leaf hash) for the payout script.\n *\n * This is the tagged hash of the script used in taproot tree construction.\n * Required for computing the control block during script path spending.\n */\n taprootScriptHash: string;\n\n /**\n * The full scriptPubKey for the vault output address.\n *\n * This is the complete output script (OP_1 <32-byte-key>) that should be\n * used when creating the vault output in a peg-in transaction.\n */\n scriptPubKey: string;\n\n /**\n * The vault Bitcoin address derived from the script.\n *\n * A human-readable bech32m address (bc1p... for mainnet, tb1p... for testnet/signet)\n * that can be used to receive funds into the vault.\n */\n address: string;\n\n /**\n * Serialized control block for Taproot script path spend (hex encoded).\n *\n * Computed by the Rust WASM PeginPayoutConnector. Used directly in\n * tapLeafScript when building payout PSBTs.\n */\n payoutControlBlock: string;\n}\n\n/**\n * Create payout script and taproot information using WASM.\n *\n * This is a pure function that wraps the Rust WASM implementation.\n * The payout connector generates the necessary taproot scripts and information\n * required for signing payout transactions.\n *\n * @remarks\n * The generated script encodes spending conditions that require signatures from\n * the depositor and vault provider (or liquidators in challenge scenarios).\n * This script is used internally by {@link buildPayoutPsbt}.\n *\n * @param params - Payout script parameters defining vault participants and network\n * @returns Payout script and taproot information for PSBT construction\n *\n * @see {@link buildPayoutPsbt} - Use this for building complete payout PSBTs\n */\nexport async function createPayoutScript(\n params: PayoutScriptParams,\n): Promise<PayoutScriptResult> {\n // Call the WASM wrapper with the correct parameter structure\n const connector = await createPayoutConnector(\n {\n txGraphVersion: params.vaultCoreVersion,\n depositor: params.depositor,\n vaultProvider: params.vaultProvider,\n vaultKeepers: params.vaultKeepers,\n universalChallengers: params.universalChallengers,\n timelockPegin: params.timelockPegin,\n },\n params.network,\n );\n\n return {\n payoutScript: connector.payoutScript,\n taprootScriptHash: connector.taprootScriptHash,\n scriptPubKey: connector.scriptPubKey,\n address: connector.address,\n payoutControlBlock: connector.payoutControlBlock,\n };\n}\n","/**\n * Payout implicit-fee band validation (floor + ceiling).\n *\n * Bands the implicit fee of a VP-built payout transaction before the\n * depositor pre-signs it:\n * - Ceiling: the Ledger device's payout vsize model (`app-babylon-vault`\n * `sign_psbt_validate.c`, HLD v22 §4.9.7.1) extended by measured script\n * excess over its 34-byte assumption — blocks a VP deflating outputs and\n * burning the difference as miner fee.\n * - Floor: the minimum fee any known VP output-sizing model produces\n * (vault-wasm `computePayoutFeeFloor`) — a lower fee is provably\n * illegitimate and risks a payout that cannot relay at redemption time.\n *\n * Preconditions, enforced by the caller (`buildPayoutPsbt`):\n * - `assertPayoutFeeBandDomain` has accepted the rate and participant counts,\n * so the band runs exactly over the domain its dominance proof was swept.\n * - `out0Len` is the layout-trusted length of the PINNED outs[0] script.\n * `out1Len` is the VP commission output's length. RFC-006 pins that output\n * to the operator's registered scriptPubKey, so it is now layout-trusted\n * too and bounded to a standard type. It still feeds only the floor and\n * must never widen the ceiling: that separation is kept deliberately, so\n * the bound holds even if a future change unpins the output again.\n * - `implicitFeeSats` is `inputs − outputs` over verified prevouts, `>= 0`.\n *\n * @module primitives/psbt/assertPayoutFeeBand\n */\n\nimport { computePayoutFeeFloor } from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\n/**\n * Payout fee-bound vsize model: `maxVsize = BASE + PER_PARTICIPANT * (N + M)`\n * where N = vault keepers, M = universal challengers. Constants and comparison\n * match the Ledger device (`app-babylon-vault` `sign_psbt_validate.c`\n * MAX_PAYOUT_VSIZE_BASE/PER_PARTICIPANT; HLD v22 §4.9.7.1) — a conservative\n * upper estimate with ~13%+ headroom over the exact vsize the VP pays. For\n * payouts whose outs[0] script is <= 34 bytes our accept-set is a subset of\n * the device's: the device bound is FLAT (no script-excess term) and our fee\n * basis (true prevout fee; real graphs build Assert:0 as 546 + council fee)\n * is stricter than its `vault_amount + 546` proxy. A pinned outs[0] script\n * above 34 bytes extends our ceiling past the device's flat bound —\n * contract-legal, but such payouts cannot pass a device today (it also\n * hard-requires 34-byte output scripts).\n */\nconst MAX_PAYOUT_VSIZE_BASE = 500;\nconst MAX_PAYOUT_VSIZE_PER_PARTICIPANT = 55;\n\n/**\n * Inclusive range cap `[1, 0xffffffff]` for the tx-graph fee rate (sat/vB):\n * the device's intent parser rejects `base_fee_rate > UINT32_MAX`\n * (`vault_tlv.c` TAG_BASE_FEE_RATE). Mirroring it keeps our bound math in\n * safe integer range and refuses rates no device could ever approve.\n */\nconst MAX_BASE_FEE_RATE_SAT_PER_VB = 0xffffffffn;\n\n/**\n * Device cap on vault keeper and universal challenger counts (u8 fields,\n * each `[1, 32]` — `app-babylon-vault` `vault_intent.h`). Enforced at the\n * payout boundary so the fee-bound dominance proof's swept domain exactly\n * equals the accepted input domain.\n */\nconst MAX_PAYOUT_PARTICIPANTS_PER_ROLE = 32;\n\n/**\n * Per-output script length the device's flat payout fee bound implicitly\n * assumes (P2TR, 34 bytes). Measured non-anchor scripts above it extend the\n * ceiling linearly — the estimator's own growth rule — keeping device parity\n * for standard scripts and contract-correctness up to 128-byte ones.\n */\nconst PAYOUT_BOUND_ASSUMED_SCRIPT_LEN = 34;\n\n/** Shape/rate inputs the fee band is evaluated over. */\nexport interface PayoutFeeBandParams {\n /** Vault core (tx-graph) version — selects the floor's pinned model set. */\n vaultCoreVersion: number;\n /** Vault keeper count (N). */\n numVaultKeepers: number;\n /** Universal challenger count (M). */\n numUniversalChallengers: number;\n /** Security council size from the locked offchain params version. */\n councilSize: number;\n /** Version-locked tx-graph fee rate (sat/vB); anchors both band ends. */\n protocolFeeRate: bigint;\n}\n\n/**\n * Validate that the fee-band inputs lie in the proven/accepted domain:\n * `protocolFeeRate` in `[1, 0xffffffff]`, participant counts in `[1, 32]`,\n * `councilSize` a positive integer.\n *\n * @throws If `protocolFeeRate` is not a bigint within the device's range\n * @throws If a participant count is not an integer in the device range `[1, 32]`\n * @throws If `councilSize` is not an integer `>= 1` — the contract write path\n * (`ProtocolParams.sol`) rejects an empty council, and the WASM floor would\n * silently treat 0 as a 1-member council rather than erroring\n */\nexport function assertPayoutFeeBandDomain(params: PayoutFeeBandParams): void {\n // Fail fast on a rate the device's own parser would reject — also keeps the\n // fee-bound product within safe integer range.\n if (\n typeof params.protocolFeeRate !== \"bigint\" ||\n params.protocolFeeRate <= 0n ||\n params.protocolFeeRate > MAX_BASE_FEE_RATE_SAT_PER_VB\n ) {\n throw new Error(\n `protocolFeeRate must be in [1, ${MAX_BASE_FEE_RATE_SAT_PER_VB}] sat/vB, ` +\n `got ${params.protocolFeeRate}`,\n );\n }\n // Device participant range ([1, 32] per role, vault_intent.h) — also pins\n // the fee band to the domain its dominance proof was swept over\n // (accepted domain == proven domain).\n for (const [role, count] of [\n [\"keepers\", params.numVaultKeepers],\n [\"challengers\", params.numUniversalChallengers],\n ] as const) {\n if (\n !Number.isInteger(count) ||\n count < 1 ||\n count > MAX_PAYOUT_PARTICIPANTS_PER_ROLE\n ) {\n throw new Error(\n `Participant count for ${role} (${count}) is outside the device ` +\n `range [1, ${MAX_PAYOUT_PARTICIPANTS_PER_ROLE}].`,\n );\n }\n }\n // councilSize crosses the WASM boundary with no glue-side validation; a\n // non-integer would silently truncate at the u32 ABI and a 0 would be\n // silently promoted to a 1-member council by the pinned estimator.\n if (!Number.isInteger(params.councilSize) || params.councilSize < 1) {\n throw new Error(\n `councilSize must be an integer >= 1, got ${params.councilSize}`,\n );\n }\n}\n\n/**\n * Assert `floor <= implicitFeeSats <= ceiling` for a payout of this shape.\n * `out1Len` is `undefined` for the 2-output (no-commission) layouts.\n *\n * @throws If the fee is below the floor or above the extended device ceiling\n */\nexport async function assertPayoutFeeInBand(\n params: PayoutFeeBandParams,\n measured: {\n implicitFeeSats: number;\n out0Len: number;\n out1Len: number | undefined;\n },\n): Promise<void> {\n const { implicitFeeSats, out0Len, out1Len } = measured;\n const numParticipants =\n params.numVaultKeepers + params.numUniversalChallengers;\n const implicitFee = BigInt(implicitFeeSats);\n\n // Ceiling first: synchronous arithmetic, no WASM round-trip.\n // Only outs[0] extends the ceiling; out1Len never does. RFC-006 now pins the\n // commission script, so a padded one can no longer reach here — but the\n // separation is kept so the bound does not silently depend on that pin.\n // Including out1Len would let a padded script widen the burnable band by up\n // to 94 vB x rate. Honest long-commission builds still fit: the flat model's\n // >=175 vB headroom over the exact estimator vsize absorbs the 94 vB with\n // >=81 vB to spare across the entire accepted domain.\n const scriptExcess = Math.max(0, out0Len - PAYOUT_BOUND_ASSUMED_SCRIPT_LEN);\n const maxPayoutVsize =\n MAX_PAYOUT_VSIZE_BASE +\n MAX_PAYOUT_VSIZE_PER_PARTICIPANT * numParticipants +\n scriptExcess;\n const maxFeeSats = params.protocolFeeRate * BigInt(maxPayoutVsize);\n if (implicitFee > maxFeeSats) {\n throw new Error(\n `Payout implicit fee ${implicitFeeSats} sats exceeds the safety cap ` +\n `of ${maxFeeSats} sats (${params.protocolFeeRate} sat/vB x ` +\n `${maxPayoutVsize} vB for ${numParticipants} ` +\n `participants); refusing to sign payout.`,\n );\n }\n\n // Local challengers are exactly the keeper count for every claimer role\n // (btc-vault graph.rs derive_challengers: VKs, or VP + N-1 VKs).\n // TODO: memoize if keeper counts grow enough for batch flows to feel it.\n const minFeeSats = await computePayoutFeeFloor(\n params.vaultCoreVersion,\n params.numVaultKeepers,\n params.numUniversalChallengers,\n params.numVaultKeepers,\n params.councilSize,\n out0Len,\n out1Len,\n params.protocolFeeRate,\n );\n if (implicitFee < minFeeSats) {\n throw new Error(\n `Payout implicit fee ${implicitFeeSats} sats is below the floor of ` +\n `${minFeeSats} sats (the smallest fee any known vault-provider ` +\n `build produces for this shape); refusing to sign payout.`,\n );\n }\n}\n","/**\n * Standard-scriptPubKey validation for registry-supplied payout destinations.\n *\n * RFC-006 lets an operator register an arbitrary payout scriptPubKey, so the\n * bytes we pin a `PayoutTx` output against are now chosen by that operator\n * rather than derived by us. Pinning an output to them without checking the\n * shape would let a keeper that registered a garbage or unspendable script get\n * the depositor to pre-sign a payout nobody can ever claim.\n *\n * This bound is ours alone — it is deliberately NOT parity with `vaultd`.\n * `vaultd` uses registry scripts verbatim at graph-build time and documents\n * why: applying a predicate the contract does not apply would block every\n * peg-in for an operator the instant the two disagreed. The registry itself\n * only bounds length to 1..128 bytes, and the registration CLI has an\n * `--allow-non-standard` escape hatch.\n *\n * We hold the stricter line because we occupy a different position: we are the\n * party being asked to *pre-sign* against these bytes, and a depositor\n * signature pinned to a provably unspendable output is not recoverable. The\n * bound is also load-bearing for the payout fee band — capping a standard\n * output at 34 bytes is what lets `assertPayoutFeeBand` reason about `outs[1]`\n * without a separate length cap.\n *\n * The deliberate consequence: an operator that registers a non-standard script\n * via `--allow-non-standard` can have its graphs built by `vaultd` and still be\n * refused here, blocking deposits against that operator in this dApp. That is\n * fail-closed by choice — the alternative is pre-signing into a destination we\n * cannot verify is spendable.\n *\n * @module primitives/psbt/standardPayoutScript\n */\n\nimport { stripHexPrefix } from \"../utils/bitcoin\";\n\n/** `OP_0 <20>` — P2WPKH. */\nconst P2WPKH_LEN = 22;\n/** `OP_0 <32>` — P2WSH. */\nconst P2WSH_LEN = 34;\n/** `OP_1 <32>` — P2TR. */\nconst P2TR_LEN = 34;\n/** `OP_DUP OP_HASH160 <20> OP_EQUALVERIFY OP_CHECKSIG` — P2PKH. */\nconst P2PKH_LEN = 25;\n/** `OP_HASH160 <20> OP_EQUAL` — P2SH. */\nconst P2SH_LEN = 23;\n\nfunction isP2wpkh(s: string): boolean {\n return s.length === P2WPKH_LEN * 2 && s.startsWith(\"0014\");\n}\nfunction isP2wsh(s: string): boolean {\n return s.length === P2WSH_LEN * 2 && s.startsWith(\"0020\");\n}\nfunction isP2tr(s: string): boolean {\n return s.length === P2TR_LEN * 2 && s.startsWith(\"5120\");\n}\nfunction isP2pkh(s: string): boolean {\n return (\n s.length === P2PKH_LEN * 2 && s.startsWith(\"76a914\") && s.endsWith(\"88ac\")\n );\n}\nfunction isP2sh(s: string): boolean {\n return s.length === P2SH_LEN * 2 && s.startsWith(\"a914\") && s.endsWith(\"87\");\n}\n\n/**\n * Assert a registry-supplied scriptPubKey is a standard, spendable output type\n * (P2TR, P2WPKH, P2WSH, P2PKH, or P2SH).\n *\n * Rejects empty scripts, `OP_RETURN` (provably unspendable), and anything else\n * that is not one of the five standard forms. `label` names the source in the\n * error, e.g. `vault keeper payout script (admin=0x…)`.\n */\nexport function assertStandardPayoutScript(\n scriptHex: string,\n label: string,\n): void {\n const script = stripHexPrefix(scriptHex).toLowerCase();\n\n if (script.length === 0) {\n throw new Error(`${label} is empty`);\n }\n if (!/^[0-9a-f]+$/.test(script) || script.length % 2 !== 0) {\n throw new Error(`${label} is not valid hex`);\n }\n if (script.startsWith(\"6a\")) {\n throw new Error(\n `${label} is an OP_RETURN output, which is provably unspendable`,\n );\n }\n\n if (\n !isP2tr(script) &&\n !isP2wpkh(script) &&\n !isP2wsh(script) &&\n !isP2pkh(script) &&\n !isP2sh(script)\n ) {\n throw new Error(\n `${label} is not a standard scriptPubKey ` +\n `(expected P2TR, P2WPKH, P2WSH, P2PKH, or P2SH; got ${script.length / 2} bytes: ${script})`,\n );\n }\n}\n","/**\n * Payout PSBT Builder Primitives\n *\n * This module provides pure functions for building unsigned payout PSBTs and extracting\n * Schnorr signatures from signed PSBTs. It uses WASM-generated scripts from the payout\n * connector and bitcoinjs-lib for PSBT construction.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @module primitives/psbt/payout\n */\n\nimport {\n type Network,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Psbt, Transaction, type TxInput, type TxOutput } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport { createPayoutScript } from \"../scripts/payout\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n isValidHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport {\n assertPayoutFeeBandDomain,\n assertPayoutFeeInBand,\n} from \"./assertPayoutFeeBand\";\nimport {\n ASSERT_PAYOUT_OUTPUT_INDEX,\n BPS_DENOMINATOR,\n DEPOSITOR_PAYOUT_INPUT_COUNT,\n MAX_PAYOUT_SCRIPT_LEN,\n MAX_VP_COMMISSION_BPS_EXCLUSIVE,\n NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT,\n PAYOUT_ANCHOR_DUST_SATS,\n PEGIN_VAULT_OUTPUT_INDEX,\n VP_CLAIMER_PAYOUT_OUTPUT_COUNT,\n} from \"./constants\";\nimport { assertStandardPayoutScript } from \"./standardPayoutScript\";\n\n/**\n * Number of items in a Taproot script-path spend witness stack for a\n * single-signature script: [signature, script, controlBlock].\n *\n * The current payout script requires exactly one depositor signature. If the\n * protocol evolves to require multiple signatures in the payout script, this\n * invariant and the finalized-PSBT extraction path must be revisited because\n * the first witness item would no longer necessarily be the depositor's.\n */\nconst TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE = 3;\n\n/**\n * Parameters for building an unsigned Payout PSBT\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface PayoutParams {\n /**\n * Vault core (tx-graph) version the vault was registered under — the\n * vault's stamped on-chain `vaultCoreVersion`. Selects which graph's\n * payout connector scripts are derived.\n */\n vaultCoreVersion: number;\n\n /**\n * Payout transaction hex (unsigned)\n * This is the transaction that needs to be signed by the depositor\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex\n * Payout input 1 references Assert output 0\n */\n assertTxHex: string;\n\n /**\n * Peg-in transaction hex\n * This transaction created the vault output that we're spending\n */\n peginTxHex: string;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix)\n */\n depositorBtcPubkey: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex)\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex)\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex)\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network\n */\n network: Network;\n\n /**\n * Claimer's x-only BTC public key (64-char hex, no prefix). Drives role\n * inference (VP / depositor-as-claimer / VK-claimer) inside `buildPayoutPsbt`.\n */\n claimerBtcPubkey: string;\n\n /**\n * On-chain registered depositor payout scriptPubKey (hex, 0x optional).\n * Expected outs[0].script for VP- and depositor-claimer roles; unused for\n * VK-claimer (its outs[0].script is derived from `claimerBtcPubkey`).\n */\n registeredPayoutScriptPubKey: string;\n\n /**\n * VP commission in basis points (`BTCVaultRegistry.vaultProviderCommissionBps`).\n * Caps the VP-claimer outs[1].value. The protocol minimum is enforced\n * upstream; here only `0 <= bps < 10_000` is checked, for safe cap math.\n */\n commissionBps: number;\n\n /**\n * Tx-graph fee rate (sat/vB) the graph was built with — the version-locked\n * `offchainParams.feeRate` at the vault's stamped `offchainParamsVersion`,\n * NOT a live read. Anchors both ends of the fee band.\n */\n protocolFeeRate: bigint;\n\n /**\n * Security council member count from the locked offchain params version.\n * Mirrors the upstream estimator's signature; at the current model pins the\n * council occupies a single taptree leaf regardless of size, so the floor\n * is council-size-invariant — passed for forward compatibility with future\n * pinned models.\n */\n councilSize: number;\n\n /**\n * RFC-006. Expected `outs[0].script` per vault-keeper claimer, keyed by\n * lowercased x-only **operation** pubkey (no `0x`), resolved from\n * `ApplicationRegistry.getPayoutScriptAtEpoch` at the vault's frozen\n * `appKeeperKeyEpoch`.\n *\n * Every VK claimer must be present: a claimer missing from the map is an\n * error rather than a cue to derive BIP-86, because a gap means resolution\n * was incomplete and we do not know what that keeper registered.\n *\n * Each entry accepts either that registered script or the BIP-86 default of\n * the same bonded key, so graphs built before btc-vault#2440 remain signable\n * — see {@link acceptedPayoutScriptHexes} for why that is required and when\n * it can be dropped.\n */\n vkClaimerPayoutScriptPubKeys: Readonly<Record<string, string>>;\n\n /**\n * RFC-006. Expected `outs[1].script` for the VP-claimer commission output,\n * from `BTCVaultRegistry.getPayoutScriptAtEpoch` at the vault's frozen\n * `vpKeyEpoch`. The BIP-86 default of the bonded VP key is accepted alongside\n * it — see {@link acceptedPayoutScriptHexes}.\n */\n vpCommissionScriptPubKey: string;\n}\n\n/**\n * Result of building an unsigned payout PSBT\n */\nexport interface PayoutPsbtResult {\n /**\n * Unsigned PSBT hex ready for signing\n */\n psbtHex: string;\n}\n\n/**\n * Build unsigned Payout PSBT for depositor to sign.\n *\n * Payout is used in the **challenge path** when the claimer proves validity:\n * 1. Vault provider submits Claim transaction\n * 2. Challenge is raised during challenge period\n * 3. Claimer submits Assert transaction to prove validity\n * 4. Payout can be executed (references Assert tx)\n *\n * Payout transactions have the following structure:\n * - Input 0: from PeginTx output0 (signed by depositor)\n * - Input 1: from Assert output0 (NOT signed by depositor)\n *\n * @param params - Payout parameters\n * @returns Unsigned PSBT ready for depositor to sign\n *\n * @throws If payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not spend PegIn:0 (vault UTXO)\n * @throws If input 1 does not spend Assert:0 (proof output)\n * @throws If previous output is not found for either input\n * @throws If sum of output values exceeds sum of input values (invalid tx)\n * @throws If the implicit fee (inputs − outputs) is outside the fee band —\n * below the floor or above the extended device ceiling (see\n * {@link assertPayoutFeeInBand})\n * @throws If `protocolFeeRate`, a participant count, or `councilSize` is\n * outside the accepted input domain (see {@link assertPayoutFeeBandDomain})\n * @throws If a non-anchor scriptPubKey length is outside `[1,\n * {@link MAX_PAYOUT_SCRIPT_LEN}]`\n * @throws If `claimerBtcPubkey` is not VP, depositor, or a registered VK\n * @throws If payout output count, outs[0] script, outs[last] anchor value, or\n * (VP-claimer) outs[1] commission cap do not match the protocol layout\n * @throws If `commissionBps` is not a non-negative integer below 10_000\n */\nexport async function buildPayoutPsbt(\n params: PayoutParams,\n): Promise<PayoutPsbtResult> {\n const feeBandParams = {\n vaultCoreVersion: params.vaultCoreVersion,\n numVaultKeepers: params.vaultKeeperBtcPubkeys.length,\n numUniversalChallengers: params.universalChallengerBtcPubkeys.length,\n councilSize: params.councilSize,\n protocolFeeRate: params.protocolFeeRate,\n };\n assertPayoutFeeBandDomain(feeBandParams);\n\n const payoutTx = Transaction.fromHex(stripHexPrefix(params.payoutTxHex));\n const peginTx = Transaction.fromHex(stripHexPrefix(params.peginTxHex));\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n\n if (payoutTx.ins.length !== DEPOSITOR_PAYOUT_INPUT_COUNT) {\n throw new Error(\n `Payout transaction must have exactly ${DEPOSITOR_PAYOUT_INPUT_COUNT} ` +\n `inputs, got ${payoutTx.ins.length}`,\n );\n }\n const peginPrevOut = requirePrevOut(\n payoutTx.ins[0],\n 0,\n peginTx,\n \"PegIn\",\n PEGIN_VAULT_OUTPUT_INDEX,\n );\n const assertPrevOut = requirePrevOut(\n payoutTx.ins[1],\n 1,\n assertTx,\n \"Assert\",\n ASSERT_PAYOUT_OUTPUT_INDEX,\n );\n // Assert:0's value is deliberately NOT validated: the taproot sighash\n // commits to input 1's amount and outpoint, so a misstated value yields a\n // signature invalid against the real Assert tx — nothing to protect. (The\n // device's ==546 pin here is the known-buggy firmware behavior, Q15.)\n\n // Per-role output validation — blocks an extra attacker output or value\n // routed into a non-payout slot. Returns the layout-trusted script lengths\n // the fee band consumes.\n const { out0Len, out1Len } = assertPayoutOutputLayout(\n payoutTx,\n peginPrevOut.value,\n params,\n );\n\n const inputValueSats = peginPrevOut.value + assertPrevOut.value;\n let outputValueSats = 0;\n for (const out of payoutTx.outs) outputValueSats += out.value;\n if (outputValueSats > inputValueSats) {\n throw new Error(\n `Payout outputs (${outputValueSats} sats) exceed inputs ` +\n `(${inputValueSats} sats); invalid transaction.`,\n );\n }\n const implicitFeeSats = inputValueSats - outputValueSats;\n await assertPayoutFeeInBand(feeBandParams, {\n implicitFeeSats,\n out0Len,\n out1Len,\n });\n\n // Only assembly needs the WASM-derived script — derive it after the\n // transaction has passed every validation gate.\n const payoutConnector = await createPayoutScript({\n vaultCoreVersion: params.vaultCoreVersion,\n depositor: params.depositorBtcPubkey,\n vaultProvider: params.vaultProviderBtcPubkey,\n vaultKeepers: params.vaultKeeperBtcPubkeys,\n universalChallengers: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: params.network,\n });\n\n return {\n psbtHex: assemblePayoutPsbt(\n payoutTx,\n peginPrevOut,\n assertPrevOut,\n payoutConnector,\n ),\n };\n}\n\n/**\n * Verify `payoutTx.ins[inputIndex]` spends `parentTx:expectedVout` (both txid\n * AND vout — the vout is the input-side anchor that prevents a malicious VP\n * from binding the depositor's signature to a different output of the same\n * parent) and return the referenced previous output.\n *\n * @internal Helper invoked by {@link buildPayoutPsbt}.\n */\nfunction requirePrevOut(\n input: TxInput,\n inputIndex: number,\n parentTx: Transaction,\n parentLabel: string,\n expectedVout: number,\n): TxOutput {\n const inputTxid = uint8ArrayToHex(\n new Uint8Array(input.hash).slice().reverse(),\n );\n const parentTxid = parentTx.getId();\n if (inputTxid !== parentTxid || input.index !== expectedVout) {\n throw new Error(\n `Input ${inputIndex} must spend ${parentLabel}:${expectedVout}. ` +\n `Expected ${parentTxid}:${expectedVout}, got ${inputTxid}:${input.index}`,\n );\n }\n const prevOut = parentTx.outs[input.index];\n if (!prevOut) {\n throw new Error(\n `Previous output not found for input ${inputIndex} ` +\n `(txid: ${inputTxid}, index: ${input.index})`,\n );\n }\n return prevOut;\n}\n\n/**\n * Assemble the unsigned PSBT from the validated payout transaction.\n *\n * IMPORTANT: For Taproot SIGHASH_DEFAULT (0x00), the sighash commits to ALL\n * inputs' prevouts, not just the one being signed — both inputs must be in\n * the PSBT so the wallet computes the sighash the VP expects.\n *\n * @internal Helper invoked by {@link buildPayoutPsbt}.\n */\nfunction assemblePayoutPsbt(\n payoutTx: Transaction,\n peginPrevOut: TxOutput,\n assertPrevOut: TxOutput,\n payoutConnector: { payoutScript: string; payoutControlBlock: string },\n): string {\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n const [input0, input1] = payoutTx.ins;\n\n // Input 0: depositor signs via Taproot script path — carries tapLeafScript.\n psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(payoutConnector.payoutScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(payoutConnector.payoutControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n // Input 1: from Assert — witnessUtxo only (in sighash, not signed by the\n // depositor), so no tapLeafScript.\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n });\n\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * The scriptPubKeys a payout output may legitimately pay for `bondedPubkey`.\n *\n * ## What this is\n *\n * A deliberate dual-accept: both the operator's RFC-006 **registered** payout\n * script and the **BIP-86 default** of its bonded operation key are treated as\n * valid destinations for the same output.\n *\n * ## Why both forms exist\n *\n * A vault provider running a daemon that predates btc-vault#2440 computes\n * operator payout destinations itself, via BIP-86 over the bonded operation\n * key. From #2440 onward it reads them from the registry instead\n * (`getPayoutScriptAtEpoch`), so an operator can point payouts at cold custody.\n *\n * The two forms are not a transition state that resolves on its own. A payout\n * graph is built once, at BaBe Setup, and is **never rebuilt** — so a vault\n * whose graph was built before its network's #2440 upgrade pays BIP-86 for the\n * rest of its life. Accepting only the registered form makes every such vault\n * permanently unsignable: the depositor can never complete the deposit, and\n * the BTC is already committed by then. Confirmed on devnet 2026-08-04, where\n * a pre-upgrade vault failed exactly this way.\n *\n * ## Why this is not a weakening\n *\n * Both candidates are derived here from on-chain state — the registry read and\n * a local BIP-86 derivation over the bonded key. Neither is taken from the VP's\n * response, so a substituted or attacker-chosen script still fails.\n *\n * The only substitution this permits is between two destinations the *same\n * operator* already controls, which moves that operator's own funds between its\n * own addresses. It cannot redirect value to a third party, and it cannot touch\n * the depositor's output. For the VP commission the value cap\n * (`floor(peginValue × commissionBps / 10_000)`) still bounds depositor\n * exposure independently of where the commission goes. The BIP-86 branch is\n * also precisely what every pre-RFC-006 client pinned, so this is the older\n * rule retained alongside the newer one, not a laxer rule invented for it.\n *\n * ## When this can be removed\n *\n * This validation runs at one point in the lifecycle: depositor payout signing\n * (`PENDING` → `VERIFIED`). It is not re-run on refund or withdrawal. So the\n * BIP-86 branch stops being reachable for a network once every vault\n * registered before that network's #2440 upgrade has left\n * `PendingDepositorSignatures` — signed and activated, or expired past its\n * activation deadline. That is bounded by the vault lifetime, not indefinite.\n *\n * Removal is therefore gated by the **last** network to upgrade, since this\n * code is shared. Concretely: drop the BIP-86 branch only once devnet, testnet\n * and mainnet have all been on #2440 for longer than the activation deadline,\n * and no vault registered before those upgrades is still awaiting signatures.\n * Deleting it earlier strands deposits with BTC already locked; there is no\n * recovery path short of the refund timelock.\n *\n * @internal Helper invoked by {@link assertPayoutOutputLayout}.\n */\nfunction acceptedPayoutScriptHexes(\n registeredScriptPubKey: string,\n bondedPubkey: string,\n): string[] {\n const registered = stripHexPrefix(registeredScriptPubKey).toLowerCase();\n const legacyBip86 = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(bondedPubkey),\n ).toLowerCase();\n return registered === legacyBip86 ? [registered] : [registered, legacyBip86];\n}\n\n/** Whether `script` matches any of `acceptedHexes`. */\nfunction matchesAnyScript(script: Buffer, acceptedHexes: string[]): boolean {\n return acceptedHexes.some((hex) => script.equals(Buffer.from(hex, \"hex\")));\n}\n\n/**\n * Validate a payout transaction's output structure for the claimer's role,\n * keyed on `claimerBtcPubkey`. Pins per role: `outs.length`, `outs[0].script`,\n * `outs[last].value` (anchor dust), and (VP-claimer) `outs[1].value` capped at\n * `floor(peginValue × commissionBps / 10_000)`. Canonical layouts: VP-claimer\n * = [payout, commission, anchor]; depositor/VK-claimer = [payout, anchor].\n *\n * `outs[last].script` (the CPFP anchor) is intentionally not pinned: the value\n * pin above bounds depositor exposure regardless of where that dust goes.\n *\n * `outs[1].script` (the VP commission) was unpinned for the same reason.\n * RFC-006 supersedes that rationale: the commission destination is now an\n * operator-registered scriptPubKey we can resolve independently at the vault's\n * frozen `vpKeyEpoch`, so when `vpCommissionScriptPubKey` is supplied it is\n * pinned too. The value cap stays — it is still what bounds exposure — and the\n * script pin is added precision, not a replacement for it.\n *\n * Returns the layout-trusted non-anchor script lengths for the fee band:\n * `out0Len` from the pinned outs[0] script (registered payout script, or\n * derived BIP-86 for the VK-claimer role — see #2150 Stage 6 for the pending\n * registered-script switch); `out1Len` measured from the deliberately\n * unpinned VP-claimer commission output, `undefined` for the other roles.\n * Both are rejected outside the contract's registration cap `[1, 128]`.\n *\n * @internal Helper invoked by {@link buildPayoutPsbt}.\n */\nfunction assertPayoutOutputLayout(\n payoutTx: Transaction,\n peginValueSats: number,\n params: PayoutParams,\n): { out0Len: number; out1Len: number | undefined } {\n const {\n claimerBtcPubkey,\n vaultProviderBtcPubkey,\n depositorBtcPubkey,\n vaultKeeperBtcPubkeys,\n registeredPayoutScriptPubKey,\n commissionBps,\n vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey,\n } = params;\n\n if (!isValidHex(registeredPayoutScriptPubKey)) {\n throw new Error(\"Invalid registeredPayoutScriptPubKey: not valid hex\");\n }\n\n const claimer = stripHexPrefix(claimerBtcPubkey).toLowerCase();\n const vp = stripHexPrefix(vaultProviderBtcPubkey).toLowerCase();\n const dep = stripHexPrefix(depositorBtcPubkey).toLowerCase();\n const keepers = vaultKeeperBtcPubkeys.map((k) =>\n stripHexPrefix(k).toLowerCase(),\n );\n\n type Role = \"vp-claimer\" | \"depositor-as-claimer\" | \"vk-claimer\";\n let role: Role;\n let expectedOutCount: number;\n let acceptedOut0ScriptHexes: string[];\n\n if (claimer === vp) {\n role = \"vp-claimer\";\n expectedOutCount = VP_CLAIMER_PAYOUT_OUTPUT_COUNT;\n acceptedOut0ScriptHexes = [stripHexPrefix(registeredPayoutScriptPubKey)];\n } else if (claimer === dep) {\n role = \"depositor-as-claimer\";\n expectedOutCount = NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT;\n acceptedOut0ScriptHexes = [stripHexPrefix(registeredPayoutScriptPubKey)];\n } else if (keepers.includes(claimer)) {\n role = \"vk-claimer\";\n expectedOutCount = NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT;\n // RFC-006: a keeper's payout goes to the scriptPubKey it registered\n // on-chain, resolved at the vault's frozen keeper epoch. Deriving BIP-86\n // locally as the sole expectation would reject a valid payout the moment a\n // keeper points its payouts at cold custody.\n //\n // A missing entry is an error, never a BIP-86 fallback: the registry\n // backfills BIP-86 itself for keepers that never registered a script, so a\n // gap here means the resolution was incomplete, not that this keeper is on\n // the default.\n const registered = vkClaimerPayoutScriptPubKeys[claimer];\n if (registered === undefined) {\n throw new Error(\n `No registered payout script resolved for vault keeper claimer ${claimer}`,\n );\n }\n assertStandardPayoutScript(\n registered,\n `Vault keeper payout script for claimer ${claimer}`,\n );\n acceptedOut0ScriptHexes = acceptedPayoutScriptHexes(registered, claimer);\n } else {\n throw new Error(\n `Unknown claimer pubkey ${claimer}: not VP, depositor, or a registered vault keeper`,\n );\n }\n\n if (payoutTx.outs.length !== expectedOutCount) {\n throw new Error(\n `Payout transaction has ${payoutTx.outs.length} output(s), ` +\n `expected exactly ${expectedOutCount} for role ${role}.`,\n );\n }\n\n if (!matchesAnyScript(payoutTx.outs[0].script, acceptedOut0ScriptHexes)) {\n throw new Error(\n `Payout transaction output 0 does not pay the expected scriptPubKey for role ${role}. ` +\n `Accepted: ${acceptedOut0ScriptHexes.join(\" or \")}; ` +\n `got ${payoutTx.outs[0].script.toString(\"hex\")}`,\n );\n }\n\n const anchorIdx = expectedOutCount - 1;\n if (payoutTx.outs[anchorIdx].value !== PAYOUT_ANCHOR_DUST_SATS) {\n throw new Error(\n `Payout CPFP anchor (out ${anchorIdx}) value ${payoutTx.outs[anchorIdx].value} sats ` +\n `must equal ${PAYOUT_ANCHOR_DUST_SATS} sats`,\n );\n }\n\n if (role === \"vp-claimer\") {\n // RFC-006 commission destination. Checked before the value cap so a\n // substituted destination reports as such rather than surfacing later as a\n // confusing amount error.\n assertStandardPayoutScript(\n vpCommissionScriptPubKey,\n \"Vault provider commission payout script\",\n );\n const acceptedCommissionScriptHexes = acceptedPayoutScriptHexes(\n vpCommissionScriptPubKey,\n vp,\n );\n if (\n !matchesAnyScript(payoutTx.outs[1].script, acceptedCommissionScriptHexes)\n ) {\n throw new Error(\n `Payout transaction output 1 does not pay the vault provider's commission scriptPubKey. ` +\n `Accepted: ${acceptedCommissionScriptHexes.join(\" or \")}; ` +\n `got ${payoutTx.outs[1].script.toString(\"hex\")}`,\n );\n }\n\n // Structural guard only — a non-negative integer below the bps\n // denominator, so the cap math `floor(peginValue * bps / 10_000)` is\n // meaningful. The protocol minimum is enforced at the trust boundary\n // (`prepareSigningContext`); a too-low value here is fail-safe.\n if (\n !Number.isInteger(commissionBps) ||\n commissionBps < 0 ||\n commissionBps >= MAX_VP_COMMISSION_BPS_EXCLUSIVE\n ) {\n throw new Error(\n `commissionBps must be an integer in ` +\n `[0, ${MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${commissionBps}`,\n );\n }\n const maxCommissionSats = Math.floor(\n (peginValueSats * commissionBps) / BPS_DENOMINATOR,\n );\n if (payoutTx.outs[1].value > maxCommissionSats) {\n throw new Error(\n `Payout VP commission (out 1) value ${payoutTx.outs[1].value} sats ` +\n `exceeds cap ${maxCommissionSats} sats ` +\n `(${commissionBps} bps of peginValue=${peginValueSats})`,\n );\n }\n }\n\n // The accepted-script set can hold more than one candidate (dual-accept), so\n // the length the fee band consumes is that of the output actually present —\n // which the check above has already pinned to one of the accepted values.\n const out0Len = payoutTx.outs[0].script.length;\n if (out0Len === 0 || out0Len > MAX_PAYOUT_SCRIPT_LEN) {\n throw new Error(\n `Payout receiver scriptPubKey length ${out0Len} is outside the ` +\n `contract's registration cap [1, ${MAX_PAYOUT_SCRIPT_LEN}]; ` +\n `refusing to sign payout.`,\n );\n }\n // No length cap on outs[1]: under RFC-006 the commission output is pinned to\n // the operator's registered script, and `assertStandardPayoutScript` above\n // already bounds that to a standard type (34 bytes at most). A separate\n // 128-byte cap here would be unreachable. Still measured, because the fee\n // floor consumes it — and now from a pinned source rather than a\n // VP-controlled one.\n const out1Len =\n role === \"vp-claimer\" ? payoutTx.outs[1].script.length : undefined;\n\n return { out0Len, out1Len };\n}\n\n/**\n * Extract Schnorr signature from signed payout PSBT.\n *\n * This function supports two cases:\n * 1. Non-finalized PSBT: Extracts from tapScriptSig field\n * 2. Finalized PSBT: Extracts from witness data\n *\n * The signature is returned as a 64-byte hex string (128 hex characters).\n * Payout signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's public key (x-only, 64-char hex)\n * @param inputIndex - Input index to extract signature from (default: 0)\n * @returns 64-byte Schnorr signature (128 hex characters, no sighash flag)\n *\n * @throws If no signature is found in the PSBT\n * @throws If the signature has an unexpected length\n */\nexport function extractPayoutSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n inputIndex = 0,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n\n if (inputIndex >= signedPsbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${signedPsbt.data.inputs.length} inputs)`,\n );\n }\n\n const input = signedPsbt.data.inputs[inputIndex];\n\n // Case 1: Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = hexToUint8Array(depositorPubkey);\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(Buffer.from(depositorPubkeyBytes))) {\n return extractSchnorrSig(sigEntry.signature, inputIndex);\n }\n }\n\n throw new Error(\n `No signature found for depositor pubkey: ${depositorPubkey} at input ${inputIndex}`,\n );\n }\n\n // Case 2: Finalized PSBT — extract from finalScriptWitness\n // Taproot single-signature script-path witness: [signature, script, controlBlock].\n // Enforce the exact stack size so that if a wallet produces an unexpected\n // finalization (e.g. a multi-signature stack, an annex, or malformed data),\n // we fail loudly instead of silently returning witnessStack[0] which may\n // not be the depositor's signature.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n const witnessStack = parseWitnessStack(input.finalScriptWitness);\n if (witnessStack.length !== TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE) {\n throw new Error(\n `Unexpected finalized witness stack size at input ${inputIndex}: ` +\n `expected ${TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE} items (signature, script, controlBlock), ` +\n `got ${witnessStack.length}`,\n );\n }\n return extractSchnorrSig(witnessStack[0], inputIndex);\n }\n\n throw new Error(\n `No tapScriptSig or finalScriptWitness found in signed PSBT at input ${inputIndex}`,\n );\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * Rejects 65-byte signatures because the appended sighash byte changes the\n * Taproot message being signed; stripping it would produce an unverifiable\n * SIGHASH_DEFAULT signature.\n * @internal\n */\nfunction extractSchnorrSig(sig: Uint8Array, inputIndex: number): 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\")} at input ${inputIndex}. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(\n `Unexpected signature length at input ${inputIndex}: ${sig.length}`,\n );\n}\n\n/**\n * Parse a BIP-141 serialized witness stack into individual stack items.\n * Format: [varint item_count] [varint len, data]...\n *\n * Throws on malformed input (truncated buffer, 8-byte varints, or trailing\n * bytes) so callers never receive silently-corrupted witness items.\n * @internal\n */\nfunction parseWitnessStack(witness: Buffer): Buffer[] {\n const items: Buffer[] = [];\n let offset = 0;\n\n const requireBytes = (n: number): void => {\n if (offset + n > witness.length) {\n throw new Error(\n `Malformed witness data: need ${n} byte(s) at offset ${offset}, only ${witness.length - offset} remaining`,\n );\n }\n };\n\n const readVarInt = (): number => {\n requireBytes(1);\n const first = witness[offset++];\n if (first < 0xfd) return first;\n if (first === 0xfd) {\n requireBytes(2);\n const val = (witness[offset] | (witness[offset + 1] << 8)) >>> 0;\n offset += 2;\n return val;\n }\n if (first === 0xfe) {\n requireBytes(4);\n const val =\n (witness[offset] |\n (witness[offset + 1] << 8) |\n (witness[offset + 2] << 16) |\n (witness[offset + 3] << 24)) >>>\n 0;\n offset += 4;\n return val;\n }\n // 0xff — 8-byte varint. Not used for witness sizes in practice and JS\n // numbers cannot represent all 64-bit values exactly, so reject rather\n // than risk silent truncation.\n throw new Error(\n `Malformed witness data: 8-byte varint (0xff) not supported at offset ${offset - 1}`,\n );\n };\n\n const count = readVarInt();\n for (let i = 0; i < count; i++) {\n const len = readVarInt();\n requireBytes(len);\n items.push(Buffer.from(witness.subarray(offset, offset + len)));\n offset += len;\n }\n\n if (offset !== witness.length) {\n throw new Error(\n `Malformed witness data: ${witness.length - offset} trailing byte(s) after parsing ${count} item(s)`,\n );\n }\n\n return items;\n}\n","/**\n * Asserts a wallet-returned PSBT encodes the same unsigned transaction\n * as the locally-built PSBT we asked the wallet to sign. Per-input PSBT\n * metadata (witnessUtxo, tapLeafScript, sighashType) is intentionally NOT\n * compared — those fields are committed to the Schnorr sighash and the\n * vault provider's `verify_depositor_signature` rejects mismatches there.\n * This primitive defends the path where a colluding VP would otherwise\n * accept a wallet-substituted signature.\n */\n\nimport { Buffer } from \"buffer\";\n\nimport { Psbt } from \"bitcoinjs-lib\";\n\n/**\n * Thrown when a wallet-returned PSBT encodes a different unsigned\n * transaction than the one the caller asked the wallet to sign.\n */\nexport class PsbtSubstitutionError extends Error {\n constructor(detail: string) {\n super(\n `Wallet returned a PSBT for a different transaction: ${detail}`,\n );\n this.name = \"PsbtSubstitutionError\";\n }\n}\n\nexport interface AssertPsbtUnsignedTxMatchesParams {\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\nfunction parsePsbt(label: \"requested\" | \"returned\", hex: string): Psbt {\n try {\n return Psbt.fromHex(hex);\n } catch (cause) {\n const reason = cause instanceof Error ? cause.message : String(cause);\n throw new Error(`Failed to parse ${label} PSBT: ${reason}`);\n }\n}\n\n/**\n * Length of the hex prefix included in mismatch errors. Short enough that\n * full prevout txids and output scriptPubKeys never reach logs / error\n * trackers, long enough to disambiguate during forensic triage.\n */\nconst REDACTED_HEX_PREFIX_LEN = 8;\n\nfunction redactHex(buf: Buffer): string {\n return `${buf.toString(\"hex\").slice(0, REDACTED_HEX_PREFIX_LEN)}…`;\n}\n\n/**\n * `bitcoinjs-lib` exposes `txInputs[i].hash` in internal little-endian form;\n * a human reading logs expects the big-endian txid an explorer would show.\n * Reverse before truncating so the surfaced prefix matches what an operator\n * can search for.\n */\nfunction redactTxid(internalHash: Buffer): string {\n const reversed = Buffer.from(internalHash).reverse();\n return redactHex(reversed);\n}\n\n/**\n * Compare two PSBTs and throw `PsbtSubstitutionError` unless they encode\n * the same unsigned transaction (version, locktime, inputs, outputs).\n *\n * @throws PsbtSubstitutionError on any mismatch in the unsigned tx\n * @throws Error if either PSBT cannot be parsed\n */\nexport function assertPsbtUnsignedTxMatches(\n params: AssertPsbtUnsignedTxMatchesParams,\n): void {\n const requested = parsePsbt(\"requested\", params.requestedPsbtHex);\n const returned = parsePsbt(\"returned\", params.returnedPsbtHex);\n\n if (requested.version !== returned.version) {\n throw new PsbtSubstitutionError(\n `tx version differs (requested=${requested.version}, returned=${returned.version})`,\n );\n }\n if (requested.locktime !== returned.locktime) {\n throw new PsbtSubstitutionError(\n `tx locktime differs (requested=${requested.locktime}, returned=${returned.locktime})`,\n );\n }\n if (requested.txInputs.length !== returned.txInputs.length) {\n throw new PsbtSubstitutionError(\n `input count differs (requested=${requested.txInputs.length}, returned=${returned.txInputs.length})`,\n );\n }\n if (requested.txOutputs.length !== returned.txOutputs.length) {\n throw new PsbtSubstitutionError(\n `output count differs (requested=${requested.txOutputs.length}, returned=${returned.txOutputs.length})`,\n );\n }\n for (let i = 0; i < requested.txInputs.length; i++) {\n const r = requested.txInputs[i];\n const s = returned.txInputs[i];\n if (!r.hash.equals(s.hash)) {\n throw new PsbtSubstitutionError(\n `input ${i} prevout txid differs (requested=${redactTxid(r.hash)}, returned=${redactTxid(s.hash)})`,\n );\n }\n if (r.index !== s.index) {\n throw new PsbtSubstitutionError(\n `input ${i} prevout vout differs (requested=${r.index}, returned=${s.index})`,\n );\n }\n if (r.sequence !== s.sequence) {\n throw new PsbtSubstitutionError(\n `input ${i} sequence differs (requested=${r.sequence}, returned=${s.sequence})`,\n );\n }\n }\n for (let i = 0; i < requested.txOutputs.length; i++) {\n const r = requested.txOutputs[i];\n const s = returned.txOutputs[i];\n if (!r.script.equals(s.script)) {\n throw new PsbtSubstitutionError(\n `output ${i} scriptPubKey differs (requested=${redactHex(r.script)}, returned=${redactHex(s.script)})`,\n );\n }\n if (r.value !== s.value) {\n throw new PsbtSubstitutionError(\n `output ${i} value differs (requested=${r.value}, returned=${s.value})`,\n );\n }\n }\n}\n","/**\n * Independent BIP-340 verification of a wallet-returned Taproot script-path\n * Schnorr signature against an independently-recomputed sighash.\n *\n * Critical Path #7 (CLAUDE.md): the SDK requests script-path signatures with\n * `useTweakedSigner: false, autoFinalized: false`. Wallet support for the\n * untweaked-key flag is inconsistent — older OKX / mobile bridges silently sign\n * with the *tweaked* key, Keystone ignores the flag — and a compromised\n * extension can stuff a 64-byte stub into `tapScriptSig`. A bad signature that\n * the SDK forwards is only caught on broadcast; in the worst case it passes the\n * VP off-chain but Bitcoin rejects it, leaving the depositor's BTC locked in the\n * HTLC until `timelockRefund` matures. This guard rejects such signatures before\n * they are trusted.\n *\n * Why verify against the *locally-built* PSBT, not the wallet-returned one:\n * `assertPsbtUnsignedTxMatches` pins the unsigned transaction but deliberately\n * skips per-input metadata (`witnessUtxo`, `tapLeafScript`). A malicious wallet\n * could rewrite those consistently in the returned PSBT so a wrong-message\n * signature self-validates. The trusted prevout scripts/values and leaf script\n * therefore come from the PSBT we built ourselves (derived from on-chain / WASM\n * sources); only the 64-byte signature comes from the wallet.\n *\n * Reuses the exact primitives `bip322Verify.ts` already depends on — no new\n * dependency:\n * - `@bitcoin-js/tiny-secp256k1-asmjs` → `verifySchnorr`\n * - `bitcoinjs-lib` → `Transaction.hashForWitnessV1`, `crypto.taggedHash` (TapLeaf hash)\n *\n * @module tbv/core/primitives/psbt/verifyScriptPathSchnorrSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Psbt, Transaction, crypto as bcrypto } from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport {\n SCHNORR_SIG_HEX_LEN,\n TAPSCRIPT_LEAF_VERSION,\n X_ONLY_PUBKEY_HEX_LEN,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n// Bitcoin CompactSize (varint) prefix markers — values fixed by the protocol.\n// https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\nconst COMPACT_SIZE_UINT16_PREFIX = 0xfd; // value in [0xfd, 0xffff] → 0xfd + uint16 LE\nconst COMPACT_SIZE_UINT32_PREFIX = 0xfe; // value in [0x10000, 0xffffffff] → 0xfe + uint32 LE\nconst COMPACT_SIZE_UINT16_MAX = 0xffff;\nconst COMPACT_SIZE_UINT32_MAX = 0xffffffff;\n\n/**\n * Encode a length as a Bitcoin CompactSize (varint). Tapscript leaf scripts can\n * exceed 252 bytes (WOTS scripts), so the multi-byte forms are required, not\n * just the single-byte fast path.\n */\nfunction encodeCompactSize(n: number): Buffer {\n if (n < COMPACT_SIZE_UINT16_PREFIX) {\n return Buffer.from([n]);\n }\n if (n <= COMPACT_SIZE_UINT16_MAX) {\n const value = Buffer.alloc(2); // uint16, little-endian\n value.writeUInt16LE(n);\n return Buffer.concat([Buffer.from([COMPACT_SIZE_UINT16_PREFIX]), value]);\n }\n if (n <= COMPACT_SIZE_UINT32_MAX) {\n const value = Buffer.alloc(4); // uint32, little-endian\n value.writeUInt32LE(n);\n return Buffer.concat([Buffer.from([COMPACT_SIZE_UINT32_PREFIX]), value]);\n }\n throw new Error(`Script too large to encode as CompactSize: ${n} bytes`);\n}\n\n/** BIP-341 tag for the TapLeaf hash. */\nconst TAPLEAF_TAG = \"TapLeaf\";\n\n/**\n * Compute the BIP-341 TapLeaf hash for a tapscript leaf:\n * `tagged_hash(\"TapLeaf\", leaf_version || compact_size(script) || script)`.\n */\nfunction computeTapLeafHash(leafVersion: number, script: Uint8Array): Buffer {\n const preimage = Buffer.concat([\n Buffer.from([leafVersion]),\n encodeCompactSize(script.length),\n Buffer.from(script),\n ]);\n return bcrypto.taggedHash(TAPLEAF_TAG, preimage);\n}\n\nexport interface VerifyScriptPathSchnorrSignatureParams {\n /**\n * Hex of the PSBT we built locally and sent to the wallet (the trusted\n * source of prevout scripts/values and the leaf script). NOT the\n * wallet-returned PSBT.\n */\n requestedPsbtHex: string;\n /** The 64-byte Schnorr signature extracted from the wallet's response (128 hex chars). */\n signatureHex: string;\n /** X-only public key (64 hex chars) the wallet signed the script-path leaf with. */\n signerXOnlyPubkeyHex: 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 by the\n * `signerXOnlyPubkeyHex` key over the Taproot script-path sighash of\n * `requestedPsbtHex` input `inputIndex` (SIGHASH_DEFAULT).\n *\n * @throws If the requested PSBT is malformed, lacks the prevout/leaf data needed\n * to recompute the sighash, or the signature does not verify.\n */\nexport function assertScriptPathSchnorrSignature(\n params: VerifyScriptPathSchnorrSignatureParams,\n): void {\n const { requestedPsbtHex, signatureHex, signerXOnlyPubkeyHex, inputIndex } =\n params;\n\n const signatureRaw = stripHexPrefix(signatureHex);\n if (signatureRaw.length !== SCHNORR_SIG_HEX_LEN) {\n throw new Error(\n `Schnorr signature for input ${inputIndex} must be ${SCHNORR_SIG_HEX_LEN} hex chars ` +\n `(64 bytes), got ${signatureRaw.length}.`,\n );\n }\n\n const signerXOnly = stripHexPrefix(signerXOnlyPubkeyHex);\n if (signerXOnly.length !== X_ONLY_PUBKEY_HEX_LEN) {\n throw new Error(\n `Signer x-only pubkey for input ${inputIndex} must be ${X_ONLY_PUBKEY_HEX_LEN} hex chars ` +\n `(32 bytes), got ${signerXOnly.length}.`,\n );\n }\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 // 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 witnessUtxo = psbt.data.inputs[i].witnessUtxo;\n if (!witnessUtxo) {\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(witnessUtxo.script);\n values.push(witnessUtxo.value);\n }\n\n // The signed input must expose exactly one tapLeafScript — the leaf the\n // depositor signs. Zero means we sent the wrong PSBT; more than one means an\n // ambiguous spend path we never construct for a single-signature input.\n const tapLeafScripts = psbt.data.inputs[inputIndex].tapLeafScript;\n if (!tapLeafScripts || tapLeafScripts.length !== 1) {\n throw new Error(\n `Cannot verify signature: input ${inputIndex} of the requested PSBT must have exactly ` +\n `one tapLeafScript, got ${tapLeafScripts?.length ?? 0}.`,\n );\n }\n const leaf = tapLeafScripts[0];\n if (leaf.leafVersion !== TAPSCRIPT_LEAF_VERSION) {\n throw new Error(\n `Cannot verify signature: input ${inputIndex} tapLeafScript has leaf version ` +\n `0x${leaf.leafVersion.toString(16)}, expected 0x${TAPSCRIPT_LEAF_VERSION.toString(16)}.`,\n );\n }\n\n const leafHash = computeTapLeafHash(leaf.leafVersion, leaf.script);\n\n // Reconstruct the unsigned transaction from the requested PSBT using only\n // public bitcoinjs-lib API (same pattern as bip322Verify.ts), then compute the\n // BIP-341 script-path sighash with SIGHASH_DEFAULT.\n const tx = new Transaction();\n tx.version = psbt.version;\n tx.locktime = psbt.locktime;\n for (const input of psbt.txInputs) {\n tx.addInput(input.hash, input.index, input.sequence);\n }\n for (const output of psbt.txOutputs) {\n tx.addOutput(output.script, output.value);\n }\n\n const sighash = tx.hashForWitnessV1(\n inputIndex,\n prevOutScripts,\n values,\n Transaction.SIGHASH_DEFAULT,\n leafHash,\n );\n\n const isValid = ecc.verifySchnorr(\n sighash,\n hexToUint8Array(signerXOnly),\n hexToUint8Array(signatureRaw),\n );\n\n if (!isValid) {\n throw new Error(\n `Schnorr signature for input ${inputIndex} (signer ${signerXOnly}) does not verify ` +\n `against the expected Taproot script-path sighash. The wallet may have signed with ` +\n `the tweaked key, signed a different transaction, or returned an invalid signature.`,\n );\n }\n}\n"],"names":["assertWasmPeginSizing","result","params","expectedCount","expectedClaimValue","computeMinClaimValue","anchor","peginP2aAnchorOutput","anchorValue","expectedPeginFee","computeMinPeginFee","expectedReserve","maxImpliedReserve","MAX_REASONABLE_PEGIN_VBYTES","i","requested","peginAmount","htlcValue","impliedReserve","assertEncodedHtlcOutputsMatch","outputs","htlcValues","htlcScriptPubKeys","encodedValue","encodedScript","expectedScript","AUTH_ANCHOR_HASH_HEX_LEN","HEX_PATTERN","buildPrePeginPsbt","authAnchorHash","normalizeAuthAnchorHash","createPrePeginTransaction","minPeginFee","parsed","parseUnfundedWasmTransaction","totalOutputValue","sum","o","authAnchorVout","value","cleaned","buildPeginTxFromFundedPrePegin","buildPeginTxFromPrePegin","assertPeginTxShape","PEGIN_BASE_OUTPUT_COUNT","PEGIN_DEPOSITOR_CLAIM_VOUT","version","validatePeginP2aAnchor","expectedOutputCount","peginTx","Transaction","stripHexPrefix","fundedPrePeginTxid","inputTxid","uint8ArrayToHex","requestedAmount","encodedVaultOut","encodedVaultScript","expectedVaultScript","encodedTxid","encodedClaimOut","expectedClaimScript","deriveDepositorClaimScriptPubKey","depositorPubkey","claimLeafScript","bscript","Buffer","hexToUint8Array","opcodes","output","payments","tapInternalPubkey","createPayoutScript","connector","createPayoutConnector","MAX_PAYOUT_VSIZE_BASE","MAX_PAYOUT_VSIZE_PER_PARTICIPANT","MAX_BASE_FEE_RATE_SAT_PER_VB","MAX_PAYOUT_PARTICIPANTS_PER_ROLE","PAYOUT_BOUND_ASSUMED_SCRIPT_LEN","assertPayoutFeeBandDomain","role","count","assertPayoutFeeInBand","measured","implicitFeeSats","out0Len","out1Len","numParticipants","implicitFee","scriptExcess","maxPayoutVsize","maxFeeSats","minFeeSats","computePayoutFeeFloor","P2WPKH_LEN","P2WSH_LEN","P2TR_LEN","P2PKH_LEN","P2SH_LEN","isP2wpkh","s","isP2wsh","isP2tr","isP2pkh","isP2sh","assertStandardPayoutScript","scriptHex","label","script","TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE","buildPayoutPsbt","feeBandParams","payoutTx","assertTx","DEPOSITOR_PAYOUT_INPUT_COUNT","peginPrevOut","requirePrevOut","PEGIN_VAULT_OUTPUT_INDEX","assertPrevOut","ASSERT_PAYOUT_OUTPUT_INDEX","assertPayoutOutputLayout","inputValueSats","outputValueSats","out","payoutConnector","assemblePayoutPsbt","input","inputIndex","parentTx","parentLabel","expectedVout","parentTxid","prevOut","psbt","Psbt","input0","input1","TAPSCRIPT_LEAF_VERSION","acceptedPayoutScriptHexes","registeredScriptPubKey","bondedPubkey","registered","legacyBip86","deriveBip86ScriptPubKeyHex","matchesAnyScript","acceptedHexes","hex","peginValueSats","claimerBtcPubkey","vaultProviderBtcPubkey","depositorBtcPubkey","vaultKeeperBtcPubkeys","registeredPayoutScriptPubKey","commissionBps","vkClaimerPayoutScriptPubKeys","vpCommissionScriptPubKey","isValidHex","claimer","vp","dep","keepers","k","expectedOutCount","acceptedOut0ScriptHexes","VP_CLAIMER_PAYOUT_OUTPUT_COUNT","NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT","anchorIdx","PAYOUT_ANCHOR_DUST_SATS","acceptedCommissionScriptHexes","MAX_VP_COMMISSION_BPS_EXCLUSIVE","maxCommissionSats","BPS_DENOMINATOR","MAX_PAYOUT_SCRIPT_LEN","extractPayoutSignature","signedPsbtHex","signedPsbt","depositorPubkeyBytes","sigEntry","extractSchnorrSig","witnessStack","parseWitnessStack","sig","witness","items","offset","requireBytes","n","readVarInt","first","val","len","PsbtSubstitutionError","detail","parsePsbt","cause","reason","REDACTED_HEX_PREFIX_LEN","redactHex","buf","redactTxid","internalHash","reversed","assertPsbtUnsignedTxMatches","returned","r","COMPACT_SIZE_UINT16_PREFIX","COMPACT_SIZE_UINT32_PREFIX","COMPACT_SIZE_UINT16_MAX","COMPACT_SIZE_UINT32_MAX","encodeCompactSize","TAPLEAF_TAG","computeTapLeafHash","leafVersion","preimage","bcrypto","assertScriptPathSchnorrSignature","requestedPsbtHex","signatureHex","signerXOnlyPubkeyHex","signatureRaw","SCHNORR_SIG_HEX_LEN","signerXOnly","X_ONLY_PUBKEY_HEX_LEN","prevOutScripts","values","witnessUtxo","tapLeafScripts","leaf","leafHash","tx","sighash","ecc"],"mappings":"wjBAoDA,eAAsBA,EACpBC,EACAC,EACiB,CACjB,MAAMC,EAAgBD,EAAO,aAAa,OAI1C,GAAID,EAAO,WAAW,SAAWE,EAC/B,MAAM,IAAI,MACR,2BAA2BF,EAAO,WAAW,MAAM,4BACrCE,CAAa,+BAAA,EAG/B,GACEF,EAAO,aAAa,SAAWE,GAC/BF,EAAO,kBAAkB,SAAWE,GACpCF,EAAO,cAAc,SAAWE,EAEhC,MAAM,IAAI,MACR,gEACiBF,EAAO,WAAW,MAAM,kBACvBA,EAAO,aAAa,MAAM,uBACrBA,EAAO,kBAAkB,MAAM,mBACnCA,EAAO,cAAc,MAAM,eAChCE,CAAa,QAAA,EAO/B,GAAIF,EAAO,qBAAuB,GAChC,MAAM,IAAI,MACR,4DACKA,EAAO,mBAAmB,iBAAA,EAGnC,MAAMG,EAAqB,MAAMC,EAAAA,qBAE/BH,EAAO,iBACPA,EAAO,oBACPA,EAAO,2BAA2B,OAClCA,EAAO,cACPA,EAAO,YACPA,EAAO,OAAA,EAET,GAAID,EAAO,sBAAwBG,EACjC,MAAM,IAAI,MACR,sCAAsCH,EAAO,mBAAmB,kEAE3DG,CAAkB,sBAAsBF,EAAO,gBAAgB,yBAC3CA,EAAO,mBAAmB,6BACtBA,EAAO,2BAA2B,MAAM,mBAClDA,EAAO,aAAa,iBAAiBA,EAAO,WAAW,aAC7DA,EAAO,OAAO,IAAA,EAU/B,MAAMI,EAAS,MAAMC,uBAAqBL,EAAO,gBAAgB,EAC3DM,GAAcF,GAAA,YAAAA,EAAQ,QAAS,GAC/BG,EAAmB,MAAMC,EAAAA,mBAC7BR,EAAO,iBACPA,EAAO,mBAAmB,OAC1BA,EAAO,2BA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