@babylonlabs-io/ts-sdk 0.36.3 → 0.37.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 (109) hide show
  1. package/dist/PayoutManager-BxAY2x0g.cjs +2 -0
  2. package/dist/PayoutManager-BxAY2x0g.cjs.map +1 -0
  3. package/dist/{PayoutManager-s_uH8Uuj.js → PayoutManager-sfxuOBGq.js} +51 -43
  4. package/dist/PayoutManager-sfxuOBGq.js.map +1 -0
  5. package/dist/{PeginManager-CB-dVkT2.js → PeginManager-C7-XYrkK.js} +13 -14
  6. package/dist/{PeginManager-CB-dVkT2.js.map → PeginManager-C7-XYrkK.js.map} +1 -1
  7. package/dist/{PeginManager-BPXVXu8t.cjs → PeginManager-CRuwG4I-.cjs} +2 -2
  8. package/dist/{PeginManager-BPXVXu8t.cjs.map → PeginManager-CRuwG4I-.cjs.map} +1 -1
  9. package/dist/assertPsbtUnsignedTxMatches-BoHwgW30.cjs +2 -0
  10. package/dist/assertPsbtUnsignedTxMatches-BoHwgW30.cjs.map +1 -0
  11. package/dist/assertPsbtUnsignedTxMatches-D7RxpR4A.js +263 -0
  12. package/dist/assertPsbtUnsignedTxMatches-D7RxpR4A.js.map +1 -0
  13. package/dist/{bitcoin-B0S8SHCX.js → bitcoin-B5aNKtsk.js} +77 -60
  14. package/dist/{bitcoin-B0S8SHCX.js.map → bitcoin-B5aNKtsk.js.map} +1 -1
  15. package/dist/bitcoin-CHfKAhcI.cjs +2 -0
  16. package/dist/{bitcoin-B3aqjuMP.cjs.map → bitcoin-CHfKAhcI.cjs.map} +1 -1
  17. package/dist/{buildAndBroadcastRefund-C2VqXiOx.js → buildAndBroadcastRefund-C1eOhIdo.js} +322 -322
  18. package/dist/buildAndBroadcastRefund-C1eOhIdo.js.map +1 -0
  19. package/dist/buildAndBroadcastRefund-_CEDUU5H.cjs +2 -0
  20. package/dist/buildAndBroadcastRefund-_CEDUU5H.cjs.map +1 -0
  21. package/dist/{challengeAssert-Yyyj-EdR.cjs → challengeAssert-BKDS_ADt.cjs} +2 -2
  22. package/dist/{challengeAssert-Yyyj-EdR.cjs.map → challengeAssert-BKDS_ADt.cjs.map} +1 -1
  23. package/dist/{challengeAssert-BzxQmdZy.js → challengeAssert-BXESW00N.js} +7 -7
  24. package/dist/{challengeAssert-BzxQmdZy.js.map → challengeAssert-BXESW00N.js.map} +1 -1
  25. package/dist/fundPeginTransaction-BBE3wTjR.cjs +2 -0
  26. package/dist/{fundPeginTransaction-DaWoYCgO.cjs.map → fundPeginTransaction-BBE3wTjR.cjs.map} +1 -1
  27. package/dist/fundPeginTransaction-t-6TsHAY.js +84 -0
  28. package/dist/{fundPeginTransaction-oV-dNJOU.js.map → fundPeginTransaction-t-6TsHAY.js.map} +1 -1
  29. package/dist/index.cjs +1 -1
  30. package/dist/index.js +174 -166
  31. package/dist/{noPayout-BXeUw0Qq.cjs → noPayout-B6s8vrW6.cjs} +2 -2
  32. package/dist/{noPayout-BXeUw0Qq.cjs.map → noPayout-B6s8vrW6.cjs.map} +1 -1
  33. package/dist/{noPayout-DBX6G96_.js → noPayout-BhgknZBx.js} +2 -2
  34. package/dist/{noPayout-DBX6G96_.js.map → noPayout-BhgknZBx.js.map} +1 -1
  35. package/dist/{peginInput-tbw9BpZy.cjs → peginInput-57FK2O99.cjs} +2 -2
  36. package/dist/{peginInput-tbw9BpZy.cjs.map → peginInput-57FK2O99.cjs.map} +1 -1
  37. package/dist/{peginInput-C2QPvuhR.js → peginInput-CYJzbuwA.js} +3 -3
  38. package/dist/{peginInput-C2QPvuhR.js.map → peginInput-CYJzbuwA.js.map} +1 -1
  39. package/dist/{reservation-fZUvejYK.js → reservation-CB-4FBPk.js} +3 -3
  40. package/dist/{reservation-fZUvejYK.js.map → reservation-CB-4FBPk.js.map} +1 -1
  41. package/dist/{reservation-DF0uiCUC.cjs → reservation-hjXStM03.cjs} +2 -2
  42. package/dist/{reservation-DF0uiCUC.cjs.map → reservation-hjXStM03.cjs.map} +1 -1
  43. package/dist/tbv/core/clients/index.cjs +1 -1
  44. package/dist/tbv/core/clients/index.js +1 -1
  45. package/dist/tbv/core/index.cjs +1 -1
  46. package/dist/tbv/core/index.js +172 -164
  47. package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -1
  48. package/dist/tbv/core/managers/PeginManager.d.ts +7 -8
  49. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  50. package/dist/tbv/core/managers/index.cjs +1 -1
  51. package/dist/tbv/core/managers/index.js +2 -2
  52. package/dist/tbv/core/primitives/index.cjs +1 -1
  53. package/dist/tbv/core/primitives/index.d.ts +3 -1
  54. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  55. package/dist/tbv/core/primitives/index.js +31 -27
  56. package/dist/tbv/core/primitives/psbt/__tests__/assertPsbtUnsignedTxMatches.test.d.ts +5 -0
  57. package/dist/tbv/core/primitives/psbt/__tests__/assertPsbtUnsignedTxMatches.test.d.ts.map +1 -0
  58. package/dist/tbv/core/primitives/psbt/assertPsbtUnsignedTxMatches.d.ts +31 -0
  59. package/dist/tbv/core/primitives/psbt/assertPsbtUnsignedTxMatches.d.ts.map +1 -0
  60. package/dist/tbv/core/primitives/psbt/index.d.ts +2 -0
  61. package/dist/tbv/core/primitives/psbt/index.d.ts.map +1 -1
  62. package/dist/tbv/core/primitives/utils/bitcoin.d.ts +33 -3
  63. package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
  64. package/dist/tbv/core/primitives/utils/index.d.ts +1 -1
  65. package/dist/tbv/core/primitives/utils/index.d.ts.map +1 -1
  66. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  67. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  68. package/dist/tbv/core/services/index.cjs +1 -1
  69. package/dist/tbv/core/services/index.js +2 -2
  70. package/dist/tbv/core/utils/fee/__tests__/peginFeeMath.test.d.ts +19 -0
  71. package/dist/tbv/core/utils/fee/__tests__/peginFeeMath.test.d.ts.map +1 -0
  72. package/dist/tbv/core/utils/fee/index.d.ts +1 -0
  73. package/dist/tbv/core/utils/fee/index.d.ts.map +1 -1
  74. package/dist/tbv/core/utils/fee/peginFeeMath.d.ts +99 -0
  75. package/dist/tbv/core/utils/fee/peginFeeMath.d.ts.map +1 -0
  76. package/dist/tbv/core/utils/index.cjs +1 -1
  77. package/dist/tbv/core/utils/index.js +44 -40
  78. package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts.map +1 -1
  79. package/dist/tbv/core/utils/utxo/selectUtxos.d.ts.map +1 -1
  80. package/dist/tbv/index.cjs +1 -1
  81. package/dist/tbv/index.js +172 -164
  82. package/dist/testing/index.cjs +1 -1
  83. package/dist/testing/index.js +1 -1
  84. package/dist/{vault-registry-reader-Br9m8bHF.cjs → vault-registry-reader-7gOYnrQD.cjs} +2 -2
  85. package/dist/{vault-registry-reader-Br9m8bHF.cjs.map → vault-registry-reader-7gOYnrQD.cjs.map} +1 -1
  86. package/dist/{vault-registry-reader-CohvzvoH.js → vault-registry-reader-Blhu9FW2.js} +2 -2
  87. package/dist/{vault-registry-reader-CohvzvoH.js.map → vault-registry-reader-Blhu9FW2.js.map} +1 -1
  88. package/dist/waitForTransactionReceiptSmartAware-CmgFXFza.js +265 -0
  89. package/dist/waitForTransactionReceiptSmartAware-CmgFXFza.js.map +1 -0
  90. package/dist/waitForTransactionReceiptSmartAware-tv1mtSIY.cjs +2 -0
  91. package/dist/waitForTransactionReceiptSmartAware-tv1mtSIY.cjs.map +1 -0
  92. package/package.json +1 -1
  93. package/dist/PayoutManager-BhJoQZsG.cjs +0 -2
  94. package/dist/PayoutManager-BhJoQZsG.cjs.map +0 -1
  95. package/dist/PayoutManager-s_uH8Uuj.js.map +0 -1
  96. package/dist/bitcoin-B3aqjuMP.cjs +0 -2
  97. package/dist/buildAndBroadcastRefund-C2VqXiOx.js.map +0 -1
  98. package/dist/buildAndBroadcastRefund-CBIfcF47.cjs +0 -2
  99. package/dist/buildAndBroadcastRefund-CBIfcF47.cjs.map +0 -1
  100. package/dist/fundPeginTransaction-DaWoYCgO.cjs +0 -2
  101. package/dist/fundPeginTransaction-oV-dNJOU.js +0 -76
  102. package/dist/payout-BNFMBXS6.js +0 -193
  103. package/dist/payout-BNFMBXS6.js.map +0 -1
  104. package/dist/payout-DQ_fmJUA.cjs +0 -2
  105. package/dist/payout-DQ_fmJUA.cjs.map +0 -1
  106. package/dist/waitForTransactionReceiptSmartAware-Cj_DKm0G.js +0 -217
  107. package/dist/waitForTransactionReceiptSmartAware-Cj_DKm0G.js.map +0 -1
  108. package/dist/waitForTransactionReceiptSmartAware-D9ykVriz.cjs +0 -2
  109. package/dist/waitForTransactionReceiptSmartAware-D9ykVriz.cjs.map +0 -1
