@babylonlabs-io/ts-sdk 0.66.1 → 0.68.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 (157) hide show
  1. package/dist/PeginManager--2R3T2S8.js +1458 -0
  2. package/dist/PeginManager--2R3T2S8.js.map +1 -0
  3. package/dist/PeginManager-CKWq8ouZ.cjs +2 -0
  4. package/dist/PeginManager-CKWq8ouZ.cjs.map +1 -0
  5. package/dist/{batchPoll-cIxrSLLJ.js → batchPoll-Cjj1du0i.js} +372 -421
  6. package/dist/batchPoll-Cjj1du0i.js.map +1 -0
  7. package/dist/batchPoll-REVZiE-M.cjs +2 -0
  8. package/dist/batchPoll-REVZiE-M.cjs.map +1 -0
  9. package/dist/{bitcoin-d9eaaZB_.js → bitcoin-Ch_jxnDa.js} +3 -3
  10. package/dist/{bitcoin-d9eaaZB_.js.map → bitcoin-Ch_jxnDa.js.map} +1 -1
  11. package/dist/{buildAndBroadcastRefund-C4LiPATK.js → buildAndBroadcastRefund-CpMDJ8up.js} +142 -150
  12. package/dist/buildAndBroadcastRefund-CpMDJ8up.js.map +1 -0
  13. package/dist/buildAndBroadcastRefund-DrXwxrW1.cjs +2 -0
  14. package/dist/buildAndBroadcastRefund-DrXwxrW1.cjs.map +1 -0
  15. package/dist/challengeAssert-BNQ8sToz.js +64 -0
  16. package/dist/challengeAssert-BNQ8sToz.js.map +1 -0
  17. package/dist/challengeAssert-BrpC3-cQ.cjs +2 -0
  18. package/dist/challengeAssert-BrpC3-cQ.cjs.map +1 -0
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +246 -243
  21. package/dist/mempoolApi-EU1La9wk.cjs +2 -0
  22. package/dist/{mempoolApi-CXfr-L6x.cjs.map → mempoolApi-EU1La9wk.cjs.map} +1 -1
  23. package/dist/{mempoolApi-BxSINXIB.js → mempoolApi-_D-jvtj_.js} +191 -117
  24. package/dist/{mempoolApi-BxSINXIB.js.map → mempoolApi-_D-jvtj_.js.map} +1 -1
  25. package/dist/{noPayout-BaZGRLD2.js → noPayout-CXn-geIS.js} +3 -3
  26. package/dist/{noPayout-BaZGRLD2.js.map → noPayout-CXn-geIS.js.map} +1 -1
  27. package/dist/{noPayout-CnQ1WLtr.cjs → noPayout-Ox27Td9x.cjs} +2 -2
  28. package/dist/{noPayout-CnQ1WLtr.cjs.map → noPayout-Ox27Td9x.cjs.map} +1 -1
  29. package/dist/{onChainBtcPubkey-DeF4cKoO.js → onChainBtcPubkey-BAHZyKQL.js} +2 -2
  30. package/dist/{onChainBtcPubkey-DeF4cKoO.js.map → onChainBtcPubkey-BAHZyKQL.js.map} +1 -1
  31. package/dist/{parseFundingOutpoints-pBRE11Hr.js → parseFundingOutpoints-CO-f6IHK.js} +2 -2
  32. package/dist/{parseFundingOutpoints-pBRE11Hr.js.map → parseFundingOutpoints-CO-f6IHK.js.map} +1 -1
  33. package/dist/{reservation-B4i_PQhY.js → reservation-CBAvoF3U.js} +2 -2
  34. package/dist/{reservation-B4i_PQhY.js.map → reservation-CBAvoF3U.js.map} +1 -1
  35. package/dist/{signPsbtsWithFallback-Bb66DfY5.js → signPsbtsWithFallback-Bv79gLFe.js} +122 -100
  36. package/dist/signPsbtsWithFallback-Bv79gLFe.js.map +1 -0
  37. package/dist/signPsbtsWithFallback-DJ4kE9UI.cjs +2 -0
  38. package/dist/signPsbtsWithFallback-DJ4kE9UI.cjs.map +1 -0
  39. package/dist/tbv/core/clients/index.cjs +1 -1
  40. package/dist/tbv/core/clients/index.js +3 -3
  41. package/dist/tbv/core/clients/vault-provider/auth/__tests__/bip322P2wpkhVectors.d.ts +32 -0
  42. package/dist/tbv/core/clients/vault-provider/auth/__tests__/bip322P2wpkhVectors.d.ts.map +1 -0
  43. package/dist/tbv/core/clients/vault-provider/auth/__tests__/bip322Verify.test.d.ts +9 -6
  44. package/dist/tbv/core/clients/vault-provider/auth/__tests__/bip322Verify.test.d.ts.map +1 -1
  45. package/dist/tbv/core/clients/vault-provider/auth/bip322Verify.d.ts +45 -20
  46. package/dist/tbv/core/clients/vault-provider/auth/bip322Verify.d.ts.map +1 -1
  47. package/dist/tbv/core/deposit-terms/__tests__/depositTerms.test.d.ts +2 -0
  48. package/dist/tbv/core/deposit-terms/__tests__/depositTerms.test.d.ts.map +1 -0
  49. package/dist/tbv/core/deposit-terms/depositTerms.d.ts +42 -5
  50. package/dist/tbv/core/deposit-terms/depositTerms.d.ts.map +1 -1
  51. package/dist/tbv/core/deposit-terms/prePeginApproval.d.ts +10 -5
  52. package/dist/tbv/core/deposit-terms/prePeginApproval.d.ts.map +1 -1
  53. package/dist/tbv/core/index.cjs +1 -1
  54. package/dist/tbv/core/index.js +244 -241
  55. package/dist/tbv/core/managers/PayoutManager.d.ts +8 -2
  56. package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -1
  57. package/dist/tbv/core/managers/PeginManager.d.ts +7 -0
  58. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  59. package/dist/tbv/core/managers/index.cjs +1 -1
  60. package/dist/tbv/core/managers/index.js +2 -2
  61. package/dist/tbv/core/managers/pegin/__tests__/verifyPopWitness.test.d.ts +11 -0
  62. package/dist/tbv/core/managers/pegin/__tests__/verifyPopWitness.test.d.ts.map +1 -0
  63. package/dist/tbv/core/managers/pegin/expandPerVaultSecrets.d.ts.map +1 -1
  64. package/dist/tbv/core/managers/pegin/index.d.ts +1 -0
  65. package/dist/tbv/core/managers/pegin/index.d.ts.map +1 -1
  66. package/dist/tbv/core/managers/pegin/verifyPopWitness.d.ts +21 -0
  67. package/dist/tbv/core/managers/pegin/verifyPopWitness.d.ts.map +1 -0
  68. package/dist/tbv/core/primitives/challengers.d.ts +31 -5
  69. package/dist/tbv/core/primitives/challengers.d.ts.map +1 -1
  70. package/dist/tbv/core/primitives/index.cjs +1 -1
  71. package/dist/tbv/core/primitives/index.d.ts +2 -0
  72. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  73. package/dist/tbv/core/primitives/index.js +43 -41
  74. package/dist/tbv/core/primitives/psbt/__tests__/helpers.d.ts +5 -0
  75. package/dist/tbv/core/primitives/psbt/__tests__/helpers.d.ts.map +1 -1
  76. package/dist/tbv/core/primitives/psbt/__tests__/verifyKeyPathSchnorrSignature.test.d.ts +12 -0
  77. package/dist/tbv/core/primitives/psbt/__tests__/verifyKeyPathSchnorrSignature.test.d.ts.map +1 -0
  78. package/dist/tbv/core/primitives/psbt/payout.d.ts +19 -7
  79. package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
  80. package/dist/tbv/core/primitives/psbt/pegin.d.ts +2 -2
  81. package/dist/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.d.ts +64 -0
  82. package/dist/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.d.ts.map +1 -0
  83. package/dist/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.d.ts +40 -0
  84. package/dist/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.d.ts.map +1 -0
  85. package/dist/tbv/core/primitives/psbt/verifyScriptPathSchnorrSignature.d.ts +2 -1
  86. package/dist/tbv/core/primitives/psbt/verifyScriptPathSchnorrSignature.d.ts.map +1 -1
  87. package/dist/tbv/core/primitives/utils/__tests__/taproot.test.d.ts +13 -0
  88. package/dist/tbv/core/primitives/utils/__tests__/taproot.test.d.ts.map +1 -0
  89. package/dist/tbv/core/primitives/utils/taproot.d.ts +29 -0
  90. package/dist/tbv/core/primitives/utils/taproot.d.ts.map +1 -0
  91. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +2 -2
  92. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  93. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  94. package/dist/tbv/core/services/index.cjs +1 -1
  95. package/dist/tbv/core/services/index.js +2 -2
  96. package/dist/tbv/core/utils/index.js +2 -2
  97. package/dist/tbv/core/utils/witness/witnessStack.d.ts +24 -0
  98. package/dist/tbv/core/utils/witness/witnessStack.d.ts.map +1 -0
  99. package/dist/tbv/core/vault-secrets/index.js +1 -1
  100. package/dist/tbv/index.cjs +1 -1
  101. package/dist/tbv/index.js +244 -241
  102. package/dist/tbv/integrations/aave/clients/__tests__/query.test.d.ts +11 -0
  103. package/dist/tbv/integrations/aave/clients/__tests__/query.test.d.ts.map +1 -0
  104. package/dist/tbv/integrations/aave/clients/query.d.ts.map +1 -1
  105. package/dist/tbv/integrations/aave/index.cjs +1 -1
  106. package/dist/tbv/integrations/aave/index.cjs.map +1 -1
  107. package/dist/tbv/integrations/aave/index.js +132 -114
  108. package/dist/tbv/integrations/aave/index.js.map +1 -1
  109. package/dist/testing/MockBitcoinWallet.d.ts +10 -1
  110. package/dist/testing/MockBitcoinWallet.d.ts.map +1 -1
  111. package/dist/testing/__tests__/MockBitcoinWallet.test.d.ts +2 -0
  112. package/dist/testing/__tests__/MockBitcoinWallet.test.d.ts.map +1 -0
  113. package/dist/testing/index.cjs +1 -1
  114. package/dist/testing/index.cjs.map +1 -1
  115. package/dist/testing/index.js +134 -47
  116. package/dist/testing/index.js.map +1 -1
  117. package/dist/testing/signBip322P2wpkhWitness.d.ts +20 -0
  118. package/dist/testing/signBip322P2wpkhWitness.d.ts.map +1 -0
  119. package/dist/{toRefundInputs-BY_fcvrv.js → toRefundInputs-9hv_6k0E.js} +6 -6
  120. package/dist/{toRefundInputs-BY_fcvrv.js.map → toRefundInputs-9hv_6k0E.js.map} +1 -1
  121. package/dist/{toRefundInputs-DYL9C-aG.cjs → toRefundInputs-D8sFs44p.cjs} +2 -2
  122. package/dist/{toRefundInputs-DYL9C-aG.cjs.map → toRefundInputs-D8sFs44p.cjs.map} +1 -1
  123. package/dist/verifyKeyPathSchnorrSignature-DCOzQkDf.cjs +2 -0
  124. package/dist/verifyKeyPathSchnorrSignature-DCOzQkDf.cjs.map +1 -0
  125. package/dist/verifyKeyPathSchnorrSignature-oGCUbjjZ.js +363 -0
  126. package/dist/verifyKeyPathSchnorrSignature-oGCUbjjZ.js.map +1 -0
  127. package/dist/verifyScriptPathSchnorrSignature-Dy9gF5RF.js +931 -0
  128. package/dist/verifyScriptPathSchnorrSignature-Dy9gF5RF.js.map +1 -0
  129. package/dist/verifyScriptPathSchnorrSignature-la8XOAFm.cjs +2 -0
  130. package/dist/verifyScriptPathSchnorrSignature-la8XOAFm.cjs.map +1 -0
  131. package/package.json +2 -2
  132. package/dist/PeginManager-BBl4xkWz.js +0 -1359
  133. package/dist/PeginManager-BBl4xkWz.js.map +0 -1
  134. package/dist/PeginManager-p-ajwSxG.cjs +0 -2
  135. package/dist/PeginManager-p-ajwSxG.cjs.map +0 -1
  136. package/dist/batchPoll-6L5oToGr.cjs +0 -2
  137. package/dist/batchPoll-6L5oToGr.cjs.map +0 -1
  138. package/dist/batchPoll-cIxrSLLJ.js.map +0 -1
  139. package/dist/buildAndBroadcastRefund-C4LiPATK.js.map +0 -1
  140. package/dist/buildAndBroadcastRefund-Daw5ZUKR.cjs +0 -2
  141. package/dist/buildAndBroadcastRefund-Daw5ZUKR.cjs.map +0 -1
  142. package/dist/challengeAssert-BFRE2DM-.cjs +0 -2
  143. package/dist/challengeAssert-BFRE2DM-.cjs.map +0 -1
  144. package/dist/challengeAssert-C7PzyJ7g.js +0 -75
  145. package/dist/challengeAssert-C7PzyJ7g.js.map +0 -1
  146. package/dist/mempoolApi-CXfr-L6x.cjs +0 -2
  147. package/dist/peginInput-Ci921gTl.cjs +0 -2
  148. package/dist/peginInput-Ci921gTl.cjs.map +0 -1
  149. package/dist/peginInput-HQPWZfly.js +0 -123
  150. package/dist/peginInput-HQPWZfly.js.map +0 -1
  151. package/dist/signPsbtsWithFallback-Bb66DfY5.js.map +0 -1
  152. package/dist/signPsbtsWithFallback-PTgWxsG3.cjs +0 -2
  153. package/dist/signPsbtsWithFallback-PTgWxsG3.cjs.map +0 -1
  154. package/dist/verifyScriptPathSchnorrSignature-DPAd_qke.cjs +0 -2
  155. package/dist/verifyScriptPathSchnorrSignature-DPAd_qke.cjs.map +0 -1
  156. package/dist/verifyScriptPathSchnorrSignature-i-koT139.js +0 -817
  157. package/dist/verifyScriptPathSchnorrSignature-i-koT139.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signPsbtsWithFallback-Bv79gLFe.js","sources":["../src/tbv/core/managers/pegin/assertAuthAnchorOpReturn.ts","../src/tbv/core/services/htlc/index.ts","../src/tbv/core/deposit-terms/depositTerms.ts","../src/tbv/core/managers/PayoutManager.ts","../src/tbv/core/managers/pegin/signPsbtsWithFallback.ts"],"sourcesContent":["/**\n * Structural verifier for the auth-anchor OP_RETURN in a funded\n * Pre-PegIn transaction.\n *\n * @module managers/pegin/assertAuthAnchorOpReturn\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\n\n/** OP_RETURN opcode. */\nconst OP_RETURN = 0x6a;\n/** Push-32-bytes opcode (raw push, not OP_PUSHDATA1). */\nconst OP_PUSH32 = 0x20;\n/** Encoded length of a standard OP_RETURN script with a 32-byte payload. */\nconst OP_RETURN_PUSH32_SCRIPT_LEN = 1 + 1 + 32;\n\n/**\n * Verify the broadcast Pre-PegIn carries the expected OP_RETURN\n * commitment to the auth anchor.\n *\n * The OP_RETURN sits at `vout = vaultCount` (right after the per-vault\n * HTLC outputs and before the depositor-claim/change outputs) and\n * pushes the 32-byte `SHA256(authAnchor)`. The script encoding is\n * exactly `OP_RETURN || PUSH32 || <32 bytes>` (34 bytes). A\n * non-conformant WASM build that omitted the OP_RETURN, swapped its\n * position, or changed its push payload would let the depositor\n * obtain a valid bearer token for a Pre-PegIn whose on-chain\n * commitment doesn't actually bind the anchor — degrading the auth\n * from on-chain-bound to a shared secret. Fail closed.\n *\n * @throws If the OP_RETURN is missing, mis-located, mis-encoded, or\n * pushes a payload other than `expectedAuthAnchorHashHex`.\n */\nexport function assertAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n vaultCount: number,\n expectedAuthAnchorHashHex: string,\n): void {\n const cleanHex = stripHexPrefix(fundedPrePeginTxHex);\n const tx = bitcoin.Transaction.fromHex(cleanHex);\n\n if (tx.outs.length <= vaultCount) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN missing: tx has ${tx.outs.length} ` +\n `outputs, expected at least ${vaultCount + 1} (vault outputs + OP_RETURN)`,\n );\n }\n\n const opReturnOutput = tx.outs[vaultCount];\n const script = opReturnOutput.script;\n if (\n script.length !== OP_RETURN_PUSH32_SCRIPT_LEN ||\n script[0] !== OP_RETURN ||\n script[1] !== OP_PUSH32\n ) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has unexpected ` +\n `script encoding (got ${script.length}-byte script with prefix ` +\n `0x${script.slice(0, Math.min(2, script.length)).toString(\"hex\")}; ` +\n `expected ${OP_RETURN_PUSH32_SCRIPT_LEN}-byte OP_RETURN + PUSH32 layout)`,\n );\n }\n\n const pushedHex = script.slice(2).toString(\"hex\").toLowerCase();\n if (pushedHex !== expectedAuthAnchorHashHex.toLowerCase()) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${vaultCount}: ` +\n `tx pushes ${pushedHex}, expected ${expectedAuthAnchorHashHex}`,\n );\n }\n\n if (opReturnOutput.value !== 0) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has non-zero ` +\n `value ${opReturnOutput.value}; OP_RETURN outputs must be 0-value`,\n );\n }\n}\n\n/**\n * Scan a funded Pre-PegIn transaction for its auth-anchor commitment\n * (an `OP_RETURN || PUSH32 || <32 bytes>` output with value 0).\n *\n * Returns `{ vout, hash }` when exactly one such output is found.\n * Returns `undefined` when:\n * - the hex is unparseable,\n * - no matching output exists (legacy non-auth-anchored Pre-PegIn),\n * - more than one matching output exists (ambiguous / malformed).\n *\n * Used by the refund orchestrator to (a) locate the on-chain anchor\n * regardless of how many HTLCs preceded it and (b) detect multi-vault\n * funded transactions structurally: the single-vault refund path\n * reconstructs only one hashlock and expects the anchor at vout 1, so\n * any other vout signals a layout this call cannot safely refund.\n */\nexport function findAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n): { vout: number; hash: string } | undefined {\n let tx: bitcoin.Transaction;\n try {\n tx = bitcoin.Transaction.fromHex(stripHexPrefix(fundedPrePeginTxHex));\n } catch {\n return undefined;\n }\n\n const hits: { vout: number; hash: string }[] = [];\n for (let i = 0; i < tx.outs.length; i++) {\n const output = tx.outs[i];\n const script = output.script;\n if (\n script.length === OP_RETURN_PUSH32_SCRIPT_LEN &&\n script[0] === OP_RETURN &&\n script[1] === OP_PUSH32 &&\n output.value === 0\n ) {\n hits.push({\n vout: i,\n hash: script.slice(2).toString(\"hex\").toLowerCase(),\n });\n }\n }\n\n return hits.length === 1 ? hits[0] : undefined;\n}\n","/**\n * HTLC Secret / Hashlock Utilities\n *\n * Pure functions for computing and validating SHA-256 hashlocks used in the\n * vault deposit protocol's HTLC (Hash Time Lock Contract).\n *\n * The SDK does NOT generate secrets — that is the caller's responsibility.\n * Today callers use `crypto.getRandomValues(32)`; when the `deriveContextHash`\n * wallet API ships, callers will use `wallet.deriveContextHash(\"babylon-btc-vault\", ctx)`.\n * These utilities work identically regardless of how the secret was produced.\n *\n * On-chain contract validation (BTCVaultRegistry.activateVaultWithSecret):\n * if (sha256(abi.encodePacked(s)) != hashlock) revert InvalidSecret();\n *\n * @module htlc\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport type { Hex } from \"viem\";\n\n/** Expected hex length for a 0x-prefixed bytes32 value. */\nconst HEX_BYTES32_LENGTH = 66; // \"0x\" + 64 hex chars\n\n/**\n * Decode a 0x-prefixed hex string to bytes, with strict validation.\n * @throws if the input is not a valid 0x-prefixed hex string\n */\nfunction hexToBytes(hex: Hex): Uint8Array {\n if (!hex.startsWith(\"0x\") && !hex.startsWith(\"0X\")) {\n throw new Error(\"Expected 0x-prefixed hex string\");\n }\n const clean = hex.slice(2);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has odd length: ${clean.length}`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error(\"Hex string contains non-hex characters\");\n }\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Encode a Uint8Array as a 0x-prefixed lowercase hex string.\n */\nfunction bytesToHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\n/**\n * Validate that a value is a 0x-prefixed bytes32 (exactly 32 bytes).\n * @throws if the value is not exactly 32 bytes\n */\nfunction assertBytes32(value: Hex, label: string): void {\n if (value.length !== HEX_BYTES32_LENGTH) {\n throw new Error(\n `${label} must be exactly 32 bytes (${HEX_BYTES32_LENGTH} hex chars with 0x prefix), got ${value.length}`,\n );\n }\n}\n\n/**\n * Compute the SHA-256 hashlock from a secret preimage.\n *\n * Matches the on-chain validation: `sha256(abi.encodePacked(s))` where `s` is a `bytes32`.\n * `abi.encodePacked(bytes32)` is just the raw 32 bytes — no ABI padding.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @returns 0x-prefixed bytes32 SHA-256 hash\n * @throws if secret is not exactly 32 bytes\n */\nexport function computeHashlock(secret: Hex): Hex {\n assertBytes32(secret, \"Secret\");\n const secretBytes = hexToBytes(secret);\n const hash = sha256(secretBytes);\n return bytesToHex(hash);\n}\n\n/**\n * Validate that a secret's SHA-256 hash matches the expected hashlock.\n *\n * Use this for client-side pre-validation before sending the activation\n * transaction to avoid wasting gas on a contract revert.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @param hashlock - 0x-prefixed bytes32 expected hashlock from the vault\n * @returns true if SHA-256(secret) matches the hashlock\n * @throws if secret or hashlock is not exactly 32 bytes\n */\nexport function validateSecretAgainstHashlock(\n secret: Hex,\n hashlock: Hex,\n): boolean {\n assertBytes32(secret, \"Secret\");\n assertBytes32(hashlock, \"Hashlock\");\n // Validate hashlock is valid hex (secret is validated inside computeHashlock)\n hexToBytes(hashlock);\n\n const computed = computeHashlock(secret);\n return computed.toLowerCase() === hashlock.toLowerCase();\n}\n","import type { BitcoinWallet } from \"../../../shared/wallets/interfaces\";\n\n// Field docs use /** */ so they survive into the emitted .d.ts — the published\n// package is the only contract the external provider author (#2109) sees.\n\nexport interface DepositTermsVaultGroup {\n /** 0-based; equals the group's position (groups are ascending by vout). */\n readonly htlcVout: number;\n /** x-only hex (64 chars), as validated on-chain upstream. */\n readonly vaultProviderBtcPubkey: string;\n /** sats */\n readonly peginAmount: bigint;\n /**\n * sats; the MAXIMUM commission the depositor accepts —\n * floor(peginAmount * maxAcceptableCommissionBps / 10_000), the same\n * ceiling the registration calldata carries. An approving wallet MUST\n * enforce the VP payout commission output `<= commissionFee` (e.g. the\n * Ledger vault app does, firmware >= c8db53e), and every commission the\n * contract admits stays under this ceiling (floor is monotonic in bps),\n * so no contract-admitted deposit can be refused at payout. The actual\n * stamped commission may be lower. Display the quoted value in UI, not this.\n */\n readonly commissionFee: bigint;\n /** sats; the same value for every vault. */\n readonly depositorClaimValue: bigint;\n /**\n * sats; the cap an approving wallet enforces on the PegIn tx fee. Equals\n * the graph's exact (minimum) PegIn fee, which is deterministic — so the\n * cap is satisfied exact-by-construction.\n */\n readonly peginMaxFee: bigint;\n}\n\n/**\n * Field names follow btc-vault vocabulary (the protocol source of truth);\n * a device-wire encoder maps them to its intent fields (e.g. the Ledger TLV:\n * protocolFeeRate -> base_fee_rate, timelockPegin -> pegin_csv_timelock,\n * timelockAssert -> payout_timelock, peginAmount -> vault_amount).\n */\nexport interface DepositTerms {\n /**\n * btc-vault tx-graph version (`vaultCoreVersion`) these terms describe —\n * the vault's stamped on-chain version for resumes, the chain's\n * `activeVaultCoreVersion` for fresh deposits. It selects the PegIn shape\n * an approving wallet must expect: v1 = 2 outputs, no anchor; v2/v3 = TRUC\n * nVersion 3, 3 outputs with a 240-sat P2A anchor at vout 2, and an\n * Assert OP_RETURN marker that raises the claim value\n * (btc-vault `transactions/pegin.rs`, `assert_marker.rs`). A provider that\n * supports only one shape MUST reject the others here rather than\n * mis-validating the PSBTs later.\n */\n vaultCoreVersion: number;\n /**\n * sat/vB; the tx-graph fee rate (protocolFeeRate), NOT the mempool funding\n * rate. Approving wallets bound each payout's fee against this rate —\n * pass the exact graph rate, not an inflated ceiling.\n */\n protocolFeeRate: bigint;\n /** Vault-UTXO CSV timelock (blocks). */\n timelockPegin: number;\n /**\n * btc-vault `timelock_assert` (t2) — the CSV on Assert output 0. Its own\n * param, though production derives it and `timelockPegin` from one value.\n */\n timelockAssert: number;\n /** HTLC refund CSV timelock (blocks). */\n timelockRefund: number;\n /**\n * 64-char hex in display order. A device-wire encoder may need the\n * little-endian form — some hardware byte-compares it against\n * PSBT_IN_PREVIOUS_TXID rather than recomputing the txid.\n */\n prepeginTxid: string;\n /** sats; the funded Pre-PegIn fee (an approving wallet caps the signed fee at this). */\n prepeginMaxFee: bigint;\n /**\n * x-only hex. Sorted ascending by the upstream on-chain validation\n * (validateOnChainParticipantKeys); the builder passes them through\n * unasserted — approving devices may reject unsorted lists at load.\n */\n vaultKeeperBtcPubkeys: readonly string[];\n /**\n * x-only hex, sorted ascending upstream independently of vaultKeeperBtcPubkeys (same\n * pass-through contract). Universal challengers only — the full graph\n * challenger set is vaultKeeperBtcPubkeys ∪ universalChallengerBtcPubkeys (vault keepers are the local\n * challengers).\n */\n universalChallengerBtcPubkeys: readonly string[];\n /** Per-vault groups, ordered by ascending htlcVout. */\n vaults: readonly DepositTermsVaultGroup[];\n}\n\n/**\n * Implemented only by depositor-approval wallets (e.g. a Ledger vault\n * provider). Provider obligations:\n *\n * - Envelope: validate terms against the device's envelope BEFORE the\n * ceremony, rejecting with the shape `{ name: \"DepositTermsRejectedError\",\n * reason: \"device-envelope\", message }` (matched structurally, not by class).\n * - Idempotence: a byte-equal re-approval MUST be a no-op while the\n * device-side approval is live; anything that invalidates it (a later\n * `deriveContextHash`, a signing failure) MUST clear the memo.\n *\n * Seam invariant: any derive invalidates a prior approval, so the SDK\n * re-approves after every derive and before the next terms-bound signature.\n * The re-approval sites are `PeginManager.preparePegin`,\n * `runDepositorPresignFlow`, and `signAndBroadcast` (the Pre-PegIn broadcast,\n * which re-derives before approving unless `holdsApprovedDepositTerms`\n * reports the byte-equal intent still live — see `ensurePrePeginTermsApproval`).\n */\nexport interface DepositTermsApprover {\n approveDepositTerms(terms: DepositTerms): Promise<void>;\n /**\n * OPTIONAL fast-path probe: can the Pre-PegIn signature for exactly these\n * terms proceed under the connection's held approval without a new\n * ceremony? MUST report false once that Pre-PegIn was signed (one-shot),\n * MUST answer from host state without device I/O, MUST return false on any\n * doubt, and MUST never throw. A stale true fails closed at the next\n * signature — this is a UX optimization, never an authorization.\n */\n holdsApprovedDepositTerms?(terms: DepositTerms): Promise<boolean>;\n}\n\n/**\n * Where Pre-PegIn change must pay. Approval (policy) wallets sign key-path\n * under a wallet policy whose change branch the device alone can derive and\n * mark internal — the receive address is NOT acceptable change\n * (`process_in_outs.c:114-117` @ e400d8d8).\n *\n * Separate from {@link DepositTermsApprover} because only the Pre-PegIn build\n * needs it: the presign/payout ceremonies approve terms without ever creating\n * change, so they must not require a wallet to implement this.\n *\n * MUST be stable across a deposit flow: the app reads it to build the tx and\n * `preparePegin` re-reads it to verify, so mid-flow rotation fails that gate.\n */\nexport interface PrePeginChangeSource {\n getChangeAddress(): Promise<string>;\n}\n\n/** Probes {@link DepositTermsApprover.approveDepositTerms}. */\nexport function supportsDepositApproval(\n wallet: BitcoinWallet,\n): wallet is BitcoinWallet & DepositTermsApprover {\n return (\n typeof (wallet as Partial<DepositTermsApprover>).approveDepositTerms ===\n \"function\"\n );\n}\n\n/**\n * The wallet's change address, for the one caller that needs it.\n *\n * Narrowing on `approveDepositTerms` alone cannot promise this method, so\n * calling it off the narrowed value would die on `is not a function` in the\n * middle of `preparePegin`, after the pubkey read. Ask here instead and fail\n * with something a provider author can act on.\n *\n * @throws If the wallet cannot report a change address.\n */\nexport async function requireChangeAddress(\n wallet: BitcoinWallet,\n): Promise<string> {\n const changeSource = wallet as Partial<PrePeginChangeSource>;\n if (typeof changeSource.getChangeAddress !== \"function\") {\n throw new Error(\n \"Approval wallet does not implement getChangeAddress; it must expose its change branch, \" +\n \"because the signing device accepts Pre-PegIn change only there.\",\n );\n }\n return changeSource.getChangeAddress();\n}\n\n/**\n * Spreadable forward of the approval capability for wallet-wrapper objects.\n * Object spread drops prototype methods, so every `{...wallet}` wrapper site\n * must re-attach the capability explicitly: `...forwardDepositApproval(wallet)`.\n */\nexport function forwardDepositApproval(\n wallet: BitcoinWallet,\n): Partial<DepositTermsApprover & PrePeginChangeSource> {\n if (!supportsDepositApproval(wallet)) {\n return {};\n }\n const holdsApprovedDepositTerms = wallet.holdsApprovedDepositTerms;\n const getChangeAddress = (wallet as Partial<PrePeginChangeSource>)\n .getChangeAddress;\n return {\n approveDepositTerms: (terms) => wallet.approveDepositTerms(terms),\n // Both optional in the seam: forward only what the provider implements, so\n // wrapper consumers can keep probing by typeof.\n ...(typeof getChangeAddress === \"function\"\n ? { getChangeAddress: () => getChangeAddress.call(wallet) }\n : {}),\n ...(typeof holdsApprovedDepositTerms === \"function\"\n ? {\n holdsApprovedDepositTerms: (terms: DepositTerms) =>\n holdsApprovedDepositTerms.call(wallet, terms),\n }\n : {}),\n };\n}\n\nexport interface BuildDepositTermsInputs {\n /** btc-vault tx-graph version the graph is built under. */\n vaultCoreVersion: number;\n protocolFeeRate: bigint;\n timelockPegin: number;\n /** btc-vault `timelock_assert` (t2) — its own param; NOT derived from timelockPegin here. */\n timelockAssert: number;\n timelockRefund: number;\n prepeginTxid: string;\n prepeginMaxFee: bigint;\n vaultProviderBtcPubkey: string;\n vaultKeeperBtcPubkeys: readonly string[];\n universalChallengerBtcPubkeys: readonly string[];\n /** Ceiling bps, not the quote — see {@link DepositTermsVaultGroup.commissionFee}. */\n maxAcceptableCommissionBps: number;\n peginAmounts: readonly bigint[];\n depositorClaimValue: bigint;\n peginMaxFee: bigint;\n}\n","/**\n * Payout Manager\n *\n * High-level manager that orchestrates the payout signing flow by coordinating\n * SDK primitives ({@link buildPayoutPsbt}, {@link extractPayoutSignature})\n * with a user-provided Bitcoin wallet.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @see {@link PeginManager} - For Steps 1–4 of the peg-in flow\n * @see {@link buildPayoutPsbt} - Lower-level primitive for custom implementations\n * @see {@link extractPayoutSignature} - Extract signatures from signed PSBTs\n *\n * @module managers/PayoutManager\n */\n\nimport type { BitcoinWallet, SignPsbtOptions } from \"../../../shared/wallets\";\nimport {\n assertPsbtUnsignedTxMatches,\n assertScriptPathSchnorrSignature,\n buildPayoutPsbt,\n extractPayoutSignature,\n validateWalletPubkey,\n type Network,\n} from \"../primitives\";\nimport { createTaprootScriptPathSignOptions } from \"../utils/signing\";\n\n/** Payout PSBTs are signed by the depositor on input 0 (Taproot script-path). */\nconst PAYOUT_SIGNED_INPUT_INDEX = 0;\n\n/**\n * Configuration for the PayoutManager.\n */\nexport interface PayoutManagerConfig {\n /**\n * Bitcoin network to use for transactions.\n */\n network: Network;\n\n /**\n * Bitcoin wallet for signing payout transactions.\n */\n btcWallet: BitcoinWallet;\n}\n\n/**\n * Base parameters shared by both payout transaction types.\n */\ninterface SignPayoutBaseParams {\n /**\n * Vault core (tx-graph) version the vault was registered under — the\n * vault's stamped on-chain `vaultCoreVersion`. Forwarded to\n * {@link buildPayoutPsbt} to derive the matching graph's payout scripts.\n */\n vaultCoreVersion: number;\n\n /**\n * Peg-in transaction hex.\n * The original transaction that created the vault output being spent.\n */\n peginTxHex: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex).\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex).\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex).\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n /** btc-vault `timelock_assert`; payout input 1's sequence. */\n timelockAssert: number;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex). This MUST be the\n * key registered on-chain for the vault — typically read from\n * `BTCVaultRegistry.getBtcVaultBasicInfo(...).depositorBtcPubKey`.\n *\n * Required: omitting it would degrade `validateWalletPubkey` to a\n * self-comparison, allowing the wrong wallet to produce a signature\n * over a script tree that doesn't match the on-chain UTXO.\n */\n depositorBtcPubkey: string;\n\n /**\n * The on-chain registered depositor payout scriptPubKey (hex, with or without 0x prefix).\n * Used to validate that the VP-provided payout transaction actually pays to the\n * correct depositor payout address before signing.\n */\n registeredPayoutScriptPubKey: string;\n\n /**\n * The claimer's x-only BTC public key for this payout (64-char hex, no prefix).\n * Forwarded to {@link buildPayoutPsbt} for per-role output validation.\n */\n claimerBtcPubkey: string;\n\n /**\n * VP commission in basis points (`1..=9999`). Forwarded to {@link buildPayoutPsbt}.\n */\n commissionBps: number;\n\n /**\n * Version-locked tx-graph fee rate (sat/vB) the graph was built with.\n * Forwarded to {@link buildPayoutPsbt} for the fee band.\n */\n protocolFeeRate: bigint;\n\n /**\n * Security council member x-only pubkeys (hex); forwarded to\n * {@link buildPayoutPsbt} to rebuild the Assert:0 payout leaf and to size the\n * fee floor (see PayoutParams).\n */\n councilMembers: string[];\n\n /** M-of-N council quorum; shapes the Assert:0 council leaf (see PayoutParams). */\n councilQuorum: number;\n\n /**\n * RFC-006 resolved payout destinations, keyed by lowercased x-only operation\n * pubkey. Forwarded verbatim to {@link buildPayoutPsbt}; every VK claimer\n * must be present.\n */\n vkClaimerPayoutScriptPubKeys: Readonly<Record<string, string>>;\n /** RFC-006 VP commission destination. Forwarded to {@link buildPayoutPsbt}. */\n vpCommissionScriptPubKey: string;\n}\n\n/**\n * Parameters for signing a Payout transaction.\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface SignPayoutParams extends SignPayoutBaseParams {\n /**\n * Payout transaction hex (unsigned).\n * This is the transaction from the vault provider that needs depositor signature.\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex.\n * Payout input 1 references Assert output 0.\n */\n assertTxHex: string;\n}\n\n/**\n * Result of signing a payout transaction.\n */\nexport interface PayoutSignatureResult {\n /**\n * 64-byte Schnorr signature (128 hex characters).\n */\n signature: string;\n\n /**\n * Depositor's BTC public key used for signing.\n */\n depositorBtcPubkey: string;\n}\n\n/**\n * High-level manager for payout transaction signing.\n *\n * @remarks\n * After registering your peg-in on Ethereum (Step 3), the vault provider prepares\n * claim/payout transaction pairs. You must sign each payout transaction using this\n * manager and submit the signatures to the vault provider's RPC API.\n *\n * **What happens internally:**\n * 1. Validates your wallet's public key matches the vault's depositor\n * 2. Builds an unsigned PSBT with taproot script path spend info\n * 3. Signs input 0 (the vault UTXO) with your wallet\n * 4. Extracts the 64-byte Schnorr signature\n *\n * **Note:** The payout transaction has 2 inputs. PayoutManager only signs input 0\n * (from the peg-in tx). Input 1 (from the assert tx) is signed by the vault provider.\n *\n * @see {@link PeginManager} - For the complete peg-in flow context\n * @see {@link buildPayoutPsbt} - Lower-level primitive used internally\n * @see {@link extractPayoutSignature} - Signature extraction primitive\n */\nexport class PayoutManager {\n private readonly config: PayoutManagerConfig;\n\n /**\n * Creates a new PayoutManager instance.\n *\n * @param config - Manager configuration including wallet\n */\n constructor(config: PayoutManagerConfig) {\n this.config = config;\n }\n\n /**\n * Signs a Payout transaction and extracts the Schnorr signature.\n *\n * Flow:\n * 1. Vault provider submits Claim transaction\n * 2. Claimer submits Assert transaction to prove validity\n * 3. Payout can be executed (references Assert tx)\n *\n * This method orchestrates the following steps:\n * 1. Get wallet's public key and convert to x-only format\n * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)\n * 3. Build unsigned PSBT using primitives\n * 4. Sign PSBT via btcWallet.signPsbt()\n * 5. Extract 64-byte Schnorr signature using primitives\n *\n * The returned signature can be submitted to the vault provider API.\n *\n * @param params - Payout signing parameters\n * @returns Signature result with 64-byte Schnorr signature and depositor pubkey\n * @throws Error if wallet pubkey doesn't match depositor pubkey\n * @throws Error if wallet operations fail or signature extraction fails\n */\n async signPayoutTransaction(\n params: SignPayoutParams,\n ): Promise<PayoutSignatureResult> {\n // Validate wallet pubkey matches depositor and get both formats\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n params.depositorBtcPubkey,\n );\n\n // Build unsigned PSBT for Payout (uses Assert tx). Per-role output\n // validation happens inside buildPayoutPsbt against the resolved input\n // values.\n const payoutPsbt = await buildPayoutPsbt({\n vaultCoreVersion: params.vaultCoreVersion,\n payoutTxHex: params.payoutTxHex,\n peginTxHex: params.peginTxHex,\n assertTxHex: params.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: params.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: params.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n timelockAssert: params.timelockAssert,\n network: this.config.network,\n claimerBtcPubkey: params.claimerBtcPubkey,\n registeredPayoutScriptPubKey: params.registeredPayoutScriptPubKey,\n commissionBps: params.commissionBps,\n protocolFeeRate: params.protocolFeeRate,\n councilMembers: params.councilMembers,\n councilQuorum: params.councilQuorum,\n vkClaimerPayoutScriptPubKeys: params.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: params.vpCommissionScriptPubKey,\n });\n\n // Sign PSBT via wallet (Taproot script-path spend, input 0 only)\n const signedPsbtHex = await this.config.btcWallet.signPsbt(\n payoutPsbt.psbtHex,\n createTaprootScriptPathSignOptions(walletPubkeyRaw, 1),\n );\n\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: payoutPsbt.psbtHex,\n returnedPsbtHex: signedPsbtHex,\n });\n\n // Extract Schnorr signature\n const signature = extractPayoutSignature(signedPsbtHex, depositorPubkey);\n // Critical Path #7: verify the signature against a sighash recomputed from\n // the PSBT we built, not the wallet-returned one.\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: payoutPsbt.psbtHex,\n signatureHex: signature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: PAYOUT_SIGNED_INPUT_INDEX,\n });\n\n return {\n signature,\n depositorBtcPubkey: depositorPubkey,\n };\n }\n\n /**\n * Gets the configured Bitcoin network.\n *\n * @returns The Bitcoin network (mainnet, testnet, signet, regtest)\n */\n getNetwork(): Network {\n return this.config.network;\n }\n\n /**\n * Checks if the wallet supports batch signing (signPsbts).\n *\n * @returns true if batch signing is supported\n */\n supportsBatchSigning(): boolean {\n return typeof this.config.btcWallet.signPsbts === \"function\";\n }\n\n /**\n * Batch signs multiple payout transactions (1 per claimer).\n * This allows signing all transactions with a single wallet interaction.\n *\n * @param transactions - Array of payout params to sign\n * @returns Array of signature results matching input order\n * @throws Error if wallet doesn't support batch signing\n * @throws Error if any signing operation fails\n */\n async signPayoutTransactionsBatch(transactions: SignPayoutParams[]): Promise<\n Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }>\n > {\n if (!this.supportsBatchSigning()) {\n throw new Error(\n \"Wallet does not support batch signing (signPsbts method not available)\",\n );\n }\n\n // Get wallet pubkey once\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n\n // Build all PSBTs (1 per claimer)\n const psbtsToSign: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n const depositorPubkeys: string[] = [];\n\n for (const tx of transactions) {\n // Validate wallet pubkey matches depositor\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n tx.depositorBtcPubkey,\n );\n depositorPubkeys.push(depositorPubkey);\n\n // Build Payout PSBT (output validation runs inside buildPayoutPsbt\n // against resolved input values).\n const payoutPsbt = await buildPayoutPsbt({\n vaultCoreVersion: tx.vaultCoreVersion,\n payoutTxHex: tx.payoutTxHex,\n peginTxHex: tx.peginTxHex,\n assertTxHex: tx.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: tx.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: tx.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: tx.universalChallengerBtcPubkeys,\n timelockPegin: tx.timelockPegin,\n timelockAssert: tx.timelockAssert,\n network: this.config.network,\n claimerBtcPubkey: tx.claimerBtcPubkey,\n registeredPayoutScriptPubKey: tx.registeredPayoutScriptPubKey,\n commissionBps: tx.commissionBps,\n protocolFeeRate: tx.protocolFeeRate,\n councilMembers: tx.councilMembers,\n councilQuorum: tx.councilQuorum,\n vkClaimerPayoutScriptPubKeys: tx.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: tx.vpCommissionScriptPubKey,\n });\n psbtsToSign.push(payoutPsbt.psbtHex);\n signOptions.push(createTaprootScriptPathSignOptions(walletPubkeyRaw, 1));\n }\n\n // Batch sign all PSBTs with single wallet interaction\n const signedPsbts = await this.config.btcWallet.signPsbts!(\n psbtsToSign,\n signOptions,\n );\n\n // Validate that wallet returned the expected number of signed PSBTs\n if (signedPsbts.length !== transactions.length) {\n throw new Error(\n `Expected ${transactions.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n\n // Extract signatures from signed PSBTs\n const results: Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }> = [];\n\n for (let i = 0; i < transactions.length; i++) {\n const depositorPubkey = depositorPubkeys[i];\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: psbtsToSign[i],\n returnedPsbtHex: signedPsbts[i],\n });\n const payoutSignature = extractPayoutSignature(\n signedPsbts[i],\n depositorPubkey,\n );\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: psbtsToSign[i],\n signatureHex: payoutSignature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: PAYOUT_SIGNED_INPUT_INDEX,\n });\n\n results.push({\n payoutSignature,\n depositorBtcPubkey: depositorPubkey,\n });\n }\n\n return results;\n }\n}\n","/**\n * Wallet-signing helper that routes a lone PSBT to `signPsbt`, prefers native\n * `signPsbts` for real batches, and falls back to sequential `signPsbt` for\n * wallets that don't implement batch signing.\n *\n * @module managers/pegin/signPsbtsWithFallback\n */\n\nimport type {\n BitcoinWallet,\n SignPsbtOptions,\n} from \"../../../../shared/wallets\";\n\n/**\n * Sign one or more PSBTs against a wallet.\n *\n * A single PSBT is always signed via `signPsbt`, never the batch endpoint: it's\n * one wallet interaction either way, and `signPsbt` is the universally-required\n * wallet method (batch `signPsbts` is optional), so single-sign is the portable\n * choice — some integrations (notably MPC / institutional wallets) prefer it.\n * For a real batch (>1), wallets exposing native `signPsbts` (e.g. UniSat) sign\n * in one interaction; others loop `signPsbt`.\n *\n * @throws If native `signPsbts` returns a different number of signed PSBTs\n * than were submitted.\n */\nexport async function signPsbtsWithFallback(\n wallet: BitcoinWallet,\n psbtsHexes: string[],\n options?: SignPsbtOptions[],\n): Promise<string[]> {\n if (psbtsHexes.length === 1) {\n return [await wallet.signPsbt(psbtsHexes[0], options?.[0])];\n }\n\n if (typeof wallet.signPsbts === \"function\") {\n const signedPsbts = await wallet.signPsbts(psbtsHexes, options);\n if (signedPsbts.length !== psbtsHexes.length) {\n throw new Error(\n `Expected ${psbtsHexes.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n return signedPsbts;\n }\n\n const signedPsbts: string[] = [];\n for (let i = 0; i < psbtsHexes.length; i++) {\n signedPsbts.push(await wallet.signPsbt(psbtsHexes[i], options?.[i]));\n }\n return signedPsbts;\n}\n"],"names":["OP_RETURN","OP_PUSH32","OP_RETURN_PUSH32_SCRIPT_LEN","assertAuthAnchorOpReturn","fundedPrePeginTxHex","vaultCount","expectedAuthAnchorHashHex","cleanHex","stripHexPrefix","tx","bitcoin","opReturnOutput","script","pushedHex","findAuthAnchorOpReturn","hits","i","output","HEX_BYTES32_LENGTH","hexToBytes","hex","clean","bytes","bytesToHex","b","assertBytes32","value","label","computeHashlock","secret","secretBytes","hash","sha256","validateSecretAgainstHashlock","hashlock","supportsDepositApproval","wallet","requireChangeAddress","changeSource","forwardDepositApproval","holdsApprovedDepositTerms","getChangeAddress","terms","PAYOUT_SIGNED_INPUT_INDEX","PayoutManager","config","__publicField","params","walletPubkeyRaw","depositorPubkey","validateWalletPubkey","payoutPsbt","buildPayoutPsbt","signedPsbtHex","createTaprootScriptPathSignOptions","assertPsbtUnsignedTxMatches","signature","extractPayoutSignature","assertScriptPathSchnorrSignature","transactions","psbtsToSign","signOptions","depositorPubkeys","signedPsbts","results","payoutSignature","signPsbtsWithFallback","psbtsHexes","options"],"mappings":";;;;;;;;;AAYA,MAAMA,IAAY,KAEZC,IAAY,IAEZC,IAA8B;AAmB7B,SAASC,EACdC,GACAC,GACAC,GACM;AACN,QAAMC,IAAWC,EAAeJ,CAAmB,GAC7CK,IAAKC,EAAQ,YAAY,QAAQH,CAAQ;AAE/C,MAAIE,EAAG,KAAK,UAAUJ;AACpB,UAAM,IAAI;AAAA,MACR,mDAAmDI,EAAG,KAAK,MAAM,+BACjCJ,IAAa,CAAC;AAAA,IAAA;AAIlD,QAAMM,IAAiBF,EAAG,KAAKJ,CAAU,GACnCO,IAASD,EAAe;AAC9B,MACEC,EAAO,WAAWV,KAClBU,EAAO,CAAC,MAAMZ,KACdY,EAAO,CAAC,MAAMX;AAEd,UAAM,IAAI;AAAA,MACR,2CAA2CI,CAAU,wCAC3BO,EAAO,MAAM,8BAChCA,EAAO,MAAM,GAAG,KAAK,IAAI,GAAGA,EAAO,MAAM,CAAC,EAAE,SAAS,KAAK,CAAC,cACpDV,CAA2B;AAAA,IAAA;AAI7C,QAAMW,IAAYD,EAAO,MAAM,CAAC,EAAE,SAAS,KAAK,EAAE,YAAA;AAClD,MAAIC,MAAcP,EAA0B;AAC1C,UAAM,IAAI;AAAA,MACR,4DAA4DD,CAAU,eACvDQ,CAAS,cAAcP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AAC,MAAM/B,EAAO,SAAS+B,EAAW,CAAC,GAAGC,KAAA,gBAAAA,EAAU,EAAE,CAAC;AAG5D,MAAI,OAAOhC,EAAO,aAAc,YAAY;AAC1C,UAAM2B,IAAc,MAAM3B,EAAO,UAAU+B,GAAYC,CAAO;AAC9D,QAAIL,EAAY,WAAWI,EAAW;AACpC,YAAM,IAAI;AAAA,QACR,YAAYA,EAAW,MAAM,8BAA8BJ,EAAY,MAAM;AAAA,MAAA;AAGjF,WAAOA;AAAAA,EACT;AAEA,QAAMA,IAAwB,CAAA;AAC9B,WAAS/C,IAAI,GAAGA,IAAImD,EAAW,QAAQnD;AACrC,IAAA+C,EAAY,KAAK,MAAM3B,EAAO,SAAS+B,EAAWnD,CAAC,GAAGoD,KAAA,gBAAAA,EAAUpD,EAAE,CAAC;AAErE,SAAO+C;AACT;"}
