@babylonlabs-io/ts-sdk 3.0.2 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (261) hide show
  1. package/dist/ApplicationRegistry.abi-s8cQ1ooR.js +160 -0
  2. package/dist/ApplicationRegistry.abi-s8cQ1ooR.js.map +1 -0
  3. package/dist/ApplicationRegistry.abi-sMiTWmnL.cjs +2 -0
  4. package/dist/ApplicationRegistry.abi-sMiTWmnL.cjs.map +1 -0
  5. package/dist/{BTCVaultRegistry.abi-BQ5tFNSu.cjs → BTCVaultRegistry.abi-CohlJX7c.cjs} +2 -2
  6. package/dist/{BTCVaultRegistry.abi-BQ5tFNSu.cjs.map → BTCVaultRegistry.abi-CohlJX7c.cjs.map} +1 -1
  7. package/dist/{BTCVaultRegistry.abi-B0x9_Bza.js → BTCVaultRegistry.abi-DBW0dyqH.js} +63 -1
  8. package/dist/{BTCVaultRegistry.abi-B0x9_Bza.js.map → BTCVaultRegistry.abi-DBW0dyqH.js.map} +1 -1
  9. package/dist/{PayoutManager-BSwbUQeF.js → PayoutManager-BZ212yml.js} +124 -123
  10. package/dist/PayoutManager-BZ212yml.js.map +1 -0
  11. package/dist/PayoutManager-DOdsgcUR.cjs +2 -0
  12. package/dist/PayoutManager-DOdsgcUR.cjs.map +1 -0
  13. package/dist/PeginManager-8EUlm10F.cjs +2 -0
  14. package/dist/{PeginManager-IgDHy_eU.cjs.map → PeginManager-8EUlm10F.cjs.map} +1 -1
  15. package/dist/{PeginManager-D8WGB8eN.js → PeginManager-QRwMUxZg.js} +45 -43
  16. package/dist/{PeginManager-D8WGB8eN.js.map → PeginManager-QRwMUxZg.js.map} +1 -1
  17. package/dist/{ProtocolParams.abi-q0AidvYX.js → ProtocolParams.abi-CKOVqFJP.js} +2 -158
  18. package/dist/ProtocolParams.abi-CKOVqFJP.js.map +1 -0
  19. package/dist/ProtocolParams.abi-CjrT0545.cjs +2 -0
  20. package/dist/ProtocolParams.abi-CjrT0545.cjs.map +1 -0
  21. package/dist/btcTxHash-BRZ8_EZq.js +9 -0
  22. package/dist/btcTxHash-BRZ8_EZq.js.map +1 -0
  23. package/dist/btcTxHash-CGb5BqFL.cjs +2 -0
  24. package/dist/btcTxHash-CGb5BqFL.cjs.map +1 -0
  25. package/dist/buildAndBroadcastReclaim-DjX7wVb2.cjs +2 -0
  26. package/dist/buildAndBroadcastReclaim-DjX7wVb2.cjs.map +1 -0
  27. package/dist/buildAndBroadcastReclaim-DoprHX7o.js +3077 -0
  28. package/dist/buildAndBroadcastReclaim-DoprHX7o.js.map +1 -0
  29. package/dist/buildVaultContextInputForClaim-9XZaqIiw.cjs +2 -0
  30. package/dist/buildVaultContextInputForClaim-9XZaqIiw.cjs.map +1 -0
  31. package/dist/buildVaultContextInputForClaim-DhBoQKyN.js +25 -0
  32. package/dist/buildVaultContextInputForClaim-DhBoQKyN.js.map +1 -0
  33. package/dist/constants-BeYquVd-.js +36 -0
  34. package/dist/constants-BeYquVd-.js.map +1 -0
  35. package/dist/constants-BwCg5K6R.cjs +2 -0
  36. package/dist/constants-BwCg5K6R.cjs.map +1 -0
  37. package/dist/{index-D2mybjXD.js → index-CVBtBjQ5.js} +2 -2
  38. package/dist/{index-D2mybjXD.js.map → index-CVBtBjQ5.js.map} +1 -1
  39. package/dist/{index-MRdle0fs.cjs → index-DpjYs5yr.cjs} +2 -2
  40. package/dist/{index-MRdle0fs.cjs.map → index-DpjYs5yr.cjs.map} +1 -1
  41. package/dist/index.cjs +1 -1
  42. package/dist/index.js +288 -260
  43. package/dist/index.js.map +1 -1
  44. package/dist/{noPayout-qBXWKwav.js → noPayout-B-vGXJ-V.js} +3 -3
  45. package/dist/{noPayout-qBXWKwav.js.map → noPayout-B-vGXJ-V.js.map} +1 -1
  46. package/dist/{noPayout-DAWBQ0eG.cjs → noPayout-DOHak0ui.cjs} +2 -2
  47. package/dist/{noPayout-DAWBQ0eG.cjs.map → noPayout-DOHak0ui.cjs.map} +1 -1
  48. package/dist/pegin-registration-client-BWMwxtr8.js +718 -0
  49. package/dist/pegin-registration-client-BWMwxtr8.js.map +1 -0
  50. package/dist/pegin-registration-client-D4EguWaz.cjs +2 -0
  51. package/dist/pegin-registration-client-D4EguWaz.cjs.map +1 -0
  52. package/dist/{primeVpAuth-BDWBKYhv.cjs → primeVpAuth-BPj2TPdD.cjs} +2 -2
  53. package/dist/{primeVpAuth-BDWBKYhv.cjs.map → primeVpAuth-BPj2TPdD.cjs.map} +1 -1
  54. package/dist/{primeVpAuth-D0ZnsjRi.js → primeVpAuth-CiCdRNGf.js} +2 -2
  55. package/dist/{primeVpAuth-D0ZnsjRi.js.map → primeVpAuth-CiCdRNGf.js.map} +1 -1
  56. package/dist/registration-records-CKLAv3gw.js +447 -0
  57. package/dist/registration-records-CKLAv3gw.js.map +1 -0
  58. package/dist/registration-records-DFQgBaYi.cjs +2 -0
  59. package/dist/registration-records-DFQgBaYi.cjs.map +1 -0
  60. package/dist/{secp256k1-D-H9jmd7.js → secp256k1-BuxBFUHm.js} +3 -3
  61. package/dist/{secp256k1-D-H9jmd7.js.map → secp256k1-BuxBFUHm.js.map} +1 -1
  62. package/dist/signer-set-reader-C1VmC9_U.js +264 -0
  63. package/dist/signer-set-reader-C1VmC9_U.js.map +1 -0
  64. package/dist/signer-set-reader-C6g47hdk.cjs +2 -0
  65. package/dist/signer-set-reader-C6g47hdk.cjs.map +1 -0
  66. package/dist/{signing-Dhr2t0Z6.js → signing-C1rR4tqs.js} +9 -15
  67. package/dist/signing-C1rR4tqs.js.map +1 -0
  68. package/dist/signing-DvISftFk.cjs +2 -0
  69. package/dist/signing-DvISftFk.cjs.map +1 -0
  70. package/dist/tbv/core/clients/eth/__tests__/registration-records.test.d.ts +2 -0
  71. package/dist/tbv/core/clients/eth/__tests__/registration-records.test.d.ts.map +1 -0
  72. package/dist/tbv/core/clients/eth/claimable-event-error.d.ts +14 -0
  73. package/dist/tbv/core/clients/eth/claimable-event-error.d.ts.map +1 -0
  74. package/dist/tbv/core/clients/eth/index.cjs +1 -1
  75. package/dist/tbv/core/clients/eth/index.d.ts +3 -1
  76. package/dist/tbv/core/clients/eth/index.d.ts.map +1 -1
  77. package/dist/tbv/core/clients/eth/index.js +27 -21
  78. package/dist/tbv/core/clients/eth/index.js.map +1 -1
  79. package/dist/tbv/core/clients/eth/payout-script.d.ts +8 -0
  80. package/dist/tbv/core/clients/eth/payout-script.d.ts.map +1 -1
  81. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts +13 -0
  82. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -1
  83. package/dist/tbv/core/clients/eth/registration-logs-error.d.ts +11 -1
  84. package/dist/tbv/core/clients/eth/registration-logs-error.d.ts.map +1 -1
  85. package/dist/tbv/core/clients/eth/registration-records.d.ts +29 -0
  86. package/dist/tbv/core/clients/eth/registration-records.d.ts.map +1 -0
  87. package/dist/tbv/core/clients/eth/types.d.ts +120 -3
  88. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  89. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +9 -10
  90. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  91. package/dist/tbv/core/clients/index.cjs +1 -1
  92. package/dist/tbv/core/clients/index.js +56 -50
  93. package/dist/tbv/core/clients/index.js.map +1 -1
  94. package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
  95. package/dist/tbv/core/clients/vault-provider/status/index.js +1 -1
  96. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +45 -0
  97. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
  98. package/dist/tbv/core/contracts/index.cjs +1 -1
  99. package/dist/tbv/core/contracts/index.js +16 -15
  100. package/dist/tbv/core/contracts/index.js.map +1 -1
  101. package/dist/tbv/core/deposit-terms/__tests__/claimSiblings.test.d.ts +2 -0
  102. package/dist/tbv/core/deposit-terms/__tests__/claimSiblings.test.d.ts.map +1 -0
  103. package/dist/tbv/core/deposit-terms/__tests__/fixtures/realFundedPrePegin.d.ts +29 -0
  104. package/dist/tbv/core/deposit-terms/__tests__/fixtures/realFundedPrePegin.d.ts.map +1 -0
  105. package/dist/tbv/core/deposit-terms/__tests__/fundedPrePeginFee.test.d.ts +2 -0
  106. package/dist/tbv/core/deposit-terms/__tests__/fundedPrePeginFee.test.d.ts.map +1 -0
  107. package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsForClaim.golden.test.d.ts +2 -0
  108. package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsForClaim.golden.test.d.ts.map +1 -0
  109. package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsForClaim.test.d.ts +2 -0
  110. package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsForClaim.test.d.ts.map +1 -0
  111. package/dist/tbv/core/deposit-terms/claimSiblings.d.ts +23 -0
  112. package/dist/tbv/core/deposit-terms/claimSiblings.d.ts.map +1 -0
  113. package/dist/tbv/core/deposit-terms/fundedPrePeginFee.d.ts +15 -0
  114. package/dist/tbv/core/deposit-terms/fundedPrePeginFee.d.ts.map +1 -0
  115. package/dist/tbv/core/deposit-terms/index.d.ts +3 -0
  116. package/dist/tbv/core/deposit-terms/index.d.ts.map +1 -1
  117. package/dist/tbv/core/deposit-terms/rebuildDepositTermsForClaim.d.ts +40 -0
  118. package/dist/tbv/core/deposit-terms/rebuildDepositTermsForClaim.d.ts.map +1 -0
  119. package/dist/tbv/core/index.cjs +1 -1
  120. package/dist/tbv/core/index.js +287 -259
  121. package/dist/tbv/core/index.js.map +1 -1
  122. package/dist/tbv/core/managers/index.cjs +1 -1
  123. package/dist/tbv/core/managers/index.js +2 -2
  124. package/dist/tbv/core/managers/pegin/signPsbtsWithFallback.d.ts +6 -2
  125. package/dist/tbv/core/managers/pegin/signPsbtsWithFallback.d.ts.map +1 -1
  126. package/dist/tbv/core/primitives/index.cjs +1 -1
  127. package/dist/tbv/core/primitives/index.js +4 -4
  128. package/dist/tbv/core/primitives/psbt/constants.d.ts +54 -6
  129. package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
  130. package/dist/tbv/core/services/delegated-claim/__tests__/assembleWatchtowerArtifactsFromSignatures.test.d.ts +2 -0
  131. package/dist/tbv/core/services/delegated-claim/__tests__/assembleWatchtowerArtifactsFromSignatures.test.d.ts.map +1 -0
  132. package/dist/tbv/core/services/delegated-claim/__tests__/assertBinding.test.d.ts +2 -0
  133. package/dist/tbv/core/services/delegated-claim/__tests__/assertBinding.test.d.ts.map +1 -0
  134. package/dist/tbv/core/services/delegated-claim/__tests__/assertPayoutFeeAndTimelocks.test.d.ts +2 -0
  135. package/dist/tbv/core/services/delegated-claim/__tests__/assertPayoutFeeAndTimelocks.test.d.ts.map +1 -0
  136. package/dist/tbv/core/services/delegated-claim/__tests__/fixtures/delegatedClaimPsbts.d.ts +49 -0
  137. package/dist/tbv/core/services/delegated-claim/__tests__/fixtures/delegatedClaimPsbts.d.ts.map +1 -0
  138. package/dist/tbv/core/services/delegated-claim/__tests__/payoutBinding.test.d.ts +2 -0
  139. package/dist/tbv/core/services/delegated-claim/__tests__/payoutBinding.test.d.ts.map +1 -0
  140. package/dist/tbv/core/services/delegated-claim/__tests__/payoutInputLeaf.test.d.ts +2 -0
  141. package/dist/tbv/core/services/delegated-claim/__tests__/payoutInputLeaf.test.d.ts.map +1 -0
  142. package/dist/tbv/core/services/delegated-claim/__tests__/planDelegatedClaimSigning.test.d.ts +2 -0
  143. package/dist/tbv/core/services/delegated-claim/__tests__/planDelegatedClaimSigning.test.d.ts.map +1 -0
  144. package/dist/tbv/core/services/delegated-claim/__tests__/readDelegatedClaimVaultContext.test.d.ts +2 -0
  145. package/dist/tbv/core/services/delegated-claim/__tests__/readDelegatedClaimVaultContext.test.d.ts.map +1 -0
  146. package/dist/tbv/core/services/delegated-claim/__tests__/realSchnorrVerification.test.d.ts +2 -0
  147. package/dist/tbv/core/services/delegated-claim/__tests__/realSchnorrVerification.test.d.ts.map +1 -0
  148. package/dist/tbv/core/services/delegated-claim/__tests__/signDelegatedClaimPlan.test.d.ts +2 -0
  149. package/dist/tbv/core/services/delegated-claim/__tests__/signDelegatedClaimPlan.test.d.ts.map +1 -0
  150. package/dist/tbv/core/services/delegated-claim/__tests__/signingRequests.test.d.ts +2 -0
  151. package/dist/tbv/core/services/delegated-claim/__tests__/signingRequests.test.d.ts.map +1 -0
  152. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts +34 -9
  153. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts.map +1 -1
  154. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifactsFromSignatures.d.ts +36 -0
  155. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifactsFromSignatures.d.ts.map +1 -0
  156. package/dist/tbv/core/services/delegated-claim/assertBinding.d.ts +37 -0
  157. package/dist/tbv/core/services/delegated-claim/assertBinding.d.ts.map +1 -0
  158. package/dist/tbv/core/services/delegated-claim/assertPayoutFeeAndTimelocks.d.ts +35 -0
  159. package/dist/tbv/core/services/delegated-claim/assertPayoutFeeAndTimelocks.d.ts.map +1 -0
  160. package/dist/tbv/core/services/delegated-claim/index.d.ts +22 -4
  161. package/dist/tbv/core/services/delegated-claim/index.d.ts.map +1 -1
  162. package/dist/tbv/core/services/delegated-claim/payoutBinding.d.ts +10 -4
  163. package/dist/tbv/core/services/delegated-claim/payoutBinding.d.ts.map +1 -1
  164. package/dist/tbv/core/services/delegated-claim/payoutInputLeaf.d.ts +34 -0
  165. package/dist/tbv/core/services/delegated-claim/payoutInputLeaf.d.ts.map +1 -0
  166. package/dist/tbv/core/services/delegated-claim/planDelegatedClaimSigning.d.ts +43 -0
  167. package/dist/tbv/core/services/delegated-claim/planDelegatedClaimSigning.d.ts.map +1 -0
  168. package/dist/tbv/core/services/delegated-claim/readDelegatedClaimVaultContext.d.ts +70 -0
  169. package/dist/tbv/core/services/delegated-claim/readDelegatedClaimVaultContext.d.ts.map +1 -0
  170. package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts +31 -2
  171. package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts.map +1 -1
  172. package/dist/tbv/core/services/delegated-claim/signDelegatedClaimPlan.d.ts +110 -0
  173. package/dist/tbv/core/services/delegated-claim/signDelegatedClaimPlan.d.ts.map +1 -0
  174. package/dist/tbv/core/services/delegated-claim/signingRequests.d.ts +24 -0
  175. package/dist/tbv/core/services/delegated-claim/signingRequests.d.ts.map +1 -0
  176. package/dist/tbv/core/services/delegated-claim/types.d.ts +110 -9
  177. package/dist/tbv/core/services/delegated-claim/types.d.ts.map +1 -1
  178. package/dist/tbv/core/services/delegated-claim/vaultIdBinding.d.ts +16 -1
  179. package/dist/tbv/core/services/delegated-claim/vaultIdBinding.d.ts.map +1 -1
  180. package/dist/tbv/core/services/delegated-claim/verifySignatureForRequest.d.ts +19 -0
  181. package/dist/tbv/core/services/delegated-claim/verifySignatureForRequest.d.ts.map +1 -0
  182. package/dist/tbv/core/services/delegated-claim/verifyingKeyBinding.d.ts +40 -0
  183. package/dist/tbv/core/services/delegated-claim/verifyingKeyBinding.d.ts.map +1 -0
  184. package/dist/tbv/core/services/delegated-claim/walletIdentity.d.ts +23 -0
  185. package/dist/tbv/core/services/delegated-claim/walletIdentity.d.ts.map +1 -0
  186. package/dist/tbv/core/services/index.cjs +1 -1
  187. package/dist/tbv/core/services/index.js +89 -76
  188. package/dist/tbv/core/services/participants/__tests__/readStampedParticipantKeys.test.d.ts +2 -0
  189. package/dist/tbv/core/services/participants/__tests__/readStampedParticipantKeys.test.d.ts.map +1 -0
  190. package/dist/tbv/core/services/participants/index.d.ts +1 -0
  191. package/dist/tbv/core/services/participants/index.d.ts.map +1 -1
  192. package/dist/tbv/core/services/participants/readStampedParticipantKeys.d.ts +29 -0
  193. package/dist/tbv/core/services/participants/readStampedParticipantKeys.d.ts.map +1 -0
  194. package/dist/tbv/core/services/participants/resolveParticipantKeys.d.ts +1 -1
  195. package/dist/tbv/core/services/participants/resolveParticipantKeys.d.ts.map +1 -1
  196. package/dist/tbv/core/utils/index.cjs +1 -1
  197. package/dist/tbv/core/utils/index.js +47 -46
  198. package/dist/tbv/core/utils/index.js.map +1 -1
  199. package/dist/tbv/core/vault-secrets/__tests__/buildVaultContextInputForClaim.test.d.ts +2 -0
  200. package/dist/tbv/core/vault-secrets/__tests__/buildVaultContextInputForClaim.test.d.ts.map +1 -0
  201. package/dist/tbv/core/vault-secrets/buildVaultContextInputForClaim.d.ts +18 -0
  202. package/dist/tbv/core/vault-secrets/buildVaultContextInputForClaim.d.ts.map +1 -0
  203. package/dist/tbv/core/vault-secrets/index.cjs +1 -1
  204. package/dist/tbv/core/vault-secrets/index.d.ts +1 -0
  205. package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -1
  206. package/dist/tbv/core/vault-secrets/index.js +12 -10
  207. package/dist/tbv/core/vault-secrets/index.js.map +1 -1
  208. package/dist/tbv/index.cjs +1 -1
  209. package/dist/tbv/index.js +287 -259
  210. package/dist/tbv/index.js.map +1 -1
  211. package/dist/toRefundInputs-BZXvuOMY.cjs +2 -0
  212. package/dist/toRefundInputs-BZXvuOMY.cjs.map +1 -0
  213. package/dist/toRefundInputs-dKDSvpVI.js +698 -0
  214. package/dist/toRefundInputs-dKDSvpVI.js.map +1 -0
  215. package/dist/types-Bda75Od0.cjs +2 -0
  216. package/dist/types-Bda75Od0.cjs.map +1 -0
  217. package/dist/types-C5jj3Cc-.js +198 -0
  218. package/dist/types-C5jj3Cc-.js.map +1 -0
  219. package/dist/{verifyKeyPathSchnorrSignature-Gm9EmZkx.cjs → verifyKeyPathSchnorrSignature-CQUut2-O.cjs} +2 -2
  220. package/dist/{verifyKeyPathSchnorrSignature-Gm9EmZkx.cjs.map → verifyKeyPathSchnorrSignature-CQUut2-O.cjs.map} +1 -1
  221. package/dist/{verifyKeyPathSchnorrSignature-BQHNhRj6.js → verifyKeyPathSchnorrSignature-DxPbeSdQ.js} +2 -2
  222. package/dist/{verifyKeyPathSchnorrSignature-BQHNhRj6.js.map → verifyKeyPathSchnorrSignature-DxPbeSdQ.js.map} +1 -1
  223. package/dist/{verifyScriptPathSchnorrSignature-CpjSTfMj.js → verifyScriptPathSchnorrSignature-B3-VkvnK.js} +6 -4
  224. package/dist/{verifyScriptPathSchnorrSignature-CpjSTfMj.js.map → verifyScriptPathSchnorrSignature-B3-VkvnK.js.map} +1 -1
  225. package/dist/{verifyScriptPathSchnorrSignature-BKZihCjk.cjs → verifyScriptPathSchnorrSignature-D2t1yACC.cjs} +2 -2
  226. package/dist/{verifyScriptPathSchnorrSignature-BKZihCjk.cjs.map → verifyScriptPathSchnorrSignature-D2t1yACC.cjs.map} +1 -1
  227. package/package.json +4 -4
  228. package/dist/PayoutManager-B6GFbG3X.cjs +0 -2
  229. package/dist/PayoutManager-B6GFbG3X.cjs.map +0 -1
  230. package/dist/PayoutManager-BSwbUQeF.js.map +0 -1
  231. package/dist/PeginManager-IgDHy_eU.cjs +0 -2
  232. package/dist/ProtocolParams.abi-Db2USqQm.cjs +0 -2
  233. package/dist/ProtocolParams.abi-Db2USqQm.cjs.map +0 -1
  234. package/dist/ProtocolParams.abi-q0AidvYX.js.map +0 -1
  235. package/dist/buildAndBroadcastReclaim-B8aFMGf-.cjs +0 -2
  236. package/dist/buildAndBroadcastReclaim-B8aFMGf-.cjs.map +0 -1
  237. package/dist/buildAndBroadcastReclaim-D5520lbL.js +0 -2210
  238. package/dist/buildAndBroadcastReclaim-D5520lbL.js.map +0 -1
  239. package/dist/constants-BTZdyOuk.cjs +0 -2
  240. package/dist/constants-BTZdyOuk.cjs.map +0 -1
  241. package/dist/constants-D5vORbQE.js +0 -29
  242. package/dist/constants-D5vORbQE.js.map +0 -1
  243. package/dist/onChainBtcPubkey-BlzxYImF.cjs +0 -2
  244. package/dist/onChainBtcPubkey-BlzxYImF.cjs.map +0 -1
  245. package/dist/onChainBtcPubkey-CCTdl53s.js +0 -159
  246. package/dist/onChainBtcPubkey-CCTdl53s.js.map +0 -1
  247. package/dist/pegin-registration-client-B0j6ugt9.cjs +0 -2
  248. package/dist/pegin-registration-client-B0j6ugt9.cjs.map +0 -1
  249. package/dist/pegin-registration-client-ilkV1mLP.js +0 -878
  250. package/dist/pegin-registration-client-ilkV1mLP.js.map +0 -1
  251. package/dist/signing-3l5Aqd-H.cjs +0 -2
  252. package/dist/signing-3l5Aqd-H.cjs.map +0 -1
  253. package/dist/signing-Dhr2t0Z6.js.map +0 -1
  254. package/dist/toRefundInputs-10RYIfh1.js +0 -559
  255. package/dist/toRefundInputs-10RYIfh1.js.map +0 -1
  256. package/dist/toRefundInputs-a-0HRyrl.cjs +0 -2
  257. package/dist/toRefundInputs-a-0HRyrl.cjs.map +0 -1
  258. package/dist/types-BueQoMjO.cjs +0 -2
  259. package/dist/types-BueQoMjO.cjs.map +0 -1
  260. package/dist/types-DGkejGZH.js +0 -456
  261. package/dist/types-DGkejGZH.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"noPayout-qBXWKwav.js","sources":["../src/tbv/core/wasm/value-guards.ts","../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/reclaim.ts","../src/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Runtime guard for satoshi amounts crossing into the WASM FFI boundary.\n *\n * `new BigUint64Array(values)` is the only way satoshi amounts are handed to\n * the constructor, and a runtime cast (`as readonly bigint[]`) lets a caller\n * pass a non-bigint or non-positive element that `BigUint64Array` would either\n * reject cryptically or, in its length-arg form, silently zero-fill. Values\n * above the u64 maximum are worse still: `BigUint64Array` wraps them mod 2^64\n * without complaint, turning an oversized amount into a small one.\n * {@link assertPositiveBigintArray} validates such inputs before the\n * typed-array construction.\n *\n * Mirrors the `assertPositiveBigintArray` half of `value-guards.ts` in\n * `@babylonlabs-io/babylon-tbv-rust-wasm`; that one function is pinned to the\n * engine's source copy by `__tests__/value-guards.test.ts`. The engine's other\n * guard, `assertWasmBigint`, has no counterpart here: the engine applies it to\n * its own WASM return values before they reach this package.\n */\n\n/** Largest value BigUint64Array stores without wrapping mod 2^64 (2^64 − 1). */\nconst U64_MAX = (1n << 64n) - 1n;\n\n/**\n * Assert a value is a non-empty array of strictly-positive `bigint`s and return\n * it narrowed, ready to feed into `new BigUint64Array(...)`.\n *\n * @param values - The candidate array of satoshi amounts.\n * @param label - Human-readable name used in the thrown error.\n * @throws If `values` is not an array, is empty, or contains any element that is\n * not a `bigint`, is not strictly greater than 0, or exceeds the u64 maximum\n * (which `BigUint64Array` would otherwise wrap mod 2^64).\n */\nexport function assertPositiveBigintArray(\n values: unknown,\n label: string,\n): bigint[] {\n if (!Array.isArray(values)) {\n throw new Error(\n `${label} must be an array of positive bigints (got ${typeof values}).`,\n );\n }\n if (values.length === 0) {\n throw new Error(`${label} must not be empty.`);\n }\n values.forEach((value, index) => {\n if (typeof value !== \"bigint\") {\n throw new Error(\n `${label}[${index}] must be a bigint (got ${typeof value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n if (value <= 0n) {\n throw new Error(`${label}[${index}] must be > 0 (got ${value}).`);\n }\n if (value > U64_MAX) {\n throw new Error(\n `${label}[${index}] must fit in a u64 (got ${value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n });\n return values as bigint[];\n}\n","/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport { loadTbvWasm, tapInternalPubkey } from \"../../wasm\";\nimport { assertPositiveBigintArray } from \"../../wasm/value-guards\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\nimport { REFUND_TX_LOCKTIME, REFUND_TX_VERSION } from \"./constants\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<depositorPubkey> OP_CHECKSIGVERIFY <timelockRefund>\n * OP_CHECKSEQUENCEVERIFY` — btc-vault `connectors/prepegin_htlc.rs`\n * `generate_refund_script`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n const { WasmPrePeginTx } = await loadTbvWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: typeof unfundedTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against an independent\n // TypeScript derivation and the funded transaction bytes.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const wasmHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n const expectedHtlc = deriveExpectedPrePeginHtlc(prePeginParams, hashlock);\n const expectedHtlcScriptPubKey = expectedHtlc.scriptPubKey.toString(\"hex\");\n if (wasmHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `WASM HTLC scriptPubKey ${wasmHtlcScriptPubKey} does not match the ` +\n `independently derived scriptPubKey ${expectedHtlcScriptPubKey}.`,\n );\n }\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + p2aAnchorValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.version !== REFUND_TX_VERSION) {\n throw new Error(\n `Refund transaction version ${refundTx.version} does not match ` +\n `protocol version ${REFUND_TX_VERSION}.`,\n );\n }\n if (refundTx.locktime !== REFUND_TX_LOCKTIME) {\n throw new Error(\n `Refund transaction locktime ${refundTx.locktime} does not match ` +\n `protocol locktime ${REFUND_TX_LOCKTIME}.`,\n );\n }\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n if (refundInput.sequence !== prePeginParams.timelockRefund) {\n throw new Error(\n `Refund input sequence ${refundInput.sequence} does not match ` +\n `timelockRefund ${prePeginParams.timelockRefund}.`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.refundScript,\n controlBlock: expectedHtlc.refundControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * Reclaim PSBT Builder Primitive\n *\n * Builds an unsigned PSBT that sweeps the depositor-claim reserve — PegIn\n * vout 1 — back to the depositor's own BIP-86 address.\n *\n * The reserve funds the depositor's `claim_tx`, their recourse if the vault\n * provider fails during peg-out. When the vault provider claims instead and\n * the depositor withdraws normally, nothing ever spends it. This primitive is\n * the only thing in the repository that can.\n *\n * Spend path: the single `<depositor> OP_CHECKSIG` tapleaf (see\n * ./depositorClaim). No timelock, no counterparty signature — the depositor's\n * Schnorr signature alone. That is also why the *caller* must gate: this\n * builder will happily sweep a reserve whose vault is still live, which would\n * permanently void the depositor's pre-signed recourse graph. Eligibility is\n * enforced upstream, in the service.\n *\n * @module primitives/psbt/reclaim\n */\n\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { DUST_THRESHOLD } from \"../../utils/fee/constants\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport {\n PEGIN_DEPOSITOR_CLAIM_VOUT,\n deriveDepositorClaimDescriptor,\n} from \"./depositorClaim\";\n\n/**\n * nVersion for the reclaim transaction. Plain v2, not TRUC: the reserve is only\n * offered once its PegIn is deeply confirmed, so the v2/v3 PegIn's nVersion-3\n * topology limits no longer constrain its children.\n */\nconst RECLAIM_TX_VERSION = 2;\n\n/**\n * nSequence for every reclaim input: RBF-enabled, no relative timelock. The\n * claim leaf carries no CSV, so this is a fee-bumping signal only.\n */\nconst RECLAIM_INPUT_SEQUENCE = 0xfffffffd;\n\n/**\n * Weight units of the reclaim transaction's skeleton — everything except the\n * inputs. Non-witness `version(4) + inCount(1) + outCount(1) + locktime(4) +\n * output(8 + 1 + 34)` = 53 B × 4, plus the 2 WU SegWit marker and flag.\n */\nconst RECLAIM_SKELETON_WEIGHT_UNITS = 214;\n\n/**\n * Weight units each script-path input adds. Non-witness `outpoint(36) +\n * scriptSigLen(1) + sequence(4)` = 41 B × 4 = 164, plus a witness of\n * `stackCount(1) + sig(1 + 64) + leafScript(1 + 34) + controlBlock(1 + 33)` =\n * 135 WU.\n *\n * Exact rather than conservative: every element is fixed-length here — a\n * 64-byte BIP-340 signature under SIGHASH_DEFAULT, the 34-byte leaf, and a\n * 33-byte control block with no merkle path.\n */\nconst RECLAIM_INPUT_WEIGHT_UNITS = 299;\n\n/** Weight units per virtual byte. */\nconst WEIGHT_UNITS_PER_VBYTE = 4;\n\n/**\n * Virtual size of an N-in/1-out reclaim transaction.\n *\n * `REFUND_VSIZE = 160` does not generalise to N inputs, and\n * `computePeginBaseFeeSats` is wrong for this shape entirely — its\n * `P2TR_INPUT_SIZE = 58` is a *key-path* input and under-fees a script-path\n * spend by roughly a quarter.\n *\n * N=1 → 129 vB; each additional input adds 75 vB.\n */\nexport function reclaimVsize(numInputs: number): number {\n if (!Number.isInteger(numInputs) || numInputs < 1) {\n throw new Error(\n `Reclaim input count must be a positive integer, got ${numInputs}.`,\n );\n }\n return Math.ceil(\n (RECLAIM_SKELETON_WEIGHT_UNITS +\n RECLAIM_INPUT_WEIGHT_UNITS * numInputs) /\n WEIGHT_UNITS_PER_VBYTE,\n );\n}\n\n/** Absolute fee in satoshis for an N-in/1-out reclaim at a given rate. */\nexport function estimateReclaimFeeSats(\n feeRateSatsVb: number,\n numInputs: number,\n): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `Reclaim fee rate must be a positive number, got ${feeRateSatsVb}.`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * reclaimVsize(numInputs)));\n}\n\n/** One depositor-claim reserve to sweep, with the material to bind it. */\nexport interface ReclaimReserve {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Authoritative: its SegWit\n * txid equals the broadcast PegIn's, and its `outs[1]` carries the reserve's\n * script and value at no extra RPC cost.\n */\n depositorSignedPeginTxHex: string;\n /** Independent chain observation of `peginTxid:1` (esplora UTXO lookup). */\n observed: {\n /**\n * The outpoint the caller actually issued its chain lookup against, so the\n * observation below can be tied to the input this builder adds.\n *\n * Without it the script and value binds prove only that *some* UTXO has\n * this shape — the claim script is a pure function of the depositor key and\n * so is byte-identical across every vault they own, and the value is a pure\n * function of protocol parameters. Neither distinguishes one of the\n * depositor's vaults from another.\n *\n * Txid in display order, 64 hex chars, with or without `0x` prefix.\n */\n txid: string;\n /** Vout the lookup was issued against. Must be the claim vout. */\n vout: number;\n /** scriptPubKey hex, with or without `0x` prefix. */\n scriptPubKey: string;\n /** Output value in satoshis. */\n value: bigint;\n };\n /**\n * The reserve value recomputed from this vault's protocol parameters via\n * `computeMinClaimValue`. Bound so a doctored PegIn that agrees with itself\n * and with a compromised indexer still fails.\n */\n expectedValue: bigint;\n}\n\nexport interface BuildReclaimPsbtParams {\n /**\n * The **connected wallet's live** x-only pubkey, 64-char hex. Never the\n * indexer's `depositorBtcPubkey`: re-deriving from the live key is what\n * proves the wallet about to sign is the wallet that can spend, and rejects\n * the wrong-wallet case with an error instead of an unspendable broadcast.\n */\n depositorPubkey: string;\n /**\n * Reserves to sweep. An array so batching several vaults into one\n * transaction is a later change rather than a rewrite; today the app passes\n * exactly one.\n */\n inputs: ReclaimReserve[];\n /** Absolute fee in satoshis. The caller sizes it; see `reclaimVsize`. */\n feeSats: bigint;\n}\n\nexport interface BuildReclaimPsbtResult {\n /** PSBT hex ready for depositor signing. */\n psbtHex: string;\n /** Value of the single output — what the depositor actually receives. */\n outputValue: bigint;\n /** Sum of the swept reserves, before fee. */\n totalInputValue: bigint;\n}\n\n/**\n * Build the N-in/1-out reclaim PSBT.\n *\n * Every input is bound three ways before it reaches the PSBT: the contract's\n * PegIn bytes, the chain observation, and a JS re-derivation from the live\n * wallet key must agree on both script and value. Any disagreement throws.\n * The observation must also name the outpoint it was taken from, since script\n * and value alone repeat across all of a depositor's vaults.\n *\n * Binding the input to the *vault* that was asked for is a further step, and\n * it belongs to the service: it needs the vault id derivation, which is async.\n * See `services/reclaim/buildAndBroadcastReclaim`.\n *\n * @throws If `inputs` is empty, the fee is non-positive, any input fails its\n * outpoint, script or value bind, or the resulting output would be at or\n * below dust.\n */\nexport function buildReclaimPsbt(\n params: BuildReclaimPsbtParams,\n): BuildReclaimPsbtResult {\n const { depositorPubkey, inputs, feeSats } = params;\n\n if (inputs.length === 0) {\n throw new Error(\"Reclaim requires at least one input; got none.\");\n }\n if (feeSats <= 0n) {\n throw new Error(\n `Reclaim fee must be positive, got ${feeSats} sat. Refusing to build a ` +\n `transaction that would not relay.`,\n );\n }\n\n // One derivation, reused for every input's bind and for the destination.\n const descriptor = deriveDepositorClaimDescriptor(depositorPubkey);\n const expectedScriptPubKey = uint8ArrayToHex(\n new Uint8Array(descriptor.scriptPubKey),\n ).toLowerCase();\n\n const psbt = new Psbt();\n psbt.setVersion(RECLAIM_TX_VERSION);\n psbt.setLocktime(0);\n\n let totalInputValue = 0n;\n const seenOutpoints = new Set<string>();\n\n inputs.forEach((input, i) => {\n const peginTx = Transaction.fromHex(\n stripHexPrefix(input.depositorSignedPeginTxHex),\n );\n const peginTxid = peginTx.getId();\n\n const claimOut = peginTx.outs[PEGIN_DEPOSITOR_CLAIM_VOUT];\n if (!claimOut) {\n throw new Error(\n `PegIn ${peginTxid} has no output at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${peginTx.outs.length}); ` +\n `there is no depositor-claim reserve to reclaim.`,\n );\n }\n\n // Bind 0: the observation is of *this* outpoint. Everything below compares\n // a script and a value, both of which repeat across every vault this\n // depositor owns under the same protocol parameters — so without this the\n // remaining binds cannot tell one of their vaults from another, and a\n // caller that resolved the wrong vault would sweep it with every check\n // passing. The independent source is the PegIn the PSBT is built from; the\n // esplora response cannot serve here because `getUtxoInfo` echoes back the\n // txid and vout it was called with rather than reading them from the body.\n const observedTxid = stripHexPrefix(input.observed.txid).toLowerCase();\n if (observedTxid !== peginTxid) {\n throw new Error(\n `Input ${i}: the observation is of ${observedTxid}, but this input ` +\n `spends PegIn ${peginTxid}. Reclaim refused — the reserve that was ` +\n `looked up is not the one being swept.`,\n );\n }\n if (input.observed.vout !== PEGIN_DEPOSITOR_CLAIM_VOUT) {\n throw new Error(\n `Input ${i}: the observation is of vout ${input.observed.vout}, but ` +\n `the depositor-claim reserve is at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`,\n );\n }\n\n // Bind 1: the contract's PegIn bytes against the JS re-derivation from the\n // live wallet key. This is the assertion that proves the connected wallet\n // can actually spend the output we are about to sign for.\n const contractScriptPubKey = uint8ArrayToHex(\n new Uint8Array(claimOut.script),\n ).toLowerCase();\n if (contractScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} pays ` +\n `${contractScriptPubKey}, but the connected wallet's depositor-claim ` +\n `script is ${expectedScriptPubKey}. Reclaim refused — this reserve ` +\n `belongs to a different wallet.`,\n );\n }\n\n // Bind 2: the independent chain observation must agree with both.\n const observedScriptPubKey = stripHexPrefix(\n input.observed.scriptPubKey,\n ).toLowerCase();\n if (observedScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: the observed UTXO ${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `pays ${observedScriptPubKey}, expected ${expectedScriptPubKey}. ` +\n `Reclaim refused — chain state disagrees with the contract's PegIn.`,\n );\n }\n\n // Value bind, same three ways.\n const contractValue = BigInt(claimOut.value);\n if (contractValue !== input.observed.value) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but the observed UTXO carries ` +\n `${input.observed.value} sat. Reclaim refused.`,\n );\n }\n if (contractValue !== input.expectedValue) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but this vault's parameters compute a ` +\n `depositor-claim value of ${input.expectedValue} sat. Reclaim refused.`,\n );\n }\n\n // A batch that names the same vault twice would otherwise double-count the\n // swept total and then fail deep inside bitcoinjs. Reject it here, where\n // the message can say which input is the duplicate.\n const outpoint = `${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT}`;\n if (seenOutpoints.has(outpoint)) {\n throw new Error(\n `Input ${i} repeats outpoint ${outpoint}, which is already being ` +\n `swept by an earlier input. Reclaim refused.`,\n );\n }\n seenOutpoints.add(outpoint);\n\n totalInputValue += contractValue;\n\n psbt.addInput({\n hash: peginTxid,\n index: PEGIN_DEPOSITOR_CLAIM_VOUT,\n sequence: RECLAIM_INPUT_SEQUENCE,\n witnessUtxo: { script: claimOut.script, value: claimOut.value },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: descriptor.leafScript,\n controlBlock: descriptor.controlBlock,\n },\n ],\n tapInternalKey: descriptor.internalKey,\n });\n });\n\n if (feeSats >= totalInputValue) {\n throw new Error(\n `Reclaim fee ${feeSats} sat is not less than the swept total ` +\n `${totalInputValue} sat. Refusing to build a transaction with no output.`,\n );\n }\n\n const outputValue = totalInputValue - feeSats;\n if (outputValue <= DUST_THRESHOLD) {\n throw new Error(\n `Reclaim output ${outputValue} sat is at or below the dust threshold ` +\n `${DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it ` +\n `is until fee rates fall.`,\n );\n }\n\n const destination = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(depositorPubkey),\n );\n psbt.addOutput({\n script: Buffer.from(hexToUint8Array(destination)),\n value: Number(outputValue),\n });\n\n return { psbtHex: psbt.toHex(), outputValue, totalInputValue };\n}\n","/**\n * Finalize a Taproot script-path spend from the PSBT *we* built, using only the\n * verified signatures the wallet returned.\n *\n * Why this exists. The obvious shape — hand the wallet's PSBT to\n * `finalizeAllInputs()` — puts wallet-controlled bytes on the trust path even\n * when the signature itself has been verified.\n * `assertPsbtUnsignedTxMatches` deliberately pins only the unsigned\n * transaction and skips per-input metadata, so `tapLeafScript`, `controlBlock`\n * and `tapKeySig` all survive from the wallet's response untouched. And\n * bitcoinjs-lib checks key-spend first (`src/psbt.js`, `_finalizeTaprootInput`:\n * \"Check key spend first. Increased privacy and reduced block space.\"), so a\n * returned `tapKeySig` wins outright and `tapScriptSig` is never consulted.\n * Every output the depositor-claim reserve and the HTLC refund spend from uses\n * a NUMS internal key, so the resulting key-path witness cannot satisfy the\n * script — the transaction is rejected at broadcast, after a wallet prompt the\n * depositor cannot make sense of.\n *\n * Verifying and then discarding the wallet's PSBT closes that off structurally\n * rather than detecting it afterwards, and it makes the code match what\n * `verifyScriptPathSchnorrSignature` already documents: \"only the 64-byte\n * signature comes from the wallet\".\n *\n * @module tbv/core/primitives/psbt/finalizeScriptPathWithSignatures\n */\n\nimport { Psbt } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { X_ONLY_PUBKEY_HEX_LEN } from \"../../utils/validation\";\nimport {\n SCHNORR_SIG_HEX_LEN,\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport { computeTapLeafHash } from \"../utils/taproot\";\n\nexport interface FinalizeScriptPathWithSignaturesParams {\n /**\n * Hex of the PSBT built locally and sent to the wallet — the sole source of\n * every per-input field. NOT the wallet-returned PSBT.\n */\n requestedPsbtHex: string;\n /**\n * Verified 64-byte Schnorr signatures, one per input, index-aligned with the\n * PSBT's inputs. Each must already have passed\n * `assertScriptPathSchnorrSignature` — this function does not re-verify them,\n * it only decides which bytes are allowed to reach the witness.\n */\n signaturesHex: readonly string[];\n /** X-only pubkey (64 hex chars) the signatures are attributed to. */\n signerXOnlyPubkeyHex: string;\n}\n\n/**\n * Attach `signaturesHex` to the locally built PSBT's script-path inputs,\n * finalize, and return the extracted transaction hex.\n *\n * @throws If the signature count does not match the input count, any signature\n * or the signer key is malformed, any input does not carry exactly one\n * tapscript leaf at the expected leaf version, any input already carries a\n * key-path signature, or bitcoinjs-lib cannot finalize.\n */\nexport function finalizeScriptPathWithSignatures(\n params: FinalizeScriptPathWithSignaturesParams,\n): string {\n const { requestedPsbtHex, signaturesHex, signerXOnlyPubkeyHex } = params;\n\n const signerXOnly = stripHexPrefix(signerXOnlyPubkeyHex);\n if (signerXOnly.length !== X_ONLY_PUBKEY_HEX_LEN) {\n throw new Error(\n `Signer x-only pubkey must be ${X_ONLY_PUBKEY_HEX_LEN} hex chars ` +\n `(32 bytes), got ${signerXOnly.length}.`,\n );\n }\n const signerPubkey = Buffer.from(hexToUint8Array(signerXOnly));\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (signaturesHex.length !== psbt.data.inputs.length) {\n throw new Error(\n `Cannot finalize: got ${signaturesHex.length} signature(s) for ` +\n `${psbt.data.inputs.length} input(s). Every input must be signed — ` +\n `refusing to broadcast a partially signed transaction.`,\n );\n }\n\n psbt.data.inputs.forEach((input, inputIndex) => {\n // Our own builders never produce a key-path signature for these spends.\n // If one is present the PSBT is not the one we built, which would defeat\n // the whole point of finalizing locally.\n if (input.tapKeySig) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} of the locally built PSBT ` +\n `carries a key-path signature. These outputs are script-path only.`,\n );\n }\n\n const tapLeafScripts = input.tapLeafScript;\n if (!tapLeafScripts || tapLeafScripts.length !== 1) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} must have exactly one ` +\n `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 finalize: input ${inputIndex} tapLeafScript has leaf version ` +\n `0x${leaf.leafVersion.toString(16)}, expected ` +\n `0x${TAPSCRIPT_LEAF_VERSION.toString(16)}.`,\n );\n }\n\n const signatureRaw = stripHexPrefix(signaturesHex[inputIndex]);\n if (signatureRaw.length !== SCHNORR_SIG_HEX_LEN) {\n throw new Error(\n `Signature for input ${inputIndex} must be ${SCHNORR_SIG_HEX_LEN} hex ` +\n `chars (64 bytes), got ${signatureRaw.length}.`,\n );\n }\n\n psbt.updateInput(inputIndex, {\n tapScriptSig: [\n {\n pubkey: signerPubkey,\n leafHash: computeTapLeafHash(leaf.leafVersion, leaf.script),\n signature: Buffer.from(hexToUint8Array(signatureRaw)),\n },\n ],\n });\n });\n\n // With no tapKeySig anywhere, bitcoinjs takes the script-path branch for\n // every input and builds `[signature, leafScript, controlBlock]` from the\n // leaf we supplied.\n psbt.finalizeAllInputs();\n\n return psbt.extractTransaction().toHex();\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"../../wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}], used verbatim — derive them from the parent txs */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["U64_MAX","assertPositiveBigintArray","values","label","value","index","buildRefundPsbt","params","WasmPrePeginTx","loadTbvWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","fundedTx","wasmHtlcScriptPubKey","expectedHtlc","deriveExpectedPrePeginHtlc","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","REFUND_TX_VERSION","REFUND_TX_LOCKTIME","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","RECLAIM_TX_VERSION","RECLAIM_INPUT_SEQUENCE","RECLAIM_SKELETON_WEIGHT_UNITS","RECLAIM_INPUT_WEIGHT_UNITS","WEIGHT_UNITS_PER_VBYTE","reclaimVsize","numInputs","estimateReclaimFeeSats","feeRateSatsVb","buildReclaimPsbt","depositorPubkey","inputs","feeSats","descriptor","deriveDepositorClaimDescriptor","expectedScriptPubKey","totalInputValue","seenOutpoints","input","i","peginTx","peginTxid","claimOut","PEGIN_DEPOSITOR_CLAIM_VOUT","observedTxid","contractScriptPubKey","observedScriptPubKey","contractValue","outpoint","outputValue","DUST_THRESHOLD","destination","hexToUint8Array","finalizeScriptPathWithSignatures","requestedPsbtHex","signaturesHex","signerXOnlyPubkeyHex","signerXOnly","X_ONLY_PUBKEY_HEX_LEN","signerPubkey","inputIndex","tapLeafScripts","leaf","signatureRaw","SCHNORR_SIG_HEX_LEN","computeTapLeafHash","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":";;;;;;;;AAoBA,MAAMA,KAAW,MAAM,OAAO;AAYvB,SAASC,GACdC,GACAC,GACU;AACV,MAAI,CAAC,MAAM,QAAQD,CAAM;AACvB,UAAM,IAAI;AAAA,MACR,GAAGC,CAAK,8CAA8C,OAAOD,CAAM;AAAA,IAAA;AAGvE,MAAIA,EAAO,WAAW;AACpB,UAAM,IAAI,MAAM,GAAGC,CAAK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,QACb,QAAQC,EAAO,KAAK4D,CAAW;AAAA,QAC/B,cAAc5D,EAAO,KAAK6D,CAAiB;AAAA,MAAA;AAAA,IAC7C,GAEFE,EAAU,iBAAiB/D,EAAO,KAAKC,CAAiB,IAG1DJ,EAAK,SAASkE,CAAS;AAAA,EACzB;AAGA,aAAWC,KAAUR,EAAW;AAC9B,IAAA3D,EAAK,UAAU;AAAA,MACb,QAAQmE,EAAO;AAAA,MACf,OAAOA,EAAO;AAAA,IAAA,CACf;AAGH,SAAOnE,EAAK,MAAA;AACd;AAmBO,SAASoE,GACdV,GACAW,GACAC,GACM;AACN,QAAMC,IAAKlF,EAAY,QAAQkB,EAAemD,CAAa,CAAC;AAE5D,MAAIa,EAAG,KAAK,WAAW;AACrB,UAAM,IAAI;AAAA,MACR,wDAAwDA,EAAG,KAAK,MAAM;AAAA,IAAA;AAI1E,QAAMC,IAAQ7B,EAAgB8B,EAAwBJ,CAAgB,CAAC,GACjE,EAAE,QAAQK,MAAmBC,EAAS,KAAK;AAAA,IAC/C,gBAAgBxE,EAAO,KAAKqE,CAAK;AAAA,IACjC,SAASI,EAAWN,CAAO;AAAA,EAAA,CAC5B;AACD,MAAI,CAACI;AACH,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAIJ,MAAI,CAACH,EAAG,KAAK,CAAC,EAAE,OAAO,OAAOG,CAAc;AAC1C,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAGN;"}
1
+ {"version":3,"file":"noPayout-B-vGXJ-V.js","sources":["../src/tbv/core/wasm/value-guards.ts","../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/reclaim.ts","../src/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Runtime guard for satoshi amounts crossing into the WASM FFI boundary.\n *\n * `new BigUint64Array(values)` is the only way satoshi amounts are handed to\n * the constructor, and a runtime cast (`as readonly bigint[]`) lets a caller\n * pass a non-bigint or non-positive element that `BigUint64Array` would either\n * reject cryptically or, in its length-arg form, silently zero-fill. Values\n * above the u64 maximum are worse still: `BigUint64Array` wraps them mod 2^64\n * without complaint, turning an oversized amount into a small one.\n * {@link assertPositiveBigintArray} validates such inputs before the\n * typed-array construction.\n *\n * Mirrors the `assertPositiveBigintArray` half of `value-guards.ts` in\n * `@babylonlabs-io/babylon-tbv-rust-wasm`; that one function is pinned to the\n * engine's source copy by `__tests__/value-guards.test.ts`. The engine's other\n * guard, `assertWasmBigint`, has no counterpart here: the engine applies it to\n * its own WASM return values before they reach this package.\n */\n\n/** Largest value BigUint64Array stores without wrapping mod 2^64 (2^64 − 1). */\nconst U64_MAX = (1n << 64n) - 1n;\n\n/**\n * Assert a value is a non-empty array of strictly-positive `bigint`s and return\n * it narrowed, ready to feed into `new BigUint64Array(...)`.\n *\n * @param values - The candidate array of satoshi amounts.\n * @param label - Human-readable name used in the thrown error.\n * @throws If `values` is not an array, is empty, or contains any element that is\n * not a `bigint`, is not strictly greater than 0, or exceeds the u64 maximum\n * (which `BigUint64Array` would otherwise wrap mod 2^64).\n */\nexport function assertPositiveBigintArray(\n values: unknown,\n label: string,\n): bigint[] {\n if (!Array.isArray(values)) {\n throw new Error(\n `${label} must be an array of positive bigints (got ${typeof values}).`,\n );\n }\n if (values.length === 0) {\n throw new Error(`${label} must not be empty.`);\n }\n values.forEach((value, index) => {\n if (typeof value !== \"bigint\") {\n throw new Error(\n `${label}[${index}] must be a bigint (got ${typeof value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n if (value <= 0n) {\n throw new Error(`${label}[${index}] must be > 0 (got ${value}).`);\n }\n if (value > U64_MAX) {\n throw new Error(\n `${label}[${index}] must fit in a u64 (got ${value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n });\n return values as bigint[];\n}\n","/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport { loadTbvWasm, tapInternalPubkey } from \"../../wasm\";\nimport { assertPositiveBigintArray } from \"../../wasm/value-guards\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\nimport { REFUND_TX_LOCKTIME, REFUND_TX_VERSION } from \"./constants\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<depositorPubkey> OP_CHECKSIGVERIFY <timelockRefund>\n * OP_CHECKSEQUENCEVERIFY` — btc-vault `connectors/prepegin_htlc.rs`\n * `generate_refund_script`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n const { WasmPrePeginTx } = await loadTbvWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: typeof unfundedTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against an independent\n // TypeScript derivation and the funded transaction bytes.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const wasmHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n const expectedHtlc = deriveExpectedPrePeginHtlc(prePeginParams, hashlock);\n const expectedHtlcScriptPubKey = expectedHtlc.scriptPubKey.toString(\"hex\");\n if (wasmHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `WASM HTLC scriptPubKey ${wasmHtlcScriptPubKey} does not match the ` +\n `independently derived scriptPubKey ${expectedHtlcScriptPubKey}.`,\n );\n }\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + p2aAnchorValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.version !== REFUND_TX_VERSION) {\n throw new Error(\n `Refund transaction version ${refundTx.version} does not match ` +\n `protocol version ${REFUND_TX_VERSION}.`,\n );\n }\n if (refundTx.locktime !== REFUND_TX_LOCKTIME) {\n throw new Error(\n `Refund transaction locktime ${refundTx.locktime} does not match ` +\n `protocol locktime ${REFUND_TX_LOCKTIME}.`,\n );\n }\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n if (refundInput.sequence !== prePeginParams.timelockRefund) {\n throw new Error(\n `Refund input sequence ${refundInput.sequence} does not match ` +\n `timelockRefund ${prePeginParams.timelockRefund}.`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.refundScript,\n controlBlock: expectedHtlc.refundControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * Reclaim PSBT Builder Primitive\n *\n * Builds an unsigned PSBT that sweeps the depositor-claim reserve — PegIn\n * vout 1 — back to the depositor's own BIP-86 address.\n *\n * The reserve funds the depositor's `claim_tx`, their recourse if the vault\n * provider fails during peg-out. When the vault provider claims instead and\n * the depositor withdraws normally, nothing ever spends it. This primitive is\n * the only thing in the repository that can.\n *\n * Spend path: the single `<depositor> OP_CHECKSIG` tapleaf (see\n * ./depositorClaim). No timelock, no counterparty signature — the depositor's\n * Schnorr signature alone. That is also why the *caller* must gate: this\n * builder will happily sweep a reserve whose vault is still live, which would\n * permanently void the depositor's pre-signed recourse graph. Eligibility is\n * enforced upstream, in the service.\n *\n * @module primitives/psbt/reclaim\n */\n\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { DUST_THRESHOLD } from \"../../utils/fee/constants\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport {\n PEGIN_DEPOSITOR_CLAIM_VOUT,\n deriveDepositorClaimDescriptor,\n} from \"./depositorClaim\";\n\n/**\n * nVersion for the reclaim transaction. Plain v2, not TRUC: the reserve is only\n * offered once its PegIn is deeply confirmed, so the v2/v3 PegIn's nVersion-3\n * topology limits no longer constrain its children.\n */\nconst RECLAIM_TX_VERSION = 2;\n\n/**\n * nSequence for every reclaim input: RBF-enabled, no relative timelock. The\n * claim leaf carries no CSV, so this is a fee-bumping signal only.\n */\nconst RECLAIM_INPUT_SEQUENCE = 0xfffffffd;\n\n/**\n * Weight units of the reclaim transaction's skeleton — everything except the\n * inputs. Non-witness `version(4) + inCount(1) + outCount(1) + locktime(4) +\n * output(8 + 1 + 34)` = 53 B × 4, plus the 2 WU SegWit marker and flag.\n */\nconst RECLAIM_SKELETON_WEIGHT_UNITS = 214;\n\n/**\n * Weight units each script-path input adds. Non-witness `outpoint(36) +\n * scriptSigLen(1) + sequence(4)` = 41 B × 4 = 164, plus a witness of\n * `stackCount(1) + sig(1 + 64) + leafScript(1 + 34) + controlBlock(1 + 33)` =\n * 135 WU.\n *\n * Exact rather than conservative: every element is fixed-length here — a\n * 64-byte BIP-340 signature under SIGHASH_DEFAULT, the 34-byte leaf, and a\n * 33-byte control block with no merkle path.\n */\nconst RECLAIM_INPUT_WEIGHT_UNITS = 299;\n\n/** Weight units per virtual byte. */\nconst WEIGHT_UNITS_PER_VBYTE = 4;\n\n/**\n * Virtual size of an N-in/1-out reclaim transaction.\n *\n * `REFUND_VSIZE = 160` does not generalise to N inputs, and\n * `computePeginBaseFeeSats` is wrong for this shape entirely — its\n * `P2TR_INPUT_SIZE = 58` is a *key-path* input and under-fees a script-path\n * spend by roughly a quarter.\n *\n * N=1 → 129 vB; each additional input adds 75 vB.\n */\nexport function reclaimVsize(numInputs: number): number {\n if (!Number.isInteger(numInputs) || numInputs < 1) {\n throw new Error(\n `Reclaim input count must be a positive integer, got ${numInputs}.`,\n );\n }\n return Math.ceil(\n (RECLAIM_SKELETON_WEIGHT_UNITS +\n RECLAIM_INPUT_WEIGHT_UNITS * numInputs) /\n WEIGHT_UNITS_PER_VBYTE,\n );\n}\n\n/** Absolute fee in satoshis for an N-in/1-out reclaim at a given rate. */\nexport function estimateReclaimFeeSats(\n feeRateSatsVb: number,\n numInputs: number,\n): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `Reclaim fee rate must be a positive number, got ${feeRateSatsVb}.`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * reclaimVsize(numInputs)));\n}\n\n/** One depositor-claim reserve to sweep, with the material to bind it. */\nexport interface ReclaimReserve {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Authoritative: its SegWit\n * txid equals the broadcast PegIn's, and its `outs[1]` carries the reserve's\n * script and value at no extra RPC cost.\n */\n depositorSignedPeginTxHex: string;\n /** Independent chain observation of `peginTxid:1` (esplora UTXO lookup). */\n observed: {\n /**\n * The outpoint the caller actually issued its chain lookup against, so the\n * observation below can be tied to the input this builder adds.\n *\n * Without it the script and value binds prove only that *some* UTXO has\n * this shape — the claim script is a pure function of the depositor key and\n * so is byte-identical across every vault they own, and the value is a pure\n * function of protocol parameters. Neither distinguishes one of the\n * depositor's vaults from another.\n *\n * Txid in display order, 64 hex chars, with or without `0x` prefix.\n */\n txid: string;\n /** Vout the lookup was issued against. Must be the claim vout. */\n vout: number;\n /** scriptPubKey hex, with or without `0x` prefix. */\n scriptPubKey: string;\n /** Output value in satoshis. */\n value: bigint;\n };\n /**\n * The reserve value recomputed from this vault's protocol parameters via\n * `computeMinClaimValue`. Bound so a doctored PegIn that agrees with itself\n * and with a compromised indexer still fails.\n */\n expectedValue: bigint;\n}\n\nexport interface BuildReclaimPsbtParams {\n /**\n * The **connected wallet's live** x-only pubkey, 64-char hex. Never the\n * indexer's `depositorBtcPubkey`: re-deriving from the live key is what\n * proves the wallet about to sign is the wallet that can spend, and rejects\n * the wrong-wallet case with an error instead of an unspendable broadcast.\n */\n depositorPubkey: string;\n /**\n * Reserves to sweep. An array so batching several vaults into one\n * transaction is a later change rather than a rewrite; today the app passes\n * exactly one.\n */\n inputs: ReclaimReserve[];\n /** Absolute fee in satoshis. The caller sizes it; see `reclaimVsize`. */\n feeSats: bigint;\n}\n\nexport interface BuildReclaimPsbtResult {\n /** PSBT hex ready for depositor signing. */\n psbtHex: string;\n /** Value of the single output — what the depositor actually receives. */\n outputValue: bigint;\n /** Sum of the swept reserves, before fee. */\n totalInputValue: bigint;\n}\n\n/**\n * Build the N-in/1-out reclaim PSBT.\n *\n * Every input is bound three ways before it reaches the PSBT: the contract's\n * PegIn bytes, the chain observation, and a JS re-derivation from the live\n * wallet key must agree on both script and value. Any disagreement throws.\n * The observation must also name the outpoint it was taken from, since script\n * and value alone repeat across all of a depositor's vaults.\n *\n * Binding the input to the *vault* that was asked for is a further step, and\n * it belongs to the service: it needs the vault id derivation, which is async.\n * See `services/reclaim/buildAndBroadcastReclaim`.\n *\n * @throws If `inputs` is empty, the fee is non-positive, any input fails its\n * outpoint, script or value bind, or the resulting output would be at or\n * below dust.\n */\nexport function buildReclaimPsbt(\n params: BuildReclaimPsbtParams,\n): BuildReclaimPsbtResult {\n const { depositorPubkey, inputs, feeSats } = params;\n\n if (inputs.length === 0) {\n throw new Error(\"Reclaim requires at least one input; got none.\");\n }\n if (feeSats <= 0n) {\n throw new Error(\n `Reclaim fee must be positive, got ${feeSats} sat. Refusing to build a ` +\n `transaction that would not relay.`,\n );\n }\n\n // One derivation, reused for every input's bind and for the destination.\n const descriptor = deriveDepositorClaimDescriptor(depositorPubkey);\n const expectedScriptPubKey = uint8ArrayToHex(\n new Uint8Array(descriptor.scriptPubKey),\n ).toLowerCase();\n\n const psbt = new Psbt();\n psbt.setVersion(RECLAIM_TX_VERSION);\n psbt.setLocktime(0);\n\n let totalInputValue = 0n;\n const seenOutpoints = new Set<string>();\n\n inputs.forEach((input, i) => {\n const peginTx = Transaction.fromHex(\n stripHexPrefix(input.depositorSignedPeginTxHex),\n );\n const peginTxid = peginTx.getId();\n\n const claimOut = peginTx.outs[PEGIN_DEPOSITOR_CLAIM_VOUT];\n if (!claimOut) {\n throw new Error(\n `PegIn ${peginTxid} has no output at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${peginTx.outs.length}); ` +\n `there is no depositor-claim reserve to reclaim.`,\n );\n }\n\n // Bind 0: the observation is of *this* outpoint. Everything below compares\n // a script and a value, both of which repeat across every vault this\n // depositor owns under the same protocol parameters — so without this the\n // remaining binds cannot tell one of their vaults from another, and a\n // caller that resolved the wrong vault would sweep it with every check\n // passing. The independent source is the PegIn the PSBT is built from; the\n // esplora response cannot serve here because `getUtxoInfo` echoes back the\n // txid and vout it was called with rather than reading them from the body.\n const observedTxid = stripHexPrefix(input.observed.txid).toLowerCase();\n if (observedTxid !== peginTxid) {\n throw new Error(\n `Input ${i}: the observation is of ${observedTxid}, but this input ` +\n `spends PegIn ${peginTxid}. Reclaim refused — the reserve that was ` +\n `looked up is not the one being swept.`,\n );\n }\n if (input.observed.vout !== PEGIN_DEPOSITOR_CLAIM_VOUT) {\n throw new Error(\n `Input ${i}: the observation is of vout ${input.observed.vout}, but ` +\n `the depositor-claim reserve is at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`,\n );\n }\n\n // Bind 1: the contract's PegIn bytes against the JS re-derivation from the\n // live wallet key. This is the assertion that proves the connected wallet\n // can actually spend the output we are about to sign for.\n const contractScriptPubKey = uint8ArrayToHex(\n new Uint8Array(claimOut.script),\n ).toLowerCase();\n if (contractScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} pays ` +\n `${contractScriptPubKey}, but the connected wallet's depositor-claim ` +\n `script is ${expectedScriptPubKey}. Reclaim refused — this reserve ` +\n `belongs to a different wallet.`,\n );\n }\n\n // Bind 2: the independent chain observation must agree with both.\n const observedScriptPubKey = stripHexPrefix(\n input.observed.scriptPubKey,\n ).toLowerCase();\n if (observedScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: the observed UTXO ${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `pays ${observedScriptPubKey}, expected ${expectedScriptPubKey}. ` +\n `Reclaim refused — chain state disagrees with the contract's PegIn.`,\n );\n }\n\n // Value bind, same three ways.\n const contractValue = BigInt(claimOut.value);\n if (contractValue !== input.observed.value) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but the observed UTXO carries ` +\n `${input.observed.value} sat. Reclaim refused.`,\n );\n }\n if (contractValue !== input.expectedValue) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but this vault's parameters compute a ` +\n `depositor-claim value of ${input.expectedValue} sat. Reclaim refused.`,\n );\n }\n\n // A batch that names the same vault twice would otherwise double-count the\n // swept total and then fail deep inside bitcoinjs. Reject it here, where\n // the message can say which input is the duplicate.\n const outpoint = `${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT}`;\n if (seenOutpoints.has(outpoint)) {\n throw new Error(\n `Input ${i} repeats outpoint ${outpoint}, which is already being ` +\n `swept by an earlier input. Reclaim refused.`,\n );\n }\n seenOutpoints.add(outpoint);\n\n totalInputValue += contractValue;\n\n psbt.addInput({\n hash: peginTxid,\n index: PEGIN_DEPOSITOR_CLAIM_VOUT,\n sequence: RECLAIM_INPUT_SEQUENCE,\n witnessUtxo: { script: claimOut.script, value: claimOut.value },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: descriptor.leafScript,\n controlBlock: descriptor.controlBlock,\n },\n ],\n tapInternalKey: descriptor.internalKey,\n });\n });\n\n if (feeSats >= totalInputValue) {\n throw new Error(\n `Reclaim fee ${feeSats} sat is not less than the swept total ` +\n `${totalInputValue} sat. Refusing to build a transaction with no output.`,\n );\n }\n\n const outputValue = totalInputValue - feeSats;\n if (outputValue <= DUST_THRESHOLD) {\n throw new Error(\n `Reclaim output ${outputValue} sat is at or below the dust threshold ` +\n `${DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it ` +\n `is until fee rates fall.`,\n );\n }\n\n const destination = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(depositorPubkey),\n );\n psbt.addOutput({\n script: Buffer.from(hexToUint8Array(destination)),\n value: Number(outputValue),\n });\n\n return { psbtHex: psbt.toHex(), outputValue, totalInputValue };\n}\n","/**\n * Finalize a Taproot script-path spend from the PSBT *we* built, using only the\n * verified signatures the wallet returned.\n *\n * Why this exists. The obvious shape — hand the wallet's PSBT to\n * `finalizeAllInputs()` — puts wallet-controlled bytes on the trust path even\n * when the signature itself has been verified.\n * `assertPsbtUnsignedTxMatches` deliberately pins only the unsigned\n * transaction and skips per-input metadata, so `tapLeafScript`, `controlBlock`\n * and `tapKeySig` all survive from the wallet's response untouched. And\n * bitcoinjs-lib checks key-spend first (`src/psbt.js`, `_finalizeTaprootInput`:\n * \"Check key spend first. Increased privacy and reduced block space.\"), so a\n * returned `tapKeySig` wins outright and `tapScriptSig` is never consulted.\n * Every output the depositor-claim reserve and the HTLC refund spend from uses\n * a NUMS internal key, so the resulting key-path witness cannot satisfy the\n * script — the transaction is rejected at broadcast, after a wallet prompt the\n * depositor cannot make sense of.\n *\n * Verifying and then discarding the wallet's PSBT closes that off structurally\n * rather than detecting it afterwards, and it makes the code match what\n * `verifyScriptPathSchnorrSignature` already documents: \"only the 64-byte\n * signature comes from the wallet\".\n *\n * @module tbv/core/primitives/psbt/finalizeScriptPathWithSignatures\n */\n\nimport { Psbt } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { X_ONLY_PUBKEY_HEX_LEN } from \"../../utils/validation\";\nimport {\n SCHNORR_SIG_HEX_LEN,\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport { computeTapLeafHash } from \"../utils/taproot\";\n\nexport interface FinalizeScriptPathWithSignaturesParams {\n /**\n * Hex of the PSBT built locally and sent to the wallet — the sole source of\n * every per-input field. NOT the wallet-returned PSBT.\n */\n requestedPsbtHex: string;\n /**\n * Verified 64-byte Schnorr signatures, one per input, index-aligned with the\n * PSBT's inputs. Each must already have passed\n * `assertScriptPathSchnorrSignature` — this function does not re-verify them,\n * it only decides which bytes are allowed to reach the witness.\n */\n signaturesHex: readonly string[];\n /** X-only pubkey (64 hex chars) the signatures are attributed to. */\n signerXOnlyPubkeyHex: string;\n}\n\n/**\n * Attach `signaturesHex` to the locally built PSBT's script-path inputs,\n * finalize, and return the extracted transaction hex.\n *\n * @throws If the signature count does not match the input count, any signature\n * or the signer key is malformed, any input does not carry exactly one\n * tapscript leaf at the expected leaf version, any input already carries a\n * key-path signature, or bitcoinjs-lib cannot finalize.\n */\nexport function finalizeScriptPathWithSignatures(\n params: FinalizeScriptPathWithSignaturesParams,\n): string {\n const { requestedPsbtHex, signaturesHex, signerXOnlyPubkeyHex } = params;\n\n const signerXOnly = stripHexPrefix(signerXOnlyPubkeyHex);\n if (signerXOnly.length !== X_ONLY_PUBKEY_HEX_LEN) {\n throw new Error(\n `Signer x-only pubkey must be ${X_ONLY_PUBKEY_HEX_LEN} hex chars ` +\n `(32 bytes), got ${signerXOnly.length}.`,\n );\n }\n const signerPubkey = Buffer.from(hexToUint8Array(signerXOnly));\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (signaturesHex.length !== psbt.data.inputs.length) {\n throw new Error(\n `Cannot finalize: got ${signaturesHex.length} signature(s) for ` +\n `${psbt.data.inputs.length} input(s). Every input must be signed — ` +\n `refusing to broadcast a partially signed transaction.`,\n );\n }\n\n psbt.data.inputs.forEach((input, inputIndex) => {\n // Our own builders never produce a key-path signature for these spends.\n // If one is present the PSBT is not the one we built, which would defeat\n // the whole point of finalizing locally.\n if (input.tapKeySig) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} of the locally built PSBT ` +\n `carries a key-path signature. These outputs are script-path only.`,\n );\n }\n\n const tapLeafScripts = input.tapLeafScript;\n if (!tapLeafScripts || tapLeafScripts.length !== 1) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} must have exactly one ` +\n `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 finalize: input ${inputIndex} tapLeafScript has leaf version ` +\n `0x${leaf.leafVersion.toString(16)}, expected ` +\n `0x${TAPSCRIPT_LEAF_VERSION.toString(16)}.`,\n );\n }\n\n const signatureRaw = stripHexPrefix(signaturesHex[inputIndex]);\n if (signatureRaw.length !== SCHNORR_SIG_HEX_LEN) {\n throw new Error(\n `Signature for input ${inputIndex} must be ${SCHNORR_SIG_HEX_LEN} hex ` +\n `chars (64 bytes), got ${signatureRaw.length}.`,\n );\n }\n\n psbt.updateInput(inputIndex, {\n tapScriptSig: [\n {\n pubkey: signerPubkey,\n leafHash: computeTapLeafHash(leaf.leafVersion, leaf.script),\n signature: Buffer.from(hexToUint8Array(signatureRaw)),\n },\n ],\n });\n });\n\n // With no tapKeySig anywhere, bitcoinjs takes the script-path branch for\n // every input and builds `[signature, leafScript, controlBlock]` from the\n // leaf we supplied.\n psbt.finalizeAllInputs();\n\n return psbt.extractTransaction().toHex();\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"../../wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}], used verbatim — derive them from the parent txs */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["U64_MAX","assertPositiveBigintArray","values","label","value","index","buildRefundPsbt","params","WasmPrePeginTx","loadTbvWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","fundedTx","wasmHtlcScriptPubKey","expectedHtlc","deriveExpectedPrePeginHtlc","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","REFUND_TX_VERSION","REFUND_TX_LOCKTIME","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","RECLAIM_TX_VERSION","RECLAIM_INPUT_SEQUENCE","RECLAIM_SKELETON_WEIGHT_UNITS","RECLAIM_INPUT_WEIGHT_UNITS","WEIGHT_UNITS_PER_VBYTE","reclaimVsize","numInputs","estimateReclaimFeeSats","feeRateSatsVb","buildReclaimPsbt","depositorPubkey","inputs","feeSats","descriptor","deriveDepositorClaimDescriptor","expectedScriptPubKey","totalInputValue","seenOutpoints","input","i","peginTx","peginTxid","claimOut","PEGIN_DEPOSITOR_CLAIM_VOUT","observedTxid","contractScriptPubKey","observedScriptPubKey","contractValue","outpoint","outputValue","DUST_THRESHOLD","destination","hexToUint8Array","finalizeScriptPathWithSignatures","requestedPsbtHex","signaturesHex","signerXOnlyPubkeyHex","signerXOnly","X_ONLY_PUBKEY_HEX_LEN","signerPubkey","inputIndex","tapLeafScripts","leaf","signatureRaw","SCHNORR_SIG_HEX_LEN","computeTapLeafHash","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","get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index.cjs"),t=require("./bitcoin-D-O2GjbC.cjs"),h=require("./verifyScriptPathSchnorrSignature-BKZihCjk.cjs"),v=require("./constants-BTZdyOuk.cjs"),N=require("./fundPeginTransaction-54-Rwb2k.cjs"),k=require("./validation-C6XTfZak.cjs"),V=(1n<<64n)-1n;function B(r,u){if(!Array.isArray(r))throw new Error(`${u} must be an array of positive bigints (got ${typeof r}).`);if(r.length===0)throw new Error(`${u} must not be empty.`);return r.forEach((e,n)=>{if(typeof e!="bigint")throw new Error(`${u}[${n}] must be a bigint (got ${typeof e}); refusing to feed it into satoshi math.`);if(e<=0n)throw new Error(`${u}[${n}] must be > 0 (got ${e}).`);if(e>V)throw new Error(`${u}[${n}] must fit in a u64 (got ${e}); refusing to feed it into satoshi math.`)}),r}async function K(r){const{WasmPrePeginTx:u}=await S.loadTbvWasm(),{prePeginParams:e,fundedPrePeginTxHex:n,htlcVout:s,refundFee:f,hashlock:c}=r,l=h.normalizeAuthAnchorHash(e.authAnchorHash),o=new u(e.vaultCoreVersion,e.depositorPubkey,e.vaultProviderPubkey,e.vaultKeeperPubkeys,e.universalChallengerPubkeys,[...e.hashlocks],new BigUint64Array(B(e.pegInAmounts,"pegInAmounts")),e.timelockRefund,e.feeRate,e.minPeginFeeRate,e.numLocalChallengers,e.councilQuorum,e.councilSize,e.network,l);let a=null;try{const d=o.getHtlcScriptPubKey(s).toLowerCase(),i=h.deriveExpectedPrePeginHtlc(e,c),P=i.scriptPubKey.toString("hex");if(d!==P)throw new Error(`WASM HTLC scriptPubKey ${d} does not match the independently derived scriptPubKey ${P}.`);const T=o.getHtlcValue(s);a=o.fromFundedTransaction(n);const w=a.buildRefundTx(f,s),b=n.startsWith("0x")?n.slice(2):n,$=m.Transaction.fromHex(b),E=$.outs[s];if(!E)throw new Error(`HTLC output at vout ${s} not found in funded Pre-PegIn tx (tx has ${$.outs.length} outputs)`);const I=t.uint8ArrayToHex(new Uint8Array(E.script)).toLowerCase();if(I!==P)throw new Error(`HTLC scriptPubKey mismatch at vout ${s}: reconstructed template expects ${P}, funded tx carries ${I}. Refund refused — the (hashlocks, pegInAmounts) vector does not match the on-chain commitment.`);const g=BigInt(E.value);if(g!==T)throw new Error(`HTLC value mismatch at vout ${s}: reconstructed template expects ${T} sat, funded tx carries ${g} sat. Refund refused — the pegInAmounts vector does not match the on-chain commitment.`);const p=m.Transaction.fromHex(w);if(p.version!==v.REFUND_TX_VERSION)throw new Error(`Refund transaction version ${p.version} does not match protocol version ${v.REFUND_TX_VERSION}.`);if(p.locktime!==v.REFUND_TX_LOCKTIME)throw new Error(`Refund transaction locktime ${p.locktime} does not match protocol locktime ${v.REFUND_TX_LOCKTIME}.`);if(p.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${p.ins.length}`);const y=p.ins[0],H=$.getId(),O=t.uint8ArrayToHex(new Uint8Array(y.hash).slice().reverse());if(O!==H)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${H}, got ${O}`);if(y.index!==s)throw new Error(`Refund input index ${y.index} does not match expected htlcVout ${s}`);if(y.sequence!==e.timelockRefund)throw new Error(`Refund input sequence ${y.sequence} does not match timelockRefund ${e.timelockRefund}.`);const R=new m.Psbt;if(R.setVersion(p.version),R.setLocktime(p.locktime),R.addInput({hash:y.hash,index:y.index,sequence:y.sequence,witnessUtxo:{script:E.script,value:E.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:i.refundScript,controlBlock:i.refundControlBlock}],tapInternalKey:x.Buffer.from(S.tapInternalPubkey),tapMerkleRoot:i.tapMerkleRoot}),p.outs.length!==1)throw new Error(`Refund transaction must have exactly 1 output, got ${p.outs.length}`);const _=p.outs[0],A=t.stripHexPrefix(t.deriveBip86ScriptPubKeyHex(e.depositorPubkey)).toLowerCase(),L=t.uint8ArrayToHex(new Uint8Array(_.script)).toLowerCase();if(L!==A)throw new Error(`Refund output scriptPubKey ${L} does not match the depositor's BIP-86 address ${A}. Refund refused — the reclaimed funds would not return to the depositor.`);const C=g-f;if(BigInt(_.value)!==C)throw new Error(`Refund output value ${BigInt(_.value)} sat does not equal the HTLC value ${g} sat minus the requested fee ${f} sat (expected ${C} sat). Refund refused — the reclaimed amount would be burned as excess fee.`);return R.addOutput({script:_.script,value:_.value}),{psbtHex:R.toHex()}}finally{a==null||a.free(),o.free()}}const M=2,D=4294967293,q=214,X=299,F=4;function U(r){if(!Number.isInteger(r)||r<1)throw new Error(`Reclaim input count must be a positive integer, got ${r}.`);return Math.ceil((q+X*r)/F)}function G(r,u){if(!Number.isFinite(r)||r<=0)throw new Error(`Reclaim fee rate must be a positive number, got ${r}.`);return BigInt(Math.ceil(r*U(u)))}function z(r){const{depositorPubkey:u,inputs:e,feeSats:n}=r;if(e.length===0)throw new Error("Reclaim requires at least one input; got none.");if(n<=0n)throw new Error(`Reclaim fee must be positive, got ${n} sat. Refusing to build a transaction that would not relay.`);const s=h.deriveDepositorClaimDescriptor(u),f=t.uint8ArrayToHex(new Uint8Array(s.scriptPubKey)).toLowerCase(),c=new m.Psbt;c.setVersion(M),c.setLocktime(0);let l=0n;const o=new Set;if(e.forEach((i,P)=>{const T=m.Transaction.fromHex(t.stripHexPrefix(i.depositorSignedPeginTxHex)),w=T.getId(),b=T.outs[h.PEGIN_DEPOSITOR_CLAIM_VOUT];if(!b)throw new Error(`PegIn ${w} has no output at vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${T.outs.length}); there is no depositor-claim reserve to reclaim.`);const $=t.stripHexPrefix(i.observed.txid).toLowerCase();if($!==w)throw new Error(`Input ${P}: the observation is of ${$}, but this input spends PegIn ${w}. Reclaim refused — the reserve that was looked up is not the one being swept.`);if(i.observed.vout!==h.PEGIN_DEPOSITOR_CLAIM_VOUT)throw new Error(`Input ${P}: the observation is of vout ${i.observed.vout}, but the depositor-claim reserve is at vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`);const E=t.uint8ArrayToHex(new Uint8Array(b.script)).toLowerCase();if(E!==f)throw new Error(`Input ${P}: PegIn ${w} vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT} pays ${E}, but the connected wallet's depositor-claim script is ${f}. Reclaim refused — this reserve belongs to a different wallet.`);const I=t.stripHexPrefix(i.observed.scriptPubKey).toLowerCase();if(I!==f)throw new Error(`Input ${P}: the observed UTXO ${w}:${h.PEGIN_DEPOSITOR_CLAIM_VOUT} pays ${I}, expected ${f}. Reclaim refused — chain state disagrees with the contract's PegIn.`);const g=BigInt(b.value);if(g!==i.observed.value)throw new Error(`Input ${P}: PegIn ${w} vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT} carries ${g} sat, but the observed UTXO carries ${i.observed.value} sat. Reclaim refused.`);if(g!==i.expectedValue)throw new Error(`Input ${P}: PegIn ${w} vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT} carries ${g} sat, but this vault's parameters compute a depositor-claim value of ${i.expectedValue} sat. Reclaim refused.`);const p=`${w}:${h.PEGIN_DEPOSITOR_CLAIM_VOUT}`;if(o.has(p))throw new Error(`Input ${P} repeats outpoint ${p}, which is already being swept by an earlier input. Reclaim refused.`);o.add(p),l+=g,c.addInput({hash:w,index:h.PEGIN_DEPOSITOR_CLAIM_VOUT,sequence:D,witnessUtxo:{script:b.script,value:b.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:s.leafScript,controlBlock:s.controlBlock}],tapInternalKey:s.internalKey})}),n>=l)throw new Error(`Reclaim fee ${n} sat is not less than the swept total ${l} sat. Refusing to build a transaction with no output.`);const a=l-n;if(a<=N.DUST_THRESHOLD)throw new Error(`Reclaim output ${a} sat is at or below the dust threshold ${N.DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it is until fee rates fall.`);const d=t.stripHexPrefix(t.deriveBip86ScriptPubKeyHex(u));return c.addOutput({script:x.Buffer.from(t.hexToUint8Array(d)),value:Number(a)}),{psbtHex:c.toHex(),outputValue:a,totalInputValue:l}}function W(r){const{requestedPsbtHex:u,signaturesHex:e,signerXOnlyPubkeyHex:n}=r,s=t.stripHexPrefix(n);if(s.length!==k.X_ONLY_PUBKEY_HEX_LEN)throw new Error(`Signer x-only pubkey must be ${k.X_ONLY_PUBKEY_HEX_LEN} hex chars (32 bytes), got ${s.length}.`);const f=x.Buffer.from(t.hexToUint8Array(s)),c=m.Psbt.fromHex(u);if(e.length!==c.data.inputs.length)throw new Error(`Cannot finalize: got ${e.length} signature(s) for ${c.data.inputs.length} input(s). Every input must be signed — refusing to broadcast a partially signed transaction.`);return c.data.inputs.forEach((l,o)=>{if(l.tapKeySig)throw new Error(`Cannot finalize: input ${o} of the locally built PSBT carries a key-path signature. These outputs are script-path only.`);const a=l.tapLeafScript;if(!a||a.length!==1)throw new Error(`Cannot finalize: input ${o} must have exactly one tapLeafScript, got ${(a==null?void 0:a.length)??0}.`);const d=a[0];if(d.leafVersion!==t.TAPSCRIPT_LEAF_VERSION)throw new Error(`Cannot finalize: input ${o} tapLeafScript has leaf version 0x${d.leafVersion.toString(16)}, expected 0x${t.TAPSCRIPT_LEAF_VERSION.toString(16)}.`);const i=t.stripHexPrefix(e[o]);if(i.length!==t.SCHNORR_SIG_HEX_LEN)throw new Error(`Signature for input ${o} must be ${t.SCHNORR_SIG_HEX_LEN} hex chars (64 bytes), got ${i.length}.`);c.updateInput(o,{tapScriptSig:[{pubkey:f,leafHash:h.computeTapLeafHash(d.leafVersion,d.script),signature:x.Buffer.from(t.hexToUint8Array(i))}]})}),c.finalizeAllInputs(),c.extractTransaction().toHex()}async function Y(r){const u=t.stripHexPrefix(r.noPayoutTxHex),e=m.Transaction.fromHex(u),{noPayoutScript:n,noPayoutControlBlock:s}=await S.getAssertNoPayoutScriptInfo(r.connectorParams,r.challengerPubkey),f=t.hexToUint8Array(n),c=t.hexToUint8Array(s),l=new m.Psbt;l.setVersion(e.version),l.setLocktime(e.locktime);for(let o=0;o<e.ins.length;o++){const a=e.ins[o],d=r.prevouts[o];if(!d)throw new Error(`Missing prevout data for input ${o}`);const i={hash:a.hash,index:a.index,sequence:a.sequence,witnessUtxo:{script:x.Buffer.from(t.hexToUint8Array(t.stripHexPrefix(d.script_pubkey))),value:d.value}};o===0&&(i.tapLeafScript=[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:x.Buffer.from(f),controlBlock:x.Buffer.from(c)}],i.tapInternalKey=x.Buffer.from(S.tapInternalPubkey)),l.addInput(i)}for(const o of e.outs)l.addOutput({script:o.script,value:o.value});return l.toHex()}function Q(r,u,e){const n=m.Transaction.fromHex(t.stripHexPrefix(r));if(n.outs.length!==1)throw new Error(`NoPayout transaction must have exactly 1 output, got ${n.outs.length}`);const s=t.hexToUint8Array(t.processPublicKeyToXOnly(u)),{output:f}=m.payments.p2tr({internalPubkey:x.Buffer.from(s),network:t.getNetwork(e)});if(!f)throw new Error("Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation");if(!n.outs[0].script.equals(f))throw new Error("NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address")}exports.assertNoPayoutOutputMatchesChallenger=Q;exports.buildNoPayoutPsbt=Y;exports.buildReclaimPsbt=z;exports.buildRefundPsbt=K;exports.estimateReclaimFeeSats=G;exports.finalizeScriptPathWithSignatures=W;exports.reclaimVsize=U;
2
- //# sourceMappingURL=noPayout-DAWBQ0eG.cjs.map
1
+ "use strict";const m=require("bitcoinjs-lib"),x=require("buffer"),S=require("./tbv/core/wasm/index.cjs"),t=require("./bitcoin-D-O2GjbC.cjs"),h=require("./verifyScriptPathSchnorrSignature-D2t1yACC.cjs"),v=require("./constants-BwCg5K6R.cjs"),N=require("./fundPeginTransaction-54-Rwb2k.cjs"),k=require("./validation-C6XTfZak.cjs"),V=(1n<<64n)-1n;function B(r,u){if(!Array.isArray(r))throw new Error(`${u} must be an array of positive bigints (got ${typeof r}).`);if(r.length===0)throw new Error(`${u} must not be empty.`);return r.forEach((e,n)=>{if(typeof e!="bigint")throw new Error(`${u}[${n}] must be a bigint (got ${typeof e}); refusing to feed it into satoshi math.`);if(e<=0n)throw new Error(`${u}[${n}] must be > 0 (got ${e}).`);if(e>V)throw new Error(`${u}[${n}] must fit in a u64 (got ${e}); refusing to feed it into satoshi math.`)}),r}async function K(r){const{WasmPrePeginTx:u}=await S.loadTbvWasm(),{prePeginParams:e,fundedPrePeginTxHex:n,htlcVout:s,refundFee:f,hashlock:c}=r,l=h.normalizeAuthAnchorHash(e.authAnchorHash),o=new u(e.vaultCoreVersion,e.depositorPubkey,e.vaultProviderPubkey,e.vaultKeeperPubkeys,e.universalChallengerPubkeys,[...e.hashlocks],new BigUint64Array(B(e.pegInAmounts,"pegInAmounts")),e.timelockRefund,e.feeRate,e.minPeginFeeRate,e.numLocalChallengers,e.councilQuorum,e.councilSize,e.network,l);let a=null;try{const d=o.getHtlcScriptPubKey(s).toLowerCase(),i=h.deriveExpectedPrePeginHtlc(e,c),P=i.scriptPubKey.toString("hex");if(d!==P)throw new Error(`WASM HTLC scriptPubKey ${d} does not match the independently derived scriptPubKey ${P}.`);const T=o.getHtlcValue(s);a=o.fromFundedTransaction(n);const w=a.buildRefundTx(f,s),b=n.startsWith("0x")?n.slice(2):n,$=m.Transaction.fromHex(b),E=$.outs[s];if(!E)throw new Error(`HTLC output at vout ${s} not found in funded Pre-PegIn tx (tx has ${$.outs.length} outputs)`);const I=t.uint8ArrayToHex(new Uint8Array(E.script)).toLowerCase();if(I!==P)throw new Error(`HTLC scriptPubKey mismatch at vout ${s}: reconstructed template expects ${P}, funded tx carries ${I}. Refund refused — the (hashlocks, pegInAmounts) vector does not match the on-chain commitment.`);const g=BigInt(E.value);if(g!==T)throw new Error(`HTLC value mismatch at vout ${s}: reconstructed template expects ${T} sat, funded tx carries ${g} sat. Refund refused — the pegInAmounts vector does not match the on-chain commitment.`);const p=m.Transaction.fromHex(w);if(p.version!==v.REFUND_TX_VERSION)throw new Error(`Refund transaction version ${p.version} does not match protocol version ${v.REFUND_TX_VERSION}.`);if(p.locktime!==v.REFUND_TX_LOCKTIME)throw new Error(`Refund transaction locktime ${p.locktime} does not match protocol locktime ${v.REFUND_TX_LOCKTIME}.`);if(p.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${p.ins.length}`);const y=p.ins[0],H=$.getId(),O=t.uint8ArrayToHex(new Uint8Array(y.hash).slice().reverse());if(O!==H)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${H}, got ${O}`);if(y.index!==s)throw new Error(`Refund input index ${y.index} does not match expected htlcVout ${s}`);if(y.sequence!==e.timelockRefund)throw new Error(`Refund input sequence ${y.sequence} does not match timelockRefund ${e.timelockRefund}.`);const R=new m.Psbt;if(R.setVersion(p.version),R.setLocktime(p.locktime),R.addInput({hash:y.hash,index:y.index,sequence:y.sequence,witnessUtxo:{script:E.script,value:E.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:i.refundScript,controlBlock:i.refundControlBlock}],tapInternalKey:x.Buffer.from(S.tapInternalPubkey),tapMerkleRoot:i.tapMerkleRoot}),p.outs.length!==1)throw new Error(`Refund transaction must have exactly 1 output, got ${p.outs.length}`);const _=p.outs[0],A=t.stripHexPrefix(t.deriveBip86ScriptPubKeyHex(e.depositorPubkey)).toLowerCase(),L=t.uint8ArrayToHex(new Uint8Array(_.script)).toLowerCase();if(L!==A)throw new Error(`Refund output scriptPubKey ${L} does not match the depositor's BIP-86 address ${A}. Refund refused — the reclaimed funds would not return to the depositor.`);const C=g-f;if(BigInt(_.value)!==C)throw new Error(`Refund output value ${BigInt(_.value)} sat does not equal the HTLC value ${g} sat minus the requested fee ${f} sat (expected ${C} sat). Refund refused — the reclaimed amount would be burned as excess fee.`);return R.addOutput({script:_.script,value:_.value}),{psbtHex:R.toHex()}}finally{a==null||a.free(),o.free()}}const M=2,D=4294967293,q=214,X=299,F=4;function U(r){if(!Number.isInteger(r)||r<1)throw new Error(`Reclaim input count must be a positive integer, got ${r}.`);return Math.ceil((q+X*r)/F)}function G(r,u){if(!Number.isFinite(r)||r<=0)throw new Error(`Reclaim fee rate must be a positive number, got ${r}.`);return BigInt(Math.ceil(r*U(u)))}function z(r){const{depositorPubkey:u,inputs:e,feeSats:n}=r;if(e.length===0)throw new Error("Reclaim requires at least one input; got none.");if(n<=0n)throw new Error(`Reclaim fee must be positive, got ${n} sat. Refusing to build a transaction that would not relay.`);const s=h.deriveDepositorClaimDescriptor(u),f=t.uint8ArrayToHex(new Uint8Array(s.scriptPubKey)).toLowerCase(),c=new m.Psbt;c.setVersion(M),c.setLocktime(0);let l=0n;const o=new Set;if(e.forEach((i,P)=>{const T=m.Transaction.fromHex(t.stripHexPrefix(i.depositorSignedPeginTxHex)),w=T.getId(),b=T.outs[h.PEGIN_DEPOSITOR_CLAIM_VOUT];if(!b)throw new Error(`PegIn ${w} has no output at vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${T.outs.length}); there is no depositor-claim reserve to reclaim.`);const $=t.stripHexPrefix(i.observed.txid).toLowerCase();if($!==w)throw new Error(`Input ${P}: the observation is of ${$}, but this input spends PegIn ${w}. Reclaim refused — the reserve that was looked up is not the one being swept.`);if(i.observed.vout!==h.PEGIN_DEPOSITOR_CLAIM_VOUT)throw new Error(`Input ${P}: the observation is of vout ${i.observed.vout}, but the depositor-claim reserve is at vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`);const E=t.uint8ArrayToHex(new Uint8Array(b.script)).toLowerCase();if(E!==f)throw new Error(`Input ${P}: PegIn ${w} vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT} pays ${E}, but the connected wallet's depositor-claim script is ${f}. Reclaim refused — this reserve belongs to a different wallet.`);const I=t.stripHexPrefix(i.observed.scriptPubKey).toLowerCase();if(I!==f)throw new Error(`Input ${P}: the observed UTXO ${w}:${h.PEGIN_DEPOSITOR_CLAIM_VOUT} pays ${I}, expected ${f}. Reclaim refused — chain state disagrees with the contract's PegIn.`);const g=BigInt(b.value);if(g!==i.observed.value)throw new Error(`Input ${P}: PegIn ${w} vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT} carries ${g} sat, but the observed UTXO carries ${i.observed.value} sat. Reclaim refused.`);if(g!==i.expectedValue)throw new Error(`Input ${P}: PegIn ${w} vout ${h.PEGIN_DEPOSITOR_CLAIM_VOUT} carries ${g} sat, but this vault's parameters compute a depositor-claim value of ${i.expectedValue} sat. Reclaim refused.`);const p=`${w}:${h.PEGIN_DEPOSITOR_CLAIM_VOUT}`;if(o.has(p))throw new Error(`Input ${P} repeats outpoint ${p}, which is already being swept by an earlier input. Reclaim refused.`);o.add(p),l+=g,c.addInput({hash:w,index:h.PEGIN_DEPOSITOR_CLAIM_VOUT,sequence:D,witnessUtxo:{script:b.script,value:b.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:s.leafScript,controlBlock:s.controlBlock}],tapInternalKey:s.internalKey})}),n>=l)throw new Error(`Reclaim fee ${n} sat is not less than the swept total ${l} sat. Refusing to build a transaction with no output.`);const a=l-n;if(a<=N.DUST_THRESHOLD)throw new Error(`Reclaim output ${a} sat is at or below the dust threshold ${N.DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it is until fee rates fall.`);const d=t.stripHexPrefix(t.deriveBip86ScriptPubKeyHex(u));return c.addOutput({script:x.Buffer.from(t.hexToUint8Array(d)),value:Number(a)}),{psbtHex:c.toHex(),outputValue:a,totalInputValue:l}}function W(r){const{requestedPsbtHex:u,signaturesHex:e,signerXOnlyPubkeyHex:n}=r,s=t.stripHexPrefix(n);if(s.length!==k.X_ONLY_PUBKEY_HEX_LEN)throw new Error(`Signer x-only pubkey must be ${k.X_ONLY_PUBKEY_HEX_LEN} hex chars (32 bytes), got ${s.length}.`);const f=x.Buffer.from(t.hexToUint8Array(s)),c=m.Psbt.fromHex(u);if(e.length!==c.data.inputs.length)throw new Error(`Cannot finalize: got ${e.length} signature(s) for ${c.data.inputs.length} input(s). Every input must be signed — refusing to broadcast a partially signed transaction.`);return c.data.inputs.forEach((l,o)=>{if(l.tapKeySig)throw new Error(`Cannot finalize: input ${o} of the locally built PSBT carries a key-path signature. These outputs are script-path only.`);const a=l.tapLeafScript;if(!a||a.length!==1)throw new Error(`Cannot finalize: input ${o} must have exactly one tapLeafScript, got ${(a==null?void 0:a.length)??0}.`);const d=a[0];if(d.leafVersion!==t.TAPSCRIPT_LEAF_VERSION)throw new Error(`Cannot finalize: input ${o} tapLeafScript has leaf version 0x${d.leafVersion.toString(16)}, expected 0x${t.TAPSCRIPT_LEAF_VERSION.toString(16)}.`);const i=t.stripHexPrefix(e[o]);if(i.length!==t.SCHNORR_SIG_HEX_LEN)throw new Error(`Signature for input ${o} must be ${t.SCHNORR_SIG_HEX_LEN} hex chars (64 bytes), got ${i.length}.`);c.updateInput(o,{tapScriptSig:[{pubkey:f,leafHash:h.computeTapLeafHash(d.leafVersion,d.script),signature:x.Buffer.from(t.hexToUint8Array(i))}]})}),c.finalizeAllInputs(),c.extractTransaction().toHex()}async function Y(r){const u=t.stripHexPrefix(r.noPayoutTxHex),e=m.Transaction.fromHex(u),{noPayoutScript:n,noPayoutControlBlock:s}=await S.getAssertNoPayoutScriptInfo(r.connectorParams,r.challengerPubkey),f=t.hexToUint8Array(n),c=t.hexToUint8Array(s),l=new m.Psbt;l.setVersion(e.version),l.setLocktime(e.locktime);for(let o=0;o<e.ins.length;o++){const a=e.ins[o],d=r.prevouts[o];if(!d)throw new Error(`Missing prevout data for input ${o}`);const i={hash:a.hash,index:a.index,sequence:a.sequence,witnessUtxo:{script:x.Buffer.from(t.hexToUint8Array(t.stripHexPrefix(d.script_pubkey))),value:d.value}};o===0&&(i.tapLeafScript=[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:x.Buffer.from(f),controlBlock:x.Buffer.from(c)}],i.tapInternalKey=x.Buffer.from(S.tapInternalPubkey)),l.addInput(i)}for(const o of e.outs)l.addOutput({script:o.script,value:o.value});return l.toHex()}function Q(r,u,e){const n=m.Transaction.fromHex(t.stripHexPrefix(r));if(n.outs.length!==1)throw new Error(`NoPayout transaction must have exactly 1 output, got ${n.outs.length}`);const s=t.hexToUint8Array(t.processPublicKeyToXOnly(u)),{output:f}=m.payments.p2tr({internalPubkey:x.Buffer.from(s),network:t.getNetwork(e)});if(!f)throw new Error("Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation");if(!n.outs[0].script.equals(f))throw new Error("NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address")}exports.assertNoPayoutOutputMatchesChallenger=Q;exports.buildNoPayoutPsbt=Y;exports.buildReclaimPsbt=z;exports.buildRefundPsbt=K;exports.estimateReclaimFeeSats=G;exports.finalizeScriptPathWithSignatures=W;exports.reclaimVsize=U;
2
+ //# sourceMappingURL=noPayout-DOHak0ui.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"noPayout-DAWBQ0eG.cjs","sources":["../src/tbv/core/wasm/value-guards.ts","../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/reclaim.ts","../src/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Runtime guard for satoshi amounts crossing into the WASM FFI boundary.\n *\n * `new BigUint64Array(values)` is the only way satoshi amounts are handed to\n * the constructor, and a runtime cast (`as readonly bigint[]`) lets a caller\n * pass a non-bigint or non-positive element that `BigUint64Array` would either\n * reject cryptically or, in its length-arg form, silently zero-fill. Values\n * above the u64 maximum are worse still: `BigUint64Array` wraps them mod 2^64\n * without complaint, turning an oversized amount into a small one.\n * {@link assertPositiveBigintArray} validates such inputs before the\n * typed-array construction.\n *\n * Mirrors the `assertPositiveBigintArray` half of `value-guards.ts` in\n * `@babylonlabs-io/babylon-tbv-rust-wasm`; that one function is pinned to the\n * engine's source copy by `__tests__/value-guards.test.ts`. The engine's other\n * guard, `assertWasmBigint`, has no counterpart here: the engine applies it to\n * its own WASM return values before they reach this package.\n */\n\n/** Largest value BigUint64Array stores without wrapping mod 2^64 (2^64 − 1). */\nconst U64_MAX = (1n << 64n) - 1n;\n\n/**\n * Assert a value is a non-empty array of strictly-positive `bigint`s and return\n * it narrowed, ready to feed into `new BigUint64Array(...)`.\n *\n * @param values - The candidate array of satoshi amounts.\n * @param label - Human-readable name used in the thrown error.\n * @throws If `values` is not an array, is empty, or contains any element that is\n * not a `bigint`, is not strictly greater than 0, or exceeds the u64 maximum\n * (which `BigUint64Array` would otherwise wrap mod 2^64).\n */\nexport function assertPositiveBigintArray(\n values: unknown,\n label: string,\n): bigint[] {\n if (!Array.isArray(values)) {\n throw new Error(\n `${label} must be an array of positive bigints (got ${typeof values}).`,\n );\n }\n if (values.length === 0) {\n throw new Error(`${label} must not be empty.`);\n }\n values.forEach((value, index) => {\n if (typeof value !== \"bigint\") {\n throw new Error(\n `${label}[${index}] must be a bigint (got ${typeof value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n if (value <= 0n) {\n throw new Error(`${label}[${index}] must be > 0 (got ${value}).`);\n }\n if (value > U64_MAX) {\n throw new Error(\n `${label}[${index}] must fit in a u64 (got ${value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n });\n return values as bigint[];\n}\n","/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport { loadTbvWasm, tapInternalPubkey } from \"../../wasm\";\nimport { assertPositiveBigintArray } from \"../../wasm/value-guards\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\nimport { REFUND_TX_LOCKTIME, REFUND_TX_VERSION } from \"./constants\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<depositorPubkey> OP_CHECKSIGVERIFY <timelockRefund>\n * OP_CHECKSEQUENCEVERIFY` — btc-vault `connectors/prepegin_htlc.rs`\n * `generate_refund_script`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n const { WasmPrePeginTx } = await loadTbvWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: typeof unfundedTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against an independent\n // TypeScript derivation and the funded transaction bytes.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const wasmHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n const expectedHtlc = deriveExpectedPrePeginHtlc(prePeginParams, hashlock);\n const expectedHtlcScriptPubKey = expectedHtlc.scriptPubKey.toString(\"hex\");\n if (wasmHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `WASM HTLC scriptPubKey ${wasmHtlcScriptPubKey} does not match the ` +\n `independently derived scriptPubKey ${expectedHtlcScriptPubKey}.`,\n );\n }\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + p2aAnchorValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.version !== REFUND_TX_VERSION) {\n throw new Error(\n `Refund transaction version ${refundTx.version} does not match ` +\n `protocol version ${REFUND_TX_VERSION}.`,\n );\n }\n if (refundTx.locktime !== REFUND_TX_LOCKTIME) {\n throw new Error(\n `Refund transaction locktime ${refundTx.locktime} does not match ` +\n `protocol locktime ${REFUND_TX_LOCKTIME}.`,\n );\n }\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n if (refundInput.sequence !== prePeginParams.timelockRefund) {\n throw new Error(\n `Refund input sequence ${refundInput.sequence} does not match ` +\n `timelockRefund ${prePeginParams.timelockRefund}.`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.refundScript,\n controlBlock: expectedHtlc.refundControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * Reclaim PSBT Builder Primitive\n *\n * Builds an unsigned PSBT that sweeps the depositor-claim reserve — PegIn\n * vout 1 — back to the depositor's own BIP-86 address.\n *\n * The reserve funds the depositor's `claim_tx`, their recourse if the vault\n * provider fails during peg-out. When the vault provider claims instead and\n * the depositor withdraws normally, nothing ever spends it. This primitive is\n * the only thing in the repository that can.\n *\n * Spend path: the single `<depositor> OP_CHECKSIG` tapleaf (see\n * ./depositorClaim). No timelock, no counterparty signature — the depositor's\n * Schnorr signature alone. That is also why the *caller* must gate: this\n * builder will happily sweep a reserve whose vault is still live, which would\n * permanently void the depositor's pre-signed recourse graph. Eligibility is\n * enforced upstream, in the service.\n *\n * @module primitives/psbt/reclaim\n */\n\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { DUST_THRESHOLD } from \"../../utils/fee/constants\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport {\n PEGIN_DEPOSITOR_CLAIM_VOUT,\n deriveDepositorClaimDescriptor,\n} from \"./depositorClaim\";\n\n/**\n * nVersion for the reclaim transaction. Plain v2, not TRUC: the reserve is only\n * offered once its PegIn is deeply confirmed, so the v2/v3 PegIn's nVersion-3\n * topology limits no longer constrain its children.\n */\nconst RECLAIM_TX_VERSION = 2;\n\n/**\n * nSequence for every reclaim input: RBF-enabled, no relative timelock. The\n * claim leaf carries no CSV, so this is a fee-bumping signal only.\n */\nconst RECLAIM_INPUT_SEQUENCE = 0xfffffffd;\n\n/**\n * Weight units of the reclaim transaction's skeleton — everything except the\n * inputs. Non-witness `version(4) + inCount(1) + outCount(1) + locktime(4) +\n * output(8 + 1 + 34)` = 53 B × 4, plus the 2 WU SegWit marker and flag.\n */\nconst RECLAIM_SKELETON_WEIGHT_UNITS = 214;\n\n/**\n * Weight units each script-path input adds. Non-witness `outpoint(36) +\n * scriptSigLen(1) + sequence(4)` = 41 B × 4 = 164, plus a witness of\n * `stackCount(1) + sig(1 + 64) + leafScript(1 + 34) + controlBlock(1 + 33)` =\n * 135 WU.\n *\n * Exact rather than conservative: every element is fixed-length here — a\n * 64-byte BIP-340 signature under SIGHASH_DEFAULT, the 34-byte leaf, and a\n * 33-byte control block with no merkle path.\n */\nconst RECLAIM_INPUT_WEIGHT_UNITS = 299;\n\n/** Weight units per virtual byte. */\nconst WEIGHT_UNITS_PER_VBYTE = 4;\n\n/**\n * Virtual size of an N-in/1-out reclaim transaction.\n *\n * `REFUND_VSIZE = 160` does not generalise to N inputs, and\n * `computePeginBaseFeeSats` is wrong for this shape entirely — its\n * `P2TR_INPUT_SIZE = 58` is a *key-path* input and under-fees a script-path\n * spend by roughly a quarter.\n *\n * N=1 → 129 vB; each additional input adds 75 vB.\n */\nexport function reclaimVsize(numInputs: number): number {\n if (!Number.isInteger(numInputs) || numInputs < 1) {\n throw new Error(\n `Reclaim input count must be a positive integer, got ${numInputs}.`,\n );\n }\n return Math.ceil(\n (RECLAIM_SKELETON_WEIGHT_UNITS +\n RECLAIM_INPUT_WEIGHT_UNITS * numInputs) /\n WEIGHT_UNITS_PER_VBYTE,\n );\n}\n\n/** Absolute fee in satoshis for an N-in/1-out reclaim at a given rate. */\nexport function estimateReclaimFeeSats(\n feeRateSatsVb: number,\n numInputs: number,\n): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `Reclaim fee rate must be a positive number, got ${feeRateSatsVb}.`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * reclaimVsize(numInputs)));\n}\n\n/** One depositor-claim reserve to sweep, with the material to bind it. */\nexport interface ReclaimReserve {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Authoritative: its SegWit\n * txid equals the broadcast PegIn's, and its `outs[1]` carries the reserve's\n * script and value at no extra RPC cost.\n */\n depositorSignedPeginTxHex: string;\n /** Independent chain observation of `peginTxid:1` (esplora UTXO lookup). */\n observed: {\n /**\n * The outpoint the caller actually issued its chain lookup against, so the\n * observation below can be tied to the input this builder adds.\n *\n * Without it the script and value binds prove only that *some* UTXO has\n * this shape — the claim script is a pure function of the depositor key and\n * so is byte-identical across every vault they own, and the value is a pure\n * function of protocol parameters. Neither distinguishes one of the\n * depositor's vaults from another.\n *\n * Txid in display order, 64 hex chars, with or without `0x` prefix.\n */\n txid: string;\n /** Vout the lookup was issued against. Must be the claim vout. */\n vout: number;\n /** scriptPubKey hex, with or without `0x` prefix. */\n scriptPubKey: string;\n /** Output value in satoshis. */\n value: bigint;\n };\n /**\n * The reserve value recomputed from this vault's protocol parameters via\n * `computeMinClaimValue`. Bound so a doctored PegIn that agrees with itself\n * and with a compromised indexer still fails.\n */\n expectedValue: bigint;\n}\n\nexport interface BuildReclaimPsbtParams {\n /**\n * The **connected wallet's live** x-only pubkey, 64-char hex. Never the\n * indexer's `depositorBtcPubkey`: re-deriving from the live key is what\n * proves the wallet about to sign is the wallet that can spend, and rejects\n * the wrong-wallet case with an error instead of an unspendable broadcast.\n */\n depositorPubkey: string;\n /**\n * Reserves to sweep. An array so batching several vaults into one\n * transaction is a later change rather than a rewrite; today the app passes\n * exactly one.\n */\n inputs: ReclaimReserve[];\n /** Absolute fee in satoshis. The caller sizes it; see `reclaimVsize`. */\n feeSats: bigint;\n}\n\nexport interface BuildReclaimPsbtResult {\n /** PSBT hex ready for depositor signing. */\n psbtHex: string;\n /** Value of the single output — what the depositor actually receives. */\n outputValue: bigint;\n /** Sum of the swept reserves, before fee. */\n totalInputValue: bigint;\n}\n\n/**\n * Build the N-in/1-out reclaim PSBT.\n *\n * Every input is bound three ways before it reaches the PSBT: the contract's\n * PegIn bytes, the chain observation, and a JS re-derivation from the live\n * wallet key must agree on both script and value. Any disagreement throws.\n * The observation must also name the outpoint it was taken from, since script\n * and value alone repeat across all of a depositor's vaults.\n *\n * Binding the input to the *vault* that was asked for is a further step, and\n * it belongs to the service: it needs the vault id derivation, which is async.\n * See `services/reclaim/buildAndBroadcastReclaim`.\n *\n * @throws If `inputs` is empty, the fee is non-positive, any input fails its\n * outpoint, script or value bind, or the resulting output would be at or\n * below dust.\n */\nexport function buildReclaimPsbt(\n params: BuildReclaimPsbtParams,\n): BuildReclaimPsbtResult {\n const { depositorPubkey, inputs, feeSats } = params;\n\n if (inputs.length === 0) {\n throw new Error(\"Reclaim requires at least one input; got none.\");\n }\n if (feeSats <= 0n) {\n throw new Error(\n `Reclaim fee must be positive, got ${feeSats} sat. Refusing to build a ` +\n `transaction that would not relay.`,\n );\n }\n\n // One derivation, reused for every input's bind and for the destination.\n const descriptor = deriveDepositorClaimDescriptor(depositorPubkey);\n const expectedScriptPubKey = uint8ArrayToHex(\n new Uint8Array(descriptor.scriptPubKey),\n ).toLowerCase();\n\n const psbt = new Psbt();\n psbt.setVersion(RECLAIM_TX_VERSION);\n psbt.setLocktime(0);\n\n let totalInputValue = 0n;\n const seenOutpoints = new Set<string>();\n\n inputs.forEach((input, i) => {\n const peginTx = Transaction.fromHex(\n stripHexPrefix(input.depositorSignedPeginTxHex),\n );\n const peginTxid = peginTx.getId();\n\n const claimOut = peginTx.outs[PEGIN_DEPOSITOR_CLAIM_VOUT];\n if (!claimOut) {\n throw new Error(\n `PegIn ${peginTxid} has no output at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${peginTx.outs.length}); ` +\n `there is no depositor-claim reserve to reclaim.`,\n );\n }\n\n // Bind 0: the observation is of *this* outpoint. Everything below compares\n // a script and a value, both of which repeat across every vault this\n // depositor owns under the same protocol parameters — so without this the\n // remaining binds cannot tell one of their vaults from another, and a\n // caller that resolved the wrong vault would sweep it with every check\n // passing. The independent source is the PegIn the PSBT is built from; the\n // esplora response cannot serve here because `getUtxoInfo` echoes back the\n // txid and vout it was called with rather than reading them from the body.\n const observedTxid = stripHexPrefix(input.observed.txid).toLowerCase();\n if (observedTxid !== peginTxid) {\n throw new Error(\n `Input ${i}: the observation is of ${observedTxid}, but this input ` +\n `spends PegIn ${peginTxid}. Reclaim refused — the reserve that was ` +\n `looked up is not the one being swept.`,\n );\n }\n if (input.observed.vout !== PEGIN_DEPOSITOR_CLAIM_VOUT) {\n throw new Error(\n `Input ${i}: the observation is of vout ${input.observed.vout}, but ` +\n `the depositor-claim reserve is at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`,\n );\n }\n\n // Bind 1: the contract's PegIn bytes against the JS re-derivation from the\n // live wallet key. This is the assertion that proves the connected wallet\n // can actually spend the output we are about to sign for.\n const contractScriptPubKey = uint8ArrayToHex(\n new Uint8Array(claimOut.script),\n ).toLowerCase();\n if (contractScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} pays ` +\n `${contractScriptPubKey}, but the connected wallet's depositor-claim ` +\n `script is ${expectedScriptPubKey}. Reclaim refused — this reserve ` +\n `belongs to a different wallet.`,\n );\n }\n\n // Bind 2: the independent chain observation must agree with both.\n const observedScriptPubKey = stripHexPrefix(\n input.observed.scriptPubKey,\n ).toLowerCase();\n if (observedScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: the observed UTXO ${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `pays ${observedScriptPubKey}, expected ${expectedScriptPubKey}. ` +\n `Reclaim refused — chain state disagrees with the contract's PegIn.`,\n );\n }\n\n // Value bind, same three ways.\n const contractValue = BigInt(claimOut.value);\n if (contractValue !== input.observed.value) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but the observed UTXO carries ` +\n `${input.observed.value} sat. Reclaim refused.`,\n );\n }\n if (contractValue !== input.expectedValue) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but this vault's parameters compute a ` +\n `depositor-claim value of ${input.expectedValue} sat. Reclaim refused.`,\n );\n }\n\n // A batch that names the same vault twice would otherwise double-count the\n // swept total and then fail deep inside bitcoinjs. Reject it here, where\n // the message can say which input is the duplicate.\n const outpoint = `${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT}`;\n if (seenOutpoints.has(outpoint)) {\n throw new Error(\n `Input ${i} repeats outpoint ${outpoint}, which is already being ` +\n `swept by an earlier input. Reclaim refused.`,\n );\n }\n seenOutpoints.add(outpoint);\n\n totalInputValue += contractValue;\n\n psbt.addInput({\n hash: peginTxid,\n index: PEGIN_DEPOSITOR_CLAIM_VOUT,\n sequence: RECLAIM_INPUT_SEQUENCE,\n witnessUtxo: { script: claimOut.script, value: claimOut.value },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: descriptor.leafScript,\n controlBlock: descriptor.controlBlock,\n },\n ],\n tapInternalKey: descriptor.internalKey,\n });\n });\n\n if (feeSats >= totalInputValue) {\n throw new Error(\n `Reclaim fee ${feeSats} sat is not less than the swept total ` +\n `${totalInputValue} sat. Refusing to build a transaction with no output.`,\n );\n }\n\n const outputValue = totalInputValue - feeSats;\n if (outputValue <= DUST_THRESHOLD) {\n throw new Error(\n `Reclaim output ${outputValue} sat is at or below the dust threshold ` +\n `${DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it ` +\n `is until fee rates fall.`,\n );\n }\n\n const destination = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(depositorPubkey),\n );\n psbt.addOutput({\n script: Buffer.from(hexToUint8Array(destination)),\n value: Number(outputValue),\n });\n\n return { psbtHex: psbt.toHex(), outputValue, totalInputValue };\n}\n","/**\n * Finalize a Taproot script-path spend from the PSBT *we* built, using only the\n * verified signatures the wallet returned.\n *\n * Why this exists. The obvious shape — hand the wallet's PSBT to\n * `finalizeAllInputs()` — puts wallet-controlled bytes on the trust path even\n * when the signature itself has been verified.\n * `assertPsbtUnsignedTxMatches` deliberately pins only the unsigned\n * transaction and skips per-input metadata, so `tapLeafScript`, `controlBlock`\n * and `tapKeySig` all survive from the wallet's response untouched. And\n * bitcoinjs-lib checks key-spend first (`src/psbt.js`, `_finalizeTaprootInput`:\n * \"Check key spend first. Increased privacy and reduced block space.\"), so a\n * returned `tapKeySig` wins outright and `tapScriptSig` is never consulted.\n * Every output the depositor-claim reserve and the HTLC refund spend from uses\n * a NUMS internal key, so the resulting key-path witness cannot satisfy the\n * script — the transaction is rejected at broadcast, after a wallet prompt the\n * depositor cannot make sense of.\n *\n * Verifying and then discarding the wallet's PSBT closes that off structurally\n * rather than detecting it afterwards, and it makes the code match what\n * `verifyScriptPathSchnorrSignature` already documents: \"only the 64-byte\n * signature comes from the wallet\".\n *\n * @module tbv/core/primitives/psbt/finalizeScriptPathWithSignatures\n */\n\nimport { Psbt } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { X_ONLY_PUBKEY_HEX_LEN } from \"../../utils/validation\";\nimport {\n SCHNORR_SIG_HEX_LEN,\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport { computeTapLeafHash } from \"../utils/taproot\";\n\nexport interface FinalizeScriptPathWithSignaturesParams {\n /**\n * Hex of the PSBT built locally and sent to the wallet — the sole source of\n * every per-input field. NOT the wallet-returned PSBT.\n */\n requestedPsbtHex: string;\n /**\n * Verified 64-byte Schnorr signatures, one per input, index-aligned with the\n * PSBT's inputs. Each must already have passed\n * `assertScriptPathSchnorrSignature` — this function does not re-verify them,\n * it only decides which bytes are allowed to reach the witness.\n */\n signaturesHex: readonly string[];\n /** X-only pubkey (64 hex chars) the signatures are attributed to. */\n signerXOnlyPubkeyHex: string;\n}\n\n/**\n * Attach `signaturesHex` to the locally built PSBT's script-path inputs,\n * finalize, and return the extracted transaction hex.\n *\n * @throws If the signature count does not match the input count, any signature\n * or the signer key is malformed, any input does not carry exactly one\n * tapscript leaf at the expected leaf version, any input already carries a\n * key-path signature, or bitcoinjs-lib cannot finalize.\n */\nexport function finalizeScriptPathWithSignatures(\n params: FinalizeScriptPathWithSignaturesParams,\n): string {\n const { requestedPsbtHex, signaturesHex, signerXOnlyPubkeyHex } = params;\n\n const signerXOnly = stripHexPrefix(signerXOnlyPubkeyHex);\n if (signerXOnly.length !== X_ONLY_PUBKEY_HEX_LEN) {\n throw new Error(\n `Signer x-only pubkey must be ${X_ONLY_PUBKEY_HEX_LEN} hex chars ` +\n `(32 bytes), got ${signerXOnly.length}.`,\n );\n }\n const signerPubkey = Buffer.from(hexToUint8Array(signerXOnly));\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (signaturesHex.length !== psbt.data.inputs.length) {\n throw new Error(\n `Cannot finalize: got ${signaturesHex.length} signature(s) for ` +\n `${psbt.data.inputs.length} input(s). Every input must be signed — ` +\n `refusing to broadcast a partially signed transaction.`,\n );\n }\n\n psbt.data.inputs.forEach((input, inputIndex) => {\n // Our own builders never produce a key-path signature for these spends.\n // If one is present the PSBT is not the one we built, which would defeat\n // the whole point of finalizing locally.\n if (input.tapKeySig) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} of the locally built PSBT ` +\n `carries a key-path signature. These outputs are script-path only.`,\n );\n }\n\n const tapLeafScripts = input.tapLeafScript;\n if (!tapLeafScripts || tapLeafScripts.length !== 1) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} must have exactly one ` +\n `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 finalize: input ${inputIndex} tapLeafScript has leaf version ` +\n `0x${leaf.leafVersion.toString(16)}, expected ` +\n `0x${TAPSCRIPT_LEAF_VERSION.toString(16)}.`,\n );\n }\n\n const signatureRaw = stripHexPrefix(signaturesHex[inputIndex]);\n if (signatureRaw.length !== SCHNORR_SIG_HEX_LEN) {\n throw new Error(\n `Signature for input ${inputIndex} must be ${SCHNORR_SIG_HEX_LEN} hex ` +\n `chars (64 bytes), got ${signatureRaw.length}.`,\n );\n }\n\n psbt.updateInput(inputIndex, {\n tapScriptSig: [\n {\n pubkey: signerPubkey,\n leafHash: computeTapLeafHash(leaf.leafVersion, leaf.script),\n signature: Buffer.from(hexToUint8Array(signatureRaw)),\n },\n ],\n });\n });\n\n // With no tapKeySig anywhere, bitcoinjs takes the script-path branch for\n // every input and builds `[signature, leafScript, controlBlock]` from the\n // leaf we supplied.\n psbt.finalizeAllInputs();\n\n return psbt.extractTransaction().toHex();\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"../../wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}], used verbatim — derive them from the parent txs */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["U64_MAX","assertPositiveBigintArray","values","label","value","index","buildRefundPsbt","params","WasmPrePeginTx","loadTbvWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","fundedTx","wasmHtlcScriptPubKey","expectedHtlc","deriveExpectedPrePeginHtlc","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","REFUND_TX_VERSION","REFUND_TX_LOCKTIME","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","RECLAIM_TX_VERSION","RECLAIM_INPUT_SEQUENCE","RECLAIM_SKELETON_WEIGHT_UNITS","RECLAIM_INPUT_WEIGHT_UNITS","WEIGHT_UNITS_PER_VBYTE","reclaimVsize","numInputs","estimateReclaimFeeSats","feeRateSatsVb","buildReclaimPsbt","depositorPubkey","inputs","feeSats","descriptor","deriveDepositorClaimDescriptor","expectedScriptPubKey","totalInputValue","seenOutpoints","input","i","peginTx","peginTxid","claimOut","PEGIN_DEPOSITOR_CLAIM_VOUT","observedTxid","contractScriptPubKey","observedScriptPubKey","contractValue","outpoint","outputValue","DUST_THRESHOLD","destination","hexToUint8Array","finalizeScriptPathWithSignatures","requestedPsbtHex","signaturesHex","signerXOnlyPubkeyHex","signerXOnly","X_ONLY_PUBKEY_HEX_LEN","signerPubkey","inputIndex","tapLeafScripts","leaf","signatureRaw","SCHNORR_SIG_HEX_LEN","computeTapLeafHash","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":"wUAoBMA,GAAW,IAAM,KAAO,GAYvB,SAASC,EACdC,EACAC,EACU,CACV,GAAI,CAAC,MAAM,QAAQD,CAAM,EACvB,MAAM,IAAI,MACR,GAAGC,CAAK,8CAA8C,OAAOD,CAAM,IAAA,EAGvE,GAAIA,EAAO,SAAW,EACpB,MAAM,IAAI,MAAM,GAAGC,CAAK,qBAAqB,EAE/C,OAAAD,EAAO,QAAQ,CAACE,EAAOC,IAAU,CAC/B,GAAI,OAAOD,GAAU,SACnB,MAAM,IAAI,MACR,GAAGD,CAAK,IAAIE,CAAK,2BAA2B,OAAOD,CAAK,2CAAA,EAI5D,GAAIA,GAAS,GACX,MAAM,IAAI,MAAM,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,MAAM,IAAI,MACR,kFAAA,CAGN"}
1
+ {"version":3,"file":"noPayout-DOHak0ui.cjs","sources":["../src/tbv/core/wasm/value-guards.ts","../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/reclaim.ts","../src/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Runtime guard for satoshi amounts crossing into the WASM FFI boundary.\n *\n * `new BigUint64Array(values)` is the only way satoshi amounts are handed to\n * the constructor, and a runtime cast (`as readonly bigint[]`) lets a caller\n * pass a non-bigint or non-positive element that `BigUint64Array` would either\n * reject cryptically or, in its length-arg form, silently zero-fill. Values\n * above the u64 maximum are worse still: `BigUint64Array` wraps them mod 2^64\n * without complaint, turning an oversized amount into a small one.\n * {@link assertPositiveBigintArray} validates such inputs before the\n * typed-array construction.\n *\n * Mirrors the `assertPositiveBigintArray` half of `value-guards.ts` in\n * `@babylonlabs-io/babylon-tbv-rust-wasm`; that one function is pinned to the\n * engine's source copy by `__tests__/value-guards.test.ts`. The engine's other\n * guard, `assertWasmBigint`, has no counterpart here: the engine applies it to\n * its own WASM return values before they reach this package.\n */\n\n/** Largest value BigUint64Array stores without wrapping mod 2^64 (2^64 − 1). */\nconst U64_MAX = (1n << 64n) - 1n;\n\n/**\n * Assert a value is a non-empty array of strictly-positive `bigint`s and return\n * it narrowed, ready to feed into `new BigUint64Array(...)`.\n *\n * @param values - The candidate array of satoshi amounts.\n * @param label - Human-readable name used in the thrown error.\n * @throws If `values` is not an array, is empty, or contains any element that is\n * not a `bigint`, is not strictly greater than 0, or exceeds the u64 maximum\n * (which `BigUint64Array` would otherwise wrap mod 2^64).\n */\nexport function assertPositiveBigintArray(\n values: unknown,\n label: string,\n): bigint[] {\n if (!Array.isArray(values)) {\n throw new Error(\n `${label} must be an array of positive bigints (got ${typeof values}).`,\n );\n }\n if (values.length === 0) {\n throw new Error(`${label} must not be empty.`);\n }\n values.forEach((value, index) => {\n if (typeof value !== \"bigint\") {\n throw new Error(\n `${label}[${index}] must be a bigint (got ${typeof value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n if (value <= 0n) {\n throw new Error(`${label}[${index}] must be > 0 (got ${value}).`);\n }\n if (value > U64_MAX) {\n throw new Error(\n `${label}[${index}] must fit in a u64 (got ${value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n });\n return values as bigint[];\n}\n","/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport { loadTbvWasm, tapInternalPubkey } from \"../../wasm\";\nimport { assertPositiveBigintArray } from \"../../wasm/value-guards\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\nimport { REFUND_TX_LOCKTIME, REFUND_TX_VERSION } from \"./constants\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<depositorPubkey> OP_CHECKSIGVERIFY <timelockRefund>\n * OP_CHECKSEQUENCEVERIFY` — btc-vault `connectors/prepegin_htlc.rs`\n * `generate_refund_script`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n const { WasmPrePeginTx } = await loadTbvWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: typeof unfundedTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against an independent\n // TypeScript derivation and the funded transaction bytes.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const wasmHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n const expectedHtlc = deriveExpectedPrePeginHtlc(prePeginParams, hashlock);\n const expectedHtlcScriptPubKey = expectedHtlc.scriptPubKey.toString(\"hex\");\n if (wasmHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `WASM HTLC scriptPubKey ${wasmHtlcScriptPubKey} does not match the ` +\n `independently derived scriptPubKey ${expectedHtlcScriptPubKey}.`,\n );\n }\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + p2aAnchorValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.version !== REFUND_TX_VERSION) {\n throw new Error(\n `Refund transaction version ${refundTx.version} does not match ` +\n `protocol version ${REFUND_TX_VERSION}.`,\n );\n }\n if (refundTx.locktime !== REFUND_TX_LOCKTIME) {\n throw new Error(\n `Refund transaction locktime ${refundTx.locktime} does not match ` +\n `protocol locktime ${REFUND_TX_LOCKTIME}.`,\n );\n }\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n if (refundInput.sequence !== prePeginParams.timelockRefund) {\n throw new Error(\n `Refund input sequence ${refundInput.sequence} does not match ` +\n `timelockRefund ${prePeginParams.timelockRefund}.`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.refundScript,\n controlBlock: expectedHtlc.refundControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * Reclaim PSBT Builder Primitive\n *\n * Builds an unsigned PSBT that sweeps the depositor-claim reserve — PegIn\n * vout 1 — back to the depositor's own BIP-86 address.\n *\n * The reserve funds the depositor's `claim_tx`, their recourse if the vault\n * provider fails during peg-out. When the vault provider claims instead and\n * the depositor withdraws normally, nothing ever spends it. This primitive is\n * the only thing in the repository that can.\n *\n * Spend path: the single `<depositor> OP_CHECKSIG` tapleaf (see\n * ./depositorClaim). No timelock, no counterparty signature — the depositor's\n * Schnorr signature alone. That is also why the *caller* must gate: this\n * builder will happily sweep a reserve whose vault is still live, which would\n * permanently void the depositor's pre-signed recourse graph. Eligibility is\n * enforced upstream, in the service.\n *\n * @module primitives/psbt/reclaim\n */\n\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { DUST_THRESHOLD } from \"../../utils/fee/constants\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport {\n PEGIN_DEPOSITOR_CLAIM_VOUT,\n deriveDepositorClaimDescriptor,\n} from \"./depositorClaim\";\n\n/**\n * nVersion for the reclaim transaction. Plain v2, not TRUC: the reserve is only\n * offered once its PegIn is deeply confirmed, so the v2/v3 PegIn's nVersion-3\n * topology limits no longer constrain its children.\n */\nconst RECLAIM_TX_VERSION = 2;\n\n/**\n * nSequence for every reclaim input: RBF-enabled, no relative timelock. The\n * claim leaf carries no CSV, so this is a fee-bumping signal only.\n */\nconst RECLAIM_INPUT_SEQUENCE = 0xfffffffd;\n\n/**\n * Weight units of the reclaim transaction's skeleton — everything except the\n * inputs. Non-witness `version(4) + inCount(1) + outCount(1) + locktime(4) +\n * output(8 + 1 + 34)` = 53 B × 4, plus the 2 WU SegWit marker and flag.\n */\nconst RECLAIM_SKELETON_WEIGHT_UNITS = 214;\n\n/**\n * Weight units each script-path input adds. Non-witness `outpoint(36) +\n * scriptSigLen(1) + sequence(4)` = 41 B × 4 = 164, plus a witness of\n * `stackCount(1) + sig(1 + 64) + leafScript(1 + 34) + controlBlock(1 + 33)` =\n * 135 WU.\n *\n * Exact rather than conservative: every element is fixed-length here — a\n * 64-byte BIP-340 signature under SIGHASH_DEFAULT, the 34-byte leaf, and a\n * 33-byte control block with no merkle path.\n */\nconst RECLAIM_INPUT_WEIGHT_UNITS = 299;\n\n/** Weight units per virtual byte. */\nconst WEIGHT_UNITS_PER_VBYTE = 4;\n\n/**\n * Virtual size of an N-in/1-out reclaim transaction.\n *\n * `REFUND_VSIZE = 160` does not generalise to N inputs, and\n * `computePeginBaseFeeSats` is wrong for this shape entirely — its\n * `P2TR_INPUT_SIZE = 58` is a *key-path* input and under-fees a script-path\n * spend by roughly a quarter.\n *\n * N=1 → 129 vB; each additional input adds 75 vB.\n */\nexport function reclaimVsize(numInputs: number): number {\n if (!Number.isInteger(numInputs) || numInputs < 1) {\n throw new Error(\n `Reclaim input count must be a positive integer, got ${numInputs}.`,\n );\n }\n return Math.ceil(\n (RECLAIM_SKELETON_WEIGHT_UNITS +\n RECLAIM_INPUT_WEIGHT_UNITS * numInputs) /\n WEIGHT_UNITS_PER_VBYTE,\n );\n}\n\n/** Absolute fee in satoshis for an N-in/1-out reclaim at a given rate. */\nexport function estimateReclaimFeeSats(\n feeRateSatsVb: number,\n numInputs: number,\n): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `Reclaim fee rate must be a positive number, got ${feeRateSatsVb}.`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * reclaimVsize(numInputs)));\n}\n\n/** One depositor-claim reserve to sweep, with the material to bind it. */\nexport interface ReclaimReserve {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Authoritative: its SegWit\n * txid equals the broadcast PegIn's, and its `outs[1]` carries the reserve's\n * script and value at no extra RPC cost.\n */\n depositorSignedPeginTxHex: string;\n /** Independent chain observation of `peginTxid:1` (esplora UTXO lookup). */\n observed: {\n /**\n * The outpoint the caller actually issued its chain lookup against, so the\n * observation below can be tied to the input this builder adds.\n *\n * Without it the script and value binds prove only that *some* UTXO has\n * this shape — the claim script is a pure function of the depositor key and\n * so is byte-identical across every vault they own, and the value is a pure\n * function of protocol parameters. Neither distinguishes one of the\n * depositor's vaults from another.\n *\n * Txid in display order, 64 hex chars, with or without `0x` prefix.\n */\n txid: string;\n /** Vout the lookup was issued against. Must be the claim vout. */\n vout: number;\n /** scriptPubKey hex, with or without `0x` prefix. */\n scriptPubKey: string;\n /** Output value in satoshis. */\n value: bigint;\n };\n /**\n * The reserve value recomputed from this vault's protocol parameters via\n * `computeMinClaimValue`. Bound so a doctored PegIn that agrees with itself\n * and with a compromised indexer still fails.\n */\n expectedValue: bigint;\n}\n\nexport interface BuildReclaimPsbtParams {\n /**\n * The **connected wallet's live** x-only pubkey, 64-char hex. Never the\n * indexer's `depositorBtcPubkey`: re-deriving from the live key is what\n * proves the wallet about to sign is the wallet that can spend, and rejects\n * the wrong-wallet case with an error instead of an unspendable broadcast.\n */\n depositorPubkey: string;\n /**\n * Reserves to sweep. An array so batching several vaults into one\n * transaction is a later change rather than a rewrite; today the app passes\n * exactly one.\n */\n inputs: ReclaimReserve[];\n /** Absolute fee in satoshis. The caller sizes it; see `reclaimVsize`. */\n feeSats: bigint;\n}\n\nexport interface BuildReclaimPsbtResult {\n /** PSBT hex ready for depositor signing. */\n psbtHex: string;\n /** Value of the single output — what the depositor actually receives. */\n outputValue: bigint;\n /** Sum of the swept reserves, before fee. */\n totalInputValue: bigint;\n}\n\n/**\n * Build the N-in/1-out reclaim PSBT.\n *\n * Every input is bound three ways before it reaches the PSBT: the contract's\n * PegIn bytes, the chain observation, and a JS re-derivation from the live\n * wallet key must agree on both script and value. Any disagreement throws.\n * The observation must also name the outpoint it was taken from, since script\n * and value alone repeat across all of a depositor's vaults.\n *\n * Binding the input to the *vault* that was asked for is a further step, and\n * it belongs to the service: it needs the vault id derivation, which is async.\n * See `services/reclaim/buildAndBroadcastReclaim`.\n *\n * @throws If `inputs` is empty, the fee is non-positive, any input fails its\n * outpoint, script or value bind, or the resulting output would be at or\n * below dust.\n */\nexport function buildReclaimPsbt(\n params: BuildReclaimPsbtParams,\n): BuildReclaimPsbtResult {\n const { depositorPubkey, inputs, feeSats } = params;\n\n if (inputs.length === 0) {\n throw new Error(\"Reclaim requires at least one input; got none.\");\n }\n if (feeSats <= 0n) {\n throw new Error(\n `Reclaim fee must be positive, got ${feeSats} sat. Refusing to build a ` +\n `transaction that would not relay.`,\n );\n }\n\n // One derivation, reused for every input's bind and for the destination.\n const descriptor = deriveDepositorClaimDescriptor(depositorPubkey);\n const expectedScriptPubKey = uint8ArrayToHex(\n new Uint8Array(descriptor.scriptPubKey),\n ).toLowerCase();\n\n const psbt = new Psbt();\n psbt.setVersion(RECLAIM_TX_VERSION);\n psbt.setLocktime(0);\n\n let totalInputValue = 0n;\n const seenOutpoints = new Set<string>();\n\n inputs.forEach((input, i) => {\n const peginTx = Transaction.fromHex(\n stripHexPrefix(input.depositorSignedPeginTxHex),\n );\n const peginTxid = peginTx.getId();\n\n const claimOut = peginTx.outs[PEGIN_DEPOSITOR_CLAIM_VOUT];\n if (!claimOut) {\n throw new Error(\n `PegIn ${peginTxid} has no output at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${peginTx.outs.length}); ` +\n `there is no depositor-claim reserve to reclaim.`,\n );\n }\n\n // Bind 0: the observation is of *this* outpoint. Everything below compares\n // a script and a value, both of which repeat across every vault this\n // depositor owns under the same protocol parameters — so without this the\n // remaining binds cannot tell one of their vaults from another, and a\n // caller that resolved the wrong vault would sweep it with every check\n // passing. The independent source is the PegIn the PSBT is built from; the\n // esplora response cannot serve here because `getUtxoInfo` echoes back the\n // txid and vout it was called with rather than reading them from the body.\n const observedTxid = stripHexPrefix(input.observed.txid).toLowerCase();\n if (observedTxid !== peginTxid) {\n throw new Error(\n `Input ${i}: the observation is of ${observedTxid}, but this input ` +\n `spends PegIn ${peginTxid}. Reclaim refused — the reserve that was ` +\n `looked up is not the one being swept.`,\n );\n }\n if (input.observed.vout !== PEGIN_DEPOSITOR_CLAIM_VOUT) {\n throw new Error(\n `Input ${i}: the observation is of vout ${input.observed.vout}, but ` +\n `the depositor-claim reserve is at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`,\n );\n }\n\n // Bind 1: the contract's PegIn bytes against the JS re-derivation from the\n // live wallet key. This is the assertion that proves the connected wallet\n // can actually spend the output we are about to sign for.\n const contractScriptPubKey = uint8ArrayToHex(\n new Uint8Array(claimOut.script),\n ).toLowerCase();\n if (contractScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} pays ` +\n `${contractScriptPubKey}, but the connected wallet's depositor-claim ` +\n `script is ${expectedScriptPubKey}. Reclaim refused — this reserve ` +\n `belongs to a different wallet.`,\n );\n }\n\n // Bind 2: the independent chain observation must agree with both.\n const observedScriptPubKey = stripHexPrefix(\n input.observed.scriptPubKey,\n ).toLowerCase();\n if (observedScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: the observed UTXO ${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `pays ${observedScriptPubKey}, expected ${expectedScriptPubKey}. ` +\n `Reclaim refused — chain state disagrees with the contract's PegIn.`,\n );\n }\n\n // Value bind, same three ways.\n const contractValue = BigInt(claimOut.value);\n if (contractValue !== input.observed.value) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but the observed UTXO carries ` +\n `${input.observed.value} sat. Reclaim refused.`,\n );\n }\n if (contractValue !== input.expectedValue) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but this vault's parameters compute a ` +\n `depositor-claim value of ${input.expectedValue} sat. Reclaim refused.`,\n );\n }\n\n // A batch that names the same vault twice would otherwise double-count the\n // swept total and then fail deep inside bitcoinjs. Reject it here, where\n // the message can say which input is the duplicate.\n const outpoint = `${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT}`;\n if (seenOutpoints.has(outpoint)) {\n throw new Error(\n `Input ${i} repeats outpoint ${outpoint}, which is already being ` +\n `swept by an earlier input. Reclaim refused.`,\n );\n }\n seenOutpoints.add(outpoint);\n\n totalInputValue += contractValue;\n\n psbt.addInput({\n hash: peginTxid,\n index: PEGIN_DEPOSITOR_CLAIM_VOUT,\n sequence: RECLAIM_INPUT_SEQUENCE,\n witnessUtxo: { script: claimOut.script, value: claimOut.value },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: descriptor.leafScript,\n controlBlock: descriptor.controlBlock,\n },\n ],\n tapInternalKey: descriptor.internalKey,\n });\n });\n\n if (feeSats >= totalInputValue) {\n throw new Error(\n `Reclaim fee ${feeSats} sat is not less than the swept total ` +\n `${totalInputValue} sat. Refusing to build a transaction with no output.`,\n );\n }\n\n const outputValue = totalInputValue - feeSats;\n if (outputValue <= DUST_THRESHOLD) {\n throw new Error(\n `Reclaim output ${outputValue} sat is at or below the dust threshold ` +\n `${DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it ` +\n `is until fee rates fall.`,\n );\n }\n\n const destination = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(depositorPubkey),\n );\n psbt.addOutput({\n script: Buffer.from(hexToUint8Array(destination)),\n value: Number(outputValue),\n });\n\n return { psbtHex: psbt.toHex(), outputValue, totalInputValue };\n}\n","/**\n * Finalize a Taproot script-path spend from the PSBT *we* built, using only the\n * verified signatures the wallet returned.\n *\n * Why this exists. The obvious shape — hand the wallet's PSBT to\n * `finalizeAllInputs()` — puts wallet-controlled bytes on the trust path even\n * when the signature itself has been verified.\n * `assertPsbtUnsignedTxMatches` deliberately pins only the unsigned\n * transaction and skips per-input metadata, so `tapLeafScript`, `controlBlock`\n * and `tapKeySig` all survive from the wallet's response untouched. And\n * bitcoinjs-lib checks key-spend first (`src/psbt.js`, `_finalizeTaprootInput`:\n * \"Check key spend first. Increased privacy and reduced block space.\"), so a\n * returned `tapKeySig` wins outright and `tapScriptSig` is never consulted.\n * Every output the depositor-claim reserve and the HTLC refund spend from uses\n * a NUMS internal key, so the resulting key-path witness cannot satisfy the\n * script — the transaction is rejected at broadcast, after a wallet prompt the\n * depositor cannot make sense of.\n *\n * Verifying and then discarding the wallet's PSBT closes that off structurally\n * rather than detecting it afterwards, and it makes the code match what\n * `verifyScriptPathSchnorrSignature` already documents: \"only the 64-byte\n * signature comes from the wallet\".\n *\n * @module tbv/core/primitives/psbt/finalizeScriptPathWithSignatures\n */\n\nimport { Psbt } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { X_ONLY_PUBKEY_HEX_LEN } from \"../../utils/validation\";\nimport {\n SCHNORR_SIG_HEX_LEN,\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport { computeTapLeafHash } from \"../utils/taproot\";\n\nexport interface FinalizeScriptPathWithSignaturesParams {\n /**\n * Hex of the PSBT built locally and sent to the wallet — the sole source of\n * every per-input field. NOT the wallet-returned PSBT.\n */\n requestedPsbtHex: string;\n /**\n * Verified 64-byte Schnorr signatures, one per input, index-aligned with the\n * PSBT's inputs. Each must already have passed\n * `assertScriptPathSchnorrSignature` — this function does not re-verify them,\n * it only decides which bytes are allowed to reach the witness.\n */\n signaturesHex: readonly string[];\n /** X-only pubkey (64 hex chars) the signatures are attributed to. */\n signerXOnlyPubkeyHex: string;\n}\n\n/**\n * Attach `signaturesHex` to the locally built PSBT's script-path inputs,\n * finalize, and return the extracted transaction hex.\n *\n * @throws If the signature count does not match the input count, any signature\n * or the signer key is malformed, any input does not carry exactly one\n * tapscript leaf at the expected leaf version, any input already carries a\n * key-path signature, or bitcoinjs-lib cannot finalize.\n */\nexport function finalizeScriptPathWithSignatures(\n params: FinalizeScriptPathWithSignaturesParams,\n): string {\n const { requestedPsbtHex, signaturesHex, signerXOnlyPubkeyHex } = params;\n\n const signerXOnly = stripHexPrefix(signerXOnlyPubkeyHex);\n if (signerXOnly.length !== X_ONLY_PUBKEY_HEX_LEN) {\n throw new Error(\n `Signer x-only pubkey must be ${X_ONLY_PUBKEY_HEX_LEN} hex chars ` +\n `(32 bytes), got ${signerXOnly.length}.`,\n );\n }\n const signerPubkey = Buffer.from(hexToUint8Array(signerXOnly));\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (signaturesHex.length !== psbt.data.inputs.length) {\n throw new Error(\n `Cannot finalize: got ${signaturesHex.length} signature(s) for ` +\n `${psbt.data.inputs.length} input(s). Every input must be signed — ` +\n `refusing to broadcast a partially signed transaction.`,\n );\n }\n\n psbt.data.inputs.forEach((input, inputIndex) => {\n // Our own builders never produce a key-path signature for these spends.\n // If one is present the PSBT is not the one we built, which would defeat\n // the whole point of finalizing locally.\n if (input.tapKeySig) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} of the locally built PSBT ` +\n `carries a key-path signature. These outputs are script-path only.`,\n );\n }\n\n const tapLeafScripts = input.tapLeafScript;\n if (!tapLeafScripts || tapLeafScripts.length !== 1) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} must have exactly one ` +\n `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 finalize: input ${inputIndex} tapLeafScript has leaf version ` +\n `0x${leaf.leafVersion.toString(16)}, expected ` +\n `0x${TAPSCRIPT_LEAF_VERSION.toString(16)}.`,\n );\n }\n\n const signatureRaw = stripHexPrefix(signaturesHex[inputIndex]);\n if (signatureRaw.length !== SCHNORR_SIG_HEX_LEN) {\n throw new Error(\n `Signature for input ${inputIndex} must be ${SCHNORR_SIG_HEX_LEN} hex ` +\n `chars (64 bytes), got ${signatureRaw.length}.`,\n );\n }\n\n psbt.updateInput(inputIndex, {\n tapScriptSig: [\n {\n pubkey: signerPubkey,\n leafHash: computeTapLeafHash(leaf.leafVersion, leaf.script),\n signature: Buffer.from(hexToUint8Array(signatureRaw)),\n },\n ],\n });\n });\n\n // With no tapKeySig anywhere, bitcoinjs takes the script-path branch for\n // every input and builds `[signature, leafScript, controlBlock]` from the\n // leaf we supplied.\n psbt.finalizeAllInputs();\n\n return psbt.extractTransaction().toHex();\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"../../wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}], used verbatim — derive them from the parent txs */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["U64_MAX","assertPositiveBigintArray","values","label","value","index","buildRefundPsbt","params","WasmPrePeginTx","loadTbvWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","fundedTx","wasmHtlcScriptPubKey","expectedHtlc","deriveExpectedPrePeginHtlc","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","REFUND_TX_VERSION","REFUND_TX_LOCKTIME","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","RECLAIM_TX_VERSION","RECLAIM_INPUT_SEQUENCE","RECLAIM_SKELETON_WEIGHT_UNITS","RECLAIM_INPUT_WEIGHT_UNITS","WEIGHT_UNITS_PER_VBYTE","reclaimVsize","numInputs","estimateReclaimFeeSats","feeRateSatsVb","buildReclaimPsbt","depositorPubkey","inputs","feeSats","descriptor","deriveDepositorClaimDescriptor","expectedScriptPubKey","totalInputValue","seenOutpoints","input","i","peginTx","peginTxid","claimOut","PEGIN_DEPOSITOR_CLAIM_VOUT","observedTxid","contractScriptPubKey","observedScriptPubKey","contractValue","outpoint","outputValue","DUST_THRESHOLD","destination","hexToUint8Array","finalizeScriptPathWithSignatures","requestedPsbtHex","signaturesHex","signerXOnlyPubkeyHex","signerXOnly","X_ONLY_PUBKEY_HEX_LEN","signerPubkey","inputIndex","tapLeafScripts","leaf","signatureRaw","SCHNORR_SIG_HEX_LEN","computeTapLeafHash","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":"wUAoBMA,GAAW,IAAM,KAAO,GAYvB,SAASC,EACdC,EACAC,EACU,CACV,GAAI,CAAC,MAAM,QAAQD,CAAM,EACvB,MAAM,IAAI,MACR,GAAGC,CAAK,8CAA8C,OAAOD,CAAM,IAAA,EAGvE,GAAIA,EAAO,SAAW,EACpB,MAAM,IAAI,MAAM,GAAGC,CAAK,qBAAqB,EAE/C,OAAAD,EAAO,QAAQ,CAACE,EAAOC,IAAU,CAC/B,GAAI,OAAOD,GAAU,SACnB,MAAM,IAAI,MACR,GAAGD,CAAK,IAAIE,CAAK,2BAA2B,OAAOD,CAAK,2CAAA,EAI5D,GAAIA,GAAS,GACX,MAAM,IAAI,MAAM,GAAGD,CAAK,IAAIE,CAAK,sBAAsBD,CAAK,IAAI,EAElE,GAAIA,EAAQJ,EACV,MAAM,IAAI,MACR,GAAGG,CAAK,IAAIE,CAAK,4BAA4BD,CAAK,2CAAA,CAIxD,CAAC,EACMF,CACT,CCSA,eAAsBI,EACpBC,EACgC,CAChC,KAAM,CAAE,eAAAC,GAAmB,MAAMC,cAAA,EAE3B,CAAE,eAAAC,EAAgB,oBAAAC,EAAqB,SAAAC,EAAU,UAAAC,EAAW,SAAAC,GAChEP,EAYIQ,EAA2BC,EAAAA,wBAC/BN,EAAe,cAAA,EAIXO,EAAa,IAAIT,EACrBE,EAAe,iBACfA,EAAe,gBACfA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