@babylonlabs-io/ts-sdk 3.3.0 → 4.0.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 (170) hide show
  1. package/dist/{BTCVaultRegistry.abi-BzNTa_EU.js → BTCVaultRegistry.abi-DnP4UkB5.js} +9 -140
  2. package/dist/BTCVaultRegistry.abi-DnP4UkB5.js.map +1 -0
  3. package/dist/{BTCVaultRegistry.abi-BH2-LHxN.cjs → BTCVaultRegistry.abi-DzbfZ9_s.cjs} +2 -2
  4. package/dist/BTCVaultRegistry.abi-DzbfZ9_s.cjs.map +1 -0
  5. package/dist/{PayoutManager-xEGvTbhL.js → PayoutManager-BUWP-H-q.js} +3 -3
  6. package/dist/PayoutManager-BUWP-H-q.js.map +1 -0
  7. package/dist/{PayoutManager-B1Ev0r7o.cjs → PayoutManager-Dopxq_Jv.cjs} +2 -2
  8. package/dist/PayoutManager-Dopxq_Jv.cjs.map +1 -0
  9. package/dist/PeginManager-CMbRRTnr.cjs +2 -0
  10. package/dist/{PeginManager-Co43rW_x.cjs.map → PeginManager-CMbRRTnr.cjs.map} +1 -1
  11. package/dist/{PeginManager-BJnUgW8C.js → PeginManager-Cas6_j7t.js} +118 -107
  12. package/dist/{PeginManager-BJnUgW8C.js.map → PeginManager-Cas6_j7t.js.map} +1 -1
  13. package/dist/{ProtocolParams.abi-Cv77fsUe.js → ProtocolParams.abi-CuDl7AuC.js} +3 -3
  14. package/dist/{ProtocolParams.abi-Cv77fsUe.js.map → ProtocolParams.abi-CuDl7AuC.js.map} +1 -1
  15. package/dist/{ProtocolParams.abi-BgEZaQ2I.cjs → ProtocolParams.abi-DWfIh6VH.cjs} +2 -2
  16. package/dist/{ProtocolParams.abi-BgEZaQ2I.cjs.map → ProtocolParams.abi-DWfIh6VH.cjs.map} +1 -1
  17. package/dist/VaultErrors.abi-Dc3UnB_h.js +5 -0
  18. package/dist/{VaultErrors.abi-Boz4w97c.js.map → VaultErrors.abi-Dc3UnB_h.js.map} +1 -1
  19. package/dist/VaultErrors.abi-Hjn1CdLs.cjs +2 -0
  20. package/dist/{VaultErrors.abi-DQ18kM0L.cjs.map → VaultErrors.abi-Hjn1CdLs.cjs.map} +1 -1
  21. package/dist/buildAndBroadcastReclaim-CVmG3ldA.cjs +2 -0
  22. package/dist/buildAndBroadcastReclaim-CVmG3ldA.cjs.map +1 -0
  23. package/dist/{buildAndBroadcastReclaim-CQANDXVJ.js → buildAndBroadcastReclaim-XRWuJWVL.js} +48 -50
  24. package/dist/buildAndBroadcastReclaim-XRWuJWVL.js.map +1 -0
  25. package/dist/{challengeAssert-C3eMcM5Y.cjs → challengeAssert-BE6Wm4x1.cjs} +2 -2
  26. package/dist/challengeAssert-BE6Wm4x1.cjs.map +1 -0
  27. package/dist/{challengeAssert-B2otuf7y.js → challengeAssert-DUKSjirl.js} +3 -3
  28. package/dist/challengeAssert-DUKSjirl.js.map +1 -0
  29. package/dist/constants-BCg6O0PX.cjs +2 -0
  30. package/dist/constants-BCg6O0PX.cjs.map +1 -0
  31. package/dist/constants-CmDDuM3L.js +50 -0
  32. package/dist/constants-CmDDuM3L.js.map +1 -0
  33. package/dist/{index-BRsWXDlv.js → index-B-9aXMxk.js} +6 -6
  34. package/dist/{index-BRsWXDlv.js.map → index-B-9aXMxk.js.map} +1 -1
  35. package/dist/{index-C6avwx1s.cjs → index-Dn7RlsKK.cjs} +2 -2
  36. package/dist/{index-C6avwx1s.cjs.map → index-Dn7RlsKK.cjs.map} +1 -1
  37. package/dist/index.cjs +1 -1
  38. package/dist/index.js +16 -16
  39. package/dist/pegin-registration-client-DLlaZbsZ.cjs +2 -0
  40. package/dist/pegin-registration-client-DLlaZbsZ.cjs.map +1 -0
  41. package/dist/{pegin-registration-client-Cvjk4ILq.js → pegin-registration-client-ZI0k10_3.js} +90 -96
  42. package/dist/pegin-registration-client-ZI0k10_3.js.map +1 -0
  43. package/dist/{primeVpAuth-D4UWXQ76.js → primeVpAuth-C-ET0XF4.js} +2 -2
  44. package/dist/{primeVpAuth-D4UWXQ76.js.map → primeVpAuth-C-ET0XF4.js.map} +1 -1
  45. package/dist/{primeVpAuth-CXNXYKrh.cjs → primeVpAuth-Ch-ig2My.cjs} +2 -2
  46. package/dist/{primeVpAuth-CXNXYKrh.cjs.map → primeVpAuth-Ch-ig2My.cjs.map} +1 -1
  47. package/dist/registration-records-CKc0OVuK.cjs +2 -0
  48. package/dist/registration-records-CKc0OVuK.cjs.map +1 -0
  49. package/dist/{registration-records-DJJC2NiO.js → registration-records-D39ApuHS.js} +141 -141
  50. package/dist/registration-records-D39ApuHS.js.map +1 -0
  51. package/dist/shared/index.cjs.map +1 -1
  52. package/dist/shared/index.js.map +1 -1
  53. package/dist/shared/wallets/interfaces/BitcoinWallet.d.ts +5 -0
  54. package/dist/shared/wallets/interfaces/BitcoinWallet.d.ts.map +1 -1
  55. package/dist/{signer-set-reader-GrFe_rsW.cjs → signer-set-reader-CJfV-GDz.cjs} +2 -2
  56. package/dist/{signer-set-reader-GrFe_rsW.cjs.map → signer-set-reader-CJfV-GDz.cjs.map} +1 -1
  57. package/dist/{signer-set-reader-CSUe92zE.js → signer-set-reader-DiwLeqik.js} +3 -3
  58. package/dist/{signer-set-reader-CSUe92zE.js.map → signer-set-reader-DiwLeqik.js.map} +1 -1
  59. package/dist/tbv/core/clients/eth/index.cjs +1 -1
  60. package/dist/tbv/core/clients/eth/index.js +4 -4
  61. package/dist/tbv/core/clients/eth/protocol-params-validation.d.ts.map +1 -1
  62. package/dist/tbv/core/clients/eth/registration-logs-error.d.ts +6 -6
  63. package/dist/tbv/core/clients/eth/registration-records.d.ts +1 -1
  64. package/dist/tbv/core/clients/eth/types.d.ts +12 -13
  65. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  66. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +1 -1
  67. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  68. package/dist/tbv/core/clients/index.cjs +1 -1
  69. package/dist/tbv/core/clients/index.js +6 -6
  70. package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
  71. package/dist/tbv/core/clients/vault-provider/status/index.js +1 -1
  72. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +5 -111
  73. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
  74. package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts +2 -2
  75. package/dist/tbv/core/contracts/abis/vaultErrors.abi.json.d.ts +1 -1
  76. package/dist/tbv/core/contracts/index.cjs +1 -1
  77. package/dist/tbv/core/contracts/index.js +3 -3
  78. package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsCore.test.d.ts +1 -1
  79. package/dist/tbv/core/deposit-terms/commissionCeiling.d.ts +1 -1
  80. package/dist/tbv/core/deposit-terms/depositTerms.d.ts +5 -5
  81. package/dist/tbv/core/deposit-terms/rebuildDepositTermsCore.d.ts.map +1 -1
  82. package/dist/tbv/core/index.cjs +1 -1
  83. package/dist/tbv/core/index.js +16 -16
  84. package/dist/tbv/core/managers/PeginManager.d.ts +2 -1
  85. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  86. package/dist/tbv/core/managers/index.cjs +1 -1
  87. package/dist/tbv/core/managers/index.js +2 -2
  88. package/dist/tbv/core/primitives/__tests__/vaultCoreVersion.test.d.ts +1 -1
  89. package/dist/tbv/core/primitives/index.cjs +1 -1
  90. package/dist/tbv/core/primitives/index.js +3 -3
  91. package/dist/tbv/core/primitives/psbt/__tests__/deriveExpectedPeginPayoutScriptPubKey.test.d.ts +1 -1
  92. package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
  93. package/dist/tbv/core/primitives/psbt/constants.d.ts +38 -13
  94. package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
  95. package/dist/tbv/core/primitives/psbt/depositorClaim.d.ts +3 -6
  96. package/dist/tbv/core/primitives/psbt/depositorClaim.d.ts.map +1 -1
  97. package/dist/tbv/core/primitives/psbt/pegin.d.ts +3 -5
  98. package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
  99. package/dist/tbv/core/recovery/peginParamsCandidates.d.ts +1 -1
  100. package/dist/tbv/core/recovery/reconstructPeginParams.d.ts.map +1 -1
  101. package/dist/tbv/core/services/delegated-claim/__tests__/realWasmWatchtowerArtifacts.test.d.ts +2 -2
  102. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts +2 -1
  103. package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts.map +1 -1
  104. package/dist/tbv/core/services/delegated-claim/deriveClaimerWotsKeypair.d.ts +1 -1
  105. package/dist/tbv/core/services/delegated-claim/deriveClaimerWotsKeypair.d.ts.map +1 -1
  106. package/dist/tbv/core/services/delegated-claim/planDelegatedClaimSigning.d.ts +2 -1
  107. package/dist/tbv/core/services/delegated-claim/planDelegatedClaimSigning.d.ts.map +1 -1
  108. package/dist/tbv/core/services/delegated-claim/readDelegatedClaimVaultContext.d.ts +1 -1
  109. package/dist/tbv/core/services/delegated-claim/readDelegatedClaimVaultContext.d.ts.map +1 -1
  110. package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts +3 -3
  111. package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts.map +1 -1
  112. package/dist/tbv/core/services/delegated-claim/types.d.ts +5 -6
  113. package/dist/tbv/core/services/delegated-claim/types.d.ts.map +1 -1
  114. package/dist/tbv/core/services/deposit/__tests__/signDepositorGraph.realGraph.test.d.ts +3 -3
  115. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  116. package/dist/tbv/core/services/index.cjs +1 -1
  117. package/dist/tbv/core/services/index.js +2 -2
  118. package/dist/tbv/core/wasm/index.cjs.map +1 -1
  119. package/dist/tbv/core/wasm/index.d.ts +8 -11
  120. package/dist/tbv/core/wasm/index.d.ts.map +1 -1
  121. package/dist/tbv/core/wasm/index.js.map +1 -1
  122. package/dist/tbv/index.cjs +1 -1
  123. package/dist/tbv/index.js +16 -16
  124. package/dist/toRefundInputs-BSQjDOK9.cjs +2 -0
  125. package/dist/toRefundInputs-BSQjDOK9.cjs.map +1 -0
  126. package/dist/{toRefundInputs-Dzw1cteD.js → toRefundInputs-BbbvPb2A.js} +175 -173
  127. package/dist/toRefundInputs-BbbvPb2A.js.map +1 -0
  128. package/dist/{types-BC2TGzcp.cjs → types-BnZIbDHb.cjs} +2 -2
  129. package/dist/types-BnZIbDHb.cjs.map +1 -0
  130. package/dist/{types-24A9Qoxb.js → types-K_aM5GZO.js} +39 -39
  131. package/dist/types-K_aM5GZO.js.map +1 -0
  132. package/dist/{verifyKeyPathSchnorrSignature-IIj3Z2se.js → verifyKeyPathSchnorrSignature-DPXOFOol.js} +2 -2
  133. package/dist/{verifyKeyPathSchnorrSignature-IIj3Z2se.js.map → verifyKeyPathSchnorrSignature-DPXOFOol.js.map} +1 -1
  134. package/dist/{verifyKeyPathSchnorrSignature-BRTpEH9X.cjs → verifyKeyPathSchnorrSignature-DcxCojp0.cjs} +2 -2
  135. package/dist/{verifyKeyPathSchnorrSignature-BRTpEH9X.cjs.map → verifyKeyPathSchnorrSignature-DcxCojp0.cjs.map} +1 -1
  136. package/dist/verifyScriptPathSchnorrSignature-CgDa9Rcg.cjs +2 -0
  137. package/dist/verifyScriptPathSchnorrSignature-CgDa9Rcg.cjs.map +1 -0
  138. package/dist/{verifyScriptPathSchnorrSignature-owu3BfyT.js → verifyScriptPathSchnorrSignature-D-fdi-sG.js} +462 -459
  139. package/dist/verifyScriptPathSchnorrSignature-D-fdi-sG.js.map +1 -0
  140. package/package.json +3 -3
  141. package/dist/BTCVaultRegistry.abi-BH2-LHxN.cjs.map +0 -1
  142. package/dist/BTCVaultRegistry.abi-BzNTa_EU.js.map +0 -1
  143. package/dist/PayoutManager-B1Ev0r7o.cjs.map +0 -1
  144. package/dist/PayoutManager-xEGvTbhL.js.map +0 -1
  145. package/dist/PeginManager-Co43rW_x.cjs +0 -2
  146. package/dist/VaultErrors.abi-Boz4w97c.js +0 -5
  147. package/dist/VaultErrors.abi-DQ18kM0L.cjs +0 -2
  148. package/dist/buildAndBroadcastReclaim-CQANDXVJ.js.map +0 -1
  149. package/dist/buildAndBroadcastReclaim-DPk36Uhp.cjs +0 -2
  150. package/dist/buildAndBroadcastReclaim-DPk36Uhp.cjs.map +0 -1
  151. package/dist/challengeAssert-B2otuf7y.js.map +0 -1
  152. package/dist/challengeAssert-C3eMcM5Y.cjs.map +0 -1
  153. package/dist/constants-CAm10Qwp.cjs +0 -2
  154. package/dist/constants-CAm10Qwp.cjs.map +0 -1
  155. package/dist/constants-CvQZuxKv.js +0 -48
  156. package/dist/constants-CvQZuxKv.js.map +0 -1
  157. package/dist/pegin-registration-client-CdRyXP3j.cjs +0 -2
  158. package/dist/pegin-registration-client-CdRyXP3j.cjs.map +0 -1
  159. package/dist/pegin-registration-client-Cvjk4ILq.js.map +0 -1
  160. package/dist/registration-records-DJJC2NiO.js.map +0 -1
  161. package/dist/registration-records-XQMIKjGV.cjs +0 -2
  162. package/dist/registration-records-XQMIKjGV.cjs.map +0 -1
  163. package/dist/toRefundInputs-DTuWi--u.cjs +0 -2
  164. package/dist/toRefundInputs-DTuWi--u.cjs.map +0 -1
  165. package/dist/toRefundInputs-Dzw1cteD.js.map +0 -1
  166. package/dist/types-24A9Qoxb.js.map +0 -1
  167. package/dist/types-BC2TGzcp.cjs.map +0 -1
  168. package/dist/verifyScriptPathSchnorrSignature-CahYx5Td.cjs +0 -2
  169. package/dist/verifyScriptPathSchnorrSignature-CahYx5Td.cjs.map +0 -1
  170. package/dist/verifyScriptPathSchnorrSignature-owu3BfyT.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"verifyKeyPathSchnorrSignature-BRTpEH9X.cjs","sources":["../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/utils/witness/witnessStack.ts","../src/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.ts","../src/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.ts"],"sourcesContent":["/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"../../wasm\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * Vault core (tx-graph) version the Pre-PegIn was built with. Must match\n * the version passed to buildPrePeginPsbt() so the HTLC connector scripts\n * are derived for the same graph.\n */\n vaultCoreVersion: number;\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n // Keep the facade's graph-version and input checks. Do not use its scripts\n // or control block as signing data.\n await getPrePeginHtlcConnectorInfo({\n txGraphVersion: params.vaultCoreVersion,\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n const expectedHtlc = deriveExpectedPrePeginHtlc(params, params.hashlock);\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n if (!expectedHtlc.scriptPubKey.equals(htlcOutput.script)) {\n throw new Error(\n \"PegIn HTLC taptree mismatch: the independent 2-leaf tree does not \" +\n \"reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.\",\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending. bitcoinjs\n // re-verifies leaf-in-tree consistency (control block vs tapMerkleRoot)\n // inside addInput — a second independent check.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.hashlockScript,\n controlBlock: expectedHtlc.hashlockControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(hexToUint8Array(depositorPubkey));\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // A wallet that ignores `autoFinalized: false` returns already-finalized\n // inputs (OKX's single-PSBT endpoint does; the wallet-connector routes OKX\n // around it). finalizeAllInputs() throws in that case, so fall back to\n // verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n","/**\n * Consensus witness-stack decoding, shared by every module that reads a\n * witness we did not build.\n *\n * Two independent decoders drifted apart before this existed: one accepted\n * non-minimal CompactSize encodings, the other rejected them. vaultd decodes\n * with rust-bitcoin, whose `VarInt::consensus_decode`\n * (0.32.8 `consensus/encode.rs:493-522`) returns `NonMinimalVarInt` for a 0xfd\n * carrying < 0xfd and a 0xfe carrying < 0x10000 — so the strict reading is the\n * only one that matches what the network will accept.\n *\n * @module tbv/core/utils/witness/witnessStack\n */\n\n/** CompactSize discriminators; 0xff (u64) is out of range for a witness. */\nconst COMPACT_SIZE_UINT16_PREFIX = 0xfd;\nconst COMPACT_SIZE_UINT32_PREFIX = 0xfe;\nconst COMPACT_SIZE_UINT16_BYTES = 3;\nconst COMPACT_SIZE_UINT32_BYTES = 5;\nconst COMPACT_SIZE_UINT16_MIN_VALUE = 0xfd;\nconst COMPACT_SIZE_UINT32_MIN_VALUE = 0x10000;\n\n/**\n * Decode a consensus-encoded witness stack: item count, then (len, bytes)*.\n *\n * @param witness - The consensus-encoded witness bytes.\n * @param subject - Names the witness in error messages (e.g. \"finalScriptWitness\").\n * @returns The stack items, as views over `witness`.\n * @throws If the encoding is truncated, non-minimal, out of range, or leaves\n * trailing bytes.\n */\nexport function decodeWitnessStack(\n witness: Uint8Array,\n subject: string,\n): Uint8Array[] {\n let offset = 0;\n\n const readCompactSize = (): number => {\n if (offset >= witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const first = witness[offset];\n if (first < COMPACT_SIZE_UINT16_PREFIX) {\n offset += 1;\n return first;\n }\n if (first === COMPACT_SIZE_UINT16_PREFIX) {\n if (offset + COMPACT_SIZE_UINT16_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value = witness[offset + 1] | (witness[offset + 2] << 8);\n if (value < COMPACT_SIZE_UINT16_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT16_BYTES;\n return value;\n }\n if (first === COMPACT_SIZE_UINT32_PREFIX) {\n if (offset + COMPACT_SIZE_UINT32_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value =\n (witness[offset + 1] |\n (witness[offset + 2] << 8) |\n (witness[offset + 3] << 16) |\n (witness[offset + 4] << 24)) >>>\n 0;\n if (value < COMPACT_SIZE_UINT32_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT32_BYTES;\n return value;\n }\n throw new Error(`${subject} carries an out-of-range item length`);\n };\n\n const count = readCompactSize();\n const items: Uint8Array[] = [];\n for (let i = 0; i < count; i++) {\n const len = readCompactSize();\n if (offset + len > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n items.push(witness.subarray(offset, offset + len));\n offset += len;\n }\n if (offset !== witness.length) {\n throw new Error(`${subject} has trailing bytes`);\n }\n return items;\n}\n","/**\n * Far-side verification of P2WPKH ECDSA signatures a wallet returned, over\n * the PSBT we requested (trusted prevouts) — the Native SegWit sibling of\n * `verifyKeyPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs:945-1000\n * verify_finalized_p2wpkh_spend`. The wallet's success/finalization is\n * never trusted on its own (CLAUDE.md §8): prevout script and value come\n * from the PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport {\n crypto as bcrypto,\n script as bscript,\n payments,\n Psbt,\n Transaction,\n} from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\n\n// P2WPKH scriptPubKey is exactly `OP_0 OP_PUSHBYTES_20 <20-byte key hash>`\n// (BIP-141 witness program v0, 20 bytes).\nconst P2WPKH_SCRIPT_LEN = 22;\nconst OP_0 = 0x00;\nconst OP_PUSHBYTES_20 = 0x14;\nconst P2WPKH_PROGRAM_START = 2;\n\n/** SEC1 compressed pubkey (client.rs:959: \"expected a 33-byte compressed key\"). */\nconst COMPRESSED_PUBKEY_BYTES = 33;\n/** Consensus P2WPKH witness: exactly [signature, pubkey] (client.rs:951-957). */\nconst P2WPKH_WITNESS_ITEMS = 2;\n\n/** Only claim P2WPKH: 22-byte scriptPubKey starting `OP_0 PUSH20`. */\nexport function isP2wpkhScript(\n script: Uint8Array | undefined,\n): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2WPKH_SCRIPT_LEN &&\n script[0] === OP_0 &&\n script[1] === OP_PUSHBYTES_20\n );\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\n/** The `[signature, pubkey]` pair of a finalized P2WPKH witness (client.rs:951-957). */\nfunction decodeP2wpkhWitness(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; pubkey: Uint8Array } {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== P2WPKH_WITNESS_ITEMS) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized P2WPKH witness must have ` +\n `exactly 2 items [signature, pubkey], got ${items.length}.`,\n );\n }\n return { signature: items[0], pubkey: items[1] };\n}\n\nexport interface AssertReturnedP2wpkhSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout script/value). NOT the wallet's. */\n requestedPsbtHex: string;\n /** The wallet-returned PSBT input carrying the signature material. */\n returnedInput: {\n partialSig?: Array<{ pubkey: Uint8Array; signature: Uint8Array }>;\n finalScriptWitness?: Uint8Array;\n };\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that the returned input carries a valid P2WPKH ECDSA signature\n * over the BIP-143 sighash of `requestedPsbtHex` input `inputIndex`:\n * `partialSig` (BIP-174: the value is the exact witness-stack signature\n * bytes, the key its pubkey), or the finalized 2-item witness — and when\n * both are present they must be the same bytes.\n *\n * @throws If the requested input is not a P2WPKH spend, no signature was\n * returned, a finalized witness disagrees with its `partialSig`,\n * or any check of `verify_finalized_p2wpkh_spend` fails.\n */\nexport function assertReturnedP2wpkhSignature(\n params: AssertReturnedP2wpkhSignatureParams,\n): void {\n const { requestedPsbtHex, returnedInput, inputIndex } = params;\n\n const partials = returnedInput.partialSig;\n // Consensus allows exactly one signature in a P2WPKH witness, so a second\n // partialSig entry is ambiguous tampering, not a fallback to pick from.\n if (partials !== undefined && partials.length > 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a P2WPKH input must carry at most one ` +\n `partial signature, got ${partials.length}.`,\n );\n }\n const partial = partials?.[0];\n const witness = returnedInput.finalScriptWitness\n ? decodeP2wpkhWitness(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify (same\n // rationale as the tapKeySig/witness agreement check).\n if (\n partial &&\n witness &&\n (!bytesEqual(partial.signature, witness.signature) ||\n !bytesEqual(partial.pubkey, witness.pubkey))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its partialSig.`,\n );\n }\n\n const material = partial ?? witness;\n if (!material) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no P2WPKH signature ` +\n `(no partialSig, not finalized).`,\n );\n }\n\n assertP2wpkhEcdsaSignature(\n requestedPsbtHex,\n material.signature,\n material.pubkey,\n inputIndex,\n );\n}\n\n/**\n * The crypto core, mirroring `verify_finalized_p2wpkh_spend` check by\n * check: pubkey shape and curve membership, hash160(pubkey) == witness\n * program, strict-DER + SIGHASH_ALL-only signature, ECDSA over the\n * BIP-143 sighash recomputed from the REQUESTED prevout.\n */\nfunction assertP2wpkhEcdsaSignature(\n requestedPsbtHex: string,\n encodedSignature: Uint8Array,\n pubkey: Uint8Array,\n inputIndex: number,\n): void {\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n const prevout = psbt.data.inputs[inputIndex].witnessUtxo;\n if (!prevout || !isP2wpkhScript(prevout.script)) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a P2WPKH input.`,\n );\n }\n\n // Pubkey: exactly 33 bytes (client.rs:959-965) and a parseable curve\n // point, as PublicKey::from_slice (client.rs:966-968).\n if (pubkey.length !== COMPRESSED_PUBKEY_BYTES) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey must be 33 bytes, ` +\n `got ${pubkey.length}.`,\n );\n }\n if (!ecc.isPointCompressed(pubkey)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey is not a valid secp256k1 point.`,\n );\n }\n\n // hash160(pubkey) must equal the prevout's witness program — what\n // consensus checks (client.rs:970-977).\n const program = prevout.script.subarray(\n P2WPKH_PROGRAM_START,\n P2WPKH_SCRIPT_LEN,\n );\n if (!bytesEqual(bcrypto.hash160(Buffer.from(pubkey)), program)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey does not hash to the ` +\n `prevout's witness program.`,\n );\n }\n\n // Strict-DER decode with defined-hashtype gate — the accept set of\n // ecdsa::Signature::from_slice / EcdsaSighashType::from_standard\n // (client.rs:978-980) — then SIGHASH_ALL exactly (client.rs:981-987).\n let decoded: { signature: Buffer; hashType: number };\n try {\n decoded = bscript.signature.decode(Buffer.from(encodedSignature));\n } catch (e) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not DER with a ` +\n `defined sighash byte: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that libsecp's strict consensus\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(decoded.signature, decoded.hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not canonical DER.`,\n );\n }\n if (decoded.hashType !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature has sighash type ` +\n `0x${decoded.hashType.toString(16)} (expected SIGHASH_ALL).`,\n );\n }\n\n // BIP-143 sighash over the REQUESTED prevout value with the standard\n // P2WPKH scriptCode built from the witness program (client.rs:988-991;\n // scriptCode template per bitcoinjs-lib's own P2WPKH signer,\n // `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: Buffer.from(program) }).output;\n if (!scriptCode) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: could not build the P2WPKH scriptCode.`,\n );\n }\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV0(\n inputIndex,\n scriptCode,\n prevout.value,\n decoded.hashType,\n );\n\n // strict=true rejects high-S, as libsecp256k1's verify_ecdsa does\n // (client.rs:992-999; secp256k1 crate `ecdsa/mod.rs:194`). ecc.verify\n // throws on out-of-range r/s — that is a failed verification here.\n let verifies = false;\n try {\n verifies = ecc.verify(sighash, pubkey, decoded.signature, true);\n } catch {\n verifies = false;\n }\n if (!verifies) {\n throw new Error(\n `P2WPKH signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout. The wallet may have signed a different ` +\n `transaction or key.`,\n );\n }\n}\n","/**\n * Far-side verification of Taproot KEY-PATH Schnorr signatures a wallet\n * returned, over the PSBT we requested (trusted prevouts) — the key-path twin\n * of `assertScriptPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs check_signatures_valid` (output key taken\n * from the prevout scriptPubKey, all prevouts committed). The wallet's\n * success/finalization is never trusted on its own (CLAUDE.md §8).\n * `assertReturnedKeyPathSignatures` additionally dispatches P2WPKH-funded\n * inputs to `verifyP2wpkhEcdsaSignature` (client.rs's\n * `verify_finalized_p2wpkh_spend` sibling), so a Native SegWit software\n * wallet's signatures no longer pass through unchecked.\n *\n * Why verify against the *requested* PSBT: `assertPsbtUnsignedTxMatches` pins\n * the unsigned transaction but deliberately skips per-input metadata, so a\n * wallet could rewrite `witnessUtxo` in its response and make a wrong-message\n * signature self-validate. Prevout scripts and values therefore come from the\n * PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\nimport { hexToUint8Array, stripHexPrefix } from \"../utils/bitcoin\";\nimport {\n assertReturnedP2wpkhSignature,\n isP2wpkhScript,\n} from \"./verifyP2wpkhEcdsaSignature\";\n\nconst SCHNORR_SIG_BYTES = 64;\nconst SIGHASH_DEFAULT = Transaction.SIGHASH_DEFAULT; // 0x00\nconst SIGHASH_ALL = Transaction.SIGHASH_ALL; // 0x01\n\n// P2TR scriptPubKey is exactly `OP_1 OP_PUSHBYTES_32 <32-byte output key>`.\nconst P2TR_SCRIPT_LEN = 34;\nconst OP_1 = 0x51;\nconst OP_PUSHBYTES_32 = 0x20;\nconst P2TR_OUTPUT_KEY_OFFSET = 2;\n\nfunction isP2trScript(script: Uint8Array | undefined): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2TR_SCRIPT_LEN &&\n script[0] === OP_1 &&\n script[1] === OP_PUSHBYTES_32\n );\n}\n\n/** BIP-341: 64 bytes ⇒ SIGHASH_DEFAULT; 65 bytes ⇒ the trailing byte is the hash type (we accept ALL only). */\nfunction splitHashType(\n sig: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; hashType: number } {\n if (sig.length === SCHNORR_SIG_BYTES) {\n return { signature: sig, hashType: SIGHASH_DEFAULT };\n }\n if (\n sig.length === SCHNORR_SIG_BYTES + 1 &&\n sig[SCHNORR_SIG_BYTES] === SIGHASH_ALL\n ) {\n return {\n signature: sig.subarray(0, SCHNORR_SIG_BYTES),\n hashType: SIGHASH_ALL,\n };\n }\n throw new Error(\n `Key-path signature for input ${inputIndex} must be 64 bytes (SIGHASH_DEFAULT) or ` +\n `65 bytes ending in 0x01 (SIGHASH_ALL), got ${sig.length}.`,\n );\n}\n\nexport interface AssertKeyPathSchnorrSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout scripts/values). NOT the wallet's. */\n requestedPsbtHex: string;\n /** 64- or 65-byte signature, hex. */\n signatureHex: string;\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that `signatureHex` is a valid BIP-340 Schnorr signature over the\n * Taproot key-path sighash of `requestedPsbtHex` input `inputIndex`, under the\n * tweaked output key taken from that input's prevout scriptPubKey.\n *\n * @throws If the input is not a key-path P2TR spend, the requested PSBT lacks\n * the prevout data needed to recompute the sighash, or the signature\n * does not verify.\n */\nexport function assertKeyPathSchnorrSignature(\n params: AssertKeyPathSchnorrSignatureParams,\n): void {\n const { requestedPsbtHex, signatureHex, inputIndex } = params;\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n\n if (!isKeyPathEligible(psbt.data.inputs[inputIndex])) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a key-path P2TR input.`,\n );\n }\n\n // Taproot's sighash commits to every input's prevout (script + value), so all\n // inputs must carry a witnessUtxo. A missing one is a build error, not a\n // value we can default — fail loudly.\n const prevOutScripts: Buffer[] = [];\n const values: number[] = [];\n for (let i = 0; i < psbt.data.inputs.length; i++) {\n const prevout = psbt.data.inputs[i].witnessUtxo;\n if (!prevout) {\n throw new Error(\n `Cannot verify signature: input ${i} of the requested PSBT has no witnessUtxo ` +\n `(required to recompute the Taproot sighash).`,\n );\n }\n prevOutScripts.push(prevout.script);\n values.push(prevout.value);\n }\n\n const { signature, hashType } = splitHashType(\n hexToUint8Array(stripHexPrefix(signatureHex)),\n inputIndex,\n );\n\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV1(\n inputIndex,\n prevOutScripts,\n values,\n hashType,\n );\n\n // Key-path signatures verify against the TWEAKED output key = the prevout's\n // witness program.\n const outputKey = prevOutScripts[inputIndex].subarray(P2TR_OUTPUT_KEY_OFFSET);\n\n if (!ecc.verifySchnorr(sighash, outputKey, signature)) {\n throw new Error(\n `Key-path Schnorr signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout (output key ${Buffer.from(outputKey).toString(\"hex\")}). ` +\n `The wallet may have signed a different transaction or key.`,\n );\n }\n}\n\n/**\n * A key-path P2TR input: an internal key, no script-path material, and a\n * taproot prevout. Script-path inputs are the script-path verifier's job.\n */\nfunction isKeyPathEligible(input: {\n tapInternalKey?: Uint8Array;\n tapLeafScript?: unknown;\n tapMerkleRoot?: Uint8Array;\n witnessUtxo?: { script: Uint8Array };\n}): boolean {\n return (\n input.tapInternalKey !== undefined &&\n input.tapLeafScript === undefined &&\n input.tapMerkleRoot === undefined &&\n isP2trScript(input.witnessUtxo?.script)\n );\n}\n\n/**\n * The lone stack item of a finalized key-path witness. An annex would add a\n * second item, but Bitcoin Core rejects annexes as nonstandard\n * (`src/policy/policy.cpp:327-329`), so such a spend could never broadcast.\n */\nfunction singleWitnessItem(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): Uint8Array {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized key-path witness must have ` +\n `exactly one item, got ${items.length}.`,\n );\n }\n return items[0];\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\nexport interface AssertReturnedKeyPathSignaturesParams {\n /** PSBT we built locally and asked the wallet to sign. */\n requestedPsbtHex: string;\n /** PSBT the wallet returned after signing. */\n returnedPsbtHex: string;\n}\n\n/**\n * Verify every key-path-eligible and P2WPKH input of the REQUESTED PSBT\n * against what the wallet RETURNED. Key-path: `tapKeySig`, or the single\n * finalized witness item for wallets that auto-finalize — and when both are\n * present they must be the same bytes. P2WPKH: `partialSig`, or the finalized\n * 2-item witness, verified as ECDSA over the BIP-143 sighash\n * ({@link assertReturnedP2wpkhSignature}); a failure throws but the input is\n * NOT counted. Any other input type (script-path, P2WSH, ...) throws — no\n * verifier here covers it, so it cannot be treated as verified.\n *\n * @returns How many inputs were verified KEY-PATH. A caller that knows every\n * input is taproot key-path (e.g. an approval wallet) must assert\n * this equals its input count — P2WPKH inputs never count toward it,\n * so that gate stays exact.\n * @throws If the input counts differ, an input is neither key-path P2TR nor\n * P2WPKH, an eligible input carries no signature, a finalized witness\n * disagrees with its `tapKeySig`/`partialSig`, or any signature does\n * not verify.\n */\nexport function assertReturnedKeyPathSignatures(\n params: AssertReturnedKeyPathSignaturesParams,\n): number {\n const { requestedPsbtHex, returnedPsbtHex } = params;\n\n const requested = Psbt.fromHex(requestedPsbtHex);\n const returned = Psbt.fromHex(returnedPsbtHex);\n\n if (returned.data.inputs.length !== requested.data.inputs.length) {\n throw new Error(\n `Returned PSBT input count ${returned.data.inputs.length} differs from the ` +\n `requested ${requested.data.inputs.length}.`,\n );\n }\n\n let verified = 0;\n requested.data.inputs.forEach((input, inputIndex) => {\n const returnedInput = returned.data.inputs[inputIndex];\n\n if (!isKeyPathEligible(input)) {\n // Native SegWit funding inputs get the ECDSA check.\n if (isP2wpkhScript(input.witnessUtxo?.script)) {\n assertReturnedP2wpkhSignature({\n requestedPsbtHex,\n returnedInput,\n inputIndex,\n });\n return;\n }\n // No verifier exists for any other type — fail closed like btc-vault's\n // check_signatures_valid rather than silently reporting it checked.\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is neither key-path P2TR ` +\n `nor P2WPKH; refusing to treat it as verified.`,\n );\n }\n verified++;\n\n const tapKeySig = returnedInput.tapKeySig;\n const witnessSig = returnedInput.finalScriptWitness\n ? singleWitnessItem(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify. Matches\n // btc-vault `crates/btc-wallet-remote/src/client.rs:1053-1072,1102-1121`,\n // which checks each independently.\n if (tapKeySig && witnessSig && !bytesEqual(tapKeySig, witnessSig)) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its tapKeySig.`,\n );\n }\n\n const sig = tapKeySig ?? witnessSig;\n if (!sig) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no key-path signature ` +\n `(no tapKeySig, not finalized).`,\n );\n }\n\n assertKeyPathSchnorrSignature({\n requestedPsbtHex,\n signatureHex: Buffer.from(sig).toString(\"hex\"),\n inputIndex,\n });\n });\n\n return verified;\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","getPrePeginHtlcConnectorInfo","expectedHtlc","deriveExpectedPrePeginHtlc","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","hexToUint8Array","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","COMPACT_SIZE_UINT16_PREFIX","COMPACT_SIZE_UINT32_PREFIX","COMPACT_SIZE_UINT16_BYTES","COMPACT_SIZE_UINT32_BYTES","COMPACT_SIZE_UINT16_MIN_VALUE","COMPACT_SIZE_UINT32_MIN_VALUE","decodeWitnessStack","witness","subject","offset","readCompactSize","first","value","count","items","i","len","P2WPKH_SCRIPT_LEN","OP_0","OP_PUSHBYTES_20","P2WPKH_PROGRAM_START","COMPRESSED_PUBKEY_BYTES","P2WPKH_WITNESS_ITEMS","isP2wpkhScript","script","bytesEqual","a","b","byte","decodeP2wpkhWitness","finalScriptWitness","inputIndex","assertReturnedP2wpkhSignature","requestedPsbtHex","returnedInput","partials","partial","material","assertP2wpkhEcdsaSignature","encodedSignature","pubkey","prevout","ecc","program","bcrypto","decoded","bscript","scriptCode","payments","sighash","verifies","SCHNORR_SIG_BYTES","SIGHASH_DEFAULT","SIGHASH_ALL","P2TR_SCRIPT_LEN","OP_1","OP_PUSHBYTES_32","P2TR_OUTPUT_KEY_OFFSET","isP2trScript","splitHashType","assertKeyPathSchnorrSignature","signatureHex","isKeyPathEligible","prevOutScripts","values","signature","hashType","outputKey","_a","singleWitnessItem","assertReturnedKeyPathSignatures","returnedPsbtHex","requested","returned","verified","tapKeySig","witnessSig"],"mappings":"khBA4FA,eAAsBA,EACpBC,EACoC,CACpC,MAAMC,EAAaC,EAAAA,eAAeF,EAAO,UAAU,EAC7CG,EAAsBD,EAAAA,eAAeF,EAAO,mBAAmB,EAIrE,MAAMI,+BAA6B,CACjC,eAAgBJ,EAAO,iBACvB,gBAAiBA,EAAO,gBACxB,oBAAqBA,EAAO,oBAC5B,mBAAoBA,EAAO,mBAC3B,2BAA4BA,EAAO,2BACnC,SAAUA,EAAO,SACjB,eAAgBA,EAAO,eACvB,QAASA,EAAO,OAAA,CACjB,EACD,MAAMK,EAAeC,EAAAA,2BAA2BN,EAAQA,EAAO,QAAQ,EAEjEO,EAAUC,EAAAA,YAAY,QAAQP,CAAU,EACxCQ,EAAaD,EAAAA,YAAY,QAAQL,CAAmB,EAE1D,GAAII,EAAQ,IAAI,SAAW,EACzB,MAAM,IAAI,MACR,oDAAoDA,EAAQ,IAAI,MAAM,EAAA,EAI1E,MAAMG,EAAaH,EAAQ,IAAI,CAAC,EAG1BI,EAAeF,EAAW,MAAA,EAC1BG,EAAiBC,EAAAA,gBACrB,IAAI,WAAWH,EAAW,IAAI,EAAE,MAAA,EAAQ,QAAA,CAAQ,EAGlD,GAAIE,IAAmBD,EACrB,MAAM,IAAI,MACR,sEACcA,CAAY,SAASC,CAAc,EAAA,EAIrD,MAAME,EAAaL,EAAW,KAAKC,EAAW,KAAK,EACnD,GAAI,CAACI,EACH,MAAM,IAAI,MACR,oBAAoBJ,EAAW,KAAK,6BAChBD,EAAW,KAAK,MAAM,WAAA,EAI9C,GAAI,CAACJ,EAAa,aAAa,OAAOS,EAAW,MAAM,EACrD,MAAM,IAAI,MACR,uIAAA,EAKJ,MAAMC,EAAO,IAAIC,OACjBD,EA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F,EAAOwC,IAAe,OACnD,MAAMG,EAAgBuC,EAAS,KAAK,OAAO1C,CAAU,EAErD,GAAI,CAAC+B,EAAkBvE,CAAK,EAAG,CAE7B,GAAIgC,GAAe6C,EAAA7E,EAAM,cAAN,YAAA6E,EAAmB,MAAM,EAAG,CAC7CpC,EAA8B,CAC5B,iBAAAC,EACA,cAAAC,EACA,WAAAH,CAAA,CACD,EACD,MACF,CAGA,MAAM,IAAI,MACR,SAASA,CAAU,+FAAA,CAGvB,CACA2C,IAEA,MAAMC,EAAYzC,EAAc,UAC1B0C,EAAa1C,EAAc,mBAC7BmC,GAAkBnC,EAAc,mBAAoBH,CAAU,EAC9D,OAMJ,GAAI4C,GAAaC,GAAc,CAACnD,GAAWkD,EAAWC,CAAU,EAC9D,MAAM,IAAI,MACR,uBAAuB7C,CAAU,kDAAA,EAIrC,MAAMhC,EAAM4E,GAAaC,EACzB,GAAI,CAAC7E,EACH,MAAM,IAAI,MACR,uBAAuBgC,CAAU,+DAAA,EAKrC6B,EAA8B,CAC5B,iBAAA3B,EACA,aAAchD,EAAAA,OAAO,KAAKc,CAAG,EAAE,SAAS,KAAK,EAC7C,WAAAgC,CAAA,CACD,CACH,CAAC,EAEM2C,CACT"}
1
+ {"version":3,"file":"verifyKeyPathSchnorrSignature-DcxCojp0.cjs","sources":["../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/utils/witness/witnessStack.ts","../src/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.ts","../src/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.ts"],"sourcesContent":["/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"../../wasm\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * Vault core (tx-graph) version the Pre-PegIn was built with. Must match\n * the version passed to buildPrePeginPsbt() so the HTLC connector scripts\n * are derived for the same graph.\n */\n vaultCoreVersion: number;\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n // Keep the facade's graph-version and input checks. Do not use its scripts\n // or control block as signing data.\n await getPrePeginHtlcConnectorInfo({\n txGraphVersion: params.vaultCoreVersion,\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n const expectedHtlc = deriveExpectedPrePeginHtlc(params, params.hashlock);\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n if (!expectedHtlc.scriptPubKey.equals(htlcOutput.script)) {\n throw new Error(\n \"PegIn HTLC taptree mismatch: the independent 2-leaf tree does not \" +\n \"reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.\",\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending. bitcoinjs\n // re-verifies leaf-in-tree consistency (control block vs tapMerkleRoot)\n // inside addInput — a second independent check.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: expectedHtlc.hashlockScript,\n controlBlock: expectedHtlc.hashlockControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(hexToUint8Array(depositorPubkey));\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // A wallet that ignores `autoFinalized: false` returns already-finalized\n // inputs (OKX's single-PSBT endpoint does; the wallet-connector routes OKX\n // around it). finalizeAllInputs() throws in that case, so fall back to\n // verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n","/**\n * Consensus witness-stack decoding, shared by every module that reads a\n * witness we did not build.\n *\n * Two independent decoders drifted apart before this existed: one accepted\n * non-minimal CompactSize encodings, the other rejected them. vaultd decodes\n * with rust-bitcoin, whose `VarInt::consensus_decode`\n * (0.32.8 `consensus/encode.rs:493-522`) returns `NonMinimalVarInt` for a 0xfd\n * carrying < 0xfd and a 0xfe carrying < 0x10000 — so the strict reading is the\n * only one that matches what the network will accept.\n *\n * @module tbv/core/utils/witness/witnessStack\n */\n\n/** CompactSize discriminators; 0xff (u64) is out of range for a witness. */\nconst COMPACT_SIZE_UINT16_PREFIX = 0xfd;\nconst COMPACT_SIZE_UINT32_PREFIX = 0xfe;\nconst COMPACT_SIZE_UINT16_BYTES = 3;\nconst COMPACT_SIZE_UINT32_BYTES = 5;\nconst COMPACT_SIZE_UINT16_MIN_VALUE = 0xfd;\nconst COMPACT_SIZE_UINT32_MIN_VALUE = 0x10000;\n\n/**\n * Decode a consensus-encoded witness stack: item count, then (len, bytes)*.\n *\n * @param witness - The consensus-encoded witness bytes.\n * @param subject - Names the witness in error messages (e.g. \"finalScriptWitness\").\n * @returns The stack items, as views over `witness`.\n * @throws If the encoding is truncated, non-minimal, out of range, or leaves\n * trailing bytes.\n */\nexport function decodeWitnessStack(\n witness: Uint8Array,\n subject: string,\n): Uint8Array[] {\n let offset = 0;\n\n const readCompactSize = (): number => {\n if (offset >= witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const first = witness[offset];\n if (first < COMPACT_SIZE_UINT16_PREFIX) {\n offset += 1;\n return first;\n }\n if (first === COMPACT_SIZE_UINT16_PREFIX) {\n if (offset + COMPACT_SIZE_UINT16_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value = witness[offset + 1] | (witness[offset + 2] << 8);\n if (value < COMPACT_SIZE_UINT16_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT16_BYTES;\n return value;\n }\n if (first === COMPACT_SIZE_UINT32_PREFIX) {\n if (offset + COMPACT_SIZE_UINT32_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value =\n (witness[offset + 1] |\n (witness[offset + 2] << 8) |\n (witness[offset + 3] << 16) |\n (witness[offset + 4] << 24)) >>>\n 0;\n if (value < COMPACT_SIZE_UINT32_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT32_BYTES;\n return value;\n }\n throw new Error(`${subject} carries an out-of-range item length`);\n };\n\n const count = readCompactSize();\n const items: Uint8Array[] = [];\n for (let i = 0; i < count; i++) {\n const len = readCompactSize();\n if (offset + len > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n items.push(witness.subarray(offset, offset + len));\n offset += len;\n }\n if (offset !== witness.length) {\n throw new Error(`${subject} has trailing bytes`);\n }\n return items;\n}\n","/**\n * Far-side verification of P2WPKH ECDSA signatures a wallet returned, over\n * the PSBT we requested (trusted prevouts) — the Native SegWit sibling of\n * `verifyKeyPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs:945-1000\n * verify_finalized_p2wpkh_spend`. The wallet's success/finalization is\n * never trusted on its own (CLAUDE.md §8): prevout script and value come\n * from the PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport {\n crypto as bcrypto,\n script as bscript,\n payments,\n Psbt,\n Transaction,\n} from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\n\n// P2WPKH scriptPubKey is exactly `OP_0 OP_PUSHBYTES_20 <20-byte key hash>`\n// (BIP-141 witness program v0, 20 bytes).\nconst P2WPKH_SCRIPT_LEN = 22;\nconst OP_0 = 0x00;\nconst OP_PUSHBYTES_20 = 0x14;\nconst P2WPKH_PROGRAM_START = 2;\n\n/** SEC1 compressed pubkey (client.rs:959: \"expected a 33-byte compressed key\"). */\nconst COMPRESSED_PUBKEY_BYTES = 33;\n/** Consensus P2WPKH witness: exactly [signature, pubkey] (client.rs:951-957). */\nconst P2WPKH_WITNESS_ITEMS = 2;\n\n/** Only claim P2WPKH: 22-byte scriptPubKey starting `OP_0 PUSH20`. */\nexport function isP2wpkhScript(\n script: Uint8Array | undefined,\n): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2WPKH_SCRIPT_LEN &&\n script[0] === OP_0 &&\n script[1] === OP_PUSHBYTES_20\n );\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\n/** The `[signature, pubkey]` pair of a finalized P2WPKH witness (client.rs:951-957). */\nfunction decodeP2wpkhWitness(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; pubkey: Uint8Array } {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== P2WPKH_WITNESS_ITEMS) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized P2WPKH witness must have ` +\n `exactly 2 items [signature, pubkey], got ${items.length}.`,\n );\n }\n return { signature: items[0], pubkey: items[1] };\n}\n\nexport interface AssertReturnedP2wpkhSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout script/value). NOT the wallet's. */\n requestedPsbtHex: string;\n /** The wallet-returned PSBT input carrying the signature material. */\n returnedInput: {\n partialSig?: Array<{ pubkey: Uint8Array; signature: Uint8Array }>;\n finalScriptWitness?: Uint8Array;\n };\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that the returned input carries a valid P2WPKH ECDSA signature\n * over the BIP-143 sighash of `requestedPsbtHex` input `inputIndex`:\n * `partialSig` (BIP-174: the value is the exact witness-stack signature\n * bytes, the key its pubkey), or the finalized 2-item witness — and when\n * both are present they must be the same bytes.\n *\n * @throws If the requested input is not a P2WPKH spend, no signature was\n * returned, a finalized witness disagrees with its `partialSig`,\n * or any check of `verify_finalized_p2wpkh_spend` fails.\n */\nexport function assertReturnedP2wpkhSignature(\n params: AssertReturnedP2wpkhSignatureParams,\n): void {\n const { requestedPsbtHex, returnedInput, inputIndex } = params;\n\n const partials = returnedInput.partialSig;\n // Consensus allows exactly one signature in a P2WPKH witness, so a second\n // partialSig entry is ambiguous tampering, not a fallback to pick from.\n if (partials !== undefined && partials.length > 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a P2WPKH input must carry at most one ` +\n `partial signature, got ${partials.length}.`,\n );\n }\n const partial = partials?.[0];\n const witness = returnedInput.finalScriptWitness\n ? decodeP2wpkhWitness(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify (same\n // rationale as the tapKeySig/witness agreement check).\n if (\n partial &&\n witness &&\n (!bytesEqual(partial.signature, witness.signature) ||\n !bytesEqual(partial.pubkey, witness.pubkey))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its partialSig.`,\n );\n }\n\n const material = partial ?? witness;\n if (!material) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no P2WPKH signature ` +\n `(no partialSig, not finalized).`,\n );\n }\n\n assertP2wpkhEcdsaSignature(\n requestedPsbtHex,\n material.signature,\n material.pubkey,\n inputIndex,\n );\n}\n\n/**\n * The crypto core, mirroring `verify_finalized_p2wpkh_spend` check by\n * check: pubkey shape and curve membership, hash160(pubkey) == witness\n * program, strict-DER + SIGHASH_ALL-only signature, ECDSA over the\n * BIP-143 sighash recomputed from the REQUESTED prevout.\n */\nfunction assertP2wpkhEcdsaSignature(\n requestedPsbtHex: string,\n encodedSignature: Uint8Array,\n pubkey: Uint8Array,\n inputIndex: number,\n): void {\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n const prevout = psbt.data.inputs[inputIndex].witnessUtxo;\n if (!prevout || !isP2wpkhScript(prevout.script)) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a P2WPKH input.`,\n );\n }\n\n // Pubkey: exactly 33 bytes (client.rs:959-965) and a parseable curve\n // point, as PublicKey::from_slice (client.rs:966-968).\n if (pubkey.length !== COMPRESSED_PUBKEY_BYTES) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey must be 33 bytes, ` +\n `got ${pubkey.length}.`,\n );\n }\n if (!ecc.isPointCompressed(pubkey)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey is not a valid secp256k1 point.`,\n );\n }\n\n // hash160(pubkey) must equal the prevout's witness program — what\n // consensus checks (client.rs:970-977).\n const program = prevout.script.subarray(\n P2WPKH_PROGRAM_START,\n P2WPKH_SCRIPT_LEN,\n );\n if (!bytesEqual(bcrypto.hash160(Buffer.from(pubkey)), program)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey does not hash to the ` +\n `prevout's witness program.`,\n );\n }\n\n // Strict-DER decode with defined-hashtype gate — the accept set of\n // ecdsa::Signature::from_slice / EcdsaSighashType::from_standard\n // (client.rs:978-980) — then SIGHASH_ALL exactly (client.rs:981-987).\n let decoded: { signature: Buffer; hashType: number };\n try {\n decoded = bscript.signature.decode(Buffer.from(encodedSignature));\n } catch (e) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not DER with a ` +\n `defined sighash byte: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that libsecp's strict consensus\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(decoded.signature, decoded.hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not canonical DER.`,\n );\n }\n if (decoded.hashType !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature has sighash type ` +\n `0x${decoded.hashType.toString(16)} (expected SIGHASH_ALL).`,\n );\n }\n\n // BIP-143 sighash over the REQUESTED prevout value with the standard\n // P2WPKH scriptCode built from the witness program (client.rs:988-991;\n // scriptCode template per bitcoinjs-lib's own P2WPKH signer,\n // `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: Buffer.from(program) }).output;\n if (!scriptCode) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: could not build the P2WPKH scriptCode.`,\n );\n }\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV0(\n inputIndex,\n scriptCode,\n prevout.value,\n decoded.hashType,\n );\n\n // strict=true rejects high-S, as libsecp256k1's verify_ecdsa does\n // (client.rs:992-999; secp256k1 crate `ecdsa/mod.rs:194`). ecc.verify\n // throws on out-of-range r/s — that is a failed verification here.\n let verifies = false;\n try {\n verifies = ecc.verify(sighash, pubkey, decoded.signature, true);\n } catch {\n verifies = false;\n }\n if (!verifies) {\n throw new Error(\n `P2WPKH signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout. The wallet may have signed a different ` +\n `transaction or key.`,\n );\n }\n}\n","/**\n * Far-side verification of Taproot KEY-PATH Schnorr signatures a wallet\n * returned, over the PSBT we requested (trusted prevouts) — the key-path twin\n * of `assertScriptPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs check_signatures_valid` (output key taken\n * from the prevout scriptPubKey, all prevouts committed). The wallet's\n * success/finalization is never trusted on its own (CLAUDE.md §8).\n * `assertReturnedKeyPathSignatures` additionally dispatches P2WPKH-funded\n * inputs to `verifyP2wpkhEcdsaSignature` (client.rs's\n * `verify_finalized_p2wpkh_spend` sibling), so a Native SegWit software\n * wallet's signatures no longer pass through unchecked.\n *\n * Why verify against the *requested* PSBT: `assertPsbtUnsignedTxMatches` pins\n * the unsigned transaction but deliberately skips per-input metadata, so a\n * wallet could rewrite `witnessUtxo` in its response and make a wrong-message\n * signature self-validate. Prevout scripts and values therefore come from the\n * PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\nimport { hexToUint8Array, stripHexPrefix } from \"../utils/bitcoin\";\nimport {\n assertReturnedP2wpkhSignature,\n isP2wpkhScript,\n} from \"./verifyP2wpkhEcdsaSignature\";\n\nconst SCHNORR_SIG_BYTES = 64;\nconst SIGHASH_DEFAULT = Transaction.SIGHASH_DEFAULT; // 0x00\nconst SIGHASH_ALL = Transaction.SIGHASH_ALL; // 0x01\n\n// P2TR scriptPubKey is exactly `OP_1 OP_PUSHBYTES_32 <32-byte output key>`.\nconst P2TR_SCRIPT_LEN = 34;\nconst OP_1 = 0x51;\nconst OP_PUSHBYTES_32 = 0x20;\nconst P2TR_OUTPUT_KEY_OFFSET = 2;\n\nfunction isP2trScript(script: Uint8Array | undefined): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2TR_SCRIPT_LEN &&\n script[0] === OP_1 &&\n script[1] === OP_PUSHBYTES_32\n );\n}\n\n/** BIP-341: 64 bytes ⇒ SIGHASH_DEFAULT; 65 bytes ⇒ the trailing byte is the hash type (we accept ALL only). */\nfunction splitHashType(\n sig: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; hashType: number } {\n if (sig.length === SCHNORR_SIG_BYTES) {\n return { signature: sig, hashType: SIGHASH_DEFAULT };\n }\n if (\n sig.length === SCHNORR_SIG_BYTES + 1 &&\n sig[SCHNORR_SIG_BYTES] === SIGHASH_ALL\n ) {\n return {\n signature: sig.subarray(0, SCHNORR_SIG_BYTES),\n hashType: SIGHASH_ALL,\n };\n }\n throw new Error(\n `Key-path signature for input ${inputIndex} must be 64 bytes (SIGHASH_DEFAULT) or ` +\n `65 bytes ending in 0x01 (SIGHASH_ALL), got ${sig.length}.`,\n );\n}\n\nexport interface AssertKeyPathSchnorrSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout scripts/values). NOT the wallet's. */\n requestedPsbtHex: string;\n /** 64- or 65-byte signature, hex. */\n signatureHex: string;\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that `signatureHex` is a valid BIP-340 Schnorr signature over the\n * Taproot key-path sighash of `requestedPsbtHex` input `inputIndex`, under the\n * tweaked output key taken from that input's prevout scriptPubKey.\n *\n * @throws If the input is not a key-path P2TR spend, the requested PSBT lacks\n * the prevout data needed to recompute the sighash, or the signature\n * does not verify.\n */\nexport function assertKeyPathSchnorrSignature(\n params: AssertKeyPathSchnorrSignatureParams,\n): void {\n const { requestedPsbtHex, signatureHex, inputIndex } = params;\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n\n if (!isKeyPathEligible(psbt.data.inputs[inputIndex])) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a key-path P2TR input.`,\n );\n }\n\n // Taproot's sighash commits to every input's prevout (script + value), so all\n // inputs must carry a witnessUtxo. A missing one is a build error, not a\n // value we can default — fail loudly.\n const prevOutScripts: Buffer[] = [];\n const values: number[] = [];\n for (let i = 0; i < psbt.data.inputs.length; i++) {\n const prevout = psbt.data.inputs[i].witnessUtxo;\n if (!prevout) {\n throw new Error(\n `Cannot verify signature: input ${i} of the requested PSBT has no witnessUtxo ` +\n `(required to recompute the Taproot sighash).`,\n );\n }\n prevOutScripts.push(prevout.script);\n values.push(prevout.value);\n }\n\n const { signature, hashType } = splitHashType(\n hexToUint8Array(stripHexPrefix(signatureHex)),\n inputIndex,\n );\n\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV1(\n inputIndex,\n prevOutScripts,\n values,\n hashType,\n );\n\n // Key-path signatures verify against the TWEAKED output key = the prevout's\n // witness program.\n const outputKey = prevOutScripts[inputIndex].subarray(P2TR_OUTPUT_KEY_OFFSET);\n\n if (!ecc.verifySchnorr(sighash, outputKey, signature)) {\n throw new Error(\n `Key-path Schnorr signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout (output key ${Buffer.from(outputKey).toString(\"hex\")}). ` +\n `The wallet may have signed a different transaction or key.`,\n );\n }\n}\n\n/**\n * A key-path P2TR input: an internal key, no script-path material, and a\n * taproot prevout. Script-path inputs are the script-path verifier's job.\n */\nfunction isKeyPathEligible(input: {\n tapInternalKey?: Uint8Array;\n tapLeafScript?: unknown;\n tapMerkleRoot?: Uint8Array;\n witnessUtxo?: { script: Uint8Array };\n}): boolean {\n return (\n input.tapInternalKey !== undefined &&\n input.tapLeafScript === undefined &&\n input.tapMerkleRoot === undefined &&\n isP2trScript(input.witnessUtxo?.script)\n );\n}\n\n/**\n * The lone stack item of a finalized key-path witness. An annex would add a\n * second item, but Bitcoin Core rejects annexes as nonstandard\n * (`src/policy/policy.cpp:327-329`), so such a spend could never broadcast.\n */\nfunction singleWitnessItem(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): Uint8Array {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized key-path witness must have ` +\n `exactly one item, got ${items.length}.`,\n );\n }\n return items[0];\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\nexport interface AssertReturnedKeyPathSignaturesParams {\n /** PSBT we built locally and asked the wallet to sign. */\n requestedPsbtHex: string;\n /** PSBT the wallet returned after signing. */\n returnedPsbtHex: string;\n}\n\n/**\n * Verify every key-path-eligible and P2WPKH input of the REQUESTED PSBT\n * against what the wallet RETURNED. Key-path: `tapKeySig`, or the single\n * finalized witness item for wallets that auto-finalize — and when both are\n * present they must be the same bytes. P2WPKH: `partialSig`, or the finalized\n * 2-item witness, verified as ECDSA over the BIP-143 sighash\n * ({@link assertReturnedP2wpkhSignature}); a failure throws but the input is\n * NOT counted. Any other input type (script-path, P2WSH, ...) throws — no\n * verifier here covers it, so it cannot be treated as verified.\n *\n * @returns How many inputs were verified KEY-PATH. A caller that knows every\n * input is taproot key-path (e.g. an approval wallet) must assert\n * this equals its input count — P2WPKH inputs never count toward it,\n * so that gate stays exact.\n * @throws If the input counts differ, an input is neither key-path P2TR nor\n * P2WPKH, an eligible input carries no signature, a finalized witness\n * disagrees with its `tapKeySig`/`partialSig`, or any signature does\n * not verify.\n */\nexport function assertReturnedKeyPathSignatures(\n params: AssertReturnedKeyPathSignaturesParams,\n): number {\n const { requestedPsbtHex, returnedPsbtHex } = params;\n\n const requested = Psbt.fromHex(requestedPsbtHex);\n const returned = Psbt.fromHex(returnedPsbtHex);\n\n if (returned.data.inputs.length !== requested.data.inputs.length) {\n throw new Error(\n `Returned PSBT input count ${returned.data.inputs.length} differs from the ` +\n `requested ${requested.data.inputs.length}.`,\n );\n }\n\n let verified = 0;\n requested.data.inputs.forEach((input, inputIndex) => {\n const returnedInput = returned.data.inputs[inputIndex];\n\n if (!isKeyPathEligible(input)) {\n // Native SegWit funding inputs get the ECDSA check.\n if (isP2wpkhScript(input.witnessUtxo?.script)) {\n assertReturnedP2wpkhSignature({\n requestedPsbtHex,\n returnedInput,\n inputIndex,\n });\n return;\n }\n // No verifier exists for any other type — fail closed like btc-vault's\n // check_signatures_valid rather than silently reporting it checked.\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is neither key-path P2TR ` +\n `nor P2WPKH; refusing to treat it as verified.`,\n );\n }\n verified++;\n\n const tapKeySig = returnedInput.tapKeySig;\n const witnessSig = returnedInput.finalScriptWitness\n ? singleWitnessItem(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify. Matches\n // btc-vault `crates/btc-wallet-remote/src/client.rs:1053-1072,1102-1121`,\n // which checks each independently.\n if (tapKeySig && witnessSig && !bytesEqual(tapKeySig, witnessSig)) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its tapKeySig.`,\n );\n }\n\n const sig = tapKeySig ?? witnessSig;\n if (!sig) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no key-path signature ` +\n `(no tapKeySig, not finalized).`,\n );\n }\n\n assertKeyPathSchnorrSignature({\n requestedPsbtHex,\n signatureHex: Buffer.from(sig).toString(\"hex\"),\n inputIndex,\n });\n });\n\n return verified;\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","getPrePeginHtlcConnectorInfo","expectedHtlc","deriveExpectedPrePeginHtlc","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","hexToUint8Array","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","COMPACT_SIZE_UINT16_PREFIX","COMPACT_SIZE_UINT32_PREFIX","COMPACT_SIZE_UINT16_BYTES","COMPACT_SIZE_UINT32_BYTES","COMPACT_SIZE_UINT16_MIN_VALUE","COMPACT_SIZE_UINT32_MIN_VALUE","decodeWitnessStack","witness","subject","offset","readCompactSize","first","value","count","items","i","len","P2WPKH_SCRIPT_LEN","OP_0","OP_PUSHBYTES_20","P2WPKH_PROGRAM_START","COMPRESSED_PUBKEY_BYTES","P2WPKH_WITNESS_ITEMS","isP2wpkhScript","script","bytesEqual","a","b","byte","decodeP2wpkhWitness","finalScriptWitness","inputIndex","assertReturnedP2wpkhSignature","requestedPsbtHex","returnedInput","partials","partial","material","assertP2wpkhEcdsaSignature","encodedSignature","pubkey","prevout","ecc","program","bcrypto","decoded","bscript","scriptCode","payments","sighash","verifies","SCHNORR_SIG_BYTES","SIGHASH_DEFAULT","SIGHASH_ALL","P2TR_SCRIPT_LEN","OP_1","OP_PUSHBYTES_32","P2TR_OUTPUT_KEY_OFFSET","isP2trScript","splitHashType","assertKeyPathSchnorrSignature","signatureHex","isKeyPathEligible","prevOutScripts","values","signature","hashType","outputKey","_a","singleWitnessItem","assertReturnedKeyPathSignatures","returnedPsbtHex","requested","returned","verified","tapKeySig","witnessSig"],"mappings":"khBA4FA,eAAsBA,EACpBC,EACoC,CACpC,MAAMC,EAAaC,EAAAA,eAAeF,EAAO,UAAU,EAC7CG,EAAsBD,EAAAA,eAAeF,EAAO,mBAAmB,EAIrE,MAAMI,+BAA6B,CACjC,eAAg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AYzC,EAAc,UAC1B0C,EAAa1C,EAAc,mBAC7BmC,GAAkBnC,EAAc,mBAAoBH,CAAU,EAC9D,OAMJ,GAAI4C,GAAaC,GAAc,CAACnD,GAAWkD,EAAWC,CAAU,EAC9D,MAAM,IAAI,MACR,uBAAuB7C,CAAU,kDAAA,EAIrC,MAAMhC,EAAM4E,GAAaC,EACzB,GAAI,CAAC7E,EACH,MAAM,IAAI,MACR,uBAAuBgC,CAAU,+DAAA,EAKrC6B,EAA8B,CAC5B,iBAAA3B,EACA,aAAchD,EAAAA,OAAO,KAAKc,CAAG,EAAE,SAAS,KAAK,EAC7C,WAAAgC,CAAA,CACD,CACH,CAAC,EAEM2C,CACT"}
@@ -0,0 +1,2 @@
1
+ "use strict";const P=require("bitcoinjs-lib"),w=require("./tbv/core/wasm/index.cjs"),k=require("./fundPeginTransaction-54-Rwb2k.cjs"),c=require("./bitcoin-D-O2GjbC.cjs"),Pe=require("./secp256k1-DDHQ1_za.cjs"),l=require("buffer"),p=require("./constants-BCg6O0PX.cjs"),pe=require("@bitcoin-js/tiny-secp256k1-asmjs"),U=require("./validation-C6XTfZak.cjs");function he(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const ee=he(pe);function m(e){return c.processPublicKeyToXOnly(e).toLowerCase()}function fe(e,t,r){const o=new Set;o.add(m(e));for(const n of t)o.add(m(n));return o.delete(m(r)),o.size}function te(e){const t=m(e.claimerBtcPubkey),r=m(e.depositorBtcPubkey),o=e.vaultKeeperBtcPubkeys.map(m);if(t===r){const s=o.filter(u=>u!==r);if(s.length===0)throw new Error("Cannot derive localChallengers: vault keeper set is empty (or contains only the depositor)");if(new Set(s).size!==s.length)throw new Error("Cannot derive localChallengers: duplicate vaultKeeper key — signing context is misconfigured");return s}const i=[...new Set([m(e.vaultProviderBtcPubkey),...o])].sort().filter(s=>s!==t);if(i.length===0)throw new Error(`Cannot derive localChallengers: no vault provider or vault keeper remains after excluding claimer ${t}`);return i}const de=32,ge=65535,Ee=2;function I(e,t){const r=c.stripHexPrefix(e).toLowerCase();if(!/^[0-9a-f]{64}$/.test(r))throw new Error(`${t} must be a 32-byte x-only public key.`);try{Pe.secp256k1.Point.fromBytes(l.Buffer.concat([l.Buffer.from([Ee]),l.Buffer.from(r,"hex")]))}catch{throw new Error(`${t} is not a secp256k1 x-coordinate.`)}return r}function O(e,t){if(e.length===0)throw new Error(`${t} must not be empty.`);const r=e.map((o,n)=>I(o,`${t}[${n}]`)).sort();if(new Set(r).size!==r.length)throw new Error(`${t} must not contain duplicate keys.`);return r}function R(e,t){const r=[];return e.forEach((o,n)=>{r.push(l.Buffer.from(o,"hex"),n===0?P.opcodes.OP_CHECKSIG:P.opcodes.OP_CHECKSIGADD)}),r.push(P.script.number.encode(e.length),t?P.opcodes.OP_NUMEQUALVERIFY:P.opcodes.OP_NUMEQUAL),r}function re(e,t){var y;c.assertEccInitialized();const r=I(e.depositorPubkey,"depositorPubkey"),o=I(e.vaultProviderPubkey,"vaultProviderPubkey"),n=O(e.vaultKeeperPubkeys,"vaultKeeperPubkeys"),i=O(e.universalChallengerPubkeys,"universalChallengerPubkeys"),s=c.stripHexPrefix(t).toLowerCase();if(!/^[0-9a-f]{64}$/.test(s))throw new Error("hashlock must be 32 bytes.");if(!Number.isInteger(e.timelockRefund)||e.timelockRefund<1||e.timelockRefund>ge)throw new Error("timelockRefund must be an integer from 1 to 65535.");const u=P.script.compile([P.opcodes.OP_SIZE,P.script.number.encode(de),P.opcodes.OP_EQUALVERIFY,P.opcodes.OP_SHA256,l.Buffer.from(s,"hex"),P.opcodes.OP_EQUALVERIFY,l.Buffer.from(r,"hex"),P.opcodes.OP_CHECKSIGVERIFY,l.Buffer.from(o,"hex"),P.opcodes.OP_CHECKSIGVERIFY,...R(n,!0),...R(i,!1)]),a=P.script.compile([l.Buffer.from(r,"hex"),P.opcodes.OP_CHECKSIGVERIFY,P.script.number.encode(e.timelockRefund),P.opcodes.OP_CHECKSEQUENCEVERIFY]),g=[{output:u,version:c.TAPSCRIPT_LEAF_VERSION},{output:a,version:c.TAPSCRIPT_LEAF_VERSION}],{hash:h,output:f,witness:d}=P.payments.p2tr({internalPubkey:l.Buffer.from(w.tapInternalPubkey),scriptTree:g,redeem:{output:u,redeemVersion:c.TAPSCRIPT_LEAF_VERSION}}),E=d==null?void 0:d[d.length-1],v=P.payments.p2tr({internalPubkey:l.Buffer.from(w.tapInternalPubkey),scriptTree:g,redeem:{output:a,redeemVersion:c.TAPSCRIPT_LEAF_VERSION}}),S=(y=v.witness)==null?void 0:y[v.witness.length-1];if(!h||!f||!E||!S)throw new Error("Failed to derive the expected Pre-PegIn HTLC output.");return{hashlockScript:u,hashlockControlBlock:E,refundScript:a,refundControlBlock:S,scriptPubKey:f,tapMerkleRoot:h}}function ye(e,t){c.assertEccInitialized();const r=I(e.depositorPubkey,"depositorPubkey"),o=I(e.vaultProviderPubkey,"vaultProviderPubkey"),n=O(e.vaultKeeperPubkeys,"vaultKeeperPubkeys"),i=O(e.universalChallengerPubkeys,"universalChallengerPubkeys"),s=P.script.compile([l.Buffer.from(r,"hex"),P.opcodes.OP_CHECKSIGVERIFY,l.Buffer.from(o,"hex"),P.opcodes.OP_CHECKSIGVERIFY,...R(n,!0),...R(i,!0),P.script.number.encode(t),P.opcodes.OP_CHECKSEQUENCEVERIFY]),{output:u}=P.payments.p2tr({internalPubkey:l.Buffer.from(w.tapInternalPubkey),scriptTree:{output:s,version:c.TAPSCRIPT_LEAF_VERSION}});if(!u)throw new Error("Failed to derive the expected PegIn payout output.");return u}async function we(e,t){const r=t.pegInAmounts.length;if(t.hashlocks.length!==r)throw new Error(`Pre-PegIn has ${t.hashlocks.length} hashlock(s), expected ${r} (one per requested deposit).`);if(e.htlcValues.length!==r)throw new Error(`WASM Pre-PegIn returned ${e.htlcValues.length} HTLC value(s), expected ${r} (one per requested deposit).`);if(e.peginAmounts.length!==r||e.htlcScriptPubKeys.length!==r||e.htlcAddresses.length!==r)throw new Error(`WASM Pre-PegIn returned mismatched array lengths (htlcValues=${e.htlcValues.length}, peginAmounts=${e.peginAmounts.length}, htlcScriptPubKeys=${e.htlcScriptPubKeys.length}, htlcAddresses=${e.htlcAddresses.length}); expected ${r} each.`);if(e.depositorClaimValue<=0n)throw new Error(`WASM Pre-PegIn returned non-positive depositorClaimValue ${e.depositorClaimValue}; expected > 0.`);const o=await w.computeMinClaimValue(t.vaultCoreVersion,t.numLocalChallengers,t.universalChallengerPubkeys.length,t.councilQuorum,t.councilSize,t.feeRate);if(e.depositorClaimValue!==o)throw new Error(`WASM Pre-PegIn depositorClaimValue ${e.depositorClaimValue} does not match the independently computed minimum claim value ${o} (vaultCoreVersion=${t.vaultCoreVersion}, numLocalChallengers=${t.numLocalChallengers}, numUniversalChallengers=${t.universalChallengerPubkeys.length}, councilQuorum=${t.councilQuorum}, councilSize=${t.councilSize}, feeRate=${t.feeRate}).`);const{value:n}=await w.peginP2aAnchorOutput(t.vaultCoreVersion),i=await w.computeMinPeginFee(t.vaultCoreVersion,t.vaultKeeperPubkeys.length,t.universalChallengerPubkeys.length,t.minPeginFeeRate),s=i+n,u=t.minPeginFeeRate*k.MAX_REASONABLE_PEGIN_VBYTES;for(let a=0;a<r;a++){const g=t.pegInAmounts[a],h=e.peginAmounts[a],f=e.htlcValues[a];if(h!==g)throw new Error(`WASM Pre-PegIn peginAmount[${a}] ${h} does not match the requested amount ${g}; refusing to build a tx whose recorded amount differs from the depositor's request.`);if(h<=0n)throw new Error(`WASM Pre-PegIn peginAmount[${a}] is non-positive (${h}); expected > 0.`);if(f<=0n)throw new Error(`WASM Pre-PegIn htlcValue[${a}] is non-positive (${f}); expected > 0.`);const d=f-h-e.depositorClaimValue;if(d<=0n)throw new Error(`WASM Pre-PegIn htlcValue[${a}] ${f} does not strictly cover peginAmount ${h} + depositorClaimValue ${e.depositorClaimValue} + a PegIn reserve (implied reserve ${d}).`);if(d>u)throw new Error(`WASM Pre-PegIn implied reserve for HTLC[${a}] (${d} sat) exceeds the plausibility cap ${u} sat (minPeginFeeRate=${t.minPeginFeeRate} × ${k.MAX_REASONABLE_PEGIN_VBYTES} vbytes); htlcValue ${f} appears grossly inflated.`);if(d!==s)throw new Error(`WASM Pre-PegIn htlcValue[${a}] ${f} implies a PegIn fee+anchor reserve of ${d} sat, expected exactly ${s} sat (minPeginFee ${i} + p2aAnchor ${n} for vaultCoreVersion ${t.vaultCoreVersion}, vaultKeepers=${t.vaultKeeperPubkeys.length}, universalChallengers=${t.universalChallengerPubkeys.length}, minPeginFeeRate=${t.minPeginFeeRate}).`)}return i}class C extends Error{constructor(t){super(t),this.name="HtlcOutputMismatchError"}}function oe(e,t,r){if(e.length<t.length)throw new C(`Encoded Pre-PegIn tx has ${e.length} output(s), fewer than the ${t.length} HTLC output(s) the cross-check validated.`);for(let o=0;o<t.length;o++){const n=BigInt(e[o].value);if(n!==t[o])throw new C(`Encoded Pre-PegIn HTLC output[${o}] value ${n} does not match the cross-checked htlcValue ${t[o]}; the funded/signed tx would not pay the validated amount.`);const i=e[o].script.toString("hex").toLowerCase(),s=r[o].toLowerCase();if(i!==s)throw new C(`Encoded Pre-PegIn HTLC output[${o}] scriptPubKey ${i} does not match the cross-checked htlcScriptPubKey ${s}.`)}}function Se(e,t,r,o,n,i,s){if(i!==p.PRE_PEGIN_TX_VERSION)throw new Error(`WASM Pre-PegIn transaction version ${i}; expected ${p.PRE_PEGIN_TX_VERSION}.`);if(s!==p.PRE_PEGIN_TX_LOCKTIME)throw new Error(`WASM Pre-PegIn transaction locktime ${s}; expected ${p.PRE_PEGIN_TX_LOCKTIME}.`);if(t.length<p.PRE_PEGIN_MIN_HTLC_OUTPUT_COUNT)throw new Error(`WASM Pre-PegIn output layout has ${t.length} HTLC output(s); expected at least ${p.PRE_PEGIN_MIN_HTLC_OUTPUT_COUNT}.`);const u=t.length,a=u+ +(n!==void 0),g=k.peginOutputCount(t.length,n!==void 0);if(e.length!==g)throw new Error(`WASM Pre-PegIn output layout has ${e.length} output(s); expected exactly ${g}.`);oe(e,t,r);for(let E=0;E<t.length;E++){const v=re(o,o.hashlocks[E]).scriptPubKey;if(!e[E].script.equals(v))throw new C(`Pre-PegIn HTLC output[${E}] does not match the independently derived scriptPubKey.`)}if(n!==void 0){const E=e[u];if(E.value!==p.PRE_PEGIN_AUTH_OUTPUT_VALUE_SATS)throw new Error(`WASM Pre-PegIn auth output[${u}] value ${E.value} sat; expected exactly ${p.PRE_PEGIN_AUTH_OUTPUT_VALUE_SATS} sat.`);const v=E.script.toString("hex").toLowerCase(),S=p.PRE_PEGIN_AUTH_SCRIPT_PREFIX+n.toLowerCase();if(v!==S)throw new Error(`WASM Pre-PegIn auth output[${u}] scriptPubKey ${v}; expected ${S}.`)}const h=e[a];if(h.value!==p.PRE_PEGIN_CPFP_VALUE_SATS)throw new Error(`WASM Pre-PegIn CPFP output[${a}] value ${h.value} sat; expected exactly ${p.PRE_PEGIN_CPFP_VALUE_SATS} sat.`);const f=h.script.toString("hex").toLowerCase(),d=c.stripHexPrefix(c.deriveBip86ScriptPubKeyHex(o.depositorPubkey)).toLowerCase();if(f!==d)throw new Error(`WASM Pre-PegIn CPFP output[${a}] scriptPubKey ${f}; expected depositor BIP-86 script ${d}.`)}const ne=1;function ie(e){const t=c.stripHexPrefix(e);if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error("Invalid depositor pubkey for the depositor-claim script: must be an x-only key of 64 hex characters (32 bytes).");const r=P.script.compile([l.Buffer.from(c.hexToUint8Array(t)),P.opcodes.OP_CHECKSIG]),o=l.Buffer.from(w.tapInternalPubkey),n={output:r,redeemVersion:c.TAPSCRIPT_LEAF_VERSION},{output:i,witness:s}=P.payments.p2tr({internalPubkey:o,scriptTree:{output:r},redeem:n});if(!i)throw new Error("Failed to derive the depositor-claim P2TR scriptPubKey for PegIn output validation");const u=s==null?void 0:s[s.length-1];if(!u)throw new Error("Failed to derive the depositor-claim tapleaf control block; refusing to build an unspendable input");return{scriptPubKey:i,leafScript:r,controlBlock:u,internalKey:o}}function se(e){return ie(e).scriptPubKey}const K=64,ve=/^[0-9a-fA-F]+$/,M=65535;async function xe(e){const t=N(e.authAnchorHash),r=await w.createPrePeginTransaction({txGraphVersion:e.vaultCoreVersion,depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlocks:[...e.hashlocks],timelockRefund:e.timelockRefund,pegInAmounts:[...e.pegInAmounts],feeRate:e.feeRate,minPeginFeeRate:e.minPeginFeeRate,numLocalChallengers:e.numLocalChallengers,councilQuorum:e.councilQuorum,councilSize:e.councilSize,network:e.network,authAnchorHash:t}),o=await we(r,e),n=k.parseUnfundedWasmTransaction(r.txHex);Se(n.outputs,r.htlcValues,r.htlcScriptPubKeys,e,t,n.version,n.locktime);const i=n.outputs.reduce((u,a)=>u+BigInt(a.value),0n),s=t!==void 0?r.htlcValues.length:null;return{psbtHex:r.txHex,totalOutputValue:i,htlcValues:r.htlcValues,htlcScriptPubKeys:r.htlcScriptPubKeys,htlcAddresses:r.htlcAddresses,peginAmounts:r.peginAmounts,depositorClaimValue:r.depositorClaimValue,authAnchorVout:s,minPeginFee:o}}function N(e){if(e===void 0)return;const t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length!==K||!ve.test(t))throw new Error(`authAnchorHash must be 32-byte hex (${K} chars, no 0x prefix); got length ${t.length}`);return t.toLowerCase()}async function _e(e){if(!Number.isInteger(e.timelockPegin)||e.timelockPegin<1||e.timelockPegin>M)throw new Error(`PegIn timelock ${e.timelockPegin} must be a whole number of blocks from 1 to ${M}.`);const t=await w.buildPeginTxFromPrePegin({txGraphVersion:e.prePeginParams.vaultCoreVersion,depositorPubkey:e.prePeginParams.depositorPubkey,vaultProviderPubkey:e.prePeginParams.vaultProviderPubkey,vaultKeeperPubkeys:e.prePeginParams.vaultKeeperPubkeys,universalChallengerPubkeys:e.prePeginParams.universalChallengerPubkeys,hashlocks:[...e.prePeginParams.hashlocks],timelockRefund:e.prePeginParams.timelockRefund,pegInAmounts:[...e.prePeginParams.pegInAmounts],feeRate:e.prePeginParams.feeRate,minPeginFeeRate:e.prePeginParams.minPeginFeeRate,numLocalChallengers:e.prePeginParams.numLocalChallengers,councilQuorum:e.prePeginParams.councilQuorum,councilSize:e.prePeginParams.councilSize,network:e.prePeginParams.network,authAnchorHash:N(e.prePeginParams.authAnchorHash)},e.timelockPegin,e.fundedPrePeginTxHex,e.htlcVout);return await $e(t,e),{txHex:t.txHex,txid:t.txid,vaultScriptPubKey:t.vaultScriptPubKey,vaultValue:t.vaultValue}}async function $e(e,t){const r=t.prePeginParams.vaultCoreVersion;if(r!==p.PEGIN_VAULT_CORE_VERSION)throw new Error(`Unsupported vaultCoreVersion ${r} for PegIn tx; only ${p.PEGIN_VAULT_CORE_VERSION} has a PegIn shape.`);await w.validatePeginP2aAnchor(r,e.txHex);const o=P.Transaction.fromHex(c.stripHexPrefix(e.txHex));if(o.version!==p.PEGIN_TX_VERSION)throw new Error(`PegIn tx version ${o.version} does not match vaultCoreVersion ${r}; expected ${p.PEGIN_TX_VERSION}.`);if(o.locktime!==p.PEGIN_TX_LOCKTIME)throw new Error(`PegIn tx locktime ${o.locktime} does not match the canonical locktime ${p.PEGIN_TX_LOCKTIME}.`);if(o.ins.length!==1)throw new Error(`PegIn tx has ${o.ins.length} input(s), expected exactly 1 (the Pre-PegIn HTLC outpoint).`);const n=P.Transaction.fromHex(c.stripHexPrefix(t.fundedPrePeginTxHex)).getId(),i=c.uint8ArrayToHex(new Uint8Array(o.ins[0].hash).slice().reverse());if(i!==n)throw new Error(`PegIn input spends txid ${i}, expected the funded Pre-PegIn ${n}.`);if(o.ins[0].index!==t.htlcVout)throw new Error(`PegIn input spends Pre-PegIn output ${o.ins[0].index}, expected the requested HTLC vout ${t.htlcVout}.`);if(o.ins[0].sequence!==p.PEGIN_INPUT_SEQUENCE)throw new Error(`PegIn input sequence ${o.ins[0].sequence} does not match the canonical sequence ${p.PEGIN_INPUT_SEQUENCE}.`);if(o.ins[0].script.length!==0)throw new Error("PegIn input scriptSig must be empty.");if(o.ins[0].witness.length!==0)throw new Error("PegIn input witness must be empty before signing.");if(o.outs.length!==p.PEGIN_OUTPUT_COUNT)throw new Error(`PegIn tx has ${o.outs.length} output(s), expected exactly ${p.PEGIN_OUTPUT_COUNT} for vaultCoreVersion ${r} (vault + depositor claim + P2A anchor).`);const s=t.prePeginParams.pegInAmounts[t.htlcVout];if(e.vaultValue!==s)throw new Error(`PegIn vault output value ${e.vaultValue} does not match the requested peg-in amount ${s} for HTLC ${t.htlcVout}; refusing to sign a vault that locks a different amount than requested.`);const u=o.outs[0];if(BigInt(u.value)!==e.vaultValue)throw new Error(`Encoded PegIn vault output value ${u.value} does not match the WASM-reported vaultValue ${e.vaultValue}.`);const a=ye(t.prePeginParams,t.timelockPegin).toString("hex");if(c.stripHexPrefix(e.vaultScriptPubKey).toLowerCase()!==a)throw new Error(`WASM-reported PegIn vaultScriptPubKey ${e.vaultScriptPubKey} does not match the independently derived payout scriptPubKey ${a}.`);const g=u.script.toString("hex");if(g!==a)throw new Error(`Encoded PegIn vault output scriptPubKey ${g} does not match the independently derived payout scriptPubKey ${a}.`);const h=o.getId();if(h!==c.stripHexPrefix(e.txid).toLowerCase())throw new Error(`Encoded PegIn txid ${h} does not match the WASM-reported txid ${e.txid}.`);const f=await w.computeMinClaimValue(r,t.prePeginParams.numLocalChallengers,t.prePeginParams.universalChallengerPubkeys.length,t.prePeginParams.councilQuorum,t.prePeginParams.councilSize,t.prePeginParams.feeRate),d=o.outs[ne];if(BigInt(d.value)!==f)throw new Error(`Encoded PegIn depositor-claim output value ${d.value} does not match the independently computed claim value ${f} for vaultCoreVersion ${r}.`);const E=se(t.prePeginParams.depositorPubkey);if(!d.script.equals(E))throw new Error(`Encoded PegIn depositor-claim output scriptPubKey ${d.script.toString("hex")} does not pay to the depositor's claim script (expected ${E.toString("hex")}).`)}async function ue(e){const t=await w.createPayoutConnector({txGraphVersion:e.vaultCoreVersion,depositor:e.depositor,vaultProvider:e.vaultProvider,vaultKeepers:e.vaultKeepers,universalChallengers:e.universalChallengers,timelockPegin:e.timelockPegin},e.network);return{payoutScript:t.payoutScript,taprootScriptHash:t.taprootScriptHash,scriptPubKey:t.scriptPubKey,address:t.address,payoutControlBlock:t.payoutControlBlock}}const F=253,me=254,Ce=65535,Ie=4294967295,be="TapLeaf",Te="TapBranch",Ae="TapTweak",T=33,A=32,q=128,ke=1,Oe=254,Re=l.Buffer.from([81,32]);function Le(e){if(e<F)return l.Buffer.from([e]);if(e<=Ce){const t=l.Buffer.alloc(2);return t.writeUInt16LE(e),l.Buffer.concat([l.Buffer.from([F]),t])}if(e<=Ie){const t=l.Buffer.alloc(4);return t.writeUInt32LE(e),l.Buffer.concat([l.Buffer.from([me]),t])}throw new Error(`Script too large to encode as CompactSize: ${e} bytes`)}function H(e,t){const r=l.Buffer.concat([l.Buffer.from([e]),Le(t.length),l.Buffer.from(t)]);return P.crypto.taggedHash(be,r)}function Ve(e){const{leafVersion:t,script:r,controlBlock:o}=e,n=o.length-T;if(n<0||n%A!==0||n/A>q)throw new Error(`Malformed Taproot control block: length ${o.length} must be ${T} + 32*m with 0 <= m <= ${q}`);const i=o[0]&Oe;if(i!==t)throw new Error(`Taproot control block leaf version 0x${i.toString(16)} does not match the tapLeafScript leaf version 0x${t.toString(16)}`);const s=l.Buffer.from(o.subarray(1,T));let u=H(t,r);for(let f=T;f<o.length;f+=A){const d=l.Buffer.from(o.subarray(f,f+A));u=P.crypto.taggedHash(Te,l.Buffer.compare(u,d)<=0?l.Buffer.concat([u,d]):l.Buffer.concat([d,u]))}const a=P.crypto.taggedHash(Ae,l.Buffer.concat([s,u])),g=ee.xOnlyPointAddTweak(s,a);if(g===null)throw new Error("Taproot control block does not yield a valid output key (tweak is off-curve)");const h=o[0]&ke;if(g.parity!==h)throw new Error(`Taproot output key parity ${g.parity} contradicts the control block's parity bit ${h}`);return l.Buffer.concat([Re,l.Buffer.from(g.xOnlyPubkey)])}const Ne=256,He=1500,X=256,G=0xffffffffn,Be=500,Ue=55,Ke=34;function ce(e){if(typeof e.protocolFeeRate!="bigint"||e.protocolFeeRate<=0n||e.protocolFeeRate>G)throw new Error(`protocolFeeRate must be in [1, ${G}] sat/vB, got ${e.protocolFeeRate}`);for(const[t,r,o,n]of[["keepers",e.numVaultKeepers,Ne,"fee-floor model limit"],["challengers",e.numUniversalChallengers,He,"protocol maximum"]])if(!Number.isInteger(r)||r<1||r>o)throw new Error(`Participant count for ${t} (${r}) is outside the supported range [1, ${o}]${r>o?` (${n})`:""}.`);if(!Number.isInteger(e.councilSize)||e.councilSize<1||e.councilSize>X)throw new Error(`councilSize must be an integer in [1, ${X}], got ${e.councilSize}`)}async function ae(e,t){const{implicitFeeSats:r,out0Len:o,out1Len:n}=t,i=e.numVaultKeepers+e.numUniversalChallengers,s=BigInt(r),u=Math.max(0,o-Ke),a=Be+Ue*i+u,g=e.protocolFeeRate*BigInt(a);if(s>g)throw new Error(`Payout implicit fee ${r} sats exceeds the safety cap of ${g} sats (${e.protocolFeeRate} sat/vB x ${a} vB for ${i} participants); refusing to sign payout.`);const h=await w.computePayoutFeeFloor(e.vaultCoreVersion,e.numVaultKeepers,e.numUniversalChallengers,e.numVaultKeepers,e.councilSize,o,n,e.protocolFeeRate);if(s<h)throw new Error(`Payout implicit fee ${r} sats is below the floor of ${h} sats (the smallest fee any known vault-provider build produces for this shape); refusing to sign payout.`)}const Me=22,Fe=34,qe=34,Xe=25,Ge=23;function We(e){return e.length===Me*2&&e.startsWith("0014")}function Ye(e){return e.length===Fe*2&&e.startsWith("0020")}function ze(e){return e.length===qe*2&&e.startsWith("5120")}function De(e){return e.length===Xe*2&&e.startsWith("76a914")&&e.endsWith("88ac")}function Qe(e){return e.length===Ge*2&&e.startsWith("a914")&&e.endsWith("87")}function W(e,t){const r=c.stripHexPrefix(e).toLowerCase();if(r.length===0)throw new Error(`${t} is empty`);if(!/^[0-9a-f]+$/.test(r)||r.length%2!==0)throw new Error(`${t} is not valid hex`);if(r.startsWith("6a"))throw new Error(`${t} is an OP_RETURN output, which is provably unspendable`);if(!ze(r)&&!We(r)&&!Ye(r)&&!De(r)&&!Qe(r))throw new Error(`${t} is not a standard scriptPubKey (expected P2TR, P2WPKH, P2WSH, P2PKH, or P2SH; got ${r.length/2} bytes: ${r})`)}const Y=3;async function Ze(e){const t={vaultCoreVersion:e.vaultCoreVersion,numVaultKeepers:e.vaultKeeperBtcPubkeys.length,numUniversalChallengers:e.universalChallengerBtcPubkeys.length,councilSize:e.councilMembers.length,protocolFeeRate:e.protocolFeeRate};ce(t);const r=P.Transaction.fromHex(c.stripHexPrefix(e.payoutTxHex)),o=P.Transaction.fromHex(c.stripHexPrefix(e.peginTxHex)),n=P.Transaction.fromHex(c.stripHexPrefix(e.assertTxHex));if(r.ins.length!==p.DEPOSITOR_PAYOUT_INPUT_COUNT)throw new Error(`Payout transaction must have exactly ${p.DEPOSITOR_PAYOUT_INPUT_COUNT} inputs, got ${r.ins.length}`);if(r.version!==p.PAYOUT_TX_VERSION)throw new Error(`Payout transaction version ${r.version} must be ${p.PAYOUT_TX_VERSION}; refusing to sign payout.`);if(r.locktime!==p.PAYOUT_TX_LOCKTIME)throw new Error(`Payout transaction locktime ${r.locktime} must be ${p.PAYOUT_TX_LOCKTIME}; refusing to sign payout.`);const i=z(r.ins[0],0,o,"PegIn",p.PEGIN_VAULT_OUTPUT_INDEX);if(r.ins[0].sequence!==e.timelockPegin)throw new Error(`Payout input 0 sequence ${r.ins[0].sequence} must equal the PegIn CSV timelock ${e.timelockPegin}; refusing to sign payout.`);const s=z(r.ins[1],1,n,"Assert",p.ASSERT_PAYOUT_OUTPUT_INDEX);if(r.ins[1].sequence!==e.timelockAssert)throw new Error(`Payout input 1 sequence ${r.ins[1].sequence} must equal the Assert CSV timelock ${e.timelockAssert}; refusing to sign payout.`);const{out0Len:u,out1Len:a}=et(r,i.value,e),g=i.value+s.value;let h=0;for(const v of r.outs)h+=v.value;if(h>g)throw new Error(`Payout outputs (${h} sats) exceed inputs (${g} sats); invalid transaction.`);const f=g-h;await ae(t,{implicitFeeSats:f,out0Len:u,out1Len:a});const d=await ue({vaultCoreVersion:e.vaultCoreVersion,depositor:e.depositorBtcPubkey,vaultProvider:e.vaultProviderBtcPubkey,vaultKeepers:e.vaultKeeperBtcPubkeys,universalChallengers:e.universalChallengerBtcPubkeys,timelockPegin:e.timelockPegin,network:e.network}),E=await je(e,s);return{psbtHex:Je(r,i,s,d,E)}}async function je(e,t){const{payoutScript:r,payoutControlBlock:o}=await w.getAssertPayoutScriptInfo({txGraphVersion:e.vaultCoreVersion,claimer:c.stripHexPrefix(e.claimerBtcPubkey).toLowerCase(),localChallengers:te({claimerBtcPubkey:e.claimerBtcPubkey,depositorBtcPubkey:e.depositorBtcPubkey,vaultProviderBtcPubkey:e.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:e.vaultKeeperBtcPubkeys}),universalChallengers:e.universalChallengerBtcPubkeys.map(u=>c.stripHexPrefix(u).toLowerCase()),timelockAssert:e.timelockAssert,councilMembers:e.councilMembers.map(u=>c.stripHexPrefix(u).toLowerCase()),councilQuorum:e.councilQuorum}),n=c.hexToUint8Array(r),i=c.hexToUint8Array(o),s=Ve({leafVersion:c.TAPSCRIPT_LEAF_VERSION,script:n,controlBlock:i});if(!t.script.equals(s))throw new Error(`Rebuilt Assert:0 payout leaf does not spend the Assert output being referenced: leaf binds to ${s.toString("hex")}, Assert:${p.ASSERT_PAYOUT_OUTPUT_INDEX} pays ${t.script.toString("hex")}; refusing to sign payout.`);return{script:n,controlBlock:i}}function z(e,t,r,o,n){const i=c.uint8ArrayToHex(new Uint8Array(e.hash).slice().reverse()),s=r.getId();if(i!==s||e.index!==n)throw new Error(`Input ${t} must spend ${o}:${n}. Expected ${s}:${n}, got ${i}:${e.index}`);const u=r.outs[e.index];if(!u)throw new Error(`Previous output not found for input ${t} (txid: ${i}, index: ${e.index})`);return u}function Je(e,t,r,o,n){const i=new P.Psbt;i.setVersion(e.version),i.setLocktime(e.locktime);const[s,u]=e.ins;i.addInput({hash:s.hash,index:s.index,sequence:s.sequence,witnessUtxo:{script:t.script,value:t.value},tapLeafScript:[{leafVersion:c.TAPSCRIPT_LEAF_VERSION,script:l.Buffer.from(c.hexToUint8Array(o.payoutScript)),controlBlock:l.Buffer.from(c.hexToUint8Array(o.payoutControlBlock))}],tapInternalKey:l.Buffer.from(w.tapInternalPubkey)}),i.addInput({hash:u.hash,index:u.index,sequence:u.sequence,witnessUtxo:{script:r.script,value:r.value},tapLeafScript:[{leafVersion:c.TAPSCRIPT_LEAF_VERSION,script:l.Buffer.from(n.script),controlBlock:l.Buffer.from(n.controlBlock)}],tapInternalKey:l.Buffer.from(w.tapInternalPubkey)});for(const a of e.outs)i.addOutput({script:a.script,value:a.value});return i.toHex()}function D(e,t){const r=c.stripHexPrefix(e).toLowerCase(),o=c.stripHexPrefix(c.deriveBip86ScriptPubKeyHex(t)).toLowerCase();return r===o?[r]:[r,o]}function Q(e,t){return t.some(r=>e.equals(l.Buffer.from(r,"hex")))}function et(e,t,r){const{claimerBtcPubkey:o,vaultProviderBtcPubkey:n,depositorBtcPubkey:i,vaultKeeperBtcPubkeys:s,registeredPayoutScriptPubKey:u,commissionBps:a,vkClaimerPayoutScriptPubKeys:g,vpCommissionScriptPubKey:h}=r;if(!c.isValidHex(u))throw new Error("Invalid registeredPayoutScriptPubKey: not valid hex");const f=c.stripHexPrefix(o).toLowerCase(),d=c.stripHexPrefix(n).toLowerCase(),E=c.stripHexPrefix(i).toLowerCase(),v=s.map($=>c.stripHexPrefix($).toLowerCase());let S,y,_;if(f===d)S="vp-claimer",y=p.VP_CLAIMER_PAYOUT_OUTPUT_COUNT,_=[c.stripHexPrefix(u)];else if(f===E)S="depositor-as-claimer",y=p.NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT,_=[c.stripHexPrefix(u)];else if(v.includes(f)){S="vk-claimer",y=p.NON_VP_CLAIMER_PAYOUT_OUTPUT_COUNT;const $=g[f];if($===void 0)throw new Error(`No registered payout script resolved for vault keeper claimer ${f}`);W($,`Vault keeper payout script for claimer ${f}`),_=D($,f)}else throw new Error(`Unknown claimer pubkey ${f}: not VP, depositor, or a registered vault keeper`);if(e.outs.length!==y)throw new Error(`Payout transaction has ${e.outs.length} output(s), expected exactly ${y} for role ${S}.`);if(!Q(e.outs[0].script,_))throw new Error(`Payout transaction output 0 does not pay the expected scriptPubKey for role ${S}. Accepted: ${_.join(" or ")}; got ${e.outs[0].script.toString("hex")}`);const L=y-1;if(e.outs[L].value!==p.PAYOUT_ANCHOR_DUST_SATS)throw new Error(`Payout CPFP anchor (out ${L}) value ${e.outs[L].value} sats must equal ${p.PAYOUT_ANCHOR_DUST_SATS} sats`);if(S==="vp-claimer"){W(h,"Vault provider commission payout script");const $=D(h,d);if(!Q(e.outs[1].script,$))throw new Error(`Payout transaction output 1 does not pay the vault provider's commission scriptPubKey. Accepted: ${$.join(" or ")}; got ${e.outs[1].script.toString("hex")}`);if(!Number.isInteger(a)||a<0||a>=p.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`commissionBps must be an integer in [0, ${p.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${a}`);const B=Math.floor(t*a/p.BPS_DENOMINATOR);if(e.outs[1].value>B)throw new Error(`Payout VP commission (out 1) value ${e.outs[1].value} sats exceeds cap ${B} sats (${a} bps of peginValue=${t})`)}const b=e.outs[0].script.length;if(b===0||b>p.MAX_PAYOUT_SCRIPT_LEN)throw new Error(`Payout receiver scriptPubKey length ${b} is outside the contract's registration cap [1, ${p.MAX_PAYOUT_SCRIPT_LEN}]; refusing to sign payout.`);const le=S==="vp-claimer"?e.outs[1].script.length:void 0;return{out0Len:b,out1Len:le}}function tt(e,t,r=0){const o=P.Psbt.fromHex(e);if(r>=o.data.inputs.length)throw new Error(`Input index ${r} out of range (${o.data.inputs.length} inputs)`);const n=o.data.inputs[r];if(n.tapScriptSig&&n.tapScriptSig.length>0){const i=c.hexToUint8Array(t);for(const s of n.tapScriptSig)if(s.pubkey.equals(l.Buffer.from(i)))return Z(s.signature,r);throw new Error(`No signature found for depositor pubkey: ${t} at input ${r}`)}if(n.finalScriptWitness&&n.finalScriptWitness.length>0){const i=rt(n.finalScriptWitness);if(i.length!==Y)throw new Error(`Unexpected finalized witness stack size at input ${r}: expected ${Y} items (signature, script, controlBlock), got ${i.length}`);return Z(i[0],r)}throw new Error(`No tapScriptSig or finalScriptWitness found in signed PSBT at input ${r}`)}function Z(e,t){if(e.length===64)return c.uint8ArrayToHex(new Uint8Array(e));throw e.length===65?new Error(`Unexpected sighash byte 0x${e[64].toString(16).padStart(2,"0")} at input ${t}. Expected implicit SIGHASH_DEFAULT as a 64-byte signature.`):new Error(`Unexpected signature length at input ${t}: ${e.length}`)}function rt(e){const t=[];let r=0;const o=s=>{if(r+s>e.length)throw new Error(`Malformed witness data: need ${s} byte(s) at offset ${r}, only ${e.length-r} remaining`)},n=()=>{o(1);const s=e[r++];if(s<253)return s;if(s===253){o(2);const u=(e[r]|e[r+1]<<8)>>>0;return r+=2,u}if(s===254){o(4);const u=(e[r]|e[r+1]<<8|e[r+2]<<16|e[r+3]<<24)>>>0;return r+=4,u}throw new Error(`Malformed witness data: 8-byte varint (0xff) not supported at offset ${r-1}`)},i=n();for(let s=0;s<i;s++){const u=n();o(u),t.push(l.Buffer.from(e.subarray(r,r+u))),r+=u}if(r!==e.length)throw new Error(`Malformed witness data: ${e.length-r} trailing byte(s) after parsing ${i} item(s)`);return t}class x extends Error{constructor(t){super(`Wallet returned a PSBT for a different transaction: ${t}`),this.name="PsbtSubstitutionError"}}function j(e,t){try{return P.Psbt.fromHex(t)}catch(r){const o=r instanceof Error?r.message:String(r);throw new Error(`Failed to parse ${e} PSBT: ${o}`)}}const ot=8;function V(e){return`${e.toString("hex").slice(0,ot)}…`}function J(e){const t=l.Buffer.from(e).reverse();return V(t)}function nt(e){const t=j("requested",e.requestedPsbtHex),r=j("returned",e.returnedPsbtHex);if(t.version!==r.version)throw new x(`tx version differs (requested=${t.version}, returned=${r.version})`);if(t.locktime!==r.locktime)throw new x(`tx locktime differs (requested=${t.locktime}, returned=${r.locktime})`);if(t.txInputs.length!==r.txInputs.length)throw new x(`input count differs (requested=${t.txInputs.length}, returned=${r.txInputs.length})`);if(t.txOutputs.length!==r.txOutputs.length)throw new x(`output count differs (requested=${t.txOutputs.length}, returned=${r.txOutputs.length})`);for(let o=0;o<t.txInputs.length;o++){const n=t.txInputs[o],i=r.txInputs[o];if(!n.hash.equals(i.hash))throw new x(`input ${o} prevout txid differs (requested=${J(n.hash)}, returned=${J(i.hash)})`);if(n.index!==i.index)throw new x(`input ${o} prevout vout differs (requested=${n.index}, returned=${i.index})`);if(n.sequence!==i.sequence)throw new x(`input ${o} sequence differs (requested=${n.sequence}, returned=${i.sequence})`)}for(let o=0;o<t.txOutputs.length;o++){const n=t.txOutputs[o],i=r.txOutputs[o];if(!n.script.equals(i.script))throw new x(`output ${o} scriptPubKey differs (requested=${V(n.script)}, returned=${V(i.script)})`);if(n.value!==i.value)throw new x(`output ${o} value differs (requested=${n.value}, returned=${i.value})`)}}function it(e){const{requestedPsbtHex:t,signatureHex:r,signerXOnlyPubkeyHex:o,inputIndex:n}=e,i=c.stripHexPrefix(r);if(i.length!==c.SCHNORR_SIG_HEX_LEN)throw new Error(`Schnorr signature for input ${n} must be ${c.SCHNORR_SIG_HEX_LEN} hex chars (64 bytes), got ${i.length}.`);const s=c.stripHexPrefix(o);if(s.length!==U.X_ONLY_PUBKEY_HEX_LEN)throw new Error(`Signer x-only pubkey for input ${n} must be ${U.X_ONLY_PUBKEY_HEX_LEN} hex chars (32 bytes), got ${s.length}.`);const u=P.Psbt.fromHex(t);if(n<0||n>=u.data.inputs.length)throw new Error(`Input index ${n} out of range (${u.data.inputs.length} inputs).`);const a=[],g=[];for(let y=0;y<u.data.inputs.length;y++){const _=u.data.inputs[y].witnessUtxo;if(!_)throw new Error(`Cannot verify signature: input ${y} of the requested PSBT has no witnessUtxo (required to recompute the Taproot sighash).`);a.push(_.script),g.push(_.value)}const h=u.data.inputs[n].tapLeafScript;if(!h||h.length!==1)throw new Error(`Cannot verify signature: input ${n} of the requested PSBT must have exactly one tapLeafScript, got ${(h==null?void 0:h.length)??0}.`);const f=h[0];if(f.leafVersion!==c.TAPSCRIPT_LEAF_VERSION)throw new Error(`Cannot verify signature: input ${n} tapLeafScript has leaf version 0x${f.leafVersion.toString(16)}, expected 0x${c.TAPSCRIPT_LEAF_VERSION.toString(16)}.`);const d=H(f.leafVersion,f.script),E=new P.Transaction;E.version=u.version,E.locktime=u.locktime;for(const y of u.txInputs)E.addInput(y.hash,y.index,y.sequence);for(const y of u.txOutputs)E.addOutput(y.script,y.value);const v=E.hashForWitnessV1(n,a,g,P.Transaction.SIGHASH_DEFAULT,d);if(!ee.verifySchnorr(v,c.hexToUint8Array(s),c.hexToUint8Array(i)))throw new Error(`Schnorr signature for input ${n} (signer ${s}) does not verify against the expected Taproot script-path sighash. The wallet may have signed with the tweaked key, signed a different transaction, or returned an invalid signature.`)}exports.HtlcOutputMismatchError=C;exports.PEGIN_DEPOSITOR_CLAIM_VOUT=ne;exports.PsbtSubstitutionError=x;exports.assertEncodedHtlcOutputsMatch=oe;exports.assertPayoutFeeBandDomain=ce;exports.assertPayoutFeeInBand=ae;exports.assertPsbtUnsignedTxMatches=nt;exports.assertScriptPathSchnorrSignature=it;exports.buildPayoutPsbt=Ze;exports.buildPeginTxFromFundedPrePegin=_e;exports.buildPrePeginPsbt=xe;exports.computeNumLocalChallengers=fe;exports.computeTapLeafHash=H;exports.createPayoutScript=ue;exports.deriveDepositorClaimDescriptor=ie;exports.deriveDepositorClaimScriptPubKey=se;exports.deriveExpectedPrePeginHtlc=re;exports.deriveLocalChallengers=te;exports.extractPayoutSignature=tt;exports.normalizeAuthAnchorHash=N;
2
+ //# sourceMappingURL=verifyScriptPathSchnorrSignature-CgDa9Rcg.cjs.map