@@ -0,0 +1,2 @@
1
+ "use strict";var T=Object.defineProperty;var H=(t,e,r)=>e in t?T(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var b=(t,e,r)=>H(t,typeof e!="symbol"?e+"":e,r);const B=require("bitcoinjs-lib"),h=require("./bitcoin-m84N5a8o.cjs"),A=require("./sha2-DsrLC4NM.cjs");require("@babylonlabs-io/babylon-tbv-rust-wasm");const u=require("./verifyScriptPathSchnorrSignature-la8XOAFm.cjs"),y=require("./signing-Bnsro0hE.cjs");function E(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const o=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,o.get?o:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const x=E(B),k=106,v=32,p=34;function R(t,e,r){const o=h.stripHexPrefix(t),s=x.Transaction.fromHex(o);if(s.outs.length<=e)throw new Error(`Pre-PegIn auth-anchor OP_RETURN missing: tx has ${s.outs.length} outputs, expected at least ${e+1} (vault outputs + OP_RETURN)`);const c=s.outs[e],i=c.script;if(i.length!==p||i[0]!==k||i[1]!==v)throw new Error(`Pre-PegIn auth-anchor OP_RETURN at vout ${e} has unexpected script encoding (got ${i.length}-byte script with prefix 0x${i.slice(0,Math.min(2,i.length)).toString("hex")}; expected ${p}-byte OP_RETURN + PUSH32 layout)`);const l=i.slice(2).toString("hex").toLowerCase();if(l!==r.toLowerCase())throw new Error(`Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${e}: tx pushes ${l}, expected ${r}`);if(c.value!==0)throw new Error(`Pre-PegIn auth-anchor OP_RETURN at vout ${e} has non-zero value ${c.value}; OP_RETURN outputs must be 0-value`)}function O(t){let e;try{e=x.Transaction.fromHex(h.stripHexPrefix(t))}catch{return}const r=[];for(let o=0;o<e.outs.length;o++){const s=e.outs[o],c=s.script;c.length===p&&c[0]===k&&c[1]===v&&s.value===0&&r.push({vout:o,hash:c.slice(2).toString("hex").toLowerCase()})}return r.length===1?r[0]:void 0}const d=66;function m(t){if(!t.startsWith("0x")&&!t.startsWith("0X"))throw new Error("Expected 0x-prefixed hex string");const e=t.slice(2);if(e.length%2!==0)throw new Error(`Hex string has odd length: ${e.length}`);if(!/^[0-9a-fA-F]*$/.test(e))throw new Error("Hex string contains non-hex characters");const r=new Uint8Array(e.length/2);for(let o=0;o<r.length;o++)r[o]=parseInt(e.slice(o*2,o*2+2),16);return r}function C(t){return`0x${Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}`}function P(t,e){if(t.length!==d)throw new Error(`${e} must be exactly 32 bytes (${d} hex chars with 0x prefix), got ${t.length}`)}function S(t){P(t,"Secret");const e=m(t),r=A.sha256(e);return C(r)}function $(t,e){return P(t,"Secret"),P(e,"Hashlock"),m(e),S(t).toLowerCase()===e.toLowerCase()}function w(t){return typeof t.approveDepositTerms=="function"}async function _(t){const e=t;if(typeof e.getChangeAddress!="function")throw new Error("Approval wallet does not implement getChangeAddress; it must expose its change branch, because the signing device accepts Pre-PegIn change only there.");return e.getChangeAddress()}function K(t){if(!w(t))return{};const e=t.holdsApprovedDepositTerms,r=t.getChangeAddress;return{approveDepositTerms:o=>t.approveDepositTerms(o),...typeof r=="function"?{getChangeAddress:()=>r.call(t)}:{},...typeof e=="function"?{holdsApprovedDepositTerms:o=>e.call(t,o)}:{}}}const f=0;class U{constructor(e){b(this,"config");this.config=e}async signPayoutTransaction(e){const r=await this.config.btcWallet.getPublicKeyHex(),{depositorPubkey:o}=h.validateWalletPubkey(r,e.depositorBtcPubkey),s=await u.buildPayoutPsbt({vaultCoreVersion:e.vaultCoreVersion,payoutTxHex:e.payoutTxHex,peginTxHex:e.peginTxHex,assertTxHex:e.assertTxHex,depositorBtcPubkey:o,vaultProviderBtcPubkey:e.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:e.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:e.universalChallengerBtcPubkeys,timelockPegin:e.timelockPegin,timelockAssert:e.timelockAssert,network:this.config.network,claimerBtcPubkey:e.claimerBtcPubkey,registeredPayoutScriptPubKey:e.registeredPayoutScriptPubKey,commissionBps:e.commissionBps,protocolFeeRate:e.protocolFeeRate,councilMembers:e.councilMembers,councilQuorum:e.councilQuorum,vkClaimerPayoutScriptPubKeys:e.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:e.vpCommissionScriptPubKey}),c=await this.config.btcWallet.signPsbt(s.psbtHex,y.createTaprootScriptPathSignOptions(r,1));u.assertPsbtUnsignedTxMatches({requestedPsbtHex:s.psbtHex,returnedPsbtHex:c});const i=u.extractPayoutSignature(c,o);return u.assertScriptPathSchnorrSignature({requestedPsbtHex:s.psbtHex,signatureHex:i,signerXOnlyPubkeyHex:o,inputIndex:f}),{signature:i,depositorBtcPubkey:o}}getNetwork(){return this.config.network}supportsBatchSigning(){return typeof this.config.btcWallet.signPsbts=="function"}async signPayoutTransactionsBatch(e){if(!this.supportsBatchSigning())throw new Error("Wallet does not support batch signing (signPsbts method not available)");const r=await this.config.btcWallet.getPublicKeyHex(),o=[],s=[],c=[];for(const n of e){const{depositorPubkey:a}=h.validateWalletPubkey(r,n.depositorBtcPubkey);c.push(a);const g=await u.buildPayoutPsbt({vaultCoreVersion:n.vaultCoreVersion,payoutTxHex:n.payoutTxHex,peginTxHex:n.peginTxHex,assertTxHex:n.assertTxHex,depositorBtcPubkey:a,vaultProviderBtcPubkey:n.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:n.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:n.universalChallengerBtcPubkeys,timelockPegin:n.timelockPegin,timelockAssert:n.timelockAssert,network:this.config.network,claimerBtcPubkey:n.claimerBtcPubkey,registeredPayoutScriptPubKey:n.registeredPayoutScriptPubKey,commissionBps:n.commissionBps,protocolFeeRate:n.protocolFeeRate,councilMembers:n.councilMembers,councilQuorum:n.councilQuorum,vkClaimerPayoutScriptPubKeys:n.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:n.vpCommissionScriptPubKey});o.push(g.psbtHex),s.push(y.createTaprootScriptPathSignOptions(r,1))}const i=await this.config.btcWallet.signPsbts(o,s);if(i.length!==e.length)throw new Error(`Expected ${e.length} signed PSBTs but received ${i.length}`);const l=[];for(let n=0;n<e.length;n++){const a=c[n];u.assertPsbtUnsignedTxMatches({requestedPsbtHex:o[n],returnedPsbtHex:i[n]});const g=u.extractPayoutSignature(i[n],a);u.assertScriptPathSchnorrSignature({requestedPsbtHex:o[n],signatureHex:g,signerXOnlyPubkeyHex:a,inputIndex:f}),l.push({payoutSignature:g,depositorBtcPubkey:a})}return l}}async function N(t,e,r){if(e.length===1)return[await t.signPsbt(e[0],r==null?void 0:r[0])];if(typeof t.signPsbts=="function"){const s=await t.signPsbts(e,r);if(s.length!==e.length)throw new Error(`Expected ${e.length} signed PSBTs but received ${s.length}`);return s}const o=[];for(let s=0;s<e.length;s++)o.push(await t.signPsbt(e[s],r==null?void 0:r[s]));return o}exports.PayoutManager=U;exports.assertAuthAnchorOpReturn=R;exports.computeHashlock=S;exports.findAuthAnchorOpReturn=O;exports.forwardDepositApproval=K;exports.requireChangeAddress=_;exports.signPsbtsWithFallback=N;exports.supportsDepositApproval=w;exports.validateSecretAgainstHashlock=$;
2
+ //# sourceMappingURL=signPsbtsWithFallback-DJ4kE9UI.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signPsbtsWithFallback-DJ4kE9UI.cjs","sources":["../src/tbv/core/managers/pegin/assertAuthAnchorOpReturn.ts","../src/tbv/core/services/htlc/index.ts","../src/tbv/core/deposit-terms/depositTerms.ts","../src/tbv/core/managers/PayoutManager.ts","../src/tbv/core/managers/pegin/signPsbtsWithFallback.ts"],"sourcesContent":["/**\n * Structural verifier for the auth-anchor OP_RETURN in a funded\n * Pre-PegIn transaction.\n *\n * @module managers/pegin/assertAuthAnchorOpReturn\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\n\n/** OP_RETURN opcode. */\nconst OP_RETURN = 0x6a;\n/** Push-32-bytes opcode (raw push, not OP_PUSHDATA1). */\nconst OP_PUSH32 = 0x20;\n/** Encoded length of a standard OP_RETURN script with a 32-byte payload. */\nconst OP_RETURN_PUSH32_SCRIPT_LEN = 1 + 1 + 32;\n\n/**\n * Verify the broadcast Pre-PegIn carries the expected OP_RETURN\n * commitment to the auth anchor.\n *\n * The OP_RETURN sits at `vout = vaultCount` (right after the per-vault\n * HTLC outputs and before the depositor-claim/change outputs) and\n * pushes the 32-byte `SHA256(authAnchor)`. The script encoding is\n * exactly `OP_RETURN || PUSH32 || <32 bytes>` (34 bytes). A\n * non-conformant WASM build that omitted the OP_RETURN, swapped its\n * position, or changed its push payload would let the depositor\n * obtain a valid bearer token for a Pre-PegIn whose on-chain\n * commitment doesn't actually bind the anchor — degrading the auth\n * from on-chain-bound to a shared secret. Fail closed.\n *\n * @throws If the OP_RETURN is missing, mis-located, mis-encoded, or\n * pushes a payload other than `expectedAuthAnchorHashHex`.\n */\nexport function assertAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n vaultCount: number,\n expectedAuthAnchorHashHex: string,\n): void {\n const cleanHex = stripHexPrefix(fundedPrePeginTxHex);\n const tx = bitcoin.Transaction.fromHex(cleanHex);\n\n if (tx.outs.length <= vaultCount) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN missing: tx has ${tx.outs.length} ` +\n `outputs, expected at least ${vaultCount + 1} (vault outputs + OP_RETURN)`,\n );\n }\n\n const opReturnOutput = tx.outs[vaultCount];\n const script = opReturnOutput.script;\n if (\n script.length !== OP_RETURN_PUSH32_SCRIPT_LEN ||\n script[0] !== OP_RETURN ||\n script[1] !== OP_PUSH32\n ) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has unexpected ` +\n `script encoding (got ${script.length}-byte script with prefix ` +\n `0x${script.slice(0, Math.min(2, script.length)).toString(\"hex\")}; ` +\n `expected ${OP_RETURN_PUSH32_SCRIPT_LEN}-byte OP_RETURN + PUSH32 layout)`,\n );\n }\n\n const pushedHex = script.slice(2).toString(\"hex\").toLowerCase();\n if (pushedHex !== expectedAuthAnchorHashHex.toLowerCase()) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${vaultCount}: ` +\n `tx pushes ${pushedHex}, expected ${expectedAuthAnchorHashHex}`,\n );\n }\n\n if (opReturnOutput.value !== 0) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has non-zero ` +\n `value ${opReturnOutput.value}; OP_RETURN outputs must be 0-value`,\n );\n }\n}\n\n/**\n * Scan a funded Pre-PegIn transaction for its auth-anchor commitment\n * (an `OP_RETURN || PUSH32 || <32 bytes>` output with value 0).\n *\n * Returns `{ vout, hash }` when exactly one such output is found.\n * Returns `undefined` when:\n * - the hex is unparseable,\n * - no matching output exists (legacy non-auth-anchored Pre-PegIn),\n * - more than one matching output exists (ambiguous / malformed).\n *\n * Used by the refund orchestrator to (a) locate the on-chain anchor\n * regardless of how many HTLCs preceded it and (b) detect multi-vault\n * funded transactions structurally: the single-vault refund path\n * reconstructs only one hashlock and expects the anchor at vout 1, so\n * any other vout signals a layout this call cannot safely refund.\n */\nexport function findAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n): { vout: number; hash: string } | undefined {\n let tx: bitcoin.Transaction;\n try {\n tx = bitcoin.Transaction.fromHex(stripHexPrefix(fundedPrePeginTxHex));\n } catch {\n return undefined;\n }\n\n const hits: { vout: number; hash: string }[] = [];\n for (let i = 0; i < tx.outs.length; i++) {\n const output = tx.outs[i];\n const script = output.script;\n if (\n script.length === OP_RETURN_PUSH32_SCRIPT_LEN &&\n script[0] === OP_RETURN &&\n script[1] === OP_PUSH32 &&\n output.value === 0\n ) {\n hits.push({\n vout: i,\n hash: script.slice(2).toString(\"hex\").toLowerCase(),\n });\n }\n }\n\n return hits.length === 1 ? hits[0] : undefined;\n}\n","/**\n * HTLC Secret / Hashlock Utilities\n *\n * Pure functions for computing and validating SHA-256 hashlocks used in the\n * vault deposit protocol's HTLC (Hash Time Lock Contract).\n *\n * The SDK does NOT generate secrets — that is the caller's responsibility.\n * Today callers use `crypto.getRandomValues(32)`; when the `deriveContextHash`\n * wallet API ships, callers will use `wallet.deriveContextHash(\"babylon-btc-vault\", ctx)`.\n * These utilities work identically regardless of how the secret was produced.\n *\n * On-chain contract validation (BTCVaultRegistry.activateVaultWithSecret):\n * if (sha256(abi.encodePacked(s)) != hashlock) revert InvalidSecret();\n *\n * @module htlc\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport type { Hex } from \"viem\";\n\n/** Expected hex length for a 0x-prefixed bytes32 value. */\nconst HEX_BYTES32_LENGTH = 66; // \"0x\" + 64 hex chars\n\n/**\n * Decode a 0x-prefixed hex string to bytes, with strict validation.\n * @throws if the input is not a valid 0x-prefixed hex string\n */\nfunction hexToBytes(hex: Hex): Uint8Array {\n if (!hex.startsWith(\"0x\") && !hex.startsWith(\"0X\")) {\n throw new Error(\"Expected 0x-prefixed hex string\");\n }\n const clean = hex.slice(2);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has odd length: ${clean.length}`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error(\"Hex string contains non-hex characters\");\n }\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Encode a Uint8Array as a 0x-prefixed lowercase hex string.\n */\nfunction bytesToHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\n/**\n * Validate that a value is a 0x-prefixed bytes32 (exactly 32 bytes).\n * @throws if the value is not exactly 32 bytes\n */\nfunction assertBytes32(value: Hex, label: string): void {\n if (value.length !== HEX_BYTES32_LENGTH) {\n throw new Error(\n `${label} must be exactly 32 bytes (${HEX_BYTES32_LENGTH} hex chars with 0x prefix), got ${value.length}`,\n );\n }\n}\n\n/**\n * Compute the SHA-256 hashlock from a secret preimage.\n *\n * Matches the on-chain validation: `sha256(abi.encodePacked(s))` where `s` is a `bytes32`.\n * `abi.encodePacked(bytes32)` is just the raw 32 bytes — no ABI padding.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @returns 0x-prefixed bytes32 SHA-256 hash\n * @throws if secret is not exactly 32 bytes\n */\nexport function computeHashlock(secret: Hex): Hex {\n assertBytes32(secret, \"Secret\");\n const secretBytes = hexToBytes(secret);\n const hash = sha256(secretBytes);\n return bytesToHex(hash);\n}\n\n/**\n * Validate that a secret's SHA-256 hash matches the expected hashlock.\n *\n * Use this for client-side pre-validation before sending the activation\n * transaction to avoid wasting gas on a contract revert.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @param hashlock - 0x-prefixed bytes32 expected hashlock from the vault\n * @returns true if SHA-256(secret) matches the hashlock\n * @throws if secret or hashlock is not exactly 32 bytes\n */\nexport function validateSecretAgainstHashlock(\n secret: Hex,\n hashlock: Hex,\n): boolean {\n assertBytes32(secret, \"Secret\");\n assertBytes32(hashlock, \"Hashlock\");\n // Validate hashlock is valid hex (secret is validated inside computeHashlock)\n hexToBytes(hashlock);\n\n const computed = computeHashlock(secret);\n return computed.toLowerCase() === hashlock.toLowerCase();\n}\n","import type { BitcoinWallet } from \"../../../shared/wallets/interfaces\";\n\n// Field docs use /** */ so they survive into the emitted .d.ts — the published\n// package is the only contract the external provider author (#2109) sees.\n\nexport interface DepositTermsVaultGroup {\n /** 0-based; equals the group's position (groups are ascending by vout). */\n readonly htlcVout: number;\n /** x-only hex (64 chars), as validated on-chain upstream. */\n readonly vaultProviderBtcPubkey: string;\n /** sats */\n readonly peginAmount: bigint;\n /**\n * sats; the MAXIMUM commission the depositor accepts —\n * floor(peginAmount * maxAcceptableCommissionBps / 10_000), the same\n * ceiling the registration calldata carries. An approving wallet MUST\n * enforce the VP payout commission output `<= commissionFee` (e.g. the\n * Ledger vault app does, firmware >= c8db53e), and every commission the\n * contract admits stays under this ceiling (floor is monotonic in bps),\n * so no contract-admitted deposit can be refused at payout. The actual\n * stamped commission may be lower. Display the quoted value in UI, not this.\n */\n readonly commissionFee: bigint;\n /** sats; the same value for every vault. */\n readonly depositorClaimValue: bigint;\n /**\n * sats; the cap an approving wallet enforces on the PegIn tx fee. Equals\n * the graph's exact (minimum) PegIn fee, which is deterministic — so the\n * cap is satisfied exact-by-construction.\n */\n readonly peginMaxFee: bigint;\n}\n\n/**\n * Field names follow btc-vault vocabulary (the protocol source of truth);\n * a device-wire encoder maps them to its intent fields (e.g. the Ledger TLV:\n * protocolFeeRate -> base_fee_rate, timelockPegin -> pegin_csv_timelock,\n * timelockAssert -> payout_timelock, peginAmount -> vault_amount).\n */\nexport interface DepositTerms {\n /**\n * btc-vault tx-graph version (`vaultCoreVersion`) these terms describe —\n * the vault's stamped on-chain version for resumes, the chain's\n * `activeVaultCoreVersion` for fresh deposits. It selects the PegIn shape\n * an approving wallet must expect: v1 = 2 outputs, no anchor; v2/v3 = TRUC\n * nVersion 3, 3 outputs with a 240-sat P2A anchor at vout 2, and an\n * Assert OP_RETURN marker that raises the claim value\n * (btc-vault `transactions/pegin.rs`, `assert_marker.rs`). A provider that\n * supports only one shape MUST reject the others here rather than\n * mis-validating the PSBTs later.\n */\n vaultCoreVersion: number;\n /**\n * sat/vB; the tx-graph fee rate (protocolFeeRate), NOT the mempool funding\n * rate. Approving wallets bound each payout's fee against this rate —\n * pass the exact graph rate, not an inflated ceiling.\n */\n protocolFeeRate: bigint;\n /** Vault-UTXO CSV timelock (blocks). */\n timelockPegin: number;\n /**\n * btc-vault `timelock_assert` (t2) — the CSV on Assert output 0. Its own\n * param, though production derives it and `timelockPegin` from one value.\n */\n timelockAssert: number;\n /** HTLC refund CSV timelock (blocks). */\n timelockRefund: number;\n /**\n * 64-char hex in display order. A device-wire encoder may need the\n * little-endian form — some hardware byte-compares it against\n * PSBT_IN_PREVIOUS_TXID rather than recomputing the txid.\n */\n prepeginTxid: string;\n /** sats; the funded Pre-PegIn fee (an approving wallet caps the signed fee at this). */\n prepeginMaxFee: bigint;\n /**\n * x-only hex. Sorted ascending by the upstream on-chain validation\n * (validateOnChainParticipantKeys); the builder passes them through\n * unasserted — approving devices may reject unsorted lists at load.\n */\n vaultKeeperBtcPubkeys: readonly string[];\n /**\n * x-only hex, sorted ascending upstream independently of vaultKeeperBtcPubkeys (same\n * pass-through contract). Universal challengers only — the full graph\n * challenger set is vaultKeeperBtcPubkeys ∪ universalChallengerBtcPubkeys (vault keepers are the local\n * challengers).\n */\n universalChallengerBtcPubkeys: readonly string[];\n /** Per-vault groups, ordered by ascending htlcVout. */\n vaults: readonly DepositTermsVaultGroup[];\n}\n\n/**\n * Implemented only by depositor-approval wallets (e.g. a Ledger vault\n * provider). Provider obligations:\n *\n * - Envelope: validate terms against the device's envelope BEFORE the\n * ceremony, rejecting with the shape `{ name: \"DepositTermsRejectedError\",\n * reason: \"device-envelope\", message }` (matched structurally, not by class).\n * - Idempotence: a byte-equal re-approval MUST be a no-op while the\n * device-side approval is live; anything that invalidates it (a later\n * `deriveContextHash`, a signing failure) MUST clear the memo.\n *\n * Seam invariant: any derive invalidates a prior approval, so the SDK\n * re-approves after every derive and before the next terms-bound signature.\n * The re-approval sites are `PeginManager.preparePegin`,\n * `runDepositorPresignFlow`, and `signAndBroadcast` (the Pre-PegIn broadcast,\n * which re-derives before approving unless `holdsApprovedDepositTerms`\n * reports the byte-equal intent still live — see `ensurePrePeginTermsApproval`).\n */\nexport interface DepositTermsApprover {\n approveDepositTerms(terms: DepositTerms): Promise<void>;\n /**\n * OPTIONAL fast-path probe: can the Pre-PegIn signature for exactly these\n * terms proceed under the connection's held approval without a new\n * ceremony? MUST report false once that Pre-PegIn was signed (one-shot),\n * MUST answer from host state without device I/O, MUST return false on any\n * doubt, and MUST never throw. A stale true fails closed at the next\n * signature — this is a UX optimization, never an authorization.\n */\n holdsApprovedDepositTerms?(terms: DepositTerms): Promise<boolean>;\n}\n\n/**\n * Where Pre-PegIn change must pay. Approval (policy) wallets sign key-path\n * under a wallet policy whose change branch the device alone can derive and\n * mark internal — the receive address is NOT acceptable change\n * (`process_in_outs.c:114-117` @ e400d8d8).\n *\n * Separate from {@link DepositTermsApprover} because only the Pre-PegIn build\n * needs it: the presign/payout ceremonies approve terms without ever creating\n * change, so they must not require a wallet to implement this.\n *\n * MUST be stable across a deposit flow: the app reads it to build the tx and\n * `preparePegin` re-reads it to verify, so mid-flow rotation fails that gate.\n */\nexport interface PrePeginChangeSource {\n getChangeAddress(): Promise<string>;\n}\n\n/** Probes {@link DepositTermsApprover.approveDepositTerms}. */\nexport function supportsDepositApproval(\n wallet: BitcoinWallet,\n): wallet is BitcoinWallet & DepositTermsApprover {\n return (\n typeof (wallet as Partial<DepositTermsApprover>).approveDepositTerms ===\n \"function\"\n );\n}\n\n/**\n * The wallet's change address, for the one caller that needs it.\n *\n * Narrowing on `approveDepositTerms` alone cannot promise this method, so\n * calling it off the narrowed value would die on `is not a function` in the\n * middle of `preparePegin`, after the pubkey read. Ask here instead and fail\n * with something a provider author can act on.\n *\n * @throws If the wallet cannot report a change address.\n */\nexport async function requireChangeAddress(\n wallet: BitcoinWallet,\n): Promise<string> {\n const changeSource = wallet as Partial<PrePeginChangeSource>;\n if (typeof changeSource.getChangeAddress !== \"function\") {\n throw new Error(\n \"Approval wallet does not implement getChangeAddress; it must expose its change branch, \" +\n \"because the signing device accepts Pre-PegIn change only there.\",\n );\n }\n return changeSource.getChangeAddress();\n}\n\n/**\n * Spreadable forward of the approval capability for wallet-wrapper objects.\n * Object spread drops prototype methods, so every `{...wallet}` wrapper site\n * must re-attach the capability explicitly: `...forwardDepositApproval(wallet)`.\n */\nexport function forwardDepositApproval(\n wallet: BitcoinWallet,\n): Partial<DepositTermsApprover & PrePeginChangeSource> {\n if (!supportsDepositApproval(wallet)) {\n return {};\n }\n const holdsApprovedDepositTerms = wallet.holdsApprovedDepositTerms;\n const getChangeAddress = (wallet as Partial<PrePeginChangeSource>)\n .getChangeAddress;\n return {\n approveDepositTerms: (terms) => wallet.approveDepositTerms(terms),\n // Both optional in the seam: forward only what the provider implements, so\n // wrapper consumers can keep probing by typeof.\n ...(typeof getChangeAddress === \"function\"\n ? { getChangeAddress: () => getChangeAddress.call(wallet) }\n : {}),\n ...(typeof holdsApprovedDepositTerms === \"function\"\n ? {\n holdsApprovedDepositTerms: (terms: DepositTerms) =>\n holdsApprovedDepositTerms.call(wallet, terms),\n }\n : {}),\n };\n}\n\nexport interface BuildDepositTermsInputs {\n /** btc-vault tx-graph version the graph is built under. */\n vaultCoreVersion: number;\n protocolFeeRate: bigint;\n timelockPegin: number;\n /** btc-vault `timelock_assert` (t2) — its own param; NOT derived from timelockPegin here. */\n timelockAssert: number;\n timelockRefund: number;\n prepeginTxid: string;\n prepeginMaxFee: bigint;\n vaultProviderBtcPubkey: string;\n vaultKeeperBtcPubkeys: readonly string[];\n universalChallengerBtcPubkeys: readonly string[];\n /** Ceiling bps, not the quote — see {@link DepositTermsVaultGroup.commissionFee}. */\n maxAcceptableCommissionBps: number;\n peginAmounts: readonly bigint[];\n depositorClaimValue: bigint;\n peginMaxFee: bigint;\n}\n","/**\n * Payout Manager\n *\n * High-level manager that orchestrates the payout signing flow by coordinating\n * SDK primitives ({@link buildPayoutPsbt}, {@link extractPayoutSignature})\n * with a user-provided Bitcoin wallet.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @see {@link PeginManager} - For Steps 1–4 of the peg-in flow\n * @see {@link buildPayoutPsbt} - Lower-level primitive for custom implementations\n * @see {@link extractPayoutSignature} - Extract signatures from signed PSBTs\n *\n * @module managers/PayoutManager\n */\n\nimport type { BitcoinWallet, SignPsbtOptions } from \"../../../shared/wallets\";\nimport {\n assertPsbtUnsignedTxMatches,\n assertScriptPathSchnorrSignature,\n buildPayoutPsbt,\n extractPayoutSignature,\n validateWalletPubkey,\n type Network,\n} from \"../primitives\";\nimport { createTaprootScriptPathSignOptions } from \"../utils/signing\";\n\n/** Payout PSBTs are signed by the depositor on input 0 (Taproot script-path). */\nconst PAYOUT_SIGNED_INPUT_INDEX = 0;\n\n/**\n * Configuration for the PayoutManager.\n */\nexport interface PayoutManagerConfig {\n /**\n * Bitcoin network to use for transactions.\n */\n network: Network;\n\n /**\n * Bitcoin wallet for signing payout transactions.\n */\n btcWallet: BitcoinWallet;\n}\n\n/**\n * Base parameters shared by both payout transaction types.\n */\ninterface SignPayoutBaseParams {\n /**\n * Vault core (tx-graph) version the vault was registered under — the\n * vault's stamped on-chain `vaultCoreVersion`. Forwarded to\n * {@link buildPayoutPsbt} to derive the matching graph's payout scripts.\n */\n vaultCoreVersion: number;\n\n /**\n * Peg-in transaction hex.\n * The original transaction that created the vault output being spent.\n */\n peginTxHex: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex).\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex).\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex).\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n /** btc-vault `timelock_assert`; payout input 1's sequence. */\n timelockAssert: number;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex). This MUST be the\n * key registered on-chain for the vault — typically read from\n * `BTCVaultRegistry.getBtcVaultBasicInfo(...).depositorBtcPubKey`.\n *\n * Required: omitting it would degrade `validateWalletPubkey` to a\n * self-comparison, allowing the wrong wallet to produce a signature\n * over a script tree that doesn't match the on-chain UTXO.\n */\n depositorBtcPubkey: string;\n\n /**\n * The on-chain registered depositor payout scriptPubKey (hex, with or without 0x prefix).\n * Used to validate that the VP-provided payout transaction actually pays to the\n * correct depositor payout address before signing.\n */\n registeredPayoutScriptPubKey: string;\n\n /**\n * The claimer's x-only BTC public key for this payout (64-char hex, no prefix).\n * Forwarded to {@link buildPayoutPsbt} for per-role output validation.\n */\n claimerBtcPubkey: string;\n\n /**\n * VP commission in basis points (`1..=9999`). Forwarded to {@link buildPayoutPsbt}.\n */\n commissionBps: number;\n\n /**\n * Version-locked tx-graph fee rate (sat/vB) the graph was built with.\n * Forwarded to {@link buildPayoutPsbt} for the fee band.\n */\n protocolFeeRate: bigint;\n\n /**\n * Security council member x-only pubkeys (hex); forwarded to\n * {@link buildPayoutPsbt} to rebuild the Assert:0 payout leaf and to size the\n * fee floor (see PayoutParams).\n */\n councilMembers: string[];\n\n /** M-of-N council quorum; shapes the Assert:0 council leaf (see PayoutParams). */\n councilQuorum: number;\n\n /**\n * RFC-006 resolved payout destinations, keyed by lowercased x-only operation\n * pubkey. Forwarded verbatim to {@link buildPayoutPsbt}; every VK claimer\n * must be present.\n */\n vkClaimerPayoutScriptPubKeys: Readonly<Record<string, string>>;\n /** RFC-006 VP commission destination. Forwarded to {@link buildPayoutPsbt}. */\n vpCommissionScriptPubKey: string;\n}\n\n/**\n * Parameters for signing a Payout transaction.\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface SignPayoutParams extends SignPayoutBaseParams {\n /**\n * Payout transaction hex (unsigned).\n * This is the transaction from the vault provider that needs depositor signature.\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex.\n * Payout input 1 references Assert output 0.\n */\n assertTxHex: string;\n}\n\n/**\n * Result of signing a payout transaction.\n */\nexport interface PayoutSignatureResult {\n /**\n * 64-byte Schnorr signature (128 hex characters).\n */\n signature: string;\n\n /**\n * Depositor's BTC public key used for signing.\n */\n depositorBtcPubkey: string;\n}\n\n/**\n * High-level manager for payout transaction signing.\n *\n * @remarks\n * After registering your peg-in on Ethereum (Step 3), the vault provider prepares\n * claim/payout transaction pairs. You must sign each payout transaction using this\n * manager and submit the signatures to the vault provider's RPC API.\n *\n * **What happens internally:**\n * 1. Validates your wallet's public key matches the vault's depositor\n * 2. Builds an unsigned PSBT with taproot script path spend info\n * 3. Signs input 0 (the vault UTXO) with your wallet\n * 4. Extracts the 64-byte Schnorr signature\n *\n * **Note:** The payout transaction has 2 inputs. PayoutManager only signs input 0\n * (from the peg-in tx). Input 1 (from the assert tx) is signed by the vault provider.\n *\n * @see {@link PeginManager} - For the complete peg-in flow context\n * @see {@link buildPayoutPsbt} - Lower-level primitive used internally\n * @see {@link extractPayoutSignature} - Signature extraction primitive\n */\nexport class PayoutManager {\n private readonly config: PayoutManagerConfig;\n\n /**\n * Creates a new PayoutManager instance.\n *\n * @param config - Manager configuration including wallet\n */\n constructor(config: PayoutManagerConfig) {\n this.config = config;\n }\n\n /**\n * Signs a Payout transaction and extracts the Schnorr signature.\n *\n * Flow:\n * 1. Vault provider submits Claim transaction\n * 2. Claimer submits Assert transaction to prove validity\n * 3. Payout can be executed (references Assert tx)\n *\n * This method orchestrates the following steps:\n * 1. Get wallet's public key and convert to x-only format\n * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)\n * 3. Build unsigned PSBT using primitives\n * 4. Sign PSBT via btcWallet.signPsbt()\n * 5. Extract 64-byte Schnorr signature using primitives\n *\n * The returned signature can be submitted to the vault provider API.\n *\n * @param params - Payout signing parameters\n * @returns Signature result with 64-byte Schnorr signature and depositor pubkey\n * @throws Error if wallet pubkey doesn't match depositor pubkey\n * @throws Error if wallet operations fail or signature extraction fails\n */\n async signPayoutTransaction(\n params: SignPayoutParams,\n ): Promise<PayoutSignatureResult> {\n // Validate wallet pubkey matches depositor and get both formats\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n params.depositorBtcPubkey,\n );\n\n // Build unsigned PSBT for Payout (uses Assert tx). Per-role output\n // validation happens inside buildPayoutPsbt against the resolved input\n // values.\n const payoutPsbt = await buildPayoutPsbt({\n vaultCoreVersion: params.vaultCoreVersion,\n payoutTxHex: params.payoutTxHex,\n peginTxHex: params.peginTxHex,\n assertTxHex: params.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: params.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: params.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n timelockAssert: params.timelockAssert,\n network: this.config.network,\n claimerBtcPubkey: params.claimerBtcPubkey,\n registeredPayoutScriptPubKey: params.registeredPayoutScriptPubKey,\n commissionBps: params.commissionBps,\n protocolFeeRate: params.protocolFeeRate,\n councilMembers: params.councilMembers,\n councilQuorum: params.councilQuorum,\n vkClaimerPayoutScriptPubKeys: params.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: params.vpCommissionScriptPubKey,\n });\n\n // Sign PSBT via wallet (Taproot script-path spend, input 0 only)\n const signedPsbtHex = await this.config.btcWallet.signPsbt(\n payoutPsbt.psbtHex,\n createTaprootScriptPathSignOptions(walletPubkeyRaw, 1),\n );\n\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: payoutPsbt.psbtHex,\n returnedPsbtHex: signedPsbtHex,\n });\n\n // Extract Schnorr signature\n const signature = extractPayoutSignature(signedPsbtHex, depositorPubkey);\n // Critical Path #7: verify the signature against a sighash recomputed from\n // the PSBT we built, not the wallet-returned one.\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: payoutPsbt.psbtHex,\n signatureHex: signature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: PAYOUT_SIGNED_INPUT_INDEX,\n });\n\n return {\n signature,\n depositorBtcPubkey: depositorPubkey,\n };\n }\n\n /**\n * Gets the configured Bitcoin network.\n *\n * @returns The Bitcoin network (mainnet, testnet, signet, regtest)\n */\n getNetwork(): Network {\n return this.config.network;\n }\n\n /**\n * Checks if the wallet supports batch signing (signPsbts).\n *\n * @returns true if batch signing is supported\n */\n supportsBatchSigning(): boolean {\n return typeof this.config.btcWallet.signPsbts === \"function\";\n }\n\n /**\n * Batch signs multiple payout transactions (1 per claimer).\n * This allows signing all transactions with a single wallet interaction.\n *\n * @param transactions - Array of payout params to sign\n * @returns Array of signature results matching input order\n * @throws Error if wallet doesn't support batch signing\n * @throws Error if any signing operation fails\n */\n async signPayoutTransactionsBatch(transactions: SignPayoutParams[]): Promise<\n Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }>\n > {\n if (!this.supportsBatchSigning()) {\n throw new Error(\n \"Wallet does not support batch signing (signPsbts method not available)\",\n );\n }\n\n // Get wallet pubkey once\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n\n // Build all PSBTs (1 per claimer)\n const psbtsToSign: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n const depositorPubkeys: string[] = [];\n\n for (const tx of transactions) {\n // Validate wallet pubkey matches depositor\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n tx.depositorBtcPubkey,\n );\n depositorPubkeys.push(depositorPubkey);\n\n // Build Payout PSBT (output validation runs inside buildPayoutPsbt\n // against resolved input values).\n const payoutPsbt = await buildPayoutPsbt({\n vaultCoreVersion: tx.vaultCoreVersion,\n payoutTxHex: tx.payoutTxHex,\n peginTxHex: tx.peginTxHex,\n assertTxHex: tx.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: tx.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: tx.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: tx.universalChallengerBtcPubkeys,\n timelockPegin: tx.timelockPegin,\n timelockAssert: tx.timelockAssert,\n network: this.config.network,\n claimerBtcPubkey: tx.claimerBtcPubkey,\n registeredPayoutScriptPubKey: tx.registeredPayoutScriptPubKey,\n commissionBps: tx.commissionBps,\n protocolFeeRate: tx.protocolFeeRate,\n councilMembers: tx.councilMembers,\n councilQuorum: tx.councilQuorum,\n vkClaimerPayoutScriptPubKeys: tx.vkClaimerPayoutScriptPubKeys,\n vpCommissionScriptPubKey: tx.vpCommissionScriptPubKey,\n });\n psbtsToSign.push(payoutPsbt.psbtHex);\n signOptions.push(createTaprootScriptPathSignOptions(walletPubkeyRaw, 1));\n }\n\n // Batch sign all PSBTs with single wallet interaction\n const signedPsbts = await this.config.btcWallet.signPsbts!(\n psbtsToSign,\n signOptions,\n );\n\n // Validate that wallet returned the expected number of signed PSBTs\n if (signedPsbts.length !== transactions.length) {\n throw new Error(\n `Expected ${transactions.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n\n // Extract signatures from signed PSBTs\n const results: Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }> = [];\n\n for (let i = 0; i < transactions.length; i++) {\n const depositorPubkey = depositorPubkeys[i];\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: psbtsToSign[i],\n returnedPsbtHex: signedPsbts[i],\n });\n const payoutSignature = extractPayoutSignature(\n signedPsbts[i],\n depositorPubkey,\n );\n assertScriptPathSchnorrSignature({\n requestedPsbtHex: psbtsToSign[i],\n signatureHex: payoutSignature,\n signerXOnlyPubkeyHex: depositorPubkey,\n inputIndex: PAYOUT_SIGNED_INPUT_INDEX,\n });\n\n results.push({\n payoutSignature,\n depositorBtcPubkey: depositorPubkey,\n });\n }\n\n return results;\n }\n}\n","/**\n * Wallet-signing helper that routes a lone PSBT to `signPsbt`, prefers native\n * `signPsbts` for real batches, and falls back to sequential `signPsbt` for\n * wallets that don't implement batch signing.\n *\n * @module managers/pegin/signPsbtsWithFallback\n */\n\nimport type {\n BitcoinWallet,\n SignPsbtOptions,\n} from \"../../../../shared/wallets\";\n\n/**\n * Sign one or more PSBTs against a wallet.\n *\n * A single PSBT is always signed via `signPsbt`, never the batch endpoint: it's\n * one wallet interaction either way, and `signPsbt` is the universally-required\n * wallet method (batch `signPsbts` is optional), so single-sign is the portable\n * choice — some integrations (notably MPC / institutional wallets) prefer it.\n * For a real batch (>1), wallets exposing native `signPsbts` (e.g. UniSat) sign\n * in one interaction; others loop `signPsbt`.\n *\n * @throws If native `signPsbts` returns a different number of signed PSBTs\n * than were submitted.\n */\nexport async function signPsbtsWithFallback(\n wallet: BitcoinWallet,\n psbtsHexes: string[],\n options?: SignPsbtOptions[],\n): Promise<string[]> {\n if (psbtsHexes.length === 1) {\n return [await wallet.signPsbt(psbtsHexes[0], options?.[0])];\n }\n\n if (typeof wallet.signPsbts === \"function\") {\n const signedPsbts = await wallet.signPsbts(psbtsHexes, options);\n if (signedPsbts.length !== psbtsHexes.length) {\n throw new Error(\n `Expected ${psbtsHexes.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n return signedPsbts;\n }\n\n const signedPsbts: string[] = [];\n for (let i = 0; i < psbtsHexes.length; i++) {\n signedPsbts.push(await wallet.signPsbt(psbtsHexes[i], options?.[i]));\n }\n return signedPsbts;\n}\n"],"names":["OP_RETURN","OP_PUSH32","OP_RETURN_PUSH32_SCRIPT_LEN","assertAuthAnchorOpReturn","fundedPrePeginTxHex","vaultCount","expectedAuthAnchorHashHex","cleanHex","stripHexPrefix","tx","bitcoin","opReturnOutput","script","pushedHex","findAuthAnchorOpReturn","hits","i","output","HEX_BYTES32_LENGTH","hexToBytes","hex","clean","bytes","bytesToHex","b","assertBytes32","value","label","computeHashlock","secret","secretBytes","hash","sha256","validateSecretAgainstHashlock","hashlock","supportsDepositApproval","wallet","requireChangeAddress","changeSource","forwardDepositApproval","holdsApprovedDepositTerms","getChangeAddress","terms","PAYOUT_SIGNED_INPUT_INDEX","PayoutManager","config","__publicField","params","walletPubkeyRaw","depositorPubkey","validateWalletPubkey","payoutPsbt","buildPayoutPsbt","signedPsbtHex","createTaprootScriptPathSignOptions","assertPsbtUnsignedTxMatches","signature","extractPayoutSignature","assertScriptPathSchnorrSignature","transactions","psbtsToSign","signOptions","depositorPubkeys","signedPsbts","results","payoutSignature","signPsbtsWithFallback","psbtsHexes","options"],"mappings":"ysBAYMA,EAAY,IAEZC,EAAY,GAEZC,EAA8B,GAmB7B,SAASC,EACdC,EACAC,EACAC,EACM,CACN,MAAMC,EAAWC,EAAAA,eAAeJ,CAAmB,EAC7CK,EAAKC,EAAQ,YAAY,QAAQH,CAAQ,EAE/C,GAAIE,EAAG,KAAK,QAAUJ,EACpB,MAAM,IAAI,MACR,mDAAmDI,EAAG,KAAK,MAAM,+BACjCJ,EAAa,CAAC,8BAAA,EAIlD,MAAMM,EAAiBF,EAAG,KAAKJ,CAAU,EACnCO,EAASD,EAAe,OAC9B,GACEC,EAAO,SAAWV,GAClBU,EAAO,CAAC,IAAMZ,GACdY,EAAO,CAAC,IAAMX,EAEd,MAAM,IAAI,MACR,2CAA2CI,CAAU,wCAC3BO,EAAO,MAAM,8BAChCA,EAAO,MAAM,EAAG,KAAK,IAAI,EAAGA,EAAO,MAAM,CAAC,EAAE,SAAS,KAAK,CAAC,cACpDV,CAA2B,kCAAA,EAI7C,MAAMW,EAAYD,EAAO,MAAM,CAAC,EAAE,SAAS,KAAK,EAAE,YAAA,EAClD,GAAIC,IAAcP,EAA0B,cAC1C,MAAM,IAAI,MACR,4DAA4DD,CAAU,eACvDQ,CAAS,cAAcP,CAAyB,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EACbiC,CAAA,EAEFS,mCAAiC,CAC/B,iBAAkBE,EAAY5C,CAAC,EAC/B,aAAciD,EACd,qBAAsBhB,EACtB,WAAYN,CAAA,CACb,EAEDqB,EAAQ,KAAK,CACX,gBAAAC,EACA,mBAAoBhB,CAAA,CACrB,CACH,CAEA,OAAOe,CACT,CACF,CCxYA,eAAsBE,EACpB9B,EACA+B,EACAC,EACmB,CACnB,GAAID,EAAW,SAAW,EACxB,MAAO,CAAC,MAAM/B,EAAO,SAAS+B,EAAW,CAAC,EAAGC,GAAA,YAAAA,EAAU,EAAE,CAAC,EAG5D,GAAI,OAAOhC,EAAO,WAAc,WAAY,CAC1C,MAAM2B,EAAc,MAAM3B,EAAO,UAAU+B,EAAYC,CAAO,EAC9D,GAAIL,EAAY,SAAWI,EAAW,OACpC,MAAM,IAAI,MACR,YAAYA,EAAW,MAAM,8BAA8BJ,EAAY,MAAM,EAAA,EAGjF,OAAOA,CACT,CAEA,MAAMA,EAAwB,CAAA,EAC9B,QAAS/C,EAAI,EAAGA,EAAImD,EAAW,OAAQnD,IACrC+C,EAAY,KAAK,MAAM3B,EAAO,SAAS+B,EAAWnD,CAAC,EAAGoD,GAAA,YAAAA,EAAUpD,EAAE,CAAC,EAErE,OAAO+C,CACT"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../../../mempoolApi-CXfr-L6x.cjs"),e=require("../../../batchPoll-6L5oToGr.cjs"),r=require("../../../json-rpc-client-BiAmg_ho.cjs"),o=require("../../../onChainBtcPubkey-C_a2L3kL.cjs");exports.MEMPOOL_API_URLS=t.MEMPOOL_API_URLS;exports.ViemVaultRegistryReader=t.ViemVaultRegistryReader;exports.getAddressTxs=t.getAddressTxs;exports.getAddressUtxos=t.getAddressUtxos;exports.getMempoolApiUrl=t.getMempoolApiUrl;exports.getNetworkFees=t.getNetworkFees;exports.getOutspend=t.getOutspend;exports.getTipHeight=t.getTipHeight;exports.getTxHex=t.getTxHex;exports.getTxInfo=t.getTxInfo;exports.getUtxoInfo=t.getUtxoInfo;exports.pushTx=t.pushTx;exports.validateOffchainParams=t.validateOffchainParams;exports.validatePegInConfiguration=t.validatePegInConfiguration;exports.validateTBVProtocolParams=t.validateTBVProtocolParams;exports.OnChainBtcVaultStatus=e.OnChainBtcVaultStatus;exports.ServerIdentityError=e.ServerIdentityError;exports.VaultProviderRpcClient=e.VaultProviderRpcClient;exports.ViemOperationKeyReader=e.ViemOperationKeyReader;exports.ViemProtocolParamsReader=e.ViemProtocolParamsReader;exports.ViemUniversalChallengerReader=e.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=e.ViemVaultKeeperReader;exports.VpResponseValidationError=e.VpResponseValidationError;exports.VpTokenRegistry=e.VpTokenRegistry;exports.batchPollByProvider=e.batchPollByProvider;exports.createAuthenticatedVpClient=e.createAuthenticatedVpClient;exports.primeVpTokenRegistry=e.primeVpTokenRegistry;exports.resolveProtocolAddresses=e.resolveProtocolAddresses;exports.validateRequestDepositorClaimerArtifactsResponse=e.validateRequestDepositorClaimerArtifactsResponse;exports.verifyServerIdentity=e.verifyServerIdentity;exports.vpTokenRegistry=e.vpTokenRegistry;exports.AUTH_REJECTED_RPC_CODE=r.AUTH_REJECTED_RPC_CODE;exports.DaemonStatus=r.DaemonStatus;exports.JSON_RPC_ERROR_CODES=r.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=r.JsonRpcClient;exports.JsonRpcError=r.JsonRpcError;exports.POST_WOTS_STATUSES=r.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=r.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=r.RpcErrorCode;exports.VP_BATCH_MAX_SIZE=r.VP_BATCH_MAX_SIZE;exports.VP_TERMINAL_FAILURE_STATUSES=r.VP_TERMINAL_FAILURE_STATUSES;exports.VP_TRANSIENT_STATUSES=r.VP_TRANSIENT_STATUSES;exports.isAuthRejectedError=r.isAuthRejectedError;exports.assertOnChainBtcPubkey=o.assertOnChainBtcPubkey;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../../../mempoolApi-EU1La9wk.cjs"),e=require("../../../batchPoll-REVZiE-M.cjs"),r=require("../../../json-rpc-client-BiAmg_ho.cjs"),o=require("../../../onChainBtcPubkey-C_a2L3kL.cjs");exports.MEMPOOL_API_URLS=t.MEMPOOL_API_URLS;exports.ViemVaultRegistryReader=t.ViemVaultRegistryReader;exports.getAddressTxs=t.getAddressTxs;exports.getAddressUtxos=t.getAddressUtxos;exports.getMempoolApiUrl=t.getMempoolApiUrl;exports.getNetworkFees=t.getNetworkFees;exports.getOutspend=t.getOutspend;exports.getTipHeight=t.getTipHeight;exports.getTxHex=t.getTxHex;exports.getTxInfo=t.getTxInfo;exports.getUtxoInfo=t.getUtxoInfo;exports.pushTx=t.pushTx;exports.validateOffchainParams=t.validateOffchainParams;exports.validatePegInConfiguration=t.validatePegInConfiguration;exports.validateTBVProtocolParams=t.validateTBVProtocolParams;exports.OnChainBtcVaultStatus=e.OnChainBtcVaultStatus;exports.ServerIdentityError=e.ServerIdentityError;exports.VaultProviderRpcClient=e.VaultProviderRpcClient;exports.ViemOperationKeyReader=e.ViemOperationKeyReader;exports.ViemProtocolParamsReader=e.ViemProtocolParamsReader;exports.ViemUniversalChallengerReader=e.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=e.ViemVaultKeeperReader;exports.VpResponseValidationError=e.VpResponseValidationError;exports.VpTokenRegistry=e.VpTokenRegistry;exports.batchPollByProvider=e.batchPollByProvider;exports.createAuthenticatedVpClient=e.createAuthenticatedVpClient;exports.primeVpTokenRegistry=e.primeVpTokenRegistry;exports.resolveProtocolAddresses=e.resolveProtocolAddresses;exports.validateRequestDepositorClaimerArtifactsResponse=e.validateRequestDepositorClaimerArtifactsResponse;exports.verifyServerIdentity=e.verifyServerIdentity;exports.vpTokenRegistry=e.vpTokenRegistry;exports.AUTH_REJECTED_RPC_CODE=r.AUTH_REJECTED_RPC_CODE;exports.DaemonStatus=r.DaemonStatus;exports.JSON_RPC_ERROR_CODES=r.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=r.JsonRpcClient;exports.JsonRpcError=r.JsonRpcError;exports.POST_WOTS_STATUSES=r.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=r.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=r.RpcErrorCode;exports.VP_BATCH_MAX_SIZE=r.VP_BATCH_MAX_SIZE;exports.VP_TERMINAL_FAILURE_STATUSES=r.VP_TERMINAL_FAILURE_STATUSES;exports.VP_TRANSIENT_STATUSES=r.VP_TRANSIENT_STATUSES;exports.isAuthRejectedError=r.isAuthRejectedError;exports.assertOnChainBtcPubkey=o.assertOnChainBtcPubkey;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1,7 +1,7 @@
1
- import { M as s, V as r, g as t, a as o, b as i, c as R, d as n, e as d, f as T, h as p, i as S, p as l, v as E, j as P, k as V } from "../../../mempoolApi-BxSINXIB.js";
2
- import { O as A, S as g, V as c, g as m, h as O, i as C, j as v, a as f, d as u, b as I, f as h, p as x, r as U, v as y, c as D, e as k } from "../../../batchPoll-cIxrSLLJ.js";
1
+ import { M as s, V as r, g as t, a as o, b as i, c as R, d as n, e as d, f as T, h as p, i as S, p as l, v as E, j as P, k as V } from "../../../mempoolApi-_D-jvtj_.js";
2
+ import { O as A, S as g, V as c, g as m, h as O, i as C, j as v, a as f, d as u, b as I, f as h, p as x, r as U, v as y, c as D, e as k } from "../../../batchPoll-Cjj1du0i.js";
3
3
  import { A as N, D as b, J as B, a as J, b as H, d as L, P as j, R as F, e as K, c as q, V as w, i as G } from "../../../json-rpc-client-DuUARJvV.js";
4
- import { a as X } from "../../../onChainBtcPubkey-DeF4cKoO.js";
4
+ import { a as X } from "../../../onChainBtcPubkey-BAHZyKQL.js";
5
5
  export {
6
6
  N as AUTH_REJECTED_RPC_CODE,
7
7
  b as DaemonStatus,
@@ -0,0 +1,32 @@
1
+ /**
2
+ * BIP-322 official P2WPKH "simple" test vectors, pinned from
3
+ * `bitcoin/bips` `bip-0322/basic-test-vectors.json` at commit
4
+ * d77863fb9e9be7829ad8bb51694b9ba80a786766 ("BIP-0322: update test
5
+ * vectors", 2026-05-06). The base64 `bip322_signatures` entries (after
6
+ * stripping the file's `smp` variant marker) decode to consensus
7
+ * witnesses `[DER sig ‖ 0x01, 33-byte compressed pubkey]`; the fields
8
+ * below are those decoded bytes as hex.
9
+ *
10
+ * Signer: private key L3VFeEujGtevx9w18HD1fhRbCH67Az2dpCymeRE1SoPK6XQtaN2k
11
+ * for address bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l — public BIP
12
+ * test material, not real key material.
13
+ */
14
+ /** 33-byte compressed pubkey shared by every vector (hash160 = the address's witness program). */
15
+ export declare const BIP322_P2WPKH_PUBKEY_HEX = "02c7f12003196442943d8588e01aee840423cc54fc1521526a3b85c2b0cbd58872";
16
+ /** x-only form of {@link BIP322_P2WPKH_PUBKEY_HEX}, as a depositor key would be normalized. */
17
+ export declare const BIP322_P2WPKH_PUBKEY_XONLY_HEX = "c7f12003196442943d8588e01aee840423cc54fc1521526a3b85c2b0cbd58872";
18
+ /**
19
+ * Encoded signatures (DER ‖ 0x01 sighash byte) per message. Each message
20
+ * carries the file's two variants: a 71-byte and a 72-byte encoding.
21
+ */
22
+ export declare const BIP322_P2WPKH_SIGNATURES: ReadonlyArray<{
23
+ readonly message: string;
24
+ readonly encodedSignatureHexes: readonly [string, string];
25
+ }>;
26
+ /**
27
+ * The "Hello World" 71-byte-signature vector as a full consensus-encoded
28
+ * two-item witness (`0x02 ‖ 0x47 ‖ sig ‖ 0x21 ‖ pubkey`), for callers
29
+ * that consume the raw witness (e.g. `verifyPopWitness`).
30
+ */
31
+ export declare const BIP322_P2WPKH_HELLO_WORLD_WITNESS_HEX: string;
32
+ //# sourceMappingURL=bip322P2wpkhVectors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bip322P2wpkhVectors.d.ts","sourceRoot":"","sources":["../../../../../../../src/tbv/core/clients/vault-provider/auth/__tests__/bip322P2wpkhVectors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,kGAAkG;AAClG,eAAO,MAAM,wBAAwB,uEACiC,CAAC;AAEvE,+FAA+F;AAC/F,eAAO,MAAM,8BAA8B,qEACyB,CAAC;AAErE;;;GAGG;AACH,eAAO,MAAM,wBAAwB,EAAE,aAAa,CAAC;IACnD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,qBAAqB,EAAE,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC3D,CAeA,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,qCAAqC,QAA6F,CAAC"}
@@ -1,17 +1,20 @@
1
1
  /**
2
- * Golden-vector test for BIP-322 simple verify.
2
+ * Golden-vector tests for BIP-322 simple verify.
3
3
  *
4
- * The signature + message + pubkey are emitted by the Rust reference
5
- * in `btc-vault/crates/btc-auth/src/server_identity.rs`. The signer
6
- * seed is 7 and the payload is produced by
4
+ * P2TR: the signature + message + pubkey are emitted by the Rust
5
+ * reference in `btc-vault/crates/btc-auth/src/server_identity.rs`.
6
+ * The signer seed is 7 and the payload is produced by
7
7
  * `build_server_identity_payload` with a seed-42 ephemeral pubkey
8
8
  * and expires_at = 1_700_000_000. These were generated end-to-end
9
9
  * by the Rust production path, not constructed ad-hoc — so if this
10
10
  * test passes, the TypeScript implementation byte-exactly matches
11
11
  * what a real VP would sign.
12
12
  *
13
- * Canonical hex lives in `./goldenVectors.ts` so that all
14
- * server-identity tests share one source of truth and can't drift.
13
+ * P2WPKH: the vectors are BIP-322's official ones, pinned in
14
+ * `./bip322P2wpkhVectors.ts`.
15
+ *
16
+ * Canonical hex lives in `./goldenVectors.ts` / `./bip322P2wpkhVectors.ts`
17
+ * so the suites share one source of truth and can't drift.
15
18
  */
16
19
  export {};
17
20
  //# sourceMappingURL=bip322Verify.test.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bip322Verify.test.d.ts","sourceRoot":"","sources":["../../../../../../../src/tbv/core/clients/vault-provider/auth/__tests__/bip322Verify.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG"}
1
+ {"version":3,"file":"bip322Verify.test.d.ts","sourceRoot":"","sources":["../../../../../../../src/tbv/core/clients/vault-provider/auth/__tests__/bip322Verify.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG"}
@@ -1,10 +1,10 @@
1
1
  /**
2
- * BIP-322 "simple" signature verification for P2TR key-path.
2
+ * BIP-322 "simple" signature verification for P2TR key-path and P2WPKH.
3
3
  *
4
4
  * Mirrors the Rust reference in
5
- * `btc-vault/crates/btc-signer/src/message.rs::verify_bip322_message`
6
- * (which delegates to `rust-bitcoin::bip322::verify_simple` for a
7
- * P2TR key-path-only address with no merkle root).
5
+ * `btc-vault/crates/btc-signer/src/message.rs` (`verify_bip322_message`
6
+ * and the P2WPKH arm of `verify_pop_witness`, both of which delegate to
7
+ * the `bip322` crate 0.0.10's `verify_simple`).
8
8
  *
9
9
  * The algorithm:
10
10
  *
@@ -14,23 +14,24 @@
14
14
  *
15
15
  * 2. Build a virtual "to_spend" transaction with one input (prevout
16
16
  * all-zero txid + 0xFFFFFFFF vout, scriptSig = `OP_0 PUSH32 m_hash`,
17
- * sequence = 0) and one output (value 0, scriptPubKey = P2TR for
18
- * the signer's x-only pubkey).
17
+ * sequence = 0) and one output (value 0, scriptPubKey = the signer's
18
+ * address: P2TR key-path-only, or P2WPKH of the compressed pubkey).
19
19
  *
20
20
  * 3. Build a "to_sign" transaction that spends to_spend[0] and has a
21
21
  * single `OP_RETURN` output (value 0).
22
22
  *
23
- * 4. Compute the BIP-341 taproot sighash of to_sign input 0 with
24
- * SIGHASH_DEFAULT (0x00).
23
+ * 4. Compute the sighash of to_sign input 0: BIP-341 taproot for P2TR
24
+ * (SIGHASH_DEFAULT 0x00 unless the witness item carried a trailing
25
+ * SIGHASH_ALL 0x01 byte), BIP-143 with the standard P2WPKH
26
+ * scriptCode for P2WPKH (SIGHASH_ALL only).
25
27
  *
26
- * 5. Verify the 64-byte Schnorr signature against the **tweaked**
27
- * output key `Q = P + tap_tweak(P) * G`, where `tap_tweak(P) =
28
- * hash_TapTweak(serialize_x_only(P))` (no merkle root — key-path
29
- * only).
28
+ * 5. Verify the signature: Schnorr against the **tweaked** output key
29
+ * `Q = P + tap_tweak(P) * G` for P2TR (no merkle root — key-path
30
+ * only), ECDSA against the compressed pubkey for P2WPKH.
30
31
  *
31
32
  * `bitcoinjs-lib` handles (2)–(4); `tiny-secp256k1-asmjs` provides
32
- * the tweak and Schnorr verify. Pulling in a full BIP-322 library
33
- * would add a peer dep for what amounts to ~40 lines of glue.
33
+ * the tweak and the Schnorr/ECDSA verifies. Pulling in a full BIP-322
34
+ * library would add a peer dep for what amounts to ~40 lines of glue.
34
35
  *
35
36
  * @module tbv/core/clients/vault-provider/auth/bip322Verify
36
37
  */
@@ -38,19 +39,43 @@
38
39
  * Verify a BIP-322 "simple" P2TR key-path signature over an arbitrary
39
40
  * byte message.
40
41
  *
41
- * @internal Exposed only so the golden-vector test suite can pin the
42
- * verifier independently of `verifyServerIdentity`. Production callers
43
- * should use `verifyServerIdentity` from `./serverIdentity` instead.
42
+ * @internal Consumed by `verifyServerIdentity` (VP auth) and
43
+ * `verifyPopWitness` (PoP pre-registration check), and exposed so the
44
+ * golden-vector test suite can pin the verifier independently.
44
45
  *
45
46
  * @param messageBytes - The bytes that were signed (e.g. a CBOR-encoded
46
47
  * payload). Not pre-hashed; this function applies
47
48
  * the BIP-322 tagged hash internally.
48
49
  * @param xOnlyPubkey - 32-byte x-only pubkey of the signer (pre-tweak).
49
50
  * @param signature - 64-byte raw Schnorr signature (BIP-340), as
50
- * emitted by a key-path witness with
51
- * SIGHASH_DEFAULT.
51
+ * emitted by a key-path witness. The trailing
52
+ * sighash byte of a 65-byte witness item is not
53
+ * part of it — pass it as `hashType` instead.
54
+ * @param hashType - BIP-341 sighash type the signature commits to.
55
+ * `SIGHASH_DEFAULT` (0x00) for a 64-byte witness
56
+ * item, `SIGHASH_ALL` (0x01) for a 65-byte one.
52
57
  * @returns `true` if the signature verifies against the address
53
58
  * derived from `xOnlyPubkey`; `false` otherwise.
54
59
  */
55
- export declare function verifyBip322Simple(messageBytes: Uint8Array, xOnlyPubkey: Uint8Array, signature: Uint8Array): boolean;
60
+ export declare function verifyBip322Simple(messageBytes: Uint8Array, xOnlyPubkey: Uint8Array, signature: Uint8Array, hashType?: number): boolean;
61
+ /**
62
+ * Verify a BIP-322 "simple" P2WPKH signature over an arbitrary byte
63
+ * message, mirroring the verifier vaultd runs on a two-item PoP witness
64
+ * (`bip322` crate 0.0.10 `verify.rs:102-186 verify_full_p2wpkh`).
65
+ *
66
+ * @internal Consumed by `verifyPopWitness` for Native SegWit software
67
+ * wallets, and exposed so the BIP-322 official-vector test suite can pin
68
+ * the verifier independently.
69
+ *
70
+ * @param compressedPubkey - 33-byte SEC1 compressed pubkey of the signer
71
+ * (witness item 1). The address is derived from
72
+ * it; network affects only bech32 encoding, not
73
+ * script or sighash (`message.rs:125-127`).
74
+ * @param encodedSignature - Witness item 0: DER signature with trailing
75
+ * sighash byte, 71 or 72 bytes, SIGHASH_ALL only
76
+ * (`verify.rs:141-161`).
77
+ * @returns `true` if the signature verifies against the P2WPKH address of
78
+ * `compressedPubkey`; `false` otherwise.
79
+ */
80
+ export declare function verifyBip322P2wpkhSimple(messageBytes: Uint8Array, compressedPubkey: Uint8Array, encodedSignature: Uint8Array): boolean;
56
81
  //# sourceMappingURL=bip322Verify.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bip322Verify.d.ts","sourceRoot":"","sources":["../../../../../../src/tbv/core/clients/vault-provider/auth/bip322Verify.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAgDH;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,kBAAkB,CAChC,YAAY,EAAE,UAAU,EACxB,WAAW,EAAE,UAAU,EACvB,SAAS,EAAE,UAAU,GACpB,OAAO,CAwET"}
1
+ {"version":3,"file":"bip322Verify.d.ts","sourceRoot":"","sources":["../../../../../../src/tbv/core/clients/vault-provider/auth/bip322Verify.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AAyHH;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,kBAAkB,CAChC,YAAY,EAAE,UAAU,EACxB,WAAW,EAAE,UAAU,EACvB,SAAS,EAAE,UAAU,EACrB,QAAQ,GAAE,MAAoC,GAC7C,OAAO,CA6CT;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,wBAAwB,CACtC,YAAY,EAAE,UAAU,EACxB,gBAAgB,EAAE,UAAU,EAC5B,gBAAgB,EAAE,UAAU,GAC3B,OAAO,CAyCT"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=depositTerms.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"depositTerms.test.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/core/deposit-terms/__tests__/depositTerms.test.ts"],"names":[],"mappings":""}
@@ -37,7 +37,7 @@ export interface DepositTerms {
37
37
  * btc-vault tx-graph version (`vaultCoreVersion`) these terms describe —
38
38
  * the vault's stamped on-chain version for resumes, the chain's
39
39
  * `activeVaultCoreVersion` for fresh deposits. It selects the PegIn shape
40
- * an approving wallet must expect: v1 = 2 outputs, no anchor; v2 = TRUC
40
+ * an approving wallet must expect: v1 = 2 outputs, no anchor; v2/v3 = TRUC
41
41
  * nVersion 3, 3 outputs with a 240-sat P2A anchor at vout 2, and an
42
42
  * Assert OP_RETURN marker that raises the claim value
43
43
  * (btc-vault `transactions/pegin.rs`, `assert_marker.rs`). A provider that
@@ -99,19 +99,56 @@ export interface DepositTerms {
99
99
  * re-approves after every derive and before the next terms-bound signature.
100
100
  * The re-approval sites are `PeginManager.preparePegin`,
101
101
  * `runDepositorPresignFlow`, and `signAndBroadcast` (the Pre-PegIn broadcast,
102
- * which derives immediately before approving — see `ensurePrePeginTermsApproval`).
102
+ * which re-derives before approving unless `holdsApprovedDepositTerms`
103
+ * reports the byte-equal intent still live — see `ensurePrePeginTermsApproval`).
103
104
  */
104
105
  export interface DepositTermsApprover {
105
106
  approveDepositTerms(terms: DepositTerms): Promise<void>;
107
+ /**
108
+ * OPTIONAL fast-path probe: can the Pre-PegIn signature for exactly these
109
+ * terms proceed under the connection's held approval without a new
110
+ * ceremony? MUST report false once that Pre-PegIn was signed (one-shot),
111
+ * MUST answer from host state without device I/O, MUST return false on any
112
+ * doubt, and MUST never throw. A stale true fails closed at the next
113
+ * signature — this is a UX optimization, never an authorization.
114
+ */
115
+ holdsApprovedDepositTerms?(terms: DepositTerms): Promise<boolean>;
106
116
  }
107
- /** True when the wallet implements {@link DepositTermsApprover.approveDepositTerms}. */
117
+ /**
118
+ * Where Pre-PegIn change must pay. Approval (policy) wallets sign key-path
119
+ * under a wallet policy whose change branch the device alone can derive and
120
+ * mark internal — the receive address is NOT acceptable change
121
+ * (`process_in_outs.c:114-117` @ e400d8d8).
122
+ *
123
+ * Separate from {@link DepositTermsApprover} because only the Pre-PegIn build
124
+ * needs it: the presign/payout ceremonies approve terms without ever creating
125
+ * change, so they must not require a wallet to implement this.
126
+ *
127
+ * MUST be stable across a deposit flow: the app reads it to build the tx and
128
+ * `preparePegin` re-reads it to verify, so mid-flow rotation fails that gate.
129
+ */
130
+ export interface PrePeginChangeSource {
131
+ getChangeAddress(): Promise<string>;
132
+ }
133
+ /** Probes {@link DepositTermsApprover.approveDepositTerms}. */
108
134
  export declare function supportsDepositApproval(wallet: BitcoinWallet): wallet is BitcoinWallet & DepositTermsApprover;
109
135
  /**
110
- * Spreadable forward of `approveDepositTerms` for wallet-wrapper objects.
136
+ * The wallet's change address, for the one caller that needs it.
137
+ *
138
+ * Narrowing on `approveDepositTerms` alone cannot promise this method, so
139
+ * calling it off the narrowed value would die on `is not a function` in the
140
+ * middle of `preparePegin`, after the pubkey read. Ask here instead and fail
141
+ * with something a provider author can act on.
142
+ *
143
+ * @throws If the wallet cannot report a change address.
144
+ */
145
+ export declare function requireChangeAddress(wallet: BitcoinWallet): Promise<string>;
146
+ /**
147
+ * Spreadable forward of the approval capability for wallet-wrapper objects.
111
148
  * Object spread drops prototype methods, so every `{...wallet}` wrapper site
112
149
  * must re-attach the capability explicitly: `...forwardDepositApproval(wallet)`.
113
150
  */
114
- export declare function forwardDepositApproval(wallet: BitcoinWallet): Partial<DepositTermsApprover>;
151
+ export declare function forwardDepositApproval(wallet: BitcoinWallet): Partial<DepositTermsApprover & PrePeginChangeSource>;
115
152
  export interface BuildDepositTermsInputs {
116
153
  /** btc-vault tx-graph version the graph is built under. */
117
154
  vaultCoreVersion: number;
@@ -1 +1 @@
1
- {"version":3,"file":"depositTerms.d.ts","sourceRoot":"","sources":["../../../../src/tbv/core/deposit-terms/depositTerms.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AAKxE,MAAM,WAAW,sBAAsB;IACrC,2EAA2E;IAC3E,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,6DAA6D;IAC7D,QAAQ,CAAC,sBAAsB,EAAE,MAAM,CAAC;IACxC,WAAW;IACX,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B;;;;;;;;;OASG;IACH,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,4CAA4C;IAC5C,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC;;;;OAIG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;CAC9B;AAED;;;;;GAKG;AACH,MAAM,WAAW,YAAY;IAC3B;;;;;;;;;;OAUG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12 +2,13 @@ import { DepositTerms } from './depositTerms';
2
2
  /**
3
3
  * Minimal structural wallet for the Pre-PegIn ceremony. Mirrors
4
4
  * `DeriveContextHashCapableWallet` so an app-side wrapper object qualifies
5
- * without implementing all of `BitcoinWallet`. Both methods are optional so
5
+ * without implementing all of `BitcoinWallet`. All methods are optional so
6
6
  * the capability probe below can run on any wallet.
7
7
  */
8
8
  export interface PrePeginApprovalWallet {
9
9
  deriveContextHash?(appName: string, context: string): Promise<string>;
10
10
  approveDepositTerms?(terms: DepositTerms): Promise<void>;
11
+ holdsApprovedDepositTerms?(terms: DepositTerms): Promise<boolean>;
11
12
  }
12
13
  export interface EnsurePrePeginTermsApprovalParams {
13
14
  wallet: PrePeginApprovalWallet;
@@ -25,10 +26,14 @@ export interface EnsurePrePeginTermsApprovalParams {
25
26
  * - Approval-capable wallets: require terms, assert they match this tx's txid,
26
27
  * derive the vault root over the tx's funding outpoints, then approve.
27
28
  *
28
- * Always derives first: the host cannot read device state, a one-shot cap means
29
- * every retry needs the full ceremony, and whether interleaved signing
30
- * nullifies a loaded intent is unresolved — so the broadcast path never
31
- * approves-only.
29
+ * Skip fast-path: when `holdsApprovedDepositTerms` reports the byte-equal
30
+ * intent still live, the ceremony is skipped — it survives everything the
31
+ * flow does in between (PoP/PegIn signing spend separate device state;
32
+ * app-babylon-vault `sign_psbt_validate.c` @ 73a57c50). A stale true fails
33
+ * closed at the signature; the retry then re-runs the full ceremony.
34
+ *
35
+ * Otherwise always derives first — the host cannot read device state, so
36
+ * this path never approves-only.
32
37
  *
33
38
  * @throws If approval-capable but no terms are provided, or the provided terms
34
39
  * are for a different transaction.
@@ -1 +1 @@
1
- {"version":3,"file":"prePeginApproval.d.ts","sourceRoot":"","sources":["../../../../src/tbv/core/deposit-terms/prePeginApproval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAOH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD;;;;;GAKG;AAC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