@babylonlabs-io/ts-sdk 0.47.1 → 0.48.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{PayoutManager-BwYlPF2C.cjs → PayoutManager-BLpgkfOS.cjs} +2 -2
- package/dist/{PayoutManager-BwYlPF2C.cjs.map → PayoutManager-BLpgkfOS.cjs.map} +1 -1
- package/dist/{PayoutManager-CXDccwDN.js → PayoutManager-BbemBIo9.js} +2 -2
- package/dist/{PayoutManager-CXDccwDN.js.map → PayoutManager-BbemBIo9.js.map} +1 -1
- package/dist/{PeginManager-CxSbzoYs.js → PeginManager-BMO6R9I9.js} +5 -5
- package/dist/{PeginManager-CxSbzoYs.js.map → PeginManager-BMO6R9I9.js.map} +1 -1
- package/dist/{PeginManager-CeloRUHV.cjs → PeginManager-CfkjDMy7.cjs} +2 -2
- package/dist/{PeginManager-CeloRUHV.cjs.map → PeginManager-CfkjDMy7.cjs.map} +1 -1
- package/dist/assertPsbtUnsignedTxMatches-BHyBdtxs.js +481 -0
- package/dist/assertPsbtUnsignedTxMatches-BHyBdtxs.js.map +1 -0
- package/dist/assertPsbtUnsignedTxMatches-s9H0Qqkl.cjs +2 -0
- package/dist/assertPsbtUnsignedTxMatches-s9H0Qqkl.cjs.map +1 -0
- package/dist/buildAndBroadcastRefund-CLvF5ETe.cjs +2 -0
- package/dist/{buildAndBroadcastRefund-CgUJ7Mpf.cjs.map → buildAndBroadcastRefund-CLvF5ETe.cjs.map} +1 -1
- package/dist/{buildAndBroadcastRefund-BssyvGWW.js → buildAndBroadcastRefund-hM9Wo0VZ.js} +371 -347
- package/dist/{buildAndBroadcastRefund-BssyvGWW.js.map → buildAndBroadcastRefund-hM9Wo0VZ.js.map} +1 -1
- package/dist/{challengeAssert-ChqnvtRg.js → challengeAssert-1fy_EzAi.js} +2 -2
- package/dist/{challengeAssert-ChqnvtRg.js.map → challengeAssert-1fy_EzAi.js.map} +1 -1
- package/dist/{challengeAssert-Cmj_OG6V.cjs → challengeAssert-DEw-z3n9.cjs} +2 -2
- package/dist/{challengeAssert-Cmj_OG6V.cjs.map → challengeAssert-DEw-z3n9.cjs.map} +1 -1
- package/dist/{fundPeginTransaction-C11tYf6I.js → fundPeginTransaction-96FxwYYJ.js} +24 -23
- package/dist/fundPeginTransaction-96FxwYYJ.js.map +1 -0
- package/dist/fundPeginTransaction-DuMwnytD.cjs +2 -0
- package/dist/fundPeginTransaction-DuMwnytD.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +109 -108
- package/dist/noPayout-B2Xd40nk.cjs +2 -0
- package/dist/noPayout-B2Xd40nk.cjs.map +1 -0
- package/dist/noPayout-BwSaoU7w.js +174 -0
- package/dist/noPayout-BwSaoU7w.js.map +1 -0
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +111 -110
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +2 -2
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.js +3 -3
- package/dist/tbv/core/primitives/psbt/__tests__/assertWasmPeginSizing.test.d.ts +7 -0
- package/dist/tbv/core/primitives/psbt/__tests__/assertWasmPeginSizing.test.d.ts.map +1 -0
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts +47 -0
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -0
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/refund.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +2 -2
- package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts +20 -0
- package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts.map +1 -1
- package/dist/tbv/core/utils/fee/constants.d.ts +16 -0
- package/dist/tbv/core/utils/fee/constants.d.ts.map +1 -1
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +33 -32
- package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts +1 -1
- package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts.map +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +111 -110
- package/dist/tbv/integrations/aave/clients/__tests__/hub.test.d.ts +2 -0
- package/dist/tbv/integrations/aave/clients/__tests__/hub.test.d.ts.map +1 -0
- package/dist/tbv/integrations/aave/clients/abis/AaveHub.abi.json.d.ts +24 -0
- package/dist/tbv/integrations/aave/clients/hub.d.ts +28 -0
- package/dist/tbv/integrations/aave/clients/hub.d.ts.map +1 -0
- package/dist/tbv/integrations/aave/clients/index.d.ts +1 -0
- package/dist/tbv/integrations/aave/clients/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.cjs +1 -1
- package/dist/tbv/integrations/aave/index.cjs.map +1 -1
- package/dist/tbv/integrations/aave/index.d.ts +1 -1
- package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.js +246 -193
- package/dist/tbv/integrations/aave/index.js.map +1 -1
- package/dist/{waitForTransactionReceiptSmartAware-Dt5VcMK0.js → waitForTransactionReceiptSmartAware-Ckg_oZAo.js} +2 -2
- package/dist/{waitForTransactionReceiptSmartAware-Dt5VcMK0.js.map → waitForTransactionReceiptSmartAware-Ckg_oZAo.js.map} +1 -1
- package/dist/{waitForTransactionReceiptSmartAware-BFMQFEzj.cjs → waitForTransactionReceiptSmartAware-U706oKTc.cjs} +2 -2
- package/dist/{waitForTransactionReceiptSmartAware-BFMQFEzj.cjs.map → waitForTransactionReceiptSmartAware-U706oKTc.cjs.map} +1 -1
- package/package.json +3 -3
- package/dist/assertPsbtUnsignedTxMatches-CABhEADu.cjs +0 -2
- package/dist/assertPsbtUnsignedTxMatches-CABhEADu.cjs.map +0 -1
- package/dist/assertPsbtUnsignedTxMatches-GHobJP-d.js +0 -404
- package/dist/assertPsbtUnsignedTxMatches-GHobJP-d.js.map +0 -1
- package/dist/buildAndBroadcastRefund-CgUJ7Mpf.cjs +0 -2
- package/dist/fundPeginTransaction-C11tYf6I.js.map +0 -1
- package/dist/fundPeginTransaction-C8qsXxNV.cjs +0 -2
- package/dist/fundPeginTransaction-C8qsXxNV.cjs.map +0 -1
- package/dist/noPayout-BtP-R-b-.js +0 -154
- package/dist/noPayout-BtP-R-b-.js.map +0 -1
- package/dist/noPayout-DliaHuc6.cjs +0 -2
- package/dist/noPayout-DliaHuc6.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fundPeginTransaction-C8qsXxNV.cjs","sources":["../src/tbv/core/utils/fee/constants.ts","../src/tbv/core/utils/transaction/fundPeginTransaction.ts"],"sourcesContent":["/**\n * Fee calculation constants for Bitcoin transactions.\n * Based on btc-staking-ts values, adapted for vault peg-in transactions.\n */\n\n// P2TR input size in vbytes (42 vbytes non-witness + 16 vbytes witness)\nexport const P2TR_INPUT_SIZE = 58;\n\n// P2TR output size in bytes (largest non-legacy output type)\nexport const MAX_NON_LEGACY_OUTPUT_SIZE = 43;\n\n// Base transaction overhead (version, input/output counts, locktime, SegWit marker)\nexport const TX_BUFFER_SIZE_OVERHEAD = 11;\n\n// Dust threshold: outputs below this may not be relayed\nexport const BTC_DUST_SAT = 546;\n\n/** Pre-computed BigInt dust threshold to avoid repeated conversions in hot paths */\nexport const DUST_THRESHOLD = BigInt(BTC_DUST_SAT);\n\n// Buffer for low fee rate estimation accuracy (when feeRate <= 2 sat/vbyte)\nexport const LOW_RATE_ESTIMATION_ACCURACY_BUFFER = 30;\n\n// Wallet relay fee rate threshold - different buffer fees are used based on this\nexport const WALLET_RELAY_FEE_RATE_THRESHOLD = 2;\n\n// Safety margin: 10% buffer for size variations and fee market volatility\nexport const FEE_SAFETY_MARGIN = 1.1;\n\n/**\n * Adds a buffer to the transaction fee calculation if the fee rate is low.\n *\n * Some wallets have a relayer fee requirement. If the fee rate is <= 2 sat/vbyte,\n * there's a risk the fee might not be sufficient for transaction relay.\n * We add a buffer to ensure the transaction can be relayed.\n *\n * @param feeRate - Fee rate in satoshis per vbyte\n * @returns Buffer amount in satoshis to add to the transaction fee\n */\nexport function rateBasedTxBufferFee(feeRate: number): number {\n return feeRate <= WALLET_RELAY_FEE_RATE_THRESHOLD\n ? LOW_RATE_ESTIMATION_ACCURACY_BUFFER\n : 0;\n}\n\n/**\n * Number of always-present fixed (non-HTLC) outputs in a Pre-PegIn\n * transaction. Currently this is 1 CPFP anchor output.\n */\nexport const PEGIN_FIXED_OUTPUTS = 1;\n\n/**\n * Size of the auth-anchor `OP_RETURN` output when committed into a\n * Pre-PegIn. The output carries `OP_RETURN <PUSH32 hash>` = 34 script\n * bytes, plus 8 bytes value + 1 byte scriptLen = ~43 bytes total —\n * same as {@link MAX_NON_LEGACY_OUTPUT_SIZE}. Counted as one output\n * toward the fee-estimation output budget.\n */\nexport const PEGIN_AUTH_ANCHOR_OUTPUTS = 1;\n\n/**\n * Compute the total number of outputs (before change) in a Pre-PegIn\n * transaction.\n *\n * A Pre-PegIn tx has: N HTLC outputs (one per vault) + optional\n * auth-anchor OP_RETURN output + fixed outputs (CPFP anchor). This\n * count is used for fee estimation only — the change output is handled\n * separately by `selectUtxosForPegin` when the change amount exceeds\n * the dust threshold.\n *\n * @param vaultCount - Number of vaults in the batch (≥1).\n * @param hasAuthAnchor - Whether the Pre-PegIn will carry an auth-anchor\n * OP_RETURN output. Pass the same value the\n * caller will hand to `buildPrePeginPsbt`'s\n * `authAnchorHash` (truthy ↔ true) so the fee\n * budget stays in lockstep with the output set.\n * @returns Total output count before change.\n * @throws If `vaultCount` is not a positive integer.\n */\nexport function peginOutputCount(\n vaultCount: number,\n hasAuthAnchor: boolean,\n): number {\n if (!Number.isInteger(vaultCount) || vaultCount < 1) {\n throw new Error(\n `peginOutputCount: vaultCount must be a positive integer, got ${vaultCount}`,\n );\n }\n return (\n vaultCount +\n PEGIN_FIXED_OUTPUTS +\n (hasAuthAnchor ? PEGIN_AUTH_ANCHOR_OUTPUTS : 0)\n );\n}\n\n/**\n * Safety multiplier for split transaction fee validation.\n * The signed PSBT's fee rate and absolute fee must not exceed this multiple\n * of the planned values. 5x accounts for witness estimation variance while\n * catching catastrophic wallet-side overpayment.\n */\nexport const SPLIT_TX_FEE_SAFETY_MULTIPLIER = 5;\n","/**\n * Transaction Funding Utility for Peg-in Transactions\n *\n * This module funds an unfunded transaction template from the SDK by adding\n * UTXO inputs and change outputs, creating a transaction ready for wallet signing.\n *\n * Transaction Flow:\n * 1. SDK buildPrePeginPsbt() → unfunded Pre-PegIn tx (0 inputs, HTLC + CPFP outputs)\n * 2. selectUtxosForPegin() → select UTXOs and calculate fees\n * 3. fundPeginTransaction() → add inputs/change, create funded transaction\n *\n * Technical Note:\n * We manually extract the vault output from SDK hex instead of using bitcoinjs-lib\n * parsing because bitcoinjs-lib cannot parse 0-input transactions (even witness format).\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { DUST_THRESHOLD } from \"../fee/constants\";\nimport type { UTXO } from \"../utxo/selectUtxos\";\n\nexport interface FundPeginTransactionParams {\n /** Unfunded transaction hex from SDK (0 inputs, vault + depositor claim outputs) */\n unfundedTxHex: string;\n /** Selected UTXOs to use as inputs */\n selectedUTXOs: UTXO[];\n /** Change address (from wallet) */\n changeAddress: string;\n /** Change amount in satoshis */\n changeAmount: bigint;\n /** Bitcoin network */\n network: bitcoin.Network;\n}\n\n/** A single parsed output from the unfunded WASM transaction */\ninterface ParsedOutput {\n value: number;\n script: Buffer;\n}\n\n/** Parsed data from an unfunded WASM transaction */\ninterface ParsedUnfundedTx {\n version: number;\n locktime: number;\n outputs: ParsedOutput[];\n}\n\n/**\n * Parses an unfunded transaction hex from WASM.\n *\n * WASM produces witness-format transactions with 0 inputs, which bitcoinjs-lib cannot parse.\n * This function manually extracts the transaction components.\n *\n * Format: [version:4bytes][marker:0x00][flag:0x01][inputs:1byte=0x00][outputCount:1byte]\n * [output1: value:8bytes + scriptLen:1byte + script:N bytes]\n * [output2: ...]\n * [locktime:4bytes]\n *\n * @param unfundedTxHex - Raw transaction hex from WASM\n * @returns Parsed transaction components\n * @throws Error if transaction structure is invalid\n */\nexport function parseUnfundedWasmTransaction(\n unfundedTxHex: string,\n): ParsedUnfundedTx {\n // Check if witness markers are present (0x00 0x01 after version)\n const hasWitnessMarkers = unfundedTxHex.substring(8, 12) === \"0001\";\n const dataOffset = hasWitnessMarkers ? 12 : 8; // Skip version (8) + optional witness markers (4)\n\n // Parse input/output counts\n const inputCount = parseInt(\n unfundedTxHex.substring(dataOffset, dataOffset + 2),\n 16,\n );\n const outputCount = parseInt(\n unfundedTxHex.substring(dataOffset + 2, dataOffset + 4),\n 16,\n );\n\n if (inputCount !== 0) {\n throw new Error(`Expected 0 inputs from WASM, got ${inputCount}`);\n }\n if (outputCount === 0) {\n throw new Error(\"Expected at least 1 output from WASM, got 0\");\n }\n\n // Parse version (first 4 bytes, little-endian)\n const version = Buffer.from(unfundedTxHex.substring(0, 8), \"hex\").readUInt32LE(0);\n\n // Parse locktime (last 4 bytes, little-endian)\n const locktime = Buffer.from(\n unfundedTxHex.substring(unfundedTxHex.length - 8),\n \"hex\",\n ).readUInt32LE(0);\n\n // Parse all outputs sequentially\n const outputs: ParsedOutput[] = [];\n let pos = dataOffset + 4; // position after input/output counts\n\n for (let i = 0; i < outputCount; i++) {\n const valueHex = unfundedTxHex.substring(pos, pos + 16);\n const value = Number(Buffer.from(valueHex, \"hex\").readBigUInt64LE(0));\n pos += 16;\n\n const scriptLen = parseInt(unfundedTxHex.substring(pos, pos + 2), 16);\n pos += 2;\n\n const scriptHex = unfundedTxHex.substring(pos, pos + scriptLen * 2);\n const script = Buffer.from(scriptHex, \"hex\");\n pos += scriptLen * 2;\n\n outputs.push({ value, script });\n }\n\n return { version, locktime, outputs };\n}\n\n/**\n * Funds an unfunded peg-in transaction by adding inputs and change output.\n *\n * Takes an unfunded transaction template (0 inputs, 1 vault output) from the SDK\n * and adds UTXO inputs and a change output to create a funded transaction ready\n * for wallet signing.\n *\n * @param params - Transaction funding parameters\n * @returns Transaction hex string ready for wallet signing\n */\nexport function fundPeginTransaction(\n params: FundPeginTransactionParams,\n): string {\n const { unfundedTxHex, selectedUTXOs, changeAddress, changeAmount, network } =\n params;\n\n // Parse the unfunded transaction from WASM\n const { version, locktime, outputs } =\n parseUnfundedWasmTransaction(unfundedTxHex);\n\n // Create a new transaction with the extracted data\n const tx = new bitcoin.Transaction();\n tx.version = version;\n tx.locktime = locktime;\n\n // Add inputs from selected UTXOs\n for (const utxo of selectedUTXOs) {\n // Bitcoin uses reversed byte order for txid\n const txHash = Buffer.from(utxo.txid, \"hex\").reverse();\n tx.addInput(txHash, utxo.vout);\n }\n\n // Add all WASM outputs (vault output at index 0, depositor claim at index 1, etc.)\n for (const output of outputs) {\n tx.addOutput(output.script, output.value);\n }\n\n // Trust the selector's change decision: `selectUtxosForPegin` runs every\n // candidate set through `applyChangeOutputPolicy` and returns\n // `changeAmount = 0n` whenever the residual would be at-or-below dust\n // after paying the change-output fee. Validate the contract at this\n // boundary — a hand-built or stale `changeAmount` in (0, DUST_THRESHOLD]\n // would produce a non-relayable dust output, and emitting one would also\n // bypass the canonical fee policy that the selector applied.\n if (changeAmount < 0n) {\n throw new Error(\n `fundPeginTransaction: changeAmount cannot be negative, got ${changeAmount}`,\n );\n }\n if (changeAmount > 0n && changeAmount <= DUST_THRESHOLD) {\n throw new Error(\n `fundPeginTransaction: changeAmount must be 0 or strictly above DUST_THRESHOLD (${DUST_THRESHOLD}), got ${changeAmount}`,\n );\n }\n if (changeAmount > 0n) {\n const changeScript = bitcoin.address.toOutputScript(changeAddress, network);\n tx.addOutput(changeScript, Number(changeAmount));\n }\n\n return tx.toHex();\n}\n\n// Re-export getNetwork from the canonical location in primitives\nexport { getNetwork } from \"../../primitives/utils/bitcoin\";\n"],"names":["P2TR_INPUT_SIZE","MAX_NON_LEGACY_OUTPUT_SIZE","TX_BUFFER_SIZE_OVERHEAD","BTC_DUST_SAT","DUST_THRESHOLD","LOW_RATE_ESTIMATION_ACCURACY_BUFFER","WALLET_RELAY_FEE_RATE_THRESHOLD","FEE_SAFETY_MARGIN","rateBasedTxBufferFee","feeRate","PEGIN_FIXED_OUTPUTS","PEGIN_AUTH_ANCHOR_OUTPUTS","peginOutputCount","vaultCount","hasAuthAnchor","SPLIT_TX_FEE_SAFETY_MULTIPLIER","parseUnfundedWasmTransaction","unfundedTxHex","dataOffset","inputCount","outputCount","version","Buffer","locktime","outputs","pos","i","valueHex","value","scriptLen","scriptHex","script","fundPeginTransaction","params","selectedUTXOs","changeAddress","changeAmount","network","tx","bitcoin","utxo","txHash","output","changeScript"],"mappings":"4VAMaA,EAAkB,GAGlBC,EAA6B,GAG7BC,EAA0B,GAG1BC,EAAe,IAGfC,EAAiB,OAAOD,CAAY,EAGpCE,EAAsC,GAGtCC,EAAkC,EAGlCC,EAAoB,IAY1B,SAASC,EAAqBC,EAAyB,CAC5D,OAAOA,GAAWH,EACdD,EACA,CACN,CAMO,MAAMK,EAAsB,EAStBC,EAA4B,EAqBlC,SAASC,EACdC,EACAC,EACQ,CACR,GAAI,CAAC,OAAO,UAAUD,CAAU,GAAKA,EAAa,EAChD,MAAM,IAAI,MACR,gEAAgEA,CAAU,EAAA,EAG9E,OACEA,EACAH,GACCI,EAAgBH,EAA4B,EAEjD,CAQO,MAAMI,EAAiC,ECtCvC,SAASC,EACdC,EACkB,CAGlB,MAAMC,EADoBD,EAAc,UAAU,EAAG,EAAE,IAAM,OACtB,GAAK,EAGtCE,EAAa,SACjBF,EAAc,UAAUC,EAAYA,EAAa,CAAC,EAClD,EAAA,EAEIE,EAAc,SAClBH,EAAc,UAAUC,EAAa,EAAGA,EAAa,CAAC,EACtD,EAAA,EAGF,GAAIC,IAAe,EACjB,MAAM,IAAI,MAAM,oCAAoCA,CAAU,EAAE,EAElE,GAAIC,IAAgB,EAClB,MAAM,IAAI,M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,EAAG,UAAUI,EAAO,OAAQA,EAAO,KAAK,EAU1C,GAAIN,EAAe,GACjB,MAAM,IAAI,MACR,8DAA8DA,CAAY,EAAA,EAG9E,GAAIA,EAAe,IAAMA,GAAgBhC,EACvC,MAAM,IAAI,MACR,kFAAkFA,CAAc,UAAUgC,CAAY,EAAA,EAG1H,GAAIA,EAAe,GAAI,CACrB,MAAMO,EAAeJ,EAAQ,QAAQ,eAAeJ,EAAeE,CAAO,EAC1EC,EAAG,UAAUK,EAAc,OAAOP,CAAY,CAAC,CACjD,CAEA,OAAOE,EAAG,MAAA,CACZ"}
|
|
@@ -1,154 +0,0 @@
|
|
|
1
|
-
import { initWasm as E, WasmPrePeginTx as S, getPrePeginHtlcConnectorInfo as $, tapInternalPubkey as I, getAssertNoPayoutScriptInfo as B } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
2
|
-
import { Buffer as u } from "buffer";
|
|
3
|
-
import { Transaction as x, Psbt as A, payments as K } from "bitcoinjs-lib";
|
|
4
|
-
import { u as T, T as R, h as f, s as k, p as L, j as N } from "./bitcoin-B5aNKtsk.js";
|
|
5
|
-
import { n as O } from "./assertPsbtUnsignedTxMatches-GHobJP-d.js";
|
|
6
|
-
async function W(s) {
|
|
7
|
-
await E();
|
|
8
|
-
const { prePeginParams: e, fundedPrePeginTxHex: n, htlcVout: o, refundFee: d, hashlock: i } = s, m = O(
|
|
9
|
-
e.authAnchorHash
|
|
10
|
-
), r = new S(
|
|
11
|
-
e.depositorPubkey,
|
|
12
|
-
e.vaultProviderPubkey,
|
|
13
|
-
e.vaultKeeperPubkeys,
|
|
14
|
-
e.universalChallengerPubkeys,
|
|
15
|
-
[...e.hashlocks],
|
|
16
|
-
new BigUint64Array(e.pegInAmounts),
|
|
17
|
-
e.timelockRefund,
|
|
18
|
-
e.feeRate,
|
|
19
|
-
e.minPeginFeeRate,
|
|
20
|
-
e.numLocalChallengers,
|
|
21
|
-
e.councilQuorum,
|
|
22
|
-
e.councilSize,
|
|
23
|
-
e.network,
|
|
24
|
-
m
|
|
25
|
-
);
|
|
26
|
-
let t = null;
|
|
27
|
-
try {
|
|
28
|
-
const a = r.getHtlcScriptPubKey(o).toLowerCase();
|
|
29
|
-
t = r.fromFundedTransaction(n);
|
|
30
|
-
const h = t.buildRefundTx(d, o), c = await $({
|
|
31
|
-
depositorPubkey: e.depositorPubkey,
|
|
32
|
-
vaultProviderPubkey: e.vaultProviderPubkey,
|
|
33
|
-
vaultKeeperPubkeys: e.vaultKeeperPubkeys,
|
|
34
|
-
universalChallengerPubkeys: e.universalChallengerPubkeys,
|
|
35
|
-
hashlock: i,
|
|
36
|
-
timelockRefund: e.timelockRefund,
|
|
37
|
-
network: e.network
|
|
38
|
-
}), C = n.startsWith("0x") ? n.slice(2) : n, g = x.fromHex(C), y = g.outs[o];
|
|
39
|
-
if (!y)
|
|
40
|
-
throw new Error(
|
|
41
|
-
`HTLC output at vout ${o} not found in funded Pre-PegIn tx (tx has ${g.outs.length} outputs)`
|
|
42
|
-
);
|
|
43
|
-
const w = T(
|
|
44
|
-
new Uint8Array(y.script)
|
|
45
|
-
).toLowerCase();
|
|
46
|
-
if (w !== a)
|
|
47
|
-
throw new Error(
|
|
48
|
-
`HTLC scriptPubKey mismatch at vout ${o}: reconstructed template expects ${a}, funded tx carries ${w}. Refund refused — the (hashlocks, pegInAmounts) vector does not match the on-chain commitment.`
|
|
49
|
-
);
|
|
50
|
-
const l = x.fromHex(h);
|
|
51
|
-
if (l.ins.length !== 1)
|
|
52
|
-
throw new Error(
|
|
53
|
-
`Refund transaction must have exactly 1 input, got ${l.ins.length}`
|
|
54
|
-
);
|
|
55
|
-
const p = l.ins[0], v = g.getId(), b = T(
|
|
56
|
-
new Uint8Array(p.hash).slice().reverse()
|
|
57
|
-
);
|
|
58
|
-
if (b !== v)
|
|
59
|
-
throw new Error(
|
|
60
|
-
`Refund input does not reference the Pre-PegIn transaction. Expected ${v}, got ${b}`
|
|
61
|
-
);
|
|
62
|
-
if (p.index !== o)
|
|
63
|
-
throw new Error(
|
|
64
|
-
`Refund input index ${p.index} does not match expected htlcVout ${o}`
|
|
65
|
-
);
|
|
66
|
-
const P = new A();
|
|
67
|
-
P.setVersion(l.version), P.setLocktime(l.locktime), P.addInput({
|
|
68
|
-
hash: p.hash,
|
|
69
|
-
index: p.index,
|
|
70
|
-
sequence: p.sequence,
|
|
71
|
-
witnessUtxo: {
|
|
72
|
-
script: y.script,
|
|
73
|
-
value: y.value
|
|
74
|
-
},
|
|
75
|
-
tapLeafScript: [
|
|
76
|
-
{
|
|
77
|
-
leafVersion: R,
|
|
78
|
-
script: u.from(f(c.refundScript)),
|
|
79
|
-
controlBlock: u.from(
|
|
80
|
-
f(c.refundControlBlock)
|
|
81
|
-
)
|
|
82
|
-
}
|
|
83
|
-
],
|
|
84
|
-
tapInternalKey: u.from(I)
|
|
85
|
-
});
|
|
86
|
-
for (const H of l.outs)
|
|
87
|
-
P.addOutput({
|
|
88
|
-
script: H.script,
|
|
89
|
-
value: H.value
|
|
90
|
-
});
|
|
91
|
-
return { psbtHex: P.toHex() };
|
|
92
|
-
} finally {
|
|
93
|
-
t == null || t.free(), r.free();
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
async function _(s) {
|
|
97
|
-
const e = k(s.noPayoutTxHex), n = x.fromHex(e), { noPayoutScript: o, noPayoutControlBlock: d } = await B(
|
|
98
|
-
s.connectorParams,
|
|
99
|
-
s.challengerPubkey
|
|
100
|
-
), i = f(o), m = f(d), r = new A();
|
|
101
|
-
r.setVersion(n.version), r.setLocktime(n.locktime);
|
|
102
|
-
for (let t = 0; t < n.ins.length; t++) {
|
|
103
|
-
const a = n.ins[t], h = s.prevouts[t];
|
|
104
|
-
if (!h)
|
|
105
|
-
throw new Error(`Missing prevout data for input ${t}`);
|
|
106
|
-
const c = {
|
|
107
|
-
hash: a.hash,
|
|
108
|
-
index: a.index,
|
|
109
|
-
sequence: a.sequence,
|
|
110
|
-
witnessUtxo: {
|
|
111
|
-
script: u.from(f(k(h.script_pubkey))),
|
|
112
|
-
value: h.value
|
|
113
|
-
}
|
|
114
|
-
};
|
|
115
|
-
t === 0 && (c.tapLeafScript = [
|
|
116
|
-
{
|
|
117
|
-
leafVersion: R,
|
|
118
|
-
script: u.from(i),
|
|
119
|
-
controlBlock: u.from(m)
|
|
120
|
-
}
|
|
121
|
-
], c.tapInternalKey = u.from(I)), r.addInput(c);
|
|
122
|
-
}
|
|
123
|
-
for (const t of n.outs)
|
|
124
|
-
r.addOutput({
|
|
125
|
-
script: t.script,
|
|
126
|
-
value: t.value
|
|
127
|
-
});
|
|
128
|
-
return r.toHex();
|
|
129
|
-
}
|
|
130
|
-
function M(s, e, n) {
|
|
131
|
-
const o = x.fromHex(k(s));
|
|
132
|
-
if (o.outs.length !== 1)
|
|
133
|
-
throw new Error(
|
|
134
|
-
`NoPayout transaction must have exactly 1 output, got ${o.outs.length}`
|
|
135
|
-
);
|
|
136
|
-
const d = f(L(e)), { output: i } = K.p2tr({
|
|
137
|
-
internalPubkey: u.from(d),
|
|
138
|
-
network: N(n)
|
|
139
|
-
});
|
|
140
|
-
if (!i)
|
|
141
|
-
throw new Error(
|
|
142
|
-
"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation"
|
|
143
|
-
);
|
|
144
|
-
if (!o.outs[0].script.equals(i))
|
|
145
|
-
throw new Error(
|
|
146
|
-
"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address"
|
|
147
|
-
);
|
|
148
|
-
}
|
|
149
|
-
export {
|
|
150
|
-
_ as a,
|
|
151
|
-
W as b,
|
|
152
|
-
M as c
|
|
153
|
-
};
|
|
154
|
-
//# sourceMappingURL=noPayout-BtP-R-b-.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"noPayout-BtP-R-b-.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 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 { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, uint8ArrayToHex } 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 const unfundedTx = new (WasmPrePeginTx as unknown as new (\n depositor: string,\n vault_provider: string,\n vault_keepers: string[],\n universal_challengers: string[],\n hashlocks: string[],\n pegin_amounts: BigUint64Array,\n timelock_refund: number,\n fee_rate: bigint,\n min_pegin_fee_rate: bigint,\n num_local_challengers: number,\n council_quorum: number,\n council_size: number,\n network: string,\n auth_anchor_hash?: string,\n ) => typeof WasmPrePeginTx.prototype)(\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(prePeginParams.pegInAmounts),\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\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\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 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 for (const output of refundTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\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","fundedTx","expectedHtlcScriptPubKey","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","refundTx","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","output","buildNoPayoutPsbt","noPayoutTxHex","stripHexPrefix","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","i","input","prevout","inputData","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":";;;;;AAkEA,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,GAEXO,IAAa,IAAKC;AAAA,IAgBtBR,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACf,CAAC,GAAGA,EAAe,SAAS;AAAA,IAC5B,IAAI,eAAeA,EAAe,YAAY;AAAA,IAC9CA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfA,EAAe;AAAA,IACfK;AAAA,EAAA;AAGF,MAAII,IAAkC;AACtC,MAAI;AASF,UAAMC,IAA2BH,EAC9B,oBAAoBL,CAAQ,EAC5B,YAAA;AAEH,IAAAO,IAAWF,EAAW,sBAAsBN,CAAmB;AAE/D,UAAMU,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C,EAAE,OAAO,OAAOG,CAAc;AAC1C,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAGN;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const h=require("@babylonlabs-io/babylon-tbv-rust-wasm"),i=require("buffer"),a=require("bitcoinjs-lib"),n=require("./bitcoin-CHfKAhcI.cjs"),A=require("./assertPsbtUnsignedTxMatches-CABhEADu.cjs");async function I(u){await h.initWasm();const{prePeginParams:e,fundedPrePeginTxHex:r,htlcVout:o,refundFee:P,hashlock:c}=u,m=A.normalizeAuthAnchorHash(e.authAnchorHash),s=new h.WasmPrePeginTx(e.depositorPubkey,e.vaultProviderPubkey,e.vaultKeeperPubkeys,e.universalChallengerPubkeys,[...e.hashlocks],new BigUint64Array(e.pegInAmounts),e.timelockRefund,e.feeRate,e.minPeginFeeRate,e.numLocalChallengers,e.councilQuorum,e.councilSize,e.network,m);let t=null;try{const l=s.getHtlcScriptPubKey(o).toLowerCase();t=s.fromFundedTransaction(r);const y=t.buildRefundTx(P,o),f=await h.getPrePeginHtlcConnectorInfo({depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlock:c,timelockRefund:e.timelockRefund,network:e.network}),H=r.startsWith("0x")?r.slice(2):r,g=a.Transaction.fromHex(H),b=g.outs[o];if(!b)throw new Error(`HTLC output at vout ${o} not found in funded Pre-PegIn tx (tx has ${g.outs.length} outputs)`);const k=n.uint8ArrayToHex(new Uint8Array(b.script)).toLowerCase();if(k!==l)throw new Error(`HTLC scriptPubKey mismatch at vout ${o}: reconstructed template expects ${l}, funded tx carries ${k}. Refund refused — the (hashlocks, pegInAmounts) vector does not match the on-chain commitment.`);const p=a.Transaction.fromHex(y);if(p.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${p.ins.length}`);const d=p.ins[0],w=g.getId(),T=n.uint8ArrayToHex(new Uint8Array(d.hash).slice().reverse());if(T!==w)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${w}, got ${T}`);if(d.index!==o)throw new Error(`Refund input index ${d.index} does not match expected htlcVout ${o}`);const x=new a.Psbt;x.setVersion(p.version),x.setLocktime(p.locktime),x.addInput({hash:d.hash,index:d.index,sequence:d.sequence,witnessUtxo:{script:b.script,value:b.value},tapLeafScript:[{leafVersion:n.TAPSCRIPT_LEAF_VERSION,script:i.Buffer.from(n.hexToUint8Array(f.refundScript)),controlBlock:i.Buffer.from(n.hexToUint8Array(f.refundControlBlock))}],tapInternalKey:i.Buffer.from(h.tapInternalPubkey)});for(const v of p.outs)x.addOutput({script:v.script,value:v.value});return{psbtHex:x.toHex()}}finally{t==null||t.free(),s.free()}}async function R(u){const e=n.stripHexPrefix(u.noPayoutTxHex),r=a.Transaction.fromHex(e),{noPayoutScript:o,noPayoutControlBlock:P}=await h.getAssertNoPayoutScriptInfo(u.connectorParams,u.challengerPubkey),c=n.hexToUint8Array(o),m=n.hexToUint8Array(P),s=new a.Psbt;s.setVersion(r.version),s.setLocktime(r.locktime);for(let t=0;t<r.ins.length;t++){const l=r.ins[t],y=u.prevouts[t];if(!y)throw new Error(`Missing prevout data for input ${t}`);const f={hash:l.hash,index:l.index,sequence:l.sequence,witnessUtxo:{script:i.Buffer.from(n.hexToUint8Array(n.stripHexPrefix(y.script_pubkey))),value:y.value}};t===0&&(f.tapLeafScript=[{leafVersion:n.TAPSCRIPT_LEAF_VERSION,script:i.Buffer.from(c),controlBlock:i.Buffer.from(m)}],f.tapInternalKey=i.Buffer.from(h.tapInternalPubkey)),s.addInput(f)}for(const t of r.outs)s.addOutput({script:t.script,value:t.value});return s.toHex()}function B(u,e,r){const o=a.Transaction.fromHex(n.stripHexPrefix(u));if(o.outs.length!==1)throw new Error(`NoPayout transaction must have exactly 1 output, got ${o.outs.length}`);const P=n.hexToUint8Array(n.processPublicKeyToXOnly(e)),{output:c}=a.payments.p2tr({internalPubkey:i.Buffer.from(P),network:n.getNetwork(r)});if(!c)throw new Error("Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation");if(!o.outs[0].script.equals(c))throw new Error("NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address")}exports.assertNoPayoutOutputMatchesChallenger=B;exports.buildNoPayoutPsbt=R;exports.buildRefundPsbt=I;
|
|
2
|
-
//# sourceMappingURL=noPayout-DliaHuc6.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"noPayout-DliaHuc6.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 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 { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, uint8ArrayToHex } 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 const unfundedTx = new (WasmPrePeginTx as unknown as new (\n depositor: string,\n vault_provider: string,\n vault_keepers: string[],\n universal_challengers: string[],\n hashlocks: string[],\n pegin_amounts: BigUint64Array,\n timelock_refund: number,\n fee_rate: bigint,\n min_pegin_fee_rate: bigint,\n num_local_challengers: number,\n council_quorum: number,\n council_size: number,\n network: string,\n auth_anchor_hash?: string,\n ) => typeof WasmPrePeginTx.prototype)(\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(prePeginParams.pegInAmounts),\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\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\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 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 for (const output of refundTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\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","fundedTx","expectedHtlcScriptPubKey","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","refundTx","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","output","buildNoPayoutPsbt","noPayoutTxHex","stripHexPrefix","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","i","input","prevout","inputData","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":"iNAkEA,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,EAEXO,EAAa,IAAKC,EAAAA,eAgBtB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