@@ -0,0 +1,2 @@
1
+ "use strict";const B=require("@babylonlabs-io/babylon-tbv-rust-wasm"),f=require("buffer"),p=require("bitcoinjs-lib"),a=require("./bitcoin-CHfKAhcI.cjs");async function m(t){const r=await B.createPayoutConnector({depositor:t.depositor,vaultProvider:t.vaultProvider,vaultKeepers:t.vaultKeepers,universalChallengers:t.universalChallengers,timelockPegin:t.timelockPegin},t.network);return{payoutScript:r.payoutScript,taprootScriptHash:r.taprootScriptHash,scriptPubKey:r.scriptPubKey,address:r.address,payoutControlBlock:r.payoutControlBlock}}const E=3;async function I(t){const r=a.stripHexPrefix(t.payoutTxHex),e=a.stripHexPrefix(t.peginTxHex),n=a.stripHexPrefix(t.assertTxHex),o=await m({depositor:t.depositorBtcPubkey,vaultProvider:t.vaultProviderBtcPubkey,vaultKeepers:t.vaultKeeperBtcPubkeys,universalChallengers:t.universalChallengerBtcPubkeys,timelockPegin:t.timelockPegin,network:t.network}),s=a.hexToUint8Array(o.payoutScript),i=a.hexToUint8Array(o.payoutControlBlock),u=p.Transaction.fromHex(r),$=p.Transaction.fromHex(e),v=p.Transaction.fromHex(n),l=new p.Psbt;if(l.setVersion(u.version),l.setLocktime(u.locktime),u.ins.length!==2)throw new Error(`Payout transaction must have exactly 2 inputs, got ${u.ins.length}`);const d=u.ins[0],h=u.ins[1],x=a.uint8ArrayToHex(new Uint8Array(d.hash).slice().reverse()),S=$.getId();if(x!==S)throw new Error(`Input 0 does not reference pegin transaction. Expected ${S}, got ${x}`);const g=a.uint8ArrayToHex(new Uint8Array(h.hash).slice().reverse()),b=v.getId();if(g!==b)throw new Error(`Input 1 does not reference assert transaction. Expected ${b}, got ${g}`);const y=$.outs[d.index];if(!y)throw new Error(`Previous output not found for input 0 (txid: ${x}, index: ${d.index})`);const w=v.outs[h.index];if(!w)throw new Error(`Previous output not found for input 1 (txid: ${g}, index: ${h.index})`);l.addInput({hash:d.hash,index:d.index,sequence:d.sequence,witnessUtxo:{script:y.script,value:y.value},tapLeafScript:[{leafVersion:a.TAPSCRIPT_LEAF_VERSION,script:f.Buffer.from(s),controlBlock:f.Buffer.from(i)}],tapInternalKey:f.Buffer.from(B.tapInternalPubkey)}),l.addInput({hash:h.hash,index:h.index,sequence:h.sequence,witnessUtxo:{script:w.script,value:w.value}});for(const T of u.outs)l.addOutput({script:T.script,value:T.value});return{psbtHex:l.toHex()}}function O(t,r){if(!a.isValidHex(r))throw new Error("Invalid registeredPayoutScriptPubKey: not valid hex");const e=f.Buffer.from(a.stripHexPrefix(r),"hex"),n=p.Transaction.fromHex(a.stripHexPrefix(t));if(n.outs.length===0)throw new Error("Payout transaction has no outputs");if(!n.outs.reduce((s,i)=>i.value>s.value?i:s).script.equals(e))throw new Error("Payout transaction does not pay to the registered depositor payout address")}function A(t,r,e=0){const n=p.Psbt.fromHex(t);if(e>=n.data.inputs.length)throw new Error(`Input index ${e} out of range (${n.data.inputs.length} inputs)`);const o=n.data.inputs[e];if(o.tapScriptSig&&o.tapScriptSig.length>0){const s=a.hexToUint8Array(r);for(const i of o.tapScriptSig)if(i.pubkey.equals(f.Buffer.from(s)))return H(i.signature,e);throw new Error(`No signature found for depositor pubkey: ${r} at input ${e}`)}if(o.finalScriptWitness&&o.finalScriptWitness.length>0){const s=U(o.finalScriptWitness);if(s.length!==E)throw new Error(`Unexpected finalized witness stack size at input ${e}: expected ${E} items (signature, script, controlBlock), got ${s.length}`);return H(s[0],e)}throw new Error(`No tapScriptSig or finalScriptWitness found in signed PSBT at input ${e}`)}function H(t,r){if(t.length===64)return a.uint8ArrayToHex(new Uint8Array(t));throw t.length===65?new Error(`Unexpected sighash byte 0x${t[64].toString(16).padStart(2,"0")} at input ${r}. Expected implicit SIGHASH_DEFAULT as a 64-byte signature.`):new Error(`Unexpected signature length at input ${r}: ${t.length}`)}function U(t){const r=[];let e=0;const n=i=>{if(e+i>t.length)throw new Error(`Malformed witness data: need ${i} byte(s) at offset ${e}, only ${t.length-e} remaining`)},o=()=>{n(1);const i=t[e++];if(i<253)return i;if(i===253){n(2);const u=(t[e]|t[e+1]<<8)>>>0;return e+=2,u}if(i===254){n(4);const u=(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0;return e+=4,u}throw new Error(`Malformed witness data: 8-byte varint (0xff) not supported at offset ${e-1}`)},s=o();for(let i=0;i<s;i++){const u=o();n(u),r.push(f.Buffer.from(t.subarray(e,e+u))),e+=u}if(e!==t.length)throw new Error(`Malformed witness data: ${t.length-e} trailing byte(s) after parsing ${s} item(s)`);return r}class c extends Error{constructor(r){super(`Wallet returned a PSBT for a different transaction: ${r}`),this.name="PsbtSubstitutionError"}}function k(t,r){try{return p.Psbt.fromHex(r)}catch(e){const n=e instanceof Error?e.message:String(e);throw new Error(`Failed to parse ${t} PSBT: ${n}`)}}const C=8;function P(t){return`${t.toString("hex").slice(0,C)}…`}function q(t){const r=f.Buffer.from(t).reverse();return P(r)}function _(t){const r=k("requested",t.requestedPsbtHex),e=k("returned",t.returnedPsbtHex);if(r.version!==e.version)throw new c(`tx version differs (requested=${r.version}, returned=${e.version})`);if(r.locktime!==e.locktime)throw new c(`tx locktime differs (requested=${r.locktime}, returned=${e.locktime})`);if(r.txInputs.length!==e.txInputs.length)throw new c(`input count differs (requested=${r.txInputs.length}, returned=${e.txInputs.length})`);if(r.txOutputs.length!==e.txOutputs.length)throw new c(`output count differs (requested=${r.txOutputs.length}, returned=${e.txOutputs.length})`);for(let n=0;n<r.txInputs.length;n++){const o=r.txInputs[n],s=e.txInputs[n];if(!o.hash.equals(s.hash))throw new c(`input ${n} prevout txid differs (requested=${q(o.hash)}, returned=${q(s.hash)})`);if(o.index!==s.index)throw new c(`input ${n} prevout vout differs (requested=${o.index}, returned=${s.index})`);if(o.sequence!==s.sequence)throw new c(`input ${n} sequence differs (requested=${o.sequence}, returned=${s.sequence})`)}for(let n=0;n<r.txOutputs.length;n++){const o=r.txOutputs[n],s=e.txOutputs[n];if(!o.script.equals(s.script))throw new c(`output ${n} scriptPubKey differs (requested=${P(o.script)}, returned=${P(s.script)})`);if(o.value!==s.value)throw new c(`output ${n} value differs (requested=${o.value}, returned=${s.value})`)}}exports.PsbtSubstitutionError=c;exports.assertPayoutOutputMatchesRegistered=O;exports.assertPsbtUnsignedTxMatches=_;exports.buildPayoutPsbt=I;exports.createPayoutScript=m;exports.extractPayoutSignature=A;
2
+ //# sourceMappingURL=assertPsbtUnsignedTxMatches-BoHwgW30.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assertPsbtUnsignedTxMatches-BoHwgW30.cjs","sources":["../src/tbv/core/primitives/scripts/payout.ts","../src/tbv/core/primitives/psbt/payout.ts","../src/tbv/core/primitives/psbt/assertPsbtUnsignedTxMatches.ts"],"sourcesContent":["/**\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 * 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 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 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 { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { createPayoutScript } from \"../scripts/payout\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n isValidHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\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 * 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/**\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 reference the pegin transaction\n * @throws If input 1 does not reference the assert transaction\n * @throws If previous output is not found for either input\n */\nexport async function buildPayoutPsbt(\n params: PayoutParams,\n): Promise<PayoutPsbtResult> {\n // Normalize hex inputs (strip 0x prefix if present)\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const assertTxHex = stripHexPrefix(params.assertTxHex);\n\n // Get payout script from WASM\n const payoutConnector = await createPayoutScript({\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 const payoutScriptBytes = hexToUint8Array(payoutConnector.payoutScript);\n const controlBlock = hexToUint8Array(payoutConnector.payoutControlBlock);\n\n // Parse transactions\n const payoutTx = Transaction.fromHex(payoutTxHex);\n const peginTx = Transaction.fromHex(peginTxHex);\n const assertTx = Transaction.fromHex(assertTxHex);\n\n // Create PSBT\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n // PayoutTx has exactly 2 inputs:\n // - Input 0: from PeginTx output0 (signed by depositor using taproot script path)\n // - Input 1: from Assert output0 (signed by claimer/challengers, not depositor)\n //\n // IMPORTANT: For Taproot SIGHASH_DEFAULT (0x00), the sighash commits to ALL inputs'\n // prevouts, not just the one being signed. Therefore, we must include BOTH inputs\n // in the PSBT so the wallet computes the correct sighash that the VP expects.\n\n // Verify payout transaction has expected structure\n if (payoutTx.ins.length !== 2) {\n throw new Error(\n `Payout transaction must have exactly 2 inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n // Verify input 0 references the pegin transaction\n const input0Txid = uint8ArrayToHex(\n new Uint8Array(input0.hash).slice().reverse(),\n );\n const peginTxid = peginTx.getId();\n\n if (input0Txid !== peginTxid) {\n throw new Error(\n `Input 0 does not reference pegin transaction. ` +\n `Expected ${peginTxid}, got ${input0Txid}`,\n );\n }\n\n // Verify input 1 references the assert transaction\n const input1Txid = uint8ArrayToHex(\n new Uint8Array(input1.hash).slice().reverse(),\n );\n const expectedInput1Txid = assertTx.getId();\n\n if (input1Txid !== expectedInput1Txid) {\n throw new Error(\n `Input 1 does not reference assert transaction. ` +\n `Expected ${expectedInput1Txid}, got ${input1Txid}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n if (!peginPrevOut) {\n throw new Error(\n `Previous output not found for input 0 (txid: ${input0Txid}, index: ${input0.index})`,\n );\n }\n\n const input1PrevOut = assertTx.outs[input1.index];\n if (!input1PrevOut) {\n throw new Error(\n `Previous output not found for input 1 (txid: ${input1Txid}, index: ${input1.index})`,\n );\n }\n\n // Input 0: Depositor signs using Taproot script path spend\n // This input includes tapLeafScript for signing\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(payoutScriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n // Input 1: From Assert transaction (NOT signed by depositor)\n // We include this with witnessUtxo so the sighash is computed correctly,\n // but we do NOT include tapLeafScript since the depositor doesn't sign it.\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: input1PrevOut.script,\n value: input1PrevOut.value,\n },\n // No tapLeafScript - depositor doesn't sign this input\n });\n\n // Add outputs\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return {\n psbtHex: psbt.toHex(),\n };\n}\n\n/**\n * Validate that a payout transaction's largest output pays to the registered\n * depositor payout scriptPubKey.\n *\n * Prevents a malicious vault provider from substituting the payout destination\n * (or routing funds through a dust output to the correct address while sending\n * the actual value to an attacker-controlled script).\n *\n * @param payoutTxHex - Raw payout transaction hex\n * @param registeredPayoutScriptPubKey - On-chain registered scriptPubKey (hex, with or without 0x prefix)\n * @throws If scriptPubKey is invalid hex\n * @throws If the transaction has no outputs\n * @throws If the largest output does not pay to the registered scriptPubKey\n */\nexport function assertPayoutOutputMatchesRegistered(\n payoutTxHex: string,\n registeredPayoutScriptPubKey: string,\n): void {\n if (!isValidHex(registeredPayoutScriptPubKey)) {\n throw new Error(\"Invalid registeredPayoutScriptPubKey: not valid hex\");\n }\n\n const expectedScript = Buffer.from(\n stripHexPrefix(registeredPayoutScriptPubKey),\n \"hex\",\n );\n const payoutTx = Transaction.fromHex(stripHexPrefix(payoutTxHex));\n\n if (payoutTx.outs.length === 0) {\n throw new Error(\"Payout transaction has no outputs\");\n }\n\n const largestOutput = payoutTx.outs.reduce((max, output) =>\n output.value > max.value ? output : max,\n );\n\n if (!largestOutput.script.equals(expectedScript)) {\n throw new Error(\n \"Payout transaction does not pay to the registered depositor payout address\",\n );\n }\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","/**\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"],"names":["createPayoutScript","params","connector","createPayoutConnector","TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE","buildPayoutPsbt","payoutTxHex","stripHexPrefix","peginTxHex","assertTxHex","payoutConnector","payoutScriptBytes","hexToUint8Array","controlBlock","payoutTx","Transaction","peginTx","assertTx","psbt","Psbt","input0","input1","input0Txid","uint8ArrayToHex","peginTxid","input1Txid","expectedInput1Txid","peginPrevOut","input1PrevOut","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","assertPayoutOutputMatchesRegistered","registeredPayoutScriptPubKey","isValidHex","expectedScript","max","extractPayoutSignature","signedPsbtHex","depositorPubkey","inputIndex","signedPsbt","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","witnessStack","parseWitnessStack","sig","witness","items","offset","requireBytes","n","readVarInt","first","val","count","len","PsbtSubstitutionError","detail","parsePsbt","label","hex","cause","reason","REDACTED_HEX_PREFIX_LEN","redactHex","buf","redactTxid","internalHash","reversed","assertPsbtUnsignedTxMatches","requested","returned","i","r"],"mappings":"yJA8IA,eAAsBA,EACpBC,EAC6B,CAE7B,MAAMC,EAAY,MAAMC,EAAAA,sBACtB,CACE,UAAWF,EAAO,UAClB,cAAeA,EAAO,cACtB,aAAcA,EAAO,aACrB,qBAAsBA,EAAO,qBAC7B,cAAeA,EAAO,aAAA,EAExBA,EAAO,OAAA,EAGT,MAAO,CACL,aAAcC,EAAU,aACxB,kBAAmBA,EAAU,kBAC7B,aAAcA,EAAU,aACxB,QAASA,EAAU,QACnB,mBAAoBA,EAAU,kBAAA,CAElC,CChIA,MAAME,EAAwC,EAyF9C,eAAsBC,EACpBJ,EAC2B,CAE3B,MAAMK,EAAcC,EAAAA,eAAeN,EAAO,WAAW,EAC/CO,EAAaD,EAAAA,eAAeN,EAAO,UA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,EAGpG,GAAIO,EAAE,QAAU,EAAE,MAChB,MAAM,IAAIjB,EACR,SAASgB,CAAC,oCAAoCC,EAAE,KAAK,cAAc,EAAE,KAAK,GAAA,EAG9E,GAAIA,EAAE,WAAa,EAAE,SACnB,MAAM,IAAIjB,EACR,SAASgB,CAAC,gCAAgCC,EAAE,QAAQ,cAAc,EAAE,QAAQ,GAAA,CAGlF,CACA,QAASD,EAAI,EAAGA,EAAIF,EAAU,UAAU,OAAQE,IAAK,CACnD,MAAMC,EAAIH,EAAU,UAAUE,CAAC,EACzB,EAAID,EAAS,UAAUC,CAAC,EAC9B,GAAI,CAACC,EAAE,OAAO,OAAO,EAAE,MAAM,EAC3B,MAAM,IAAIjB,EACR,UAAUgB,CAAC,oCAAoCR,EAAUS,EAAE,MAAM,CAAC,cAAcT,EAAU,EAAE,MAAM,CAAC,GAAA,EAGvG,GAAIS,EAAE,QAAU,EAAE,MAChB,MAAM,IAAIjB,EACR,UAAUgB,CAAC,6BAA6BC,EAAE,KAAK,cAAc,EAAE,KAAK,GAAA,CAG1E,CACF"}
@@ -0,0 +1,263 @@
1
+ import { createPayoutConnector as O, tapInternalPubkey as A } from "@babylonlabs-io/babylon-tbv-rust-wasm";
2
+ import { Buffer as c } from "buffer";
3
+ import { Transaction as h, Psbt as S } from "bitcoinjs-lib";
4
+ import { c as C, s as f, h as y, u as v, T as U } from "./bitcoin-B5aNKtsk.js";
5
+ async function _(t) {
6
+ const r = await O(
7
+ {
8
+ depositor: t.depositor,
9
+ vaultProvider: t.vaultProvider,
10
+ vaultKeepers: t.vaultKeepers,
11
+ universalChallengers: t.universalChallengers,
12
+ timelockPegin: t.timelockPegin
13
+ },
14
+ t.network
15
+ );
16
+ return {
17
+ payoutScript: r.payoutScript,
18
+ taprootScriptHash: r.taprootScriptHash,
19
+ scriptPubKey: r.scriptPubKey,
20
+ address: r.address,
21
+ payoutControlBlock: r.payoutControlBlock
22
+ };
23
+ }
24
+ const q = 3;
25
+ async function V(t) {
26
+ const r = f(t.payoutTxHex), e = f(t.peginTxHex), n = f(t.assertTxHex), o = await _({
27
+ depositor: t.depositorBtcPubkey,
28
+ vaultProvider: t.vaultProviderBtcPubkey,
29
+ vaultKeepers: t.vaultKeeperBtcPubkeys,
30
+ universalChallengers: t.universalChallengerBtcPubkeys,
31
+ timelockPegin: t.timelockPegin,
32
+ network: t.network
33
+ }), s = y(o.payoutScript), i = y(o.payoutControlBlock), u = h.fromHex(r), E = h.fromHex(e), b = h.fromHex(n), p = new S();
34
+ if (p.setVersion(u.version), p.setLocktime(u.locktime), u.ins.length !== 2)
35
+ throw new Error(
36
+ `Payout transaction must have exactly 2 inputs, got ${u.ins.length}`
37
+ );
38
+ const l = u.ins[0], d = u.ins[1], x = v(
39
+ new Uint8Array(l.hash).slice().reverse()
40
+ ), T = E.getId();
41
+ if (x !== T)
42
+ throw new Error(
43
+ `Input 0 does not reference pegin transaction. Expected ${T}, got ${x}`
44
+ );
45
+ const g = v(
46
+ new Uint8Array(d.hash).slice().reverse()
47
+ ), k = b.getId();
48
+ if (g !== k)
49
+ throw new Error(
50
+ `Input 1 does not reference assert transaction. Expected ${k}, got ${g}`
51
+ );
52
+ const w = E.outs[l.index];
53
+ if (!w)
54
+ throw new Error(
55
+ `Previous output not found for input 0 (txid: ${x}, index: ${l.index})`
56
+ );
57
+ const $ = b.outs[d.index];
58
+ if (!$)
59
+ throw new Error(
60
+ `Previous output not found for input 1 (txid: ${g}, index: ${d.index})`
61
+ );
62
+ p.addInput({
63
+ hash: l.hash,
64
+ index: l.index,
65
+ sequence: l.sequence,
66
+ witnessUtxo: {
67
+ script: w.script,
68
+ value: w.value
69
+ },
70
+ tapLeafScript: [
71
+ {
72
+ leafVersion: U,
73
+ script: c.from(s),
74
+ controlBlock: c.from(i)
75
+ }
76
+ ],
77
+ tapInternalKey: c.from(A)
78
+ // sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot
79
+ }), p.addInput({
80
+ hash: d.hash,
81
+ index: d.index,
82
+ sequence: d.sequence,
83
+ witnessUtxo: {
84
+ script: $.script,
85
+ value: $.value
86
+ }
87
+ // No tapLeafScript - depositor doesn't sign this input
88
+ });
89
+ for (const m of u.outs)
90
+ p.addOutput({
91
+ script: m.script,
92
+ value: m.value
93
+ });
94
+ return {
95
+ psbtHex: p.toHex()
96
+ };
97
+ }
98
+ function F(t, r) {
99
+ if (!C(r))
100
+ throw new Error("Invalid registeredPayoutScriptPubKey: not valid hex");
101
+ const e = c.from(
102
+ f(r),
103
+ "hex"
104
+ ), n = h.fromHex(f(t));
105
+ if (n.outs.length === 0)
106
+ throw new Error("Payout transaction has no outputs");
107
+ if (!n.outs.reduce(
108
+ (s, i) => i.value > s.value ? i : s
109
+ ).script.equals(e))
110
+ throw new Error(
111
+ "Payout transaction does not pay to the registered depositor payout address"
112
+ );
113
+ }
114
+ function D(t, r, e = 0) {
115
+ const n = S.fromHex(t);
116
+ if (e >= n.data.inputs.length)
117
+ throw new Error(
118
+ `Input index ${e} out of range (${n.data.inputs.length} inputs)`
119
+ );
120
+ const o = n.data.inputs[e];
121
+ if (o.tapScriptSig && o.tapScriptSig.length > 0) {
122
+ const s = y(r);
123
+ for (const i of o.tapScriptSig)
124
+ if (i.pubkey.equals(c.from(s)))
125
+ return H(i.signature, e);
126
+ throw new Error(
127
+ `No signature found for depositor pubkey: ${r} at input ${e}`
128
+ );
129
+ }
130
+ if (o.finalScriptWitness && o.finalScriptWitness.length > 0) {
131
+ const s = K(o.finalScriptWitness);
132
+ if (s.length !== q)
133
+ throw new Error(
134
+ `Unexpected finalized witness stack size at input ${e}: expected ${q} items (signature, script, controlBlock), got ${s.length}`
135
+ );
136
+ return H(s[0], e);
137
+ }
138
+ throw new Error(
139
+ `No tapScriptSig or finalScriptWitness found in signed PSBT at input ${e}`
140
+ );
141
+ }
142
+ function H(t, r) {
143
+ if (t.length === 64)
144
+ return v(new Uint8Array(t));
145
+ throw t.length === 65 ? new Error(
146
+ `Unexpected sighash byte 0x${t[64].toString(16).padStart(2, "0")} at input ${r}. Expected implicit SIGHASH_DEFAULT as a 64-byte signature.`
147
+ ) : new Error(
148
+ `Unexpected signature length at input ${r}: ${t.length}`
149
+ );
150
+ }
151
+ function K(t) {
152
+ const r = [];
153
+ let e = 0;
154
+ const n = (i) => {
155
+ if (e + i > t.length)
156
+ throw new Error(
157
+ `Malformed witness data: need ${i} byte(s) at offset ${e}, only ${t.length - e} remaining`
158
+ );
159
+ }, o = () => {
160
+ n(1);
161
+ const i = t[e++];
162
+ if (i < 253) return i;
163
+ if (i === 253) {
164
+ n(2);
165
+ const u = (t[e] | t[e + 1] << 8) >>> 0;
166
+ return e += 2, u;
167
+ }
168
+ if (i === 254) {
169
+ n(4);
170
+ const u = (t[e] | t[e + 1] << 8 | t[e + 2] << 16 | t[e + 3] << 24) >>> 0;
171
+ return e += 4, u;
172
+ }
173
+ throw new Error(
174
+ `Malformed witness data: 8-byte varint (0xff) not supported at offset ${e - 1}`
175
+ );
176
+ }, s = o();
177
+ for (let i = 0; i < s; i++) {
178
+ const u = o();
179
+ n(u), r.push(c.from(t.subarray(e, e + u))), e += u;
180
+ }
181
+ if (e !== t.length)
182
+ throw new Error(
183
+ `Malformed witness data: ${t.length - e} trailing byte(s) after parsing ${s} item(s)`
184
+ );
185
+ return r;
186
+ }
187
+ class a extends Error {
188
+ constructor(r) {
189
+ super(
190
+ `Wallet returned a PSBT for a different transaction: ${r}`
191
+ ), this.name = "PsbtSubstitutionError";
192
+ }
193
+ }
194
+ function I(t, r) {
195
+ try {
196
+ return S.fromHex(r);
197
+ } catch (e) {
198
+ const n = e instanceof Error ? e.message : String(e);
199
+ throw new Error(`Failed to parse ${t} PSBT: ${n}`);
200
+ }
201
+ }
202
+ const W = 8;
203
+ function P(t) {
204
+ return `${t.toString("hex").slice(0, W)}…`;
205
+ }
206
+ function B(t) {
207
+ const r = c.from(t).reverse();
208
+ return P(r);
209
+ }
210
+ function G(t) {
211
+ const r = I("requested", t.requestedPsbtHex), e = I("returned", t.returnedPsbtHex);
212
+ if (r.version !== e.version)
213
+ throw new a(
214
+ `tx version differs (requested=${r.version}, returned=${e.version})`
215
+ );
216
+ if (r.locktime !== e.locktime)
217
+ throw new a(
218
+ `tx locktime differs (requested=${r.locktime}, returned=${e.locktime})`
219
+ );
220
+ if (r.txInputs.length !== e.txInputs.length)
221
+ throw new a(
222
+ `input count differs (requested=${r.txInputs.length}, returned=${e.txInputs.length})`
223
+ );
224
+ if (r.txOutputs.length !== e.txOutputs.length)
225
+ throw new a(
226
+ `output count differs (requested=${r.txOutputs.length}, returned=${e.txOutputs.length})`
227
+ );
228
+ for (let n = 0; n < r.txInputs.length; n++) {
229
+ const o = r.txInputs[n], s = e.txInputs[n];
230
+ if (!o.hash.equals(s.hash))
231
+ throw new a(
232
+ `input ${n} prevout txid differs (requested=${B(o.hash)}, returned=${B(s.hash)})`
233
+ );
234
+ if (o.index !== s.index)
235
+ throw new a(
236
+ `input ${n} prevout vout differs (requested=${o.index}, returned=${s.index})`
237
+ );
238
+ if (o.sequence !== s.sequence)
239
+ throw new a(
240
+ `input ${n} sequence differs (requested=${o.sequence}, returned=${s.sequence})`
241
+ );
242
+ }
243
+ for (let n = 0; n < r.txOutputs.length; n++) {
244
+ const o = r.txOutputs[n], s = e.txOutputs[n];
245
+ if (!o.script.equals(s.script))
246
+ throw new a(
247
+ `output ${n} scriptPubKey differs (requested=${P(o.script)}, returned=${P(s.script)})`
248
+ );
249
+ if (o.value !== s.value)
250
+ throw new a(
251
+ `output ${n} value differs (requested=${o.value}, returned=${s.value})`
252
+ );
253
+ }
254
+ }
255
+ export {
256
+ a as P,
257
+ F as a,
258
+ V as b,
259
+ G as c,
260
+ _ as d,
261
+ D as e
262
+ };
263
+ //# sourceMappingURL=assertPsbtUnsignedTxMatches-D7RxpR4A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assertPsbtUnsignedTxMatches-D7RxpR4A.js","sources":["../src/tbv/core/primitives/scripts/payout.ts","../src/tbv/core/primitives/psbt/payout.ts","../src/tbv/core/primitives/psbt/assertPsbtUnsignedTxMatches.ts"],"sourcesContent":["/**\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 * 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 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 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 { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { createPayoutScript } from \"../scripts/payout\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n isValidHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\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 * 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/**\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 reference the pegin transaction\n * @throws If input 1 does not reference the assert transaction\n * @throws If previous output is not found for either input\n */\nexport async function buildPayoutPsbt(\n params: PayoutParams,\n): Promise<PayoutPsbtResult> {\n // Normalize hex inputs (strip 0x prefix if present)\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const assertTxHex = stripHexPrefix(params.assertTxHex);\n\n // Get payout script from WASM\n const payoutConnector = await createPayoutScript({\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 const payoutScriptBytes = hexToUint8Array(payoutConnector.payoutScript);\n const controlBlock = hexToUint8Array(payoutConnector.payoutControlBlock);\n\n // Parse transactions\n const payoutTx = Transaction.fromHex(payoutTxHex);\n const peginTx = Transaction.fromHex(peginTxHex);\n const assertTx = Transaction.fromHex(assertTxHex);\n\n // Create PSBT\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n // PayoutTx has exactly 2 inputs:\n // - Input 0: from PeginTx output0 (signed by depositor using taproot script path)\n // - Input 1: from Assert output0 (signed by claimer/challengers, not depositor)\n //\n // IMPORTANT: For Taproot SIGHASH_DEFAULT (0x00), the sighash commits to ALL inputs'\n // prevouts, not just the one being signed. Therefore, we must include BOTH inputs\n // in the PSBT so the wallet computes the correct sighash that the VP expects.\n\n // Verify payout transaction has expected structure\n if (payoutTx.ins.length !== 2) {\n throw new Error(\n `Payout transaction must have exactly 2 inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n // Verify input 0 references the pegin transaction\n const input0Txid = uint8ArrayToHex(\n new Uint8Array(input0.hash).slice().reverse(),\n );\n const peginTxid = peginTx.getId();\n\n if (input0Txid !== peginTxid) {\n throw new Error(\n `Input 0 does not reference pegin transaction. ` +\n `Expected ${peginTxid}, got ${input0Txid}`,\n );\n }\n\n // Verify input 1 references the assert transaction\n const input1Txid = uint8ArrayToHex(\n new Uint8Array(input1.hash).slice().reverse(),\n );\n const expectedInput1Txid = assertTx.getId();\n\n if (input1Txid !== expectedInput1Txid) {\n throw new Error(\n `Input 1 does not reference assert transaction. ` +\n `Expected ${expectedInput1Txid}, got ${input1Txid}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n if (!peginPrevOut) {\n throw new Error(\n `Previous output not found for input 0 (txid: ${input0Txid}, index: ${input0.index})`,\n );\n }\n\n const input1PrevOut = assertTx.outs[input1.index];\n if (!input1PrevOut) {\n throw new Error(\n `Previous output not found for input 1 (txid: ${input1Txid}, index: ${input1.index})`,\n );\n }\n\n // Input 0: Depositor signs using Taproot script path spend\n // This input includes tapLeafScript for signing\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(payoutScriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n // Input 1: From Assert transaction (NOT signed by depositor)\n // We include this with witnessUtxo so the sighash is computed correctly,\n // but we do NOT include tapLeafScript since the depositor doesn't sign it.\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: input1PrevOut.script,\n value: input1PrevOut.value,\n },\n // No tapLeafScript - depositor doesn't sign this input\n });\n\n // Add outputs\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return {\n psbtHex: psbt.toHex(),\n };\n}\n\n/**\n * Validate that a payout transaction's largest output pays to the registered\n * depositor payout scriptPubKey.\n *\n * Prevents a malicious vault provider from substituting the payout destination\n * (or routing funds through a dust output to the correct address while sending\n * the actual value to an attacker-controlled script).\n *\n * @param payoutTxHex - Raw payout transaction hex\n * @param registeredPayoutScriptPubKey - On-chain registered scriptPubKey (hex, with or without 0x prefix)\n * @throws If scriptPubKey is invalid hex\n * @throws If the transaction has no outputs\n * @throws If the largest output does not pay to the registered scriptPubKey\n */\nexport function assertPayoutOutputMatchesRegistered(\n payoutTxHex: string,\n registeredPayoutScriptPubKey: string,\n): void {\n if (!isValidHex(registeredPayoutScriptPubKey)) {\n throw new Error(\"Invalid registeredPayoutScriptPubKey: not valid hex\");\n }\n\n const expectedScript = Buffer.from(\n stripHexPrefix(registeredPayoutScriptPubKey),\n \"hex\",\n );\n const payoutTx = Transaction.fromHex(stripHexPrefix(payoutTxHex));\n\n if (payoutTx.outs.length === 0) {\n throw new Error(\"Payout transaction has no outputs\");\n }\n\n const largestOutput = payoutTx.outs.reduce((max, output) =>\n output.value > max.value ? output : max,\n );\n\n if (!largestOutput.script.equals(expectedScript)) {\n throw new Error(\n \"Payout transaction does not pay to the registered depositor payout address\",\n );\n }\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","/**\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"],"names":["createPayoutScript","params","connector","createPayoutConnector","TAPROOT_SINGLE_SIG_WITNESS_STACK_SIZE","buildPayoutPsbt","payoutTxHex","stripHexPrefix","peginTxHex","assertTxHex","payoutConnector","payoutScriptBytes","hexToUint8Array","controlBlock","payoutTx","Transaction","peginTx","assertTx","psbt","Psbt","input0","input1","input0Txid","uint8ArrayToHex","peginTxid","input1Txid","expectedInput1Txid","peginPrevOut","input1PrevOut","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","assertPayoutOutputMatchesRegistered","registeredPayoutScriptPubKey","isValidHex","expectedScript","max","extractPayoutSignature","signedPsbtHex","depositorPubkey","inputIndex","signedPsbt","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","witnessStack","parseWitnessStack","sig","witness","items","offset","requireBytes","n","readVarInt","first","val","count","len","PsbtSubstitutionError","detail","parsePsbt","label","hex","cause","reason","REDACTED_HEX_PREFIX_LEN","redactHex","buf","redactTxid","internalHash","reversed","assertPsbtUnsignedTxMatches","requested","returned","i","r"],"mappings":";;;;AA8IA,eAAsBA,EACpBC,GAC6B;AAE7B,QAAMC,IAAY,MAAMC;AAAA,IACtB;AAAA,MACE,WA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;AACnD,UAAMC,IAAIH,EAAU,UAAUE,CAAC,GACzB,IAAID,EAAS,UAAUC,CAAC;AAC9B,QAAI,CAACC,EAAE,OAAO,OAAO,EAAE,MAAM;AAC3B,YAAM,IAAIjB;AAAA,QACR,UAAUgB,CAAC,oCAAoCR,EAAUS,EAAE,MAAM,CAAC,cAAcT,EAAU,EAAE,MAAM,CAAC;AAAA,MAAA;AAGvG,QAAIS,EAAE,UAAU,EAAE;AAChB,YAAM,IAAIjB;AAAA,QACR,UAAUgB,CAAC,6BAA6BC,EAAE,KAAK,cAAc,EAAE,KAAK;AAAA,MAAA;AAAA,EAG1E;AACF;"}
@@ -1,51 +1,51 @@
1
- import { Buffer as l } from "buffer";
2
- import { payments as u, networks as s } from "bitcoinjs-lib";
3
- const x = 192, a = 64, c = 66, h = 130, _ = 128;
1
+ import { Buffer as i } from "buffer";
2
+ import { payments as s, networks as a } from "bitcoinjs-lib";
3
+ const m = 192, f = 64, c = 66, d = 130, v = 128;
4
4
  function o(t) {
5
5
  return t.startsWith("0x") || t.startsWith("0X") ? t.slice(2) : t;
6
6
  }
7
- function H(t) {
7
+ function $(t) {
8
8
  return t.startsWith("0x") ? t : t.startsWith("0X") ? `0x${t.slice(2)}` : `0x${t}`;
9
9
  }
10
- function f(t) {
10
+ function u(t) {
11
11
  const e = o(t);
12
- if (!d(e))
12
+ if (!l(e))
13
13
  throw new Error(`Invalid hex string: ${t}`);
14
14
  const n = new Uint8Array(e.length / 2);
15
15
  for (let r = 0; r < e.length; r += 2)
16
16
  n[r / 2] = parseInt(e.slice(r, r + 2), 16);
17
17
  return n;
18
18
  }
19
- function E(t) {
19
+ function p(t) {
20
20
  return Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("");
21
21
  }
22
- function A(t) {
23
- return E(new Uint8Array(t.hash).slice().reverse());
22
+ function H(t) {
23
+ return p(new Uint8Array(t.hash).slice().reverse());
24
24
  }
25
- function b(t) {
25
+ function g(t) {
26
26
  return t.length === 32 ? t : t.slice(1, 33);
27
27
  }
28
- function d(t) {
28
+ function l(t) {
29
29
  return /^[0-9a-fA-F]*$/.test(t) && t.length % 2 === 0;
30
30
  }
31
31
  function w(t) {
32
32
  const e = o(t);
33
- if (!d(e))
33
+ if (!l(e))
34
34
  throw new Error(`Invalid hex characters in public key: ${t}`);
35
- if (e.length === a)
35
+ if (e.length === f)
36
36
  return e;
37
- if (e.length !== c && e.length !== h)
37
+ if (e.length !== c && e.length !== d)
38
38
  throw new Error(
39
- `Invalid public key length: ${e.length} (expected ${a}, ${c}, or ${h} hex chars)`
39
+ `Invalid public key length: ${e.length} (expected ${f}, ${c}, or ${d} hex chars)`
40
40
  );
41
- const n = f(e);
42
- return E(b(n));
41
+ const n = u(e);
42
+ return p(g(n));
43
43
  }
44
- function C(t) {
44
+ function _(t) {
45
45
  const e = o(t);
46
- return d(e);
46
+ return l(e);
47
47
  }
48
- function N(t, e) {
48
+ function A(t, e) {
49
49
  if (!e)
50
50
  throw new Error(
51
51
  "validateWalletPubkey requires expectedDepositorPubkey. Pass the on-chain registered depositor pubkey to avoid a self-comparison."
@@ -57,17 +57,17 @@ function N(t, e) {
57
57
  );
58
58
  return { walletPubkeyRaw: t, walletPubkeyXOnly: n, depositorPubkey: r };
59
59
  }
60
- const p = 100000000n;
61
- function S(t) {
60
+ const h = 100000000n;
61
+ function b(t) {
62
62
  if (t < 0n)
63
- return `-${S(-t)}`;
64
- const e = t / p;
65
- let r = (t % p).toString().padStart(8, "0");
63
+ return `-${b(-t)}`;
64
+ const e = t / h;
65
+ let r = (t % h).toString().padStart(8, "0");
66
66
  return r = r.replace(/0+$/, ""), r.length > 0 ? `${e}.${r}` : e.toString();
67
67
  }
68
- function k() {
68
+ function y() {
69
69
  try {
70
- u.p2tr({ internalPubkey: l.alloc(32, 1) });
70
+ s.p2tr({ internalPubkey: i.alloc(32, 1) });
71
71
  } catch (t) {
72
72
  if (t instanceof Error && t.message.includes("No ECC Library provided"))
73
73
  throw new Error(
@@ -75,38 +75,55 @@ function k() {
75
75
  );
76
76
  }
77
77
  }
78
- function y(t) {
78
+ function E(t) {
79
79
  switch (t) {
80
80
  case "bitcoin":
81
- return s.bitcoin;
81
+ return a.bitcoin;
82
82
  case "testnet":
83
83
  case "signet":
84
- return s.testnet;
84
+ return a.testnet;
85
85
  case "regtest":
86
- return s.regtest;
86
+ return a.regtest;
87
87
  default:
88
88
  throw new Error(`Unknown network: ${t}`);
89
89
  }
90
90
  }
91
- function m(t, e) {
92
- k();
93
- const n = f(w(t)), { address: r } = u.p2tr({
94
- internalPubkey: l.from(n),
95
- network: y(e)
91
+ function x(t, e) {
92
+ y();
93
+ const n = u(w(t)), { address: r } = s.p2tr({
94
+ internalPubkey: i.from(n),
95
+ network: E(e)
96
96
  });
97
97
  if (!r)
98
98
  throw new Error("Failed to derive taproot address from public key");
99
99
  return r;
100
100
  }
101
- function P(t, e) {
101
+ function C(t) {
102
+ return t.map(o).sort();
103
+ }
104
+ function N(t) {
105
+ y();
106
+ const e = o(t);
107
+ if (!/^[0-9a-fA-F]{64}$/.test(e))
108
+ throw new Error(
109
+ "Invalid x-only pubkey: must be 64 hex characters (32 bytes, no 0x prefix)"
110
+ );
111
+ const { output: n } = s.p2tr({
112
+ internalPubkey: i.from(e, "hex")
113
+ });
114
+ if (!n)
115
+ throw new Error("Failed to derive BIP-86 P2TR scriptPubKey");
116
+ return `0x${n.toString("hex")}`;
117
+ }
118
+ function S(t, e) {
102
119
  const n = o(t);
103
120
  if (n.length !== 66)
104
121
  throw new Error(
105
122
  `Native SegWit requires a compressed public key (66 hex chars), got ${n.length}`
106
123
  );
107
- const { address: r } = u.p2wpkh({
108
- pubkey: l.from(f(n)),
109
- network: y(e)
124
+ const { address: r } = s.p2wpkh({
125
+ pubkey: i.from(u(n)),
126
+ network: E(e)
110
127
  });
111
128
  if (!r)
112
129
  throw new Error(
@@ -117,15 +134,13 @@ function P(t, e) {
117
134
  function T(t, e, n) {
118
135
  const r = o(e);
119
136
  try {
120
- if (t === m(r, n))
137
+ if (t === x(r, n))
121
138
  return !0;
122
139
  } catch {
123
140
  }
124
- const i = [];
125
- r.length === c ? i.push(r) : r.length === a && i.push(`02${r}`, `03${r}`);
126
- for (const g of i)
141
+ if (r.length === c)
127
142
  try {
128
- if (t === P(g, n))
143
+ if (t === S(r, n))
129
144
  return !0;
130
145
  } catch {
131
146
  }
@@ -133,22 +148,24 @@ function T(t, e, n) {
133
148
  }
134
149
  export {
135
150
  c as C,
136
- _ as S,
137
- x as T,
138
- a as X,
139
- m as a,
140
- C as b,
141
- A as c,
142
- P as d,
143
- H as e,
144
- S as f,
145
- y as g,
146
- f as h,
151
+ v as S,
152
+ m as T,
153
+ f as X,
154
+ S as a,
155
+ x as b,
156
+ _ as c,
157
+ N as d,
158
+ $ as e,
159
+ b as f,
160
+ C as g,
161
+ u as h,
147
162
  T as i,
163
+ E as j,
164
+ H as k,
148
165
  w as p,
149
166
  o as s,
150
- b as t,
151
- E as u,
152
- N as v
167
+ g as t,
168
+ p as u,
169
+ A as v
153
170
  };
154
- //# sourceMappingURL=bitcoin-B0S8SHCX.js.map
171
+ //# sourceMappingURL=bitcoin-B5aNKtsk.js.map