@babylonlabs-io/ts-sdk 0.52.0 → 0.53.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 (132) hide show
  1. package/dist/ApplicationRegistry.abi-CLaa6E99.cjs +2 -0
  2. package/dist/ApplicationRegistry.abi-CLaa6E99.cjs.map +1 -0
  3. package/dist/{ApplicationRegistry.abi-Dn2qk6JG.js → ApplicationRegistry.abi-w5prf7Ig.js} +14 -1
  4. package/dist/ApplicationRegistry.abi-w5prf7Ig.js.map +1 -0
  5. package/dist/PayoutManager-1GWmbvI9.cjs +2 -0
  6. package/dist/PayoutManager-1GWmbvI9.cjs.map +1 -0
  7. package/dist/{PayoutManager-BwrV3xFW.js → PayoutManager-Ddo9_Ozc.js} +34 -32
  8. package/dist/PayoutManager-Ddo9_Ozc.js.map +1 -0
  9. package/dist/{PeginManager-BGWNJYPk.js → PeginManager-CTU0wgkJ.js} +37 -34
  10. package/dist/PeginManager-CTU0wgkJ.js.map +1 -0
  11. package/dist/PeginManager-De-eHl3v.cjs +2 -0
  12. package/dist/PeginManager-De-eHl3v.cjs.map +1 -0
  13. package/dist/buildAndBroadcastRefund-BnD2qUDW.cjs +2 -0
  14. package/dist/buildAndBroadcastRefund-BnD2qUDW.cjs.map +1 -0
  15. package/dist/{buildAndBroadcastRefund-BAT5A6MP.js → buildAndBroadcastRefund-DjS9nf87.js} +188 -177
  16. package/dist/buildAndBroadcastRefund-DjS9nf87.js.map +1 -0
  17. package/dist/{challengeAssert-HNbugpqL.cjs → challengeAssert-DLQfNcfU.cjs} +2 -2
  18. package/dist/{challengeAssert-HNbugpqL.cjs.map → challengeAssert-DLQfNcfU.cjs.map} +1 -1
  19. package/dist/{challengeAssert-csvYXBJB.js → challengeAssert-DvdbpEDY.js} +2 -2
  20. package/dist/{challengeAssert-csvYXBJB.js.map → challengeAssert-DvdbpEDY.js.map} +1 -1
  21. package/dist/constants-BhclpREj.js +19 -0
  22. package/dist/constants-BhclpREj.js.map +1 -0
  23. package/dist/constants-CvbARMl-.cjs +2 -0
  24. package/dist/constants-CvbARMl-.cjs.map +1 -0
  25. package/dist/index.cjs +1 -1
  26. package/dist/index.js +182 -181
  27. package/dist/index.js.map +1 -1
  28. package/dist/{mempoolApi-Dc1KSVNI.js → mempoolApi-CB7bHuwi.js} +106 -101
  29. package/dist/mempoolApi-CB7bHuwi.js.map +1 -0
  30. package/dist/mempoolApi-DqJByvqR.cjs +2 -0
  31. package/dist/mempoolApi-DqJByvqR.cjs.map +1 -0
  32. package/dist/noPayout-8dDKwi6n.cjs +2 -0
  33. package/dist/noPayout-8dDKwi6n.cjs.map +1 -0
  34. package/dist/{noPayout-DVx3zxUz.js → noPayout-tZFoNun3.js} +30 -30
  35. package/dist/noPayout-tZFoNun3.js.map +1 -0
  36. package/dist/{peginInput-B5XDDHpy.js → peginInput-BKD_b3gq.js} +10 -11
  37. package/dist/peginInput-BKD_b3gq.js.map +1 -0
  38. package/dist/{peginInput-De0C6aSj.cjs → peginInput-CAiiDZeO.cjs} +2 -2
  39. package/dist/peginInput-CAiiDZeO.cjs.map +1 -0
  40. package/dist/primeVpAuth-CF4cH5_e.cjs +2 -0
  41. package/dist/primeVpAuth-CF4cH5_e.cjs.map +1 -0
  42. package/dist/{primeVpAuth-DxMuWQCi.js → primeVpAuth-l-5x_2UV.js} +91 -85
  43. package/dist/{primeVpAuth-yTddDmGy.cjs.map → primeVpAuth-l-5x_2UV.js.map} +1 -1
  44. package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -1
  45. package/dist/tbv/core/clients/eth/protocol-params-validation.d.ts.map +1 -1
  46. package/dist/tbv/core/clients/eth/types.d.ts +8 -0
  47. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  48. package/dist/tbv/core/clients/index.cjs +1 -1
  49. package/dist/tbv/core/clients/index.js +2 -2
  50. package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts +10 -0
  51. package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts.map +1 -1
  52. package/dist/tbv/core/contracts/index.cjs +1 -1
  53. package/dist/tbv/core/contracts/index.js +1 -1
  54. package/dist/tbv/core/index.cjs +1 -1
  55. package/dist/tbv/core/index.js +177 -176
  56. package/dist/tbv/core/index.js.map +1 -1
  57. package/dist/tbv/core/managers/PayoutManager.d.ts +6 -0
  58. package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -1
  59. package/dist/tbv/core/managers/PeginManager.d.ts +7 -0
  60. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  61. package/dist/tbv/core/managers/index.cjs +1 -1
  62. package/dist/tbv/core/managers/index.js +2 -2
  63. package/dist/tbv/core/primitives/__tests__/vaultCoreVersion.test.d.ts +8 -0
  64. package/dist/tbv/core/primitives/__tests__/vaultCoreVersion.test.d.ts.map +1 -0
  65. package/dist/tbv/core/primitives/index.cjs +1 -1
  66. package/dist/tbv/core/primitives/index.d.ts +1 -1
  67. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  68. package/dist/tbv/core/primitives/index.js +37 -36
  69. package/dist/tbv/core/primitives/index.js.map +1 -1
  70. package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
  71. package/dist/tbv/core/primitives/psbt/payout.d.ts +6 -0
  72. package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
  73. package/dist/tbv/core/primitives/psbt/pegin.d.ts +7 -0
  74. package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
  75. package/dist/tbv/core/primitives/psbt/peginInput.d.ts +6 -0
  76. package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
  77. package/dist/tbv/core/primitives/psbt/refund.d.ts.map +1 -1
  78. package/dist/tbv/core/primitives/scripts/payout.d.ts +6 -0
  79. package/dist/tbv/core/primitives/scripts/payout.d.ts.map +1 -1
  80. package/dist/tbv/core/primitives/vaultCoreVersion.d.ts +26 -0
  81. package/dist/tbv/core/primitives/vaultCoreVersion.d.ts.map +1 -0
  82. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +7 -0
  83. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
  84. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts +6 -0
  85. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  86. package/dist/tbv/core/services/deposit/verifyRegisteredVaultVersions.d.ts +8 -0
  87. package/dist/tbv/core/services/deposit/verifyRegisteredVaultVersions.d.ts.map +1 -1
  88. package/dist/tbv/core/services/index.cjs +1 -1
  89. package/dist/tbv/core/services/index.js +2 -2
  90. package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts +6 -0
  91. package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts.map +1 -1
  92. package/dist/tbv/index.cjs +1 -1
  93. package/dist/tbv/index.js +177 -176
  94. package/dist/tbv/index.js.map +1 -1
  95. package/dist/{verifyScriptPathSchnorrSignature-BKECXOpa.js → verifyScriptPathSchnorrSignature-DpWZx5J0.js} +125 -130
  96. package/dist/verifyScriptPathSchnorrSignature-DpWZx5J0.js.map +1 -0
  97. package/dist/verifyScriptPathSchnorrSignature-a4Us7D3e.cjs +2 -0
  98. package/dist/verifyScriptPathSchnorrSignature-a4Us7D3e.cjs.map +1 -0
  99. package/package.json +3 -3
  100. package/dist/ApplicationRegistry.abi-BAPhJch3.cjs +0 -2
  101. package/dist/ApplicationRegistry.abi-BAPhJch3.cjs.map +0 -1
  102. package/dist/ApplicationRegistry.abi-Dn2qk6JG.js.map +0 -1
  103. package/dist/PayoutManager-BwrV3xFW.js.map +0 -1
  104. package/dist/PayoutManager-CBfHfLfz.cjs +0 -2
  105. package/dist/PayoutManager-CBfHfLfz.cjs.map +0 -1
  106. package/dist/PeginManager-BGWNJYPk.js.map +0 -1
  107. package/dist/PeginManager-DDp-ZRIa.cjs +0 -2
  108. package/dist/PeginManager-DDp-ZRIa.cjs.map +0 -1
  109. package/dist/buildAndBroadcastRefund-3MLyCOtv.cjs +0 -2
  110. package/dist/buildAndBroadcastRefund-3MLyCOtv.cjs.map +0 -1
  111. package/dist/buildAndBroadcastRefund-BAT5A6MP.js.map +0 -1
  112. package/dist/constants-CSG2XeD8.cjs +0 -2
  113. package/dist/constants-CSG2XeD8.cjs.map +0 -1
  114. package/dist/constants-Cd_fN8VT.js +0 -12
  115. package/dist/constants-Cd_fN8VT.js.map +0 -1
  116. package/dist/mempoolApi-Dc1KSVNI.js.map +0 -1
  117. package/dist/mempoolApi-NMiYQAXI.cjs +0 -2
  118. package/dist/mempoolApi-NMiYQAXI.cjs.map +0 -1
  119. package/dist/noPayout-ChPNKTbm.cjs +0 -2
  120. package/dist/noPayout-ChPNKTbm.cjs.map +0 -1
  121. package/dist/noPayout-DVx3zxUz.js.map +0 -1
  122. package/dist/peginInput-B5XDDHpy.js.map +0 -1
  123. package/dist/peginInput-De0C6aSj.cjs.map +0 -1
  124. package/dist/primeVpAuth-DxMuWQCi.js.map +0 -1
  125. package/dist/primeVpAuth-yTddDmGy.cjs +0 -2
  126. package/dist/tbv/core/primitives/__tests__/txGraphVersion.test.d.ts +0 -7
  127. package/dist/tbv/core/primitives/__tests__/txGraphVersion.test.d.ts.map +0 -1
  128. package/dist/tbv/core/primitives/txGraphVersion.d.ts +0 -11
  129. package/dist/tbv/core/primitives/txGraphVersion.d.ts.map +0 -1
  130. package/dist/verifyScriptPathSchnorrSignature-BKECXOpa.js.map +0 -1
  131. package/dist/verifyScriptPathSchnorrSignature-CVPh04ZI.cjs +0 -2
  132. package/dist/verifyScriptPathSchnorrSignature-CVPh04ZI.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mempoolApi-DqJByvqR.cjs","sources":["../src/tbv/core/clients/eth/protocol-params-validation.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts","../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * Validation for protocol parameters fetched from the ProtocolParams contract.\n *\n * These values feed Bitcoin script construction and deposit validation.\n * Invalid params must be caught before they reach transaction-building code,\n * since errors after wallet signing prompts are unrecoverable.\n *\n * The {@link ViemProtocolParamsReader} runs these on every read; consumers\n * implementing their own reader against the same `ProtocolParamsReader`\n * interface should call them too.\n */\n\nimport { assertValidVaultCoreVersion } from \"../../primitives/vaultCoreVersion\";\n\nimport type {\n PegInConfiguration,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n/** Maximum valid value for basis points (100%) */\nconst MAX_BASIS_POINTS = 10000;\n\n/** Maximum value for a Solidity uint32. */\nconst UINT32_MAX = 4_294_967_295;\n\n/** Maximum valid value for a uint8 (e.g. maxHtlcOutputCount). */\nconst UINT8_MAX = 255;\n\n/**\n * Validate an `offchainParamsVersion` value sourced from a contract read.\n * `Number()` on a malformed payload yields `NaN` or a non-integer; both\n * silently break consumers that loop `1..version` or use the value as a\n * map key. Used by reader entry points that surface the version to JS.\n */\nexport function assertValidOffchainParamsVersion(version: number): void {\n if (\n !Number.isInteger(version) ||\n version < 0 ||\n version > UINT32_MAX\n ) {\n throw new Error(\n `Invalid offchainParamsVersion from contract: must be a uint32, got ${version}`,\n );\n }\n}\n\n/**\n * Validate offchain params consistency and bounds.\n * @throws Error on invalid values to prevent constructing invalid Bitcoin scripts.\n */\nexport function validateOffchainParams(params: VersionedOffchainParams): void {\n const errors: string[] = [];\n\n if (params.timelockAssert <= 0n) {\n errors.push(\n `timelockAssert must be positive, got ${params.timelockAssert}`,\n );\n }\n if (params.timelockAssert > BigInt(UINT16_MAX)) {\n errors.push(\n `timelockAssert ${params.timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n\n if (params.timelockChallengeAssert <= 0n) {\n errors.push(\n `timelockChallengeAssert must be positive, got ${params.timelockChallengeAssert}`,\n );\n }\n\n if (params.tRefund <= 0) {\n errors.push(`tRefund must be positive, got ${params.tRefund}`);\n }\n\n if (params.tStale <= 0) {\n errors.push(`tStale must be positive, got ${params.tStale}`);\n }\n\n if (params.securityCouncilKeys.length === 0) {\n errors.push(\"securityCouncilKeys must not be empty\");\n }\n\n if (params.councilQuorum <= 0) {\n errors.push(`councilQuorum must be positive, got ${params.councilQuorum}`);\n }\n if (params.councilQuorum > params.securityCouncilKeys.length) {\n errors.push(\n `councilQuorum (${params.councilQuorum}) exceeds securityCouncilKeys count (${params.securityCouncilKeys.length})`,\n );\n }\n\n if (params.feeRate <= 0n) {\n errors.push(`feeRate must be positive, got ${params.feeRate}`);\n }\n\n if (params.minPeginFeeRate <= 0n) {\n errors.push(\n `minPeginFeeRate must be positive, got ${params.minPeginFeeRate}`,\n );\n }\n\n if (\n !Number.isInteger(params.proverCircuitVersion) ||\n params.proverCircuitVersion < 0 ||\n params.proverCircuitVersion > UINT16_MAX\n ) {\n errors.push(\n `proverCircuitVersion must be a uint16, got ${params.proverCircuitVersion}`,\n );\n }\n\n if (\n !Number.isInteger(params.minPrepeginDepth) ||\n params.minPrepeginDepth <= 0 ||\n params.minPrepeginDepth > UINT32_MAX\n ) {\n errors.push(\n `minPrepeginDepth must be a uint32 in [1, ${UINT32_MAX}], got ${params.minPrepeginDepth}`,\n );\n }\n\n if (params.babeTotalInstances <= 0) {\n errors.push(\n `babeTotalInstances must be positive, got ${params.babeTotalInstances}`,\n );\n }\n if (params.babeInstancesToFinalize <= 0) {\n errors.push(\n `babeInstancesToFinalize must be positive, got ${params.babeInstancesToFinalize}`,\n );\n }\n if (params.babeInstancesToFinalize > params.babeTotalInstances) {\n errors.push(\n `babeInstancesToFinalize (${params.babeInstancesToFinalize}) exceeds babeTotalInstances (${params.babeTotalInstances})`,\n );\n }\n\n if (\n params.minVpCommissionBps < 0 ||\n params.minVpCommissionBps > MAX_BASIS_POINTS\n ) {\n errors.push(\n `minVpCommissionBps must be in [0, ${MAX_BASIS_POINTS}], got ${params.minVpCommissionBps}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid offchain protocol parameters: ${errors.join(\"; \")}`,\n );\n }\n}\n\n/**\n * Validate TBV protocol params returned from the contract.\n * @throws Error on invalid amounts or out-of-range bounded fields.\n */\nexport function validateTBVProtocolParams(params: TBVProtocolParams): void {\n const errors: string[] = [];\n\n if (params.minimumPegInAmount <= 0n) {\n errors.push(\n `minimumPegInAmount must be positive, got ${params.minimumPegInAmount}`,\n );\n }\n\n if (params.maxPegInAmount < params.minimumPegInAmount) {\n errors.push(\n `maxPegInAmount (${params.maxPegInAmount}) must be >= minimumPegInAmount (${params.minimumPegInAmount})`,\n );\n }\n\n if (params.pegInAckTimeout <= 0n) {\n errors.push(\n `pegInAckTimeout must be positive, got ${params.pegInAckTimeout}`,\n );\n }\n\n if (params.pegInActivationTimeout <= 0n) {\n errors.push(\n `pegInActivationTimeout must be positive, got ${params.pegInActivationTimeout}`,\n );\n }\n\n if (\n !Number.isInteger(params.maxHtlcOutputCount) ||\n params.maxHtlcOutputCount <= 0 ||\n params.maxHtlcOutputCount > UINT8_MAX\n ) {\n errors.push(\n `maxHtlcOutputCount must be an integer in [1, ${UINT8_MAX}], got ${params.maxHtlcOutputCount}`,\n );\n }\n\n if (\n typeof params.expiredPegInGraceBlocks !== \"bigint\" ||\n params.expiredPegInGraceBlocks <= 0n\n ) {\n errors.push(\n `expiredPegInGraceBlocks must be a positive bigint, got ${params.expiredPegInGraceBlocks}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`Invalid TBV protocol parameters: ${errors.join(\"; \")}`);\n }\n}\n\n/**\n * Validate the full peg-in configuration after assembly.\n * Checks both TBV params and offchain params consistency, and the\n * top-level `offchainParamsVersion` (which originates from a separate\n * multicall result and so must be range-checked alongside the params it\n * names).\n */\nexport function validatePegInConfiguration(config: PegInConfiguration): void {\n validateTBVProtocolParams(config);\n validateOffchainParams(config.offchainParams);\n\n if (\n !Number.isInteger(config.offchainParamsVersion) ||\n config.offchainParamsVersion < 0 ||\n config.offchainParamsVersion > UINT32_MAX\n ) {\n throw new Error(\n `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${config.offchainParamsVersion}`,\n );\n }\n\n // The contract enforces ≥ 1 (setter rejects 0); a 0 here means a\n // mis-decoded read or a pre-vaultCoreVersion contract — fail closed.\n assertValidVaultCoreVersion(\n config.activeVaultCoreVersion,\n \"ProtocolParams.activeVaultCoreVersion()\",\n );\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { hexToUint8Array } from \"../../primitives/utils/bitcoin\";\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { assertValidOffchainParamsVersion } from \"./protocol-params-validation\";\nimport type {\n OnChainBtcPubkey,\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Inclusive upper bound the BTCVaultRegistry contract enforces on a vault\n * provider's commission (the contract check is `< 10000`).\n */\nconst MAX_VP_COMMISSION_BPS = 9999;\n\n/** Raw `getBtcVaultBasicInfo` tuple as decoded by viem. */\ntype RawVaultBasicInfo = {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n};\n\n/** Raw `getBtcVaultProtocolInfo` tuple as decoded by viem. */\ntype RawVaultProtocolInfo = {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n};\n\nfunction mapVaultBasicInfo(result: RawVaultBasicInfo): VaultBasicInfo {\n return {\n depositor: result.depositor,\n depositorBtcPubKey: result.depositorBtcPubKey,\n amount: result.amount,\n vaultProvider: result.vaultProvider,\n status: result.status,\n applicationEntryPoint: result.applicationEntryPoint,\n createdAt: result.createdAt,\n };\n}\n\nfunction mapVaultProtocolInfo(result: RawVaultProtocolInfo): VaultProtocolInfo {\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n}\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n /**\n * Read the VP's persistent x-only BTC pubkey from the on-chain\n * registry. Validates length, hex form, and secp256k1 curve\n * membership before minting the brand. Returns 64-char lowercase\n * hex without the `0x` prefix.\n */\n async getVaultProviderBtcPubKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderBTCKey\",\n args: [vpAddress],\n })) as Hex;\n const lowered = result.toLowerCase();\n if (!/^0x[0-9a-f]{64}$/.test(lowered)) {\n throw new Error(\n `getVaultProviderBTCKey returned an unexpected value (vp=${vpAddress}, length ${lowered.length}, prefix \"${lowered.slice(0, 2)}\")`,\n );\n }\n const stripped = lowered.slice(2);\n if (!ecc.isXOnlyPoint(hexToUint8Array(stripped))) {\n throw new Error(\n `getVaultProviderBTCKey returned a value that is not on the secp256k1 curve (vp=${vpAddress})`,\n );\n }\n return stripped as OnChainBtcPubkey;\n }\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as RawVaultBasicInfo;\n\n return mapVaultBasicInfo(result);\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as RawVaultProtocolInfo;\n\n return mapVaultProtocolInfo(result);\n }\n\n async getProtocolInfoBatch(\n vaultIds: readonly Hex[],\n ): Promise<VaultProtocolInfo[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) => {\n const result = info as unknown as {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n };\n if (\n !result.depositorSignedPeginTx ||\n result.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultIds[i]} not found on-chain or has no pegin transaction`,\n );\n }\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n });\n }\n\n /**\n * Read the protocol pegin fee (in wei) for a given vault provider.\n * Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.\n */\n async getPegInFee(vaultProvider: Address): Promise<bigint> {\n return (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n }\n\n /**\n * Read a vault provider's current commission in basis points from\n * BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the\n * legitimate range is `[0, 9999]`; anything outside indicates a wrong\n * contract address or ABI drift and is surfaced as an error rather than\n * trusted.\n */\n async getVaultProviderCommission(vaultProvider: Address): Promise<number> {\n // viem infers `number` from the `uint16` return in the `as const` ABI.\n const bps = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderCommission\",\n args: [vaultProvider],\n });\n\n if (!Number.isInteger(bps) || bps < 0 || bps > MAX_VP_COMMISSION_BPS) {\n throw new Error(\n `getVaultProviderCommission returned ${bps} bps for ${vaultProvider}, ` +\n `outside the protocol range [0, ${MAX_VP_COMMISSION_BPS}]`,\n );\n }\n\n return bps;\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n // One round-trip for both structs (hard-fail): they feed signing/refund/\n // broadcast rebinds, so reading them in a single multicall also pins both\n // to the same block — no basic/protocol skew across two `eth_call`s.\n const [basicRaw, protocolRaw] = await this.publicClient.multicall({\n contracts: [\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n },\n {\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n },\n ],\n allowFailure: false,\n });\n\n const basic = mapVaultBasicInfo(basicRaw);\n const protocol = mapVaultProtocolInfo(protocolRaw);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n\n /**\n * Read `offchainParamsVersion` for many vaults in a single multicall.\n * Reads only `getBtcVaultProtocolInfo` (one read per vault), so an N-vault\n * batch costs one RPC round-trip instead of 2N parallel `eth_call`s.\n */\n async getOffchainParamsVersionsByVaultIds(\n vaultIds: readonly Hex[],\n ): Promise<number[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info) => {\n const protocolInfo = info as unknown as VaultProtocolInfo;\n if (\n !protocolInfo.depositorSignedPeginTx ||\n protocolInfo.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n \"Vault not found on-chain or has no pegin transaction while reading offchain params version\",\n );\n }\n const version = Number(protocolInfo.offchainParamsVersion);\n assertValidOffchainParamsVersion(version);\n return version;\n });\n }\n}\n","/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type {\n MempoolUTXO,\n NetworkFees,\n OutspendStatus,\n TxInfo,\n UtxoInfo,\n} from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers\n return await fetch(url, {\n ...options,\n signal: AbortSignal.any(signals),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message ?? errorJson.error;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n assertValidTxid(txid);\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the current block tip height.\n *\n * Source: mempool.space API — `GET /api/blocks/tip/height` returns the height\n * of the most recent block as a plain-text integer.\n *\n * @param apiUrl - Mempool API base URL\n * @returns The height of the most recent block\n * @throws Error if the response is not a whole number\n */\nexport async function getTipHeight(apiUrl: string): Promise<number> {\n const raw = await fetchApi<string>(`${apiUrl}/blocks/tip/height`);\n const trimmed = raw.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new Error(\n `Mempool API returned an invalid block tip height: \"${raw}\"`,\n );\n }\n return Number.parseInt(trimmed, 10);\n}\n\n/**\n * Get the spend status of a specific transaction output.\n *\n * Calls the esplora-compatible `GET /tx/{txid}/outspend/{vout}` endpoint\n * (mempool.space backend, mempool/electrs `rest.rs`). Returns\n * `{ spent: false }` for an unspent output, or\n * `{ spent: true, txid, vin, status }` when the output has been spent.\n *\n * @param txid - The transaction id whose output is being checked (no 0x prefix)\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns The output's spend status\n */\nexport async function getOutspend(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<OutspendStatus> {\n assertValidTxid(txid);\n if (!isValidVout(vout)) {\n throw new Error(`Invalid vout ${vout} for transaction ${txid}`);\n }\n return fetchApi<OutspendStatus>(`${apiUrl}/tx/${txid}/outspend/${vout}`);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n assertValidTxid(txid);\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx/${txid}/hex`);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n return await response.text();\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get transaction hex for ${txid}: ${error.message}`);\n }\n throw new Error(`Failed to get transaction hex for ${txid}: Unknown error`);\n }\n}\n\n/**\n * Get UTXO information for a specific transaction output.\n *\n * This is used for constructing PSBTs where we need the witnessUtxo data.\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param txid - The transaction ID containing the UTXO\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns UTXO information with value and scriptPubKey\n */\nexport async function getUtxoInfo(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<UtxoInfo> {\n assertValidTxid(txid);\n const txInfo = await getTxInfo(txid, apiUrl);\n\n if (!isValidVout(vout, txInfo.vout.length)) {\n throw new Error(\n `Invalid vout ${vout} for transaction ${txid} (has ${txInfo.vout.length} outputs)`,\n );\n }\n\n const output = txInfo.vout[vout];\n if (!isValidSatoshiValue(output.value)) {\n throw new Error(`Invalid UTXO value ${output.value} for ${txid}:${vout}`);\n }\n assertValidScriptPubKey(output.scriptpubkey, `${txid}:${vout}`);\n\n return {\n txid,\n vout,\n value: output.value,\n scriptPubKey: output.scriptpubkey,\n };\n}\n\n/**\n * Get all UTXOs for a Bitcoin address.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of UTXOs sorted by value (largest first)\n */\nexport async function getAddressUtxos(\n address: string,\n apiUrl: string,\n): Promise<MempoolUTXO[]> {\n assertValidAddress(address);\n try {\n // Fetch UTXOs for the address\n const utxos = await fetchApi<\n {\n txid: string;\n vout: number;\n value: number;\n status: {\n confirmed: boolean;\n };\n }[]\n >(`${apiUrl}/address/${address}/utxo`);\n\n // Fetch scriptPubKey for the address\n const addressInfo = await fetchApi<{\n isvalid: boolean;\n scriptPubKey: string;\n }>(`${apiUrl}/v1/validate-address/${address}`);\n\n if (!addressInfo.isvalid) {\n throw new Error(\n `Invalid Bitcoin address: ${address}. Mempool API validation failed.`,\n );\n }\n assertValidScriptPubKey(addressInfo.scriptPubKey, address);\n\n // Validate UTXO fields from the listing endpoint.\n // Per-UTXO cross-verification against /tx/{txid} is intentionally NOT done\n // here — it would be expensive (N API calls) and redundant: the broadcast\n // path already verifies each selected input via getUtxoInfo before signing.\n // Both endpoints come from the same mempool API, so cross-checking one\n // against the other on the same server does not add real security.\n for (const utxo of utxos) {\n assertValidTxid(utxo.txid);\n if (!isValidVout(utxo.vout)) {\n throw new Error(`Invalid vout ${utxo.vout} for ${utxo.txid}`);\n }\n if (!isValidSatoshiValue(utxo.value)) {\n throw new Error(\n `Invalid UTXO value ${utxo.value} for ${utxo.txid}:${utxo.vout}`,\n );\n }\n }\n\n // Sort by value (largest first) and map to our UTXO format\n const sortedUTXOs = utxos.sort((a, b) => b.value - a.value);\n\n return sortedUTXOs.map((utxo) => ({\n txid: utxo.txid,\n vout: utxo.vout,\n value: utxo.value,\n scriptPubKey: addressInfo.scriptPubKey,\n confirmed: utxo.status.confirmed,\n }));\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Failed to get UTXOs for address ${address}: ${error.message}`,\n );\n }\n throw new Error(\n `Failed to get UTXOs for address ${address}: Unknown error`,\n );\n }\n}\n\n/**\n * Get the mempool API URL for a given network.\n *\n * @param network - Bitcoin network (mainnet, testnet, signet)\n * @returns The mempool API URL\n */\nexport function getMempoolApiUrl(\n network: \"mainnet\" | \"testnet\" | \"signet\",\n): string {\n return MEMPOOL_API_URLS[network];\n}\n\n/**\n * Transaction summary from address transactions endpoint.\n */\nexport interface AddressTx {\n txid: string;\n status: {\n confirmed: boolean;\n block_height?: number;\n };\n}\n\n/**\n * Get recent transactions for a Bitcoin address.\n *\n * Returns the last 25 confirmed transactions plus any unconfirmed (mempool) transactions.\n * This is useful for checking if a specific transaction has been broadcast.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of recent transactions\n */\nexport async function getAddressTxs(\n address: string,\n apiUrl: string,\n): Promise<AddressTx[]> {\n assertValidAddress(address);\n return fetchApi<AddressTx[]>(`${apiUrl}/address/${address}/txs`);\n}\n\n/**\n * Fetches Bitcoin network fee recommendations from mempool.space API.\n *\n * @param apiUrl - Mempool API base URL\n * @returns Fee rates in sat/vbyte for different confirmation times\n * @throws Error if request fails or returns invalid data\n *\n * @see https://mempool.space/docs/api/rest#get-recommended-fees\n */\nexport async function getNetworkFees(apiUrl: string): Promise<NetworkFees> {\n const response = await fetchWithTimeout(`${apiUrl}/v1/fees/recommended`);\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch network fees: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n const feeFields = [\n \"fastestFee\",\n \"halfHourFee\",\n \"hourFee\",\n \"economyFee\",\n \"minimumFee\",\n ] as const;\n\n for (const field of feeFields) {\n if (!isValidFeeRate(data[field])) {\n throw new Error(\n `Invalid fee rate ${field}=${data[field]} from mempool API: expected a positive number ≤ ${MAX_FEE_RATE}`,\n );\n }\n }\n\n if (\n data.minimumFee > data.economyFee ||\n data.economyFee > data.hourFee ||\n data.hourFee > data.halfHourFee ||\n data.halfHourFee > data.fastestFee\n ) {\n throw new Error(\n `Fee rate ordering violation from mempool API: expected ` +\n `minimumFee (${data.minimumFee}) <= economyFee (${data.economyFee}) <= ` +\n `hourFee (${data.hourFee}) <= halfHourFee (${data.halfHourFee}) <= ` +\n `fastestFee (${data.fastestFee}).`,\n );\n }\n\n return data as NetworkFees;\n}\n\n"],"names":["UINT16_MAX","MAX_BASIS_POINTS","UINT32_MAX","UINT8_MAX","assertValidOffchainParamsVersion","version","validateOffchainParams","params","errors","validateTBVProtocolParams","validatePegInConfiguration","config","assertValidVaultCoreVersion","MAX_VP_COMMISSION_BPS","mapVaultBasicInfo","result","mapVaultProtocolInfo","offchainParamsVersion","ViemVaultRegistryReader","publicClient","contractAddress","vpAddress","lowered","BTCVaultRegistryABI","stripped","ecc","hexToUint8Array","vaultId","vaultIds","info","vaultProvider","bps","basicRaw","protocolRaw","basic","protocol","protocolInfo","MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","error","MAX_FEE_RATE","isValidSatoshiValue","value","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","scriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","errorJson","getTxInfo","getTipHeight","raw","trimmed","getOutspend","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field"],"mappings":"6fAwBMA,EAAa,MAGbC,EAAmB,IAGnBC,EAAa,WAGbC,EAAY,IAQX,SAASC,EAAiCC,EAAuB,CACtE,GACE,CAAC,OAAO,UAAUA,CAAO,GACzBA,EAAU,GACVA,EAAUH,EAEV,MAAM,IAAI,MACR,sEAAsEG,CAAO,EAA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,WAAW,oBAC9CA,EAAK,UAAU,IAAA,EAIpC,OAAOA,CACT"}
@@ -0,0 +1,2 @@
1
+ "use strict";const l=require("@babylonlabs-io/babylon-tbv-rust-wasm"),a=require("buffer"),d=require("bitcoinjs-lib"),t=require("./bitcoin-CHfKAhcI.cjs"),C=require("./verifyScriptPathSchnorrSignature-a4Us7D3e.cjs");async function S(s){await l.initWasm();const{prePeginParams:e,fundedPrePeginTxHex:o,htlcVout:r,refundFee:c,hashlock:f}=s,g=C.normalizeAuthAnchorHash(e.authAnchorHash),u=new l.WasmPrePeginTx(e.vaultCoreVersion,e.depositorPubkey,e.vaultProviderPubkey,e.vaultKeeperPubkeys,e.universalChallengerPubkeys,[...e.hashlocks],new BigUint64Array(l.assertPositiveBigintArray(e.pegInAmounts,"pegInAmounts")),e.timelockRefund,e.feeRate,e.minPeginFeeRate,e.numLocalChallengers,e.councilQuorum,e.councilSize,e.network,g);let n=null;try{const p=u.getHtlcScriptPubKey(r).toLowerCase(),h=u.getHtlcValue(r);n=u.fromFundedTransaction(o);const x=n.buildRefundTx(c,r),k=await l.getPrePeginHtlcConnectorInfo({txGraphVersion:e.vaultCoreVersion,depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlock:f,timelockRefund:e.timelockRefund,network:e.network}),$=o.startsWith("0x")?o.slice(2):o,v=d.Transaction.fromHex($),y=v.outs[r];if(!y)throw new Error(`HTLC output at vout ${r} not found in funded Pre-PegIn tx (tx has ${v.outs.length} outputs)`);const T=t.uint8ArrayToHex(new Uint8Array(y.script)).toLowerCase();if(T!==p)throw new Error(`HTLC scriptPubKey mismatch at vout ${r}: reconstructed template expects ${p}, funded tx carries ${T}. Refund refused — the (hashlocks, pegInAmounts) vector does not match the on-chain commitment.`);const w=BigInt(y.value);if(w!==h)throw new Error(`HTLC value mismatch at vout ${r}: reconstructed template expects ${h} sat, funded tx carries ${w} sat. Refund refused — the pegInAmounts vector does not match the on-chain commitment.`);const i=d.Transaction.fromHex(x);if(i.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${i.ins.length}`);const P=i.ins[0],H=v.getId(),A=t.uint8ArrayToHex(new Uint8Array(P.hash).slice().reverse());if(A!==H)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${H}, got ${A}`);if(P.index!==r)throw new Error(`Refund input index ${P.index} does not match expected htlcVout ${r}`);const m=new d.Psbt;if(m.setVersion(i.version),m.setLocktime(i.locktime),m.addInput({hash:P.hash,index:P.index,sequence:P.sequence,witnessUtxo:{script:y.script,value:y.value},tapLeafScript:[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(t.hexToUint8Array(k.refundScript)),controlBlock:a.Buffer.from(t.hexToUint8Array(k.refundControlBlock))}],tapInternalKey:a.Buffer.from(l.tapInternalPubkey)}),i.outs.length!==1)throw new Error(`Refund transaction must have exactly 1 output, got ${i.outs.length}`);const b=i.outs[0],I=t.stripHexPrefix(t.deriveBip86ScriptPubKeyHex(e.depositorPubkey)).toLowerCase(),R=t.uint8ArrayToHex(new Uint8Array(b.script)).toLowerCase();if(R!==I)throw new Error(`Refund output scriptPubKey ${R} does not match the depositor's BIP-86 address ${I}. Refund refused — the reclaimed funds would not return to the depositor.`);const B=w-c;if(BigInt(b.value)!==B)throw new Error(`Refund output value ${BigInt(b.value)} sat does not equal the HTLC value ${w} sat minus the requested fee ${c} sat (expected ${B} sat). Refund refused — the reclaimed amount would be burned as excess fee.`);return m.addOutput({script:b.script,value:b.value}),{psbtHex:m.toHex()}}finally{n==null||n.free(),u.free()}}async function E(s){const e=t.stripHexPrefix(s.noPayoutTxHex),o=d.Transaction.fromHex(e),{noPayoutScript:r,noPayoutControlBlock:c}=await l.getAssertNoPayoutScriptInfo(s.connectorParams,s.challengerPubkey),f=t.hexToUint8Array(r),g=t.hexToUint8Array(c),u=new d.Psbt;u.setVersion(o.version),u.setLocktime(o.locktime);for(let n=0;n<o.ins.length;n++){const p=o.ins[n],h=s.prevouts[n];if(!h)throw new Error(`Missing prevout data for input ${n}`);const x={hash:p.hash,index:p.index,sequence:p.sequence,witnessUtxo:{script:a.Buffer.from(t.hexToUint8Array(t.stripHexPrefix(h.script_pubkey))),value:h.value}};n===0&&(x.tapLeafScript=[{leafVersion:t.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(f),controlBlock:a.Buffer.from(g)}],x.tapInternalKey=a.Buffer.from(l.tapInternalPubkey)),u.addInput(x)}for(const n of o.outs)u.addOutput({script:n.script,value:n.value});return u.toHex()}function K(s,e,o){const r=d.Transaction.fromHex(t.stripHexPrefix(s));if(r.outs.length!==1)throw new Error(`NoPayout transaction must have exactly 1 output, got ${r.outs.length}`);const c=t.hexToUint8Array(t.processPublicKeyToXOnly(e)),{output:f}=d.payments.p2tr({internalPubkey:a.Buffer.from(c),network:t.getNetwork(o)});if(!f)throw new Error("Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation");if(!r.outs[0].script.equals(f))throw new Error("NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address")}exports.assertNoPayoutOutputMatchesChallenger=K;exports.buildNoPayoutPsbt=E;exports.buildRefundPsbt=S;
2
+ //# sourceMappingURL=noPayout-8dDKwi6n.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"noPayout-8dDKwi6n.cjs","sources":["../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n assertPositiveBigintArray,\n getPrePeginHtlcConnectorInfo,\n initWasm,\n tapInternalPubkey,\n WasmPrePeginTx,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<timelockRefund> CSV DROP <depositorPubkey> CHECKSIG`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n await initWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against the funded\n // transaction: the WASM template's HTLC scriptPubKey at `htlcVout`\n // must equal the bytes the funded tx carries at the same output.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const expectedHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: prePeginParams.vaultCoreVersion,\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["buildRefundPsbt","params","initWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","WasmPrePeginTx","assertPositiveBigintArray","fundedTx","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","i","input","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":"sNAyEA,eAAsBA,EACpBC,EACgC,CAChC,MAAMC,WAAA,EAEN,KAAM,CAAE,eAAAC,EAAgB,oBAAAC,EAAqB,SAAAC,EAAU,UAAAC,EAAW,SAAAC,GAChEN,EAYIO,EAA2BC,EAAAA,wBAC/BN,EAAe,cAAA,EAIXO,EAAa,IAAIC,EAAAA,eACrBR,EAAe,iBACfA,EAAe,gBACfA,EAAe,oBACfA,EAAe,mBACfA,EAAe,2BACf,CAAC,GAAGA,EAAe,SAAS,EAC5B,IAAI,eACFS,4BAA0BT,EAAe,aAAc,cAAc,CAAA,EAEvEA,EAAe,eACfA,EAAe,QACfA,EA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,EAEFI,EAAU,eAAiBpB,SAAO,KAAKE,EAAAA,iBAAiB,GAG1DL,EAAK,SAASuB,CAAS,CACzB,CAGA,UAAWC,KAAUV,EAAW,KAC9Bd,EAAK,UAAU,CACb,OAAQwB,EAAO,OACf,MAAOA,EAAO,KAAA,CACf,EAGH,OAAOxB,EAAK,MAAA,CACd,CAmBO,SAASyB,EACdZ,EACAa,EACAC,EACM,CACN,MAAMC,EAAKrC,EAAAA,YAAY,QAAQiB,EAAAA,eAAeK,CAAa,CAAC,EAE5D,GAAIe,EAAG,KAAK,SAAW,EACrB,MAAM,IAAI,MACR,wDAAwDA,EAAG,KAAK,MAAM,EAAA,EAI1E,MAAMC,EAAQzB,EAAAA,gBAAgB0B,EAAAA,wBAAwBJ,CAAgB,CAAC,EACjE,CAAE,OAAQK,GAAmBC,EAAAA,SAAS,KAAK,CAC/C,eAAgB7B,EAAAA,OAAO,KAAK0B,CAAK,EACjC,QAASI,EAAAA,WAAWN,CAAO,CAAA,CAC5B,EACD,GAAI,CAACI,EACH,MAAM,IAAI,MACR,qFAAA,EAIJ,GAAI,CAACH,EAAG,KAAK,CAAC,EAAE,OAAO,OAAOG,CAAc,EAC1C,MAAM,IAAI,MACR,kFAAA,CAGN"}
@@ -1,21 +1,21 @@
1
- import { initWasm as V, WasmPrePeginTx as O, assertPositiveBigintArray as N, getPrePeginHtlcConnectorInfo as q, tapInternalPubkey as E, getAssertNoPayoutScriptInfo as U } from "@babylonlabs-io/babylon-tbv-rust-wasm";
1
+ import { initWasm as L, WasmPrePeginTx as V, assertPositiveBigintArray as O, getPrePeginHtlcConnectorInfo as N, tapInternalPubkey as B, getAssertNoPayoutScriptInfo as q } from "@babylonlabs-io/babylon-tbv-rust-wasm";
2
2
  import { Buffer as a } from "buffer";
3
- import { Transaction as w, Psbt as S, payments as _ } from "bitcoinjs-lib";
3
+ import { Transaction as w, Psbt as E, payments as U } from "bitcoinjs-lib";
4
4
  import { u as k, T as K, h as f, s as g, d as F, p as z, j as W } from "./bitcoin-B5aNKtsk.js";
5
- import { n as D, T as B } from "./verifyScriptPathSchnorrSignature-BKECXOpa.js";
6
- async function J(s) {
7
- await V();
8
- const { prePeginParams: e, fundedPrePeginTxHex: n, htlcVout: t, refundFee: i, hashlock: c } = s, v = D(
5
+ import { n as _ } from "./verifyScriptPathSchnorrSignature-DpWZx5J0.js";
6
+ async function X(s) {
7
+ await L();
8
+ const { prePeginParams: e, fundedPrePeginTxHex: n, htlcVout: t, refundFee: i, hashlock: c } = s, v = _(
9
9
  e.authAnchorHash
10
- ), r = new O(
11
- B,
10
+ ), r = new V(
11
+ e.vaultCoreVersion,
12
12
  e.depositorPubkey,
13
13
  e.vaultProviderPubkey,
14
14
  e.vaultKeeperPubkeys,
15
15
  e.universalChallengerPubkeys,
16
16
  [...e.hashlocks],
17
17
  new BigUint64Array(
18
- N(e.pegInAmounts, "pegInAmounts")
18
+ O(e.pegInAmounts, "pegInAmounts")
19
19
  ),
20
20
  e.timelockRefund,
21
21
  e.feeRate,
@@ -30,8 +30,8 @@ async function J(s) {
30
30
  try {
31
31
  const l = r.getHtlcScriptPubKey(t).toLowerCase(), p = r.getHtlcValue(t);
32
32
  o = r.fromFundedTransaction(n);
33
- const h = o.buildRefundTx(i, t), H = await q({
34
- txGraphVersion: B,
33
+ const h = o.buildRefundTx(i, t), H = await N({
34
+ txGraphVersion: e.vaultCoreVersion,
35
35
  depositorPubkey: e.depositorPubkey,
36
36
  vaultProviderPubkey: e.vaultProviderPubkey,
37
37
  vaultKeeperPubkeys: e.vaultKeeperPubkeys,
@@ -39,7 +39,7 @@ async function J(s) {
39
39
  hashlock: c,
40
40
  timelockRefund: e.timelockRefund,
41
41
  network: e.network
42
- }), L = n.startsWith("0x") ? n.slice(2) : n, b = w.fromHex(L), P = b.outs[t];
42
+ }), S = n.startsWith("0x") ? n.slice(2) : n, b = w.fromHex(S), P = b.outs[t];
43
43
  if (!P)
44
44
  throw new Error(
45
45
  `HTLC output at vout ${t} not found in funded Pre-PegIn tx (tx has ${b.outs.length} outputs)`
@@ -72,7 +72,7 @@ async function J(s) {
72
72
  throw new Error(
73
73
  `Refund input index ${d.index} does not match expected htlcVout ${t}`
74
74
  );
75
- const m = new S();
75
+ const m = new E();
76
76
  if (m.setVersion(u.version), m.setLocktime(u.locktime), m.addInput({
77
77
  hash: d.hash,
78
78
  index: d.index,
@@ -90,24 +90,24 @@ async function J(s) {
90
90
  )
91
91
  }
92
92
  ],
93
- tapInternalKey: a.from(E)
93
+ tapInternalKey: a.from(B)
94
94
  }), u.outs.length !== 1)
95
95
  throw new Error(
96
96
  `Refund transaction must have exactly 1 output, got ${u.outs.length}`
97
97
  );
98
98
  const x = u.outs[0], $ = g(
99
99
  F(e.depositorPubkey)
100
- ).toLowerCase(), A = k(
100
+ ).toLowerCase(), C = k(
101
101
  new Uint8Array(x.script)
102
102
  ).toLowerCase();
103
- if (A !== $)
103
+ if (C !== $)
104
104
  throw new Error(
105
- `Refund output scriptPubKey ${A} does not match the depositor's BIP-86 address ${$}. Refund refused — the reclaimed funds would not return to the depositor.`
105
+ `Refund output scriptPubKey ${C} does not match the depositor's BIP-86 address ${$}. Refund refused — the reclaimed funds would not return to the depositor.`
106
106
  );
107
- const C = y - i;
108
- if (BigInt(x.value) !== C)
107
+ const A = y - i;
108
+ if (BigInt(x.value) !== A)
109
109
  throw new Error(
110
- `Refund output value ${BigInt(x.value)} sat does not equal the HTLC value ${y} sat minus the requested fee ${i} sat (expected ${C} sat). Refund refused — the reclaimed amount would be burned as excess fee.`
110
+ `Refund output value ${BigInt(x.value)} sat does not equal the HTLC value ${y} sat minus the requested fee ${i} sat (expected ${A} sat). Refund refused — the reclaimed amount would be burned as excess fee.`
111
111
  );
112
112
  return m.addOutput({
113
113
  script: x.script,
@@ -117,11 +117,11 @@ async function J(s) {
117
117
  o == null || o.free(), r.free();
118
118
  }
119
119
  }
120
- async function Y(s) {
121
- const e = g(s.noPayoutTxHex), n = w.fromHex(e), { noPayoutScript: t, noPayoutControlBlock: i } = await U(
120
+ async function J(s) {
121
+ const e = g(s.noPayoutTxHex), n = w.fromHex(e), { noPayoutScript: t, noPayoutControlBlock: i } = await q(
122
122
  s.connectorParams,
123
123
  s.challengerPubkey
124
- ), c = f(t), v = f(i), r = new S();
124
+ ), c = f(t), v = f(i), r = new E();
125
125
  r.setVersion(n.version), r.setLocktime(n.locktime);
126
126
  for (let o = 0; o < n.ins.length; o++) {
127
127
  const l = n.ins[o], p = s.prevouts[o];
@@ -142,7 +142,7 @@ async function Y(s) {
142
142
  script: a.from(c),
143
143
  controlBlock: a.from(v)
144
144
  }
145
- ], h.tapInternalKey = a.from(E)), r.addInput(h);
145
+ ], h.tapInternalKey = a.from(B)), r.addInput(h);
146
146
  }
147
147
  for (const o of n.outs)
148
148
  r.addOutput({
@@ -151,13 +151,13 @@ async function Y(s) {
151
151
  });
152
152
  return r.toHex();
153
153
  }
154
- function Z(s, e, n) {
154
+ function Y(s, e, n) {
155
155
  const t = w.fromHex(g(s));
156
156
  if (t.outs.length !== 1)
157
157
  throw new Error(
158
158
  `NoPayout transaction must have exactly 1 output, got ${t.outs.length}`
159
159
  );
160
- const i = f(z(e)), { output: c } = _.p2tr({
160
+ const i = f(z(e)), { output: c } = U.p2tr({
161
161
  internalPubkey: a.from(i),
162
162
  network: W(n)
163
163
  });
@@ -171,8 +171,8 @@ function Z(s, e, n) {
171
171
  );
172
172
  }
173
173
  export {
174
- Y as a,
175
- J as b,
176
- Z as c
174
+ J as a,
175
+ X as b,
176
+ Y as c
177
177
  };
178
- //# sourceMappingURL=noPayout-DVx3zxUz.js.map
178
+ //# sourceMappingURL=noPayout-tZFoNun3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"noPayout-tZFoNun3.js","sources":["../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n assertPositiveBigintArray,\n getPrePeginHtlcConnectorInfo,\n initWasm,\n tapInternalPubkey,\n WasmPrePeginTx,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<timelockRefund> CSV DROP <depositorPubkey> CHECKSIG`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n await initWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against the funded\n // transaction: the WASM template's HTLC scriptPubKey at `htlcVout`\n // must equal the bytes the funded tx carries at the same output.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const expectedHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: prePeginParams.vaultCoreVersion,\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["buildRefundPsbt","params","initWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","WasmPrePeginTx","assertPositiveBigintArray","fundedTx","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","i","input","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":";;;;;AAyEA,eAAsBA,EACpBC,GACgC;AAChC,QAAMC,EAAA;AAEN,QAAM,EAAE,gBAAAC,GAAgB,qBAAAC,GAAqB,UAAAC,GAAU,WAAAC,GAAW,UAAAC,MAChEN,GAYIO,IAA2BC;AAAA,IAC/BN,EAAe;AAAA,EAAA,GAIXO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I;AAAA,MACR;AAAA,IAAA;AAIJ,MAAI,CAACH,EAAG,KAAK,CAAC,EAAE,OAAO,OAAOG,CAAc;AAC1C,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAGN;"}
@@ -2,10 +2,9 @@ import { getPrePeginHtlcConnectorInfo as k, tapInternalPubkey as y } from "@baby
2
2
  import { Buffer as u } from "buffer";
3
3
  import { Transaction as P, Psbt as p } from "bitcoinjs-lib";
4
4
  import { s as d, u as x, h as l, T as I } from "./bitcoin-B5aNKtsk.js";
5
- import { T as b } from "./verifyScriptPathSchnorrSignature-BKECXOpa.js";
6
- async function B(t) {
5
+ async function m(t) {
7
6
  const r = d(t.peginTxHex), a = d(t.fundedPrePeginTxHex), n = await k({
8
- txGraphVersion: b,
7
+ txGraphVersion: t.vaultCoreVersion,
9
8
  depositorPubkey: t.depositorPubkey,
10
9
  vaultProviderPubkey: t.vaultProviderPubkey,
11
10
  vaultKeeperPubkeys: t.vaultKeeperPubkeys,
@@ -56,7 +55,7 @@ async function B(t) {
56
55
  });
57
56
  return { psbtHex: s.toHex() };
58
57
  }
59
- function $(t, r) {
58
+ function B(t, r) {
60
59
  const n = p.fromHex(t).data.inputs[0];
61
60
  if (!n)
62
61
  throw new Error("PegIn PSBT has no inputs");
@@ -66,7 +65,7 @@ function $(t, r) {
66
65
  );
67
66
  for (const i of n.tapScriptSig)
68
67
  if (i.pubkey.equals(e))
69
- return T(i.signature);
68
+ return b(i.signature);
70
69
  throw new Error(
71
70
  `No PegIn input signature found for depositor pubkey: ${r}`
72
71
  );
@@ -77,7 +76,7 @@ function $(t, r) {
77
76
  "No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT"
78
77
  );
79
78
  }
80
- function z(t) {
79
+ function A(t) {
81
80
  const r = p.fromHex(t);
82
81
  try {
83
82
  r.finalizeAllInputs();
@@ -91,7 +90,7 @@ function z(t) {
91
90
  }
92
91
  return r.extractTransaction().toHex();
93
92
  }
94
- function T(t) {
93
+ function b(t) {
95
94
  if (t.length === 64)
96
95
  return x(new Uint8Array(t));
97
96
  throw t.length === 65 ? new Error(
@@ -99,8 +98,8 @@ function T(t) {
99
98
  ) : new Error(`Unexpected PegIn input signature length: ${t.length}`);
100
99
  }
101
100
  export {
102
- B as b,
103
- $ as e,
104
- z as f
101
+ m as b,
102
+ B as e,
103
+ A as f
105
104
  };
106
- //# sourceMappingURL=peginInput-B5XDDHpy.js.map
105
+ //# sourceMappingURL=peginInput-BKD_b3gq.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"peginInput-BKD_b3gq.js","sources":["../src/tbv/core/primitives/psbt/peginInput.ts"],"sourcesContent":["/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, stripHexPrefix, uint8ArrayToHex } from \"../utils/bitcoin\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * Vault core (tx-graph) version the Pre-PegIn was built with. Must match\n * the version passed to buildPrePeginPsbt() so the HTLC connector scripts\n * are derived for the same graph.\n */\n vaultCoreVersion: number;\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: params.vaultCoreVersion,\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const hashlockScript = hexToUint8Array(htlcConnector.hashlockScript);\n const hashlockControlBlock = hexToUint8Array(htlcConnector.hashlockControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hashlockScript),\n controlBlock: Buffer.from(hashlockControlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(\n hexToUint8Array(depositorPubkey),\n );\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","hashlockScript","hexToUint8Array","hashlockControlBlock","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","finalizePeginInputPsb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e,MAAQA,EAAI,sBAAsBA,EAAI;AAAA,IAAA;AAGvC,YAAM,IAAI;AAAA,QACR,8DAA8DD,CAAC;AAAA,MAAA;AAAA,EAGrE;AAEA,SAAOd,EAAK,mBAAA,EAAqB,MAAA;AACnC;AASO,SAASY,EAAkBI,GAAyB;AACzD,MAAIA,EAAI,WAAW;AACjB,WAAOrB,EAAgB,IAAI,WAAWqB,CAAG,CAAC;AAE5C,QAAIA,EAAI,WAAW,KACX,IAAI;AAAA,IACR,6BAA6BA,EAAI,EAAE,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC;AAAA,EAAA,IAIhE,IAAI,MAAM,4CAA4CA,EAAI,MAAM,EAAE;AAC1E;"}
@@ -1,2 +1,2 @@
1
- "use strict";const P=require("@babylonlabs-io/babylon-tbv-rust-wasm"),l=require("buffer"),a=require("bitcoinjs-lib"),i=require("./bitcoin-CHfKAhcI.cjs"),S=require("./verifyScriptPathSchnorrSignature-CVPh04ZI.cjs");async function b(t){const r=i.stripHexPrefix(t.peginTxHex),c=i.stripHexPrefix(t.fundedPrePeginTxHex),n=await P.getPrePeginHtlcConnectorInfo({txGraphVersion:S.TX_GRAPH_VERSION_V1,depositorPubkey:t.depositorPubkey,vaultProviderPubkey:t.vaultProviderPubkey,vaultKeeperPubkeys:t.vaultKeeperPubkeys,universalChallengerPubkeys:t.universalChallengerPubkeys,hashlock:t.hashlock,timelockRefund:t.timelockRefund,network:t.network}),e=a.Transaction.fromHex(r),o=a.Transaction.fromHex(c);if(e.ins.length!==1)throw new Error(`PegIn transaction must have exactly 1 input, got ${e.ins.length}`);const s=e.ins[0],f=o.getId(),g=i.uint8ArrayToHex(new Uint8Array(s.hash).slice().reverse());if(g!==f)throw new Error(`PegIn input does not reference the Pre-PegIn transaction. Expected ${f}, got ${g}`);const p=o.outs[s.index];if(!p)throw new Error(`Pre-PegIn output ${s.index} not found (Pre-PegIn has ${o.outs.length} outputs)`);const d=i.hexToUint8Array(n.hashlockScript),x=i.hexToUint8Array(n.hashlockControlBlock),u=new a.Psbt;u.setVersion(e.version),u.setLocktime(e.locktime),u.addInput({hash:s.hash,index:s.index,sequence:s.sequence,witnessUtxo:{script:p.script,value:p.value},tapLeafScript:[{leafVersion:i.TAPSCRIPT_LEAF_VERSION,script:l.Buffer.from(d),controlBlock:l.Buffer.from(x)}],tapInternalKey:l.Buffer.from(P.tapInternalPubkey)});for(const h of e.outs)u.addOutput({script:h.script,value:h.value});return{psbtHex:u.toHex()}}function w(t,r){const n=a.Psbt.fromHex(t).data.inputs[0];if(!n)throw new Error("PegIn PSBT has no inputs");if(n.tapScriptSig&&n.tapScriptSig.length>0){const e=l.Buffer.from(i.hexToUint8Array(r));for(const o of n.tapScriptSig)if(o.pubkey.equals(e))return I(o.signature);throw new Error(`No PegIn input signature found for depositor pubkey: ${r}`)}throw n.finalScriptWitness&&n.finalScriptWitness.length>0?new Error("PegIn input PSBT is already finalized. Cannot reliably extract the depositor signature from the witness stack. Ensure the wallet returns a non-finalized PSBT with tapScriptSig entries."):new Error("No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT")}function y(t){const r=a.Psbt.fromHex(t);try{r.finalizeAllInputs()}catch(c){if(!r.data.inputs.every(e=>e.finalScriptWitness||e.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${c}`)}return r.extractTransaction().toHex()}function I(t){if(t.length===64)return i.uint8ArrayToHex(new Uint8Array(t));throw t.length===65?new Error(`Unexpected sighash byte 0x${t[64].toString(16).padStart(2,"0")} in PegIn input signature. Expected implicit SIGHASH_DEFAULT as a 64-byte signature.`):new Error(`Unexpected PegIn input signature length: ${t.length}`)}exports.buildPeginInputPsbt=b;exports.extractPeginInputSignature=w;exports.finalizePeginInputPsbt=y;
2
- //# sourceMappingURL=peginInput-De0C6aSj.cjs.map
1
+ "use strict";const P=require("@babylonlabs-io/babylon-tbv-rust-wasm"),l=require("buffer"),a=require("bitcoinjs-lib"),i=require("./bitcoin-CHfKAhcI.cjs");async function b(t){const r=i.stripHexPrefix(t.peginTxHex),c=i.stripHexPrefix(t.fundedPrePeginTxHex),n=await P.getPrePeginHtlcConnectorInfo({txGraphVersion:t.vaultCoreVersion,depositorPubkey:t.depositorPubkey,vaultProviderPubkey:t.vaultProviderPubkey,vaultKeeperPubkeys:t.vaultKeeperPubkeys,universalChallengerPubkeys:t.universalChallengerPubkeys,hashlock:t.hashlock,timelockRefund:t.timelockRefund,network:t.network}),e=a.Transaction.fromHex(r),o=a.Transaction.fromHex(c);if(e.ins.length!==1)throw new Error(`PegIn transaction must have exactly 1 input, got ${e.ins.length}`);const s=e.ins[0],f=o.getId(),g=i.uint8ArrayToHex(new Uint8Array(s.hash).slice().reverse());if(g!==f)throw new Error(`PegIn input does not reference the Pre-PegIn transaction. Expected ${f}, got ${g}`);const p=o.outs[s.index];if(!p)throw new Error(`Pre-PegIn output ${s.index} not found (Pre-PegIn has ${o.outs.length} outputs)`);const d=i.hexToUint8Array(n.hashlockScript),x=i.hexToUint8Array(n.hashlockControlBlock),u=new a.Psbt;u.setVersion(e.version),u.setLocktime(e.locktime),u.addInput({hash:s.hash,index:s.index,sequence:s.sequence,witnessUtxo:{script:p.script,value:p.value},tapLeafScript:[{leafVersion:i.TAPSCRIPT_LEAF_VERSION,script:l.Buffer.from(d),controlBlock:l.Buffer.from(x)}],tapInternalKey:l.Buffer.from(P.tapInternalPubkey)});for(const h of e.outs)u.addOutput({script:h.script,value:h.value});return{psbtHex:u.toHex()}}function S(t,r){const n=a.Psbt.fromHex(t).data.inputs[0];if(!n)throw new Error("PegIn PSBT has no inputs");if(n.tapScriptSig&&n.tapScriptSig.length>0){const e=l.Buffer.from(i.hexToUint8Array(r));for(const o of n.tapScriptSig)if(o.pubkey.equals(e))return y(o.signature);throw new Error(`No PegIn input signature found for depositor pubkey: ${r}`)}throw n.finalScriptWitness&&n.finalScriptWitness.length>0?new Error("PegIn input PSBT is already finalized. Cannot reliably extract the depositor signature from the witness stack. Ensure the wallet returns a non-finalized PSBT with tapScriptSig entries."):new Error("No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT")}function w(t){const r=a.Psbt.fromHex(t);try{r.finalizeAllInputs()}catch(c){if(!r.data.inputs.every(e=>e.finalScriptWitness||e.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${c}`)}return r.extractTransaction().toHex()}function y(t){if(t.length===64)return i.uint8ArrayToHex(new Uint8Array(t));throw t.length===65?new Error(`Unexpected sighash byte 0x${t[64].toString(16).padStart(2,"0")} in PegIn input signature. Expected implicit SIGHASH_DEFAULT as a 64-byte signature.`):new Error(`Unexpected PegIn input signature length: ${t.length}`)}exports.buildPeginInputPsbt=b;exports.extractPeginInputSignature=S;exports.finalizePeginInputPsbt=w;
2
+ //# sourceMappingURL=peginInput-CAiiDZeO.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"peginInput-CAiiDZeO.cjs","sources":["../src/tbv/core/primitives/psbt/peginInput.ts"],"sourcesContent":["/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, stripHexPrefix, uint8ArrayToHex } from \"../utils/bitcoin\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * Vault core (tx-graph) version the Pre-PegIn was built with. Must match\n * the version passed to buildPrePeginPsbt() so the HTLC connector scripts\n * are derived for the same graph.\n */\n vaultCoreVersion: number;\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: params.vaultCoreVersion,\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const hashlockScript = hexToUint8Array(htlcConnector.hashlockScript);\n const hashlockControlBlock = hexToUint8Array(htlcConnector.hashlockControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hashlockScript),\n controlBlock: Buffer.from(hashlockControlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(\n hexToUint8Array(depositorPubkey),\n );\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","hashlockScript","hexToUint8Array","hashlockControlBlock","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig"],"mappings":"yJAqFA,eAAsBA,EACpBC,EACoC,CACpC,MAAMC,EAAaC,EAAAA,eAAeF,EAAO,UAAU,EAC7CG,EAAsBD,EAAAA,eAAeF,EAAO,mBAAmB,EAE/DI,EAAgB,MAAMC,+BAA6B,CACvD,eAAgBL,EAAO,iBACvB,gBAAiBA,EAAO,gBACxB,oBAAqBA,EAAO,oBAC5B,mBAAoBA,EAAO,mBAC3B,2BAA4BA,EAAO,2BACnC,SAAUA,EAAO,SACjB,eAAgBA,EAAO,eACvB,QAASA,EAAO,OAAA,CACjB,EAEKM,EAAUC,EAAAA,YAAY,QAAQN,CAAU,EACxCO,EAAaD,EAAAA,YAAY,QAAQJ,CAAmB,EAE1D,GAAIG,EAAQ,IAAI,SAAW,EACzB,MAAM,IAAI,MACR,oDAAoDA,EAAQ,IAAI,MAAM,EAAA,EAI1E,MAAMG,EAAaH,EAAQ,IAAI,CAAC,EAG1BI,EAAeF,EAAW,MAAA,EAC1BG,EAAiBC,EAAAA,gBACrB,IAAI,WAAWH,EAAW,IAAI,EAAE,MAAA,EAAQ,QAAA,CAAQ,EAGlD,GAAIE,IAAmBD,EACrB,MAAM,IAAI,MACR,sEACcA,CAAY,SAASC,CAAc,EAAA,EAIrD,MAAME,EAAaL,EAAW,KAAKC,EAAW,KAAK,EACnD,GAAI,CAACI,EACH,MAAM,IAAI,MACR,oBAAoBJ,EAAW,KAAK,6BAChBD,EAAW,KAAK,MAAM,WAAA,EAI9C,MAAMM,EAAiBC,EAAAA,gBAAgBX,EAAc,cAAc,EAC7DY,EAAuBD,EAAAA,gBAAgBX,EAAc,oBAAoB,EAEzEa,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