@babylonlabs-io/ts-sdk 0.74.0 → 0.74.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/{PeginManager-E-UHA1un.cjs → PeginManager-DEByBX5R.cjs} +2 -2
- package/dist/{PeginManager-E-UHA1un.cjs.map → PeginManager-DEByBX5R.cjs.map} +1 -1
- package/dist/{PeginManager-C9RPOd0L.js → PeginManager-DNimKlmw.js} +11 -11
- package/dist/{PeginManager-C9RPOd0L.js.map → PeginManager-DNimKlmw.js.map} +1 -1
- package/dist/{bip322Verify-D6sBBUHE.js → bip322Verify-DSco3Yhl.js} +2 -2
- package/dist/{bip322Verify-D6sBBUHE.js.map → bip322Verify-DSco3Yhl.js.map} +1 -1
- package/dist/buildAndBroadcastReclaim-Cqc6Jiqk.cjs +2 -0
- package/dist/{buildAndBroadcastReclaim-U-PyFfDg.cjs.map → buildAndBroadcastReclaim-Cqc6Jiqk.cjs.map} +1 -1
- package/dist/{buildAndBroadcastReclaim-BXclIcu_.js → buildAndBroadcastReclaim-DCGcupg7.js} +6 -6
- package/dist/{buildAndBroadcastReclaim-BXclIcu_.js.map → buildAndBroadcastReclaim-DCGcupg7.js.map} +1 -1
- package/dist/constants-BTZdyOuk.cjs +2 -0
- package/dist/constants-BTZdyOuk.cjs.map +1 -0
- package/dist/constants-D5vORbQE.js +29 -0
- package/dist/constants-D5vORbQE.js.map +1 -0
- package/dist/fundPeginTransaction-54-Rwb2k.cjs +2 -0
- package/dist/fundPeginTransaction-54-Rwb2k.cjs.map +1 -0
- package/dist/fundPeginTransaction-CwhRbCQC.js +88 -0
- package/dist/fundPeginTransaction-CwhRbCQC.js.map +1 -0
- package/dist/{index-Cs7_Evtk.cjs → index-CK1Xvq4K.cjs} +2 -2
- package/dist/{index-Cs7_Evtk.cjs.map → index-CK1Xvq4K.cjs.map} +1 -1
- package/dist/{index-LgmJhdEN.js → index-DQ5bfoT3.js} +2 -2
- package/dist/{index-LgmJhdEN.js.map → index-DQ5bfoT3.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +15 -15
- package/dist/noPayout-4RZB2g1e.cjs +2 -0
- package/dist/noPayout-4RZB2g1e.cjs.map +1 -0
- package/dist/noPayout-DiGr4eas.js +361 -0
- package/dist/noPayout-DiGr4eas.js.map +1 -0
- package/dist/{parseFundingOutpoints-B67CoXpF.js → parseFundingOutpoints-BQWvINfm.js} +2 -2
- package/dist/{parseFundingOutpoints-B67CoXpF.js.map → parseFundingOutpoints-BQWvINfm.js.map} +1 -1
- package/dist/pegin-registration-client-CXK3B_D1.js +882 -0
- package/dist/pegin-registration-client-CXK3B_D1.js.map +1 -0
- package/dist/pegin-registration-client-DLsMNm8Z.cjs +2 -0
- package/dist/pegin-registration-client-DLsMNm8Z.cjs.map +1 -0
- package/dist/{primeVpAuth-DBHohVKM.cjs → primeVpAuth-BOGKniTl.cjs} +2 -2
- package/dist/{primeVpAuth-DBHohVKM.cjs.map → primeVpAuth-BOGKniTl.cjs.map} +1 -1
- package/dist/{primeVpAuth-DvaD45q_.js → primeVpAuth-DdfHSC53.js} +4 -4
- package/dist/{primeVpAuth-DvaD45q_.js.map → primeVpAuth-DdfHSC53.js.map} +1 -1
- package/dist/{psbtInputFields-BIxBpPj2.cjs → psbtInputFields-BrV_ZfL_.cjs} +2 -2
- package/dist/{psbtInputFields-BIxBpPj2.cjs.map → psbtInputFields-BrV_ZfL_.cjs.map} +1 -1
- package/dist/{psbtInputFields-B3e05Xe6.js → psbtInputFields-CCVyaQMi.js} +2 -2
- package/dist/{psbtInputFields-B3e05Xe6.js.map → psbtInputFields-CCVyaQMi.js.map} +1 -1
- package/dist/secp256k1-D-H9jmd7.js +1766 -0
- package/dist/secp256k1-D-H9jmd7.js.map +1 -0
- package/dist/secp256k1-DDHQ1_za.cjs +2 -0
- package/dist/secp256k1-DDHQ1_za.cjs.map +1 -0
- package/dist/{sha2-CrlWM5S8.js → sha2-CLpQd0Rd.js} +8 -8
- package/dist/{sha2-CrlWM5S8.js.map → sha2-CLpQd0Rd.js.map} +1 -1
- package/dist/{signPsbtsWithFallback-DMSpIQWH.cjs → signPsbtsWithFallback-DtwzL5AA.cjs} +2 -2
- package/dist/{signPsbtsWithFallback-DMSpIQWH.cjs.map → signPsbtsWithFallback-DtwzL5AA.cjs.map} +1 -1
- package/dist/{signPsbtsWithFallback-0VBALhjS.js → signPsbtsWithFallback-f7QLp0q8.js} +4 -4
- package/dist/{signPsbtsWithFallback-0VBALhjS.js.map → signPsbtsWithFallback-f7QLp0q8.js.map} +1 -1
- package/dist/tbv/core/clients/eth/index.cjs +1 -1
- package/dist/tbv/core/clients/eth/index.js +3 -3
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +5 -5
- package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.js +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +15 -15
- 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 +4 -4
- package/dist/tbv/core/primitives/psbt/__tests__/assertPeginTxShape.test.d.ts +5 -6
- package/dist/tbv/core/primitives/psbt/__tests__/assertPeginTxShape.test.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/__tests__/assertWasmPeginSizing.test.d.ts +2 -2
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts +36 -14
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/constants.d.ts +39 -0
- package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/peginInput.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/utils/fee/constants.d.ts +4 -4
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +2 -2
- package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/index.js +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +15 -15
- package/dist/test/setup.browser.d.ts +2 -0
- package/dist/test/setup.browser.d.ts.map +1 -0
- package/dist/testing/index.js +1 -1
- package/dist/{toRefundInputs-C3oIN0aW.js → toRefundInputs-BNSXIymn.js} +7 -7
- package/dist/{toRefundInputs-C3oIN0aW.js.map → toRefundInputs-BNSXIymn.js.map} +1 -1
- package/dist/{toRefundInputs-BwG6T0PP.cjs → toRefundInputs-meTyor7r.cjs} +2 -2
- package/dist/{toRefundInputs-BwG6T0PP.cjs.map → toRefundInputs-meTyor7r.cjs.map} +1 -1
- package/dist/{types-DSlcXtog.cjs → types-BzSOthHH.cjs} +2 -2
- package/dist/{types-DSlcXtog.cjs.map → types-BzSOthHH.cjs.map} +1 -1
- package/dist/{types-CPDLZm3l.js → types-C5DyrC8F.js} +2 -2
- package/dist/{types-CPDLZm3l.js.map → types-C5DyrC8F.js.map} +1 -1
- package/dist/verifyKeyPathSchnorrSignature-BVtNwgK6.js +360 -0
- package/dist/verifyKeyPathSchnorrSignature-BVtNwgK6.js.map +1 -0
- package/dist/verifyKeyPathSchnorrSignature-BjB8Znly.cjs +2 -0
- package/dist/verifyKeyPathSchnorrSignature-BjB8Znly.cjs.map +1 -0
- package/dist/verifyScriptPathSchnorrSignature-D_epga4j.js +1140 -0
- package/dist/verifyScriptPathSchnorrSignature-D_epga4j.js.map +1 -0
- package/dist/verifyScriptPathSchnorrSignature-DaRqvEgW.cjs +2 -0
- package/dist/verifyScriptPathSchnorrSignature-DaRqvEgW.cjs.map +1 -0
- package/package.json +4 -1
- package/dist/buildAndBroadcastReclaim-U-PyFfDg.cjs +0 -2
- package/dist/constants-Bh38W9mq.cjs +0 -2
- package/dist/constants-Bh38W9mq.cjs.map +0 -1
- package/dist/constants-CPzppOdq.js +0 -17
- package/dist/constants-CPzppOdq.js.map +0 -1
- package/dist/fundPeginTransaction-B2wyjqp0.js +0 -83
- package/dist/fundPeginTransaction-B2wyjqp0.js.map +0 -1
- package/dist/fundPeginTransaction-BLD8FRL9.cjs +0 -2
- package/dist/fundPeginTransaction-BLD8FRL9.cjs.map +0 -1
- package/dist/noPayout-DpGRzidi.js +0 -353
- package/dist/noPayout-DpGRzidi.js.map +0 -1
- package/dist/noPayout-zEifyecV.cjs +0 -2
- package/dist/noPayout-zEifyecV.cjs.map +0 -1
- package/dist/pegin-registration-client-6vLk2itL.cjs +0 -2
- package/dist/pegin-registration-client-6vLk2itL.cjs.map +0 -1
- package/dist/pegin-registration-client-BdRiR8br.js +0 -2635
- package/dist/pegin-registration-client-BdRiR8br.js.map +0 -1
- package/dist/vaultCoreVersion-DYfw3qed.cjs +0 -2
- package/dist/vaultCoreVersion-DYfw3qed.cjs.map +0 -1
- package/dist/vaultCoreVersion-D_fP9P3C.js +0 -10
- package/dist/vaultCoreVersion-D_fP9P3C.js.map +0 -1
- package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs +0 -2
- package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs.map +0 -1
- package/dist/verifyKeyPathSchnorrSignature-BrgUJmV0.js +0 -372
- package/dist/verifyKeyPathSchnorrSignature-BrgUJmV0.js.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-BfNUSgA7.cjs +0 -2
- package/dist/verifyScriptPathSchnorrSignature-BfNUSgA7.cjs.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-Ciq_xZhw.js +0 -951
- package/dist/verifyScriptPathSchnorrSignature-Ciq_xZhw.js.map +0 -1
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
import * as T from "bitcoinjs-lib";
|
|
2
|
-
import { Buffer as a } from "buffer";
|
|
3
|
-
const P = 58, R = 43, w = 11, I = 546, f = BigInt(I), S = 30, h = 2;
|
|
4
|
-
function N(t) {
|
|
5
|
-
return t <= h ? S : 0;
|
|
6
|
-
}
|
|
7
|
-
const U = 1, O = 1;
|
|
8
|
-
function d(t, c) {
|
|
9
|
-
if (!Number.isInteger(t) || t < 1)
|
|
10
|
-
throw new Error(
|
|
11
|
-
`peginOutputCount: vaultCount must be a positive integer, got ${t}`
|
|
12
|
-
);
|
|
13
|
-
return t + U + (c ? O : 0);
|
|
14
|
-
}
|
|
15
|
-
const B = 5, l = 100000n;
|
|
16
|
-
function b(t) {
|
|
17
|
-
const e = t.substring(8, 12) === "0001" ? 12 : 8, i = parseInt(
|
|
18
|
-
t.substring(e, e + 2),
|
|
19
|
-
16
|
|
20
|
-
), n = parseInt(
|
|
21
|
-
t.substring(e + 2, e + 4),
|
|
22
|
-
16
|
|
23
|
-
);
|
|
24
|
-
if (i !== 0)
|
|
25
|
-
throw new Error(`Expected 0 inputs from WASM, got ${i}`);
|
|
26
|
-
if (n === 0)
|
|
27
|
-
throw new Error("Expected at least 1 output from WASM, got 0");
|
|
28
|
-
const E = a.from(t.substring(0, 8), "hex").readUInt32LE(0), p = a.from(
|
|
29
|
-
t.substring(t.length - 8),
|
|
30
|
-
"hex"
|
|
31
|
-
).readUInt32LE(0), u = [];
|
|
32
|
-
let s = e + 4;
|
|
33
|
-
for (let o = 0; o < n; o++) {
|
|
34
|
-
const r = t.substring(s, s + 16), _ = Number(a.from(r, "hex").readBigUInt64LE(0));
|
|
35
|
-
s += 16;
|
|
36
|
-
const g = parseInt(t.substring(s, s + 2), 16);
|
|
37
|
-
s += 2;
|
|
38
|
-
const m = t.substring(s, s + g * 2), A = a.from(m, "hex");
|
|
39
|
-
s += g * 2, u.push({ value: _, script: A });
|
|
40
|
-
}
|
|
41
|
-
return { version: E, locktime: p, outputs: u };
|
|
42
|
-
}
|
|
43
|
-
function v(t) {
|
|
44
|
-
const { unfundedTxHex: c, selectedUTXOs: e, changeAddress: i, changeAmount: n, network: E } = t, { version: p, locktime: u, outputs: s } = b(c), o = new T.Transaction();
|
|
45
|
-
o.version = p, o.locktime = u;
|
|
46
|
-
for (const r of e) {
|
|
47
|
-
const _ = a.from(r.txid, "hex").reverse();
|
|
48
|
-
o.addInput(_, r.vout);
|
|
49
|
-
}
|
|
50
|
-
for (const r of s)
|
|
51
|
-
o.addOutput(r.script, r.value);
|
|
52
|
-
if (n < 0n)
|
|
53
|
-
throw new Error(
|
|
54
|
-
`fundPeginTransaction: changeAmount cannot be negative, got ${n}`
|
|
55
|
-
);
|
|
56
|
-
if (n > 0n && n <= f)
|
|
57
|
-
throw new Error(
|
|
58
|
-
`fundPeginTransaction: changeAmount must be 0 or strictly above DUST_THRESHOLD (${f}), got ${n}`
|
|
59
|
-
);
|
|
60
|
-
if (n > 0n) {
|
|
61
|
-
const r = T.address.toOutputScript(i, E);
|
|
62
|
-
o.addOutput(r, Number(n));
|
|
63
|
-
}
|
|
64
|
-
return o.toHex();
|
|
65
|
-
}
|
|
66
|
-
export {
|
|
67
|
-
I as B,
|
|
68
|
-
f as D,
|
|
69
|
-
S as L,
|
|
70
|
-
R as M,
|
|
71
|
-
P,
|
|
72
|
-
B as S,
|
|
73
|
-
w as T,
|
|
74
|
-
h as W,
|
|
75
|
-
U as a,
|
|
76
|
-
O as b,
|
|
77
|
-
l as c,
|
|
78
|
-
b as d,
|
|
79
|
-
v as f,
|
|
80
|
-
d as p,
|
|
81
|
-
N as r
|
|
82
|
-
};
|
|
83
|
-
//# sourceMappingURL=fundPeginTransaction-B2wyjqp0.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fundPeginTransaction-B2wyjqp0.js","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/**\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/**\n * Binary-independent cap on the implied per-HTLC reserve\n * (`htlcValue - peginAmount - depositorClaimValue`): the exact identity in\n * `assertWasmPeginSizing` is WASM-vs-WASM, so this pure-JS bound is what\n * limits a doctored binary. 100,000 vbytes = Bitcoin Core's relay ceiling\n * (MAX_STANDARD_TX_WEIGHT / 4) — ~19× the protocol-max PegIn (~5,150 vbytes\n * at 99 VKs + 99 UCs), so it can never false-positive.\n */\nexport const MAX_REASONABLE_PEGIN_VBYTES = 100_000n;\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 */\nexport interface 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","rateBasedTxBufferFee","feeRate","PEGIN_FIXED_OUTPUTS","PEGIN_AUTH_ANCHOR_OUTPUTS","peginOutputCount","vaultCount","hasAuthAnchor","SPLIT_TX_FEE_SAFETY_MULTIPLIER","MAX_REASONABLE_PEGIN_VBYTES","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":";;AAMO,MAAMA,IAAkB,IAGlBC,IAA6B,IAG7BC,IAA0B,IAG1BC,IAAe,KAGfC,IAAiB,OAAOD,CAAY,GAGpCE,IAAsC,IAGtCC,IAAkC;AAYxC,SAASC,EAAqBC,GAAyB;AAC5D,SAAOA,KAAWF,IACdD,IACA;AACN;AAMO,MAAMI,IAAsB,GAStBC,IAA4B;AAqBlC,SAASC,EACdC,GACAC,GACQ;AACR,MAAI,CAAC,OAAO,UAAUD,CAAU,KAAKA,IAAa;AAChD,UAAM,IAAI;AAAA,MACR,gEAAgEA,CAAU;AAAA,IAAA;AAG9E,SACEA,IACAH,KACCI,IAAgBH,IAA4B;AAEjD;AAQO,MAAMI,IAAiC,GAUjCC,IAA8B;AC7CpC,SAASC,EACdC,GACkB;AAGlB,QAAMC,IADoBD,EAAc,UAAU,GAAG,EAAE,MAAM,SACtB,KAAK,GAGtCE,IAAa;AAAA,IACjBF,EAAc,UAAUC,GAAYA,IAAa,CAAC;AAAA,IAClD;AAAA,EAAA,GAEIE,IAAc;AAAA,IAClBH,EAAc,UAAUC,IAAa,GAAGA,IAAa,CAAC;AAAA,IACtD;AAAA,EAAA;AAGF,MAAIC,MAAe;AACjB,UAAM,IAAI,MAAM,oCAAoCA,CAAU,EAAE;AAElE,MAAIC,MAAgB;AAClB,UAAM,IAAI,MAAM,6CAA6C;AAI/D,QAAMC,IAAUC,EAAO,KAAKL,EAAc,UAAU,GAAG,CAAC,GAAG,KAAK,EAAE,aAAa,CAAC,GAG1EM,IAAWD,EAAO;AAAA,IACtBL,EAAc,UAAUA,EAAc,SAAS,CAAC;AAAA,IAChD;AAAA,EAAA,EACA,aAAa,CAAC,GAGVO,IAA0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AAkFA,CAAc,UAAUgC,CAAY;AAAA,IAAA;AAG1H,MAAIA,IAAe,IAAI;AACrB,UAAMO,IAAeJ,EAAQ,QAAQ,eAAeJ,GAAeE,CAAO;AAC1E,IAAAC,EAAG,UAAUK,GAAc,OAAOP,CAAY,CAAC;AAAA,EACjD;AAEA,SAAOE,EAAG,MAAA;AACZ;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const b=require("bitcoinjs-lib"),u=require("buffer");function m(t){const c=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(c,n,i.get?i:{enumerable:!0,get:()=>t[n]})}}return c.default=t,Object.freeze(c)}const p=m(b),N=58,B=43,h=11,S=546,f=BigInt(S),g=30,O=2;function d(t){return t<=O?g:0}const I=1,U=1;function l(t,c){if(!Number.isInteger(t)||t<1)throw new Error(`peginOutputCount: vaultCount must be a positive integer, got ${t}`);return t+I+(c?U:0)}const F=5,D=100000n;function L(t){const n=t.substring(8,12)==="0001"?12:8,i=parseInt(t.substring(n,n+2),16),r=parseInt(t.substring(n+2,n+4),16);if(i!==0)throw new Error(`Expected 0 inputs from WASM, got ${i}`);if(r===0)throw new Error("Expected at least 1 output from WASM, got 0");const E=u.Buffer.from(t.substring(0,8),"hex").readUInt32LE(0),a=u.Buffer.from(t.substring(t.length-8),"hex").readUInt32LE(0),_=[];let e=n+4;for(let o=0;o<r;o++){const s=t.substring(e,e+16),T=Number(u.Buffer.from(s,"hex").readBigUInt64LE(0));e+=16;const A=parseInt(t.substring(e,e+2),16);e+=2;const R=t.substring(e,e+A*2),P=u.Buffer.from(R,"hex");e+=A*2,_.push({value:T,script:P})}return{version:E,locktime:a,outputs:_}}function C(t){const{unfundedTxHex:c,selectedUTXOs:n,changeAddress:i,changeAmount:r,network:E}=t,{version:a,locktime:_,outputs:e}=L(c),o=new p.Transaction;o.version=a,o.locktime=_;for(const s of n){const T=u.Buffer.from(s.txid,"hex").reverse();o.addInput(T,s.vout)}for(const s of e)o.addOutput(s.script,s.value);if(r<0n)throw new Error(`fundPeginTransaction: changeAmount cannot be negative, got ${r}`);if(r>0n&&r<=f)throw new Error(`fundPeginTransaction: changeAmount must be 0 or strictly above DUST_THRESHOLD (${f}), got ${r}`);if(r>0n){const s=p.address.toOutputScript(i,E);o.addOutput(s,Number(r))}return o.toHex()}exports.BTC_DUST_SAT=S;exports.DUST_THRESHOLD=f;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=g;exports.MAX_NON_LEGACY_OUTPUT_SIZE=B;exports.MAX_REASONABLE_PEGIN_VBYTES=D;exports.P2TR_INPUT_SIZE=N;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=U;exports.PEGIN_FIXED_OUTPUTS=I;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=F;exports.TX_BUFFER_SIZE_OVERHEAD=h;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=O;exports.fundPeginTransaction=C;exports.parseUnfundedWasmTransaction=L;exports.peginOutputCount=l;exports.rateBasedTxBufferFee=d;
|
|
2
|
-
//# sourceMappingURL=fundPeginTransaction-BLD8FRL9.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fundPeginTransaction-BLD8FRL9.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/**\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/**\n * Binary-independent cap on the implied per-HTLC reserve\n * (`htlcValue - peginAmount - depositorClaimValue`): the exact identity in\n * `assertWasmPeginSizing` is WASM-vs-WASM, so this pure-JS bound is what\n * limits a doctored binary. 100,000 vbytes = Bitcoin Core's relay ceiling\n * (MAX_STANDARD_TX_WEIGHT / 4) — ~19× the protocol-max PegIn (~5,150 vbytes\n * at 99 VKs + 99 UCs), so it can never false-positive.\n */\nexport const MAX_REASONABLE_PEGIN_VBYTES = 100_000n;\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 */\nexport interface 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","rateBasedTxBufferFee","feeRate","PEGIN_FIXED_OUTPUTS","PEGIN_AUTH_ANCHOR_OUTPUTS","peginOutputCount","vaultCount","hasAuthAnchor","SPLIT_TX_FEE_SAFETY_MULTIPLIER","MAX_REASONABLE_PEGIN_VBYTES","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,EAGpC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UQ,EAAKA,EAAMI,EAAY,CAAC,EAC5DE,EAAST,EAAAA,OAAO,KAAKQ,EAAW,KAAK,EAC3CL,GAAOI,EAAY,EAEnBL,EAAQ,KAAK,CAAE,MAAAI,EAAO,OAAAG,CAAA,CAAQ,CAChC,CAEA,MAAO,CAAE,QAAAV,EAAS,SAAAE,EAAU,QAAAC,CAAA,CAC9B,CAYO,SAASQ,EACdC,EACQ,CACR,KAAM,CAAE,cAAAhB,EAAe,cAAAiB,EAAe,cAAAC,EAAe,aAAAC,EAAc,QAAAC,GACjEJ,EAGI,CAAE,QAAAZ,EAAS,SAAAE,EAAU,QAAAC,CAAA,EACzBR,EAA6BC,CAAa,EAGtCqB,EAAK,IAAIC,EAAQ,YACvBD,EAAG,QAAUjB,EACbiB,EAAG,SAAWf,EAGd,UAAWiB,KAAQN,EAAe,CAEhC,MAAMO,EAASnB,EAAAA,OAAO,KAAKkB,EAAK,KAAM,KAAK,EAAE,QAAA,EAC7CF,EAAG,SAASG,EAAQD,EAAK,IAAI,CAC/B,CAGA,UAAWE,KAAUlB,EACnBc,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,353 +0,0 @@
|
|
|
1
|
-
import { loadRawTbvWasm as X, getPrePeginHtlcConnectorInfo as q, tapInternalPubkey as N, getAssertNoPayoutScriptInfo as z } from "./tbv/core/wasm/index.js";
|
|
2
|
-
import { Buffer as d } from "buffer";
|
|
3
|
-
import { Transaction as R, Psbt as S, payments as M } from "bitcoinjs-lib";
|
|
4
|
-
import { u as k, T as H, h as b, s as g, d as U, S as O, p as D, k as F } from "./bitcoin-C-TuHb-v.js";
|
|
5
|
-
import { n as W, d as G, P as m, l as Y } from "./verifyScriptPathSchnorrSignature-Ciq_xZhw.js";
|
|
6
|
-
import { D as V } from "./fundPeginTransaction-B2wyjqp0.js";
|
|
7
|
-
import { X as B } from "./validation-OSC0xTHB.js";
|
|
8
|
-
const Q = (1n << 64n) - 1n;
|
|
9
|
-
function j(t, a) {
|
|
10
|
-
if (!Array.isArray(t))
|
|
11
|
-
throw new Error(
|
|
12
|
-
`${a} must be an array of positive bigints (got ${typeof t}).`
|
|
13
|
-
);
|
|
14
|
-
if (t.length === 0)
|
|
15
|
-
throw new Error(`${a} must not be empty.`);
|
|
16
|
-
return t.forEach((e, o) => {
|
|
17
|
-
if (typeof e != "bigint")
|
|
18
|
-
throw new Error(
|
|
19
|
-
`${a}[${o}] must be a bigint (got ${typeof e}); refusing to feed it into satoshi math.`
|
|
20
|
-
);
|
|
21
|
-
if (e <= 0n)
|
|
22
|
-
throw new Error(`${a}[${o}] must be > 0 (got ${e}).`);
|
|
23
|
-
if (e > Q)
|
|
24
|
-
throw new Error(
|
|
25
|
-
`${a}[${o}] must fit in a u64 (got ${e}); refusing to feed it into satoshi math.`
|
|
26
|
-
);
|
|
27
|
-
}), t;
|
|
28
|
-
}
|
|
29
|
-
async function pe(t) {
|
|
30
|
-
const { WasmPrePeginTx: a } = await X(), { prePeginParams: e, fundedPrePeginTxHex: o, htlcVout: n, refundFee: l, hashlock: u } = t, c = W(
|
|
31
|
-
e.authAnchorHash
|
|
32
|
-
), r = new a(
|
|
33
|
-
e.vaultCoreVersion,
|
|
34
|
-
e.depositorPubkey,
|
|
35
|
-
e.vaultProviderPubkey,
|
|
36
|
-
e.vaultKeeperPubkeys,
|
|
37
|
-
e.universalChallengerPubkeys,
|
|
38
|
-
[...e.hashlocks],
|
|
39
|
-
new BigUint64Array(
|
|
40
|
-
j(e.pegInAmounts, "pegInAmounts")
|
|
41
|
-
),
|
|
42
|
-
e.timelockRefund,
|
|
43
|
-
e.feeRate,
|
|
44
|
-
e.minPeginFeeRate,
|
|
45
|
-
e.numLocalChallengers,
|
|
46
|
-
e.councilQuorum,
|
|
47
|
-
e.councilSize,
|
|
48
|
-
e.network,
|
|
49
|
-
c
|
|
50
|
-
);
|
|
51
|
-
let s = null;
|
|
52
|
-
try {
|
|
53
|
-
const f = r.getHtlcScriptPubKey(n).toLowerCase(), i = r.getHtlcValue(n);
|
|
54
|
-
s = r.fromFundedTransaction(o);
|
|
55
|
-
const y = s.buildRefundTx(l, n), v = await q({
|
|
56
|
-
txGraphVersion: e.vaultCoreVersion,
|
|
57
|
-
depositorPubkey: e.depositorPubkey,
|
|
58
|
-
vaultProviderPubkey: e.vaultProviderPubkey,
|
|
59
|
-
vaultKeeperPubkeys: e.vaultKeeperPubkeys,
|
|
60
|
-
universalChallengerPubkeys: e.universalChallengerPubkeys,
|
|
61
|
-
hashlock: u,
|
|
62
|
-
timelockRefund: e.timelockRefund,
|
|
63
|
-
network: e.network
|
|
64
|
-
}), h = o.startsWith("0x") ? o.slice(2) : o, P = R.fromHex(h), $ = P.outs[n];
|
|
65
|
-
if (!$)
|
|
66
|
-
throw new Error(
|
|
67
|
-
`HTLC output at vout ${n} not found in funded Pre-PegIn tx (tx has ${P.outs.length} outputs)`
|
|
68
|
-
);
|
|
69
|
-
const E = k(
|
|
70
|
-
new Uint8Array($.script)
|
|
71
|
-
).toLowerCase();
|
|
72
|
-
if (E !== f)
|
|
73
|
-
throw new Error(
|
|
74
|
-
`HTLC scriptPubKey mismatch at vout ${n}: reconstructed template expects ${f}, funded tx carries ${E}. Refund refused — the (hashlocks, pegInAmounts) vector does not match the on-chain commitment.`
|
|
75
|
-
);
|
|
76
|
-
const x = BigInt($.value);
|
|
77
|
-
if (x !== i)
|
|
78
|
-
throw new Error(
|
|
79
|
-
`HTLC value mismatch at vout ${n}: reconstructed template expects ${i} sat, funded tx carries ${x} sat. Refund refused — the pegInAmounts vector does not match the on-chain commitment.`
|
|
80
|
-
);
|
|
81
|
-
const p = R.fromHex(y);
|
|
82
|
-
if (p.ins.length !== 1)
|
|
83
|
-
throw new Error(
|
|
84
|
-
`Refund transaction must have exactly 1 input, got ${p.ins.length}`
|
|
85
|
-
);
|
|
86
|
-
const w = p.ins[0], C = P.getId(), L = k(
|
|
87
|
-
new Uint8Array(w.hash).slice().reverse()
|
|
88
|
-
);
|
|
89
|
-
if (L !== C)
|
|
90
|
-
throw new Error(
|
|
91
|
-
`Refund input does not reference the Pre-PegIn transaction. Expected ${C}, got ${L}`
|
|
92
|
-
);
|
|
93
|
-
if (w.index !== n)
|
|
94
|
-
throw new Error(
|
|
95
|
-
`Refund input index ${w.index} does not match expected htlcVout ${n}`
|
|
96
|
-
);
|
|
97
|
-
const I = new S();
|
|
98
|
-
if (I.setVersion(p.version), I.setLocktime(p.locktime), I.addInput({
|
|
99
|
-
hash: w.hash,
|
|
100
|
-
index: w.index,
|
|
101
|
-
sequence: w.sequence,
|
|
102
|
-
witnessUtxo: {
|
|
103
|
-
script: $.script,
|
|
104
|
-
value: $.value
|
|
105
|
-
},
|
|
106
|
-
tapLeafScript: [
|
|
107
|
-
{
|
|
108
|
-
leafVersion: H,
|
|
109
|
-
script: d.from(b(v.refundScript)),
|
|
110
|
-
controlBlock: d.from(
|
|
111
|
-
b(v.refundControlBlock)
|
|
112
|
-
)
|
|
113
|
-
}
|
|
114
|
-
],
|
|
115
|
-
tapInternalKey: d.from(N)
|
|
116
|
-
}), p.outs.length !== 1)
|
|
117
|
-
throw new Error(
|
|
118
|
-
`Refund transaction must have exactly 1 output, got ${p.outs.length}`
|
|
119
|
-
);
|
|
120
|
-
const T = p.outs[0], A = g(
|
|
121
|
-
U(e.depositorPubkey)
|
|
122
|
-
).toLowerCase(), _ = k(
|
|
123
|
-
new Uint8Array(T.script)
|
|
124
|
-
).toLowerCase();
|
|
125
|
-
if (_ !== A)
|
|
126
|
-
throw new Error(
|
|
127
|
-
`Refund output scriptPubKey ${_} does not match the depositor's BIP-86 address ${A}. Refund refused — the reclaimed funds would not return to the depositor.`
|
|
128
|
-
);
|
|
129
|
-
const K = x - l;
|
|
130
|
-
if (BigInt(T.value) !== K)
|
|
131
|
-
throw new Error(
|
|
132
|
-
`Refund output value ${BigInt(T.value)} sat does not equal the HTLC value ${x} sat minus the requested fee ${l} sat (expected ${K} sat). Refund refused — the reclaimed amount would be burned as excess fee.`
|
|
133
|
-
);
|
|
134
|
-
return I.addOutput({
|
|
135
|
-
script: T.script,
|
|
136
|
-
value: T.value
|
|
137
|
-
}), { psbtHex: I.toHex() };
|
|
138
|
-
} finally {
|
|
139
|
-
s == null || s.free(), r.free();
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
const J = 2, Z = 4294967293, ee = 214, te = 299, re = 4;
|
|
143
|
-
function oe(t) {
|
|
144
|
-
if (!Number.isInteger(t) || t < 1)
|
|
145
|
-
throw new Error(
|
|
146
|
-
`Reclaim input count must be a positive integer, got ${t}.`
|
|
147
|
-
);
|
|
148
|
-
return Math.ceil(
|
|
149
|
-
(ee + te * t) / re
|
|
150
|
-
);
|
|
151
|
-
}
|
|
152
|
-
function fe(t, a) {
|
|
153
|
-
if (!Number.isFinite(t) || t <= 0)
|
|
154
|
-
throw new Error(
|
|
155
|
-
`Reclaim fee rate must be a positive number, got ${t}.`
|
|
156
|
-
);
|
|
157
|
-
return BigInt(Math.ceil(t * oe(a)));
|
|
158
|
-
}
|
|
159
|
-
function he(t) {
|
|
160
|
-
const { depositorPubkey: a, inputs: e, feeSats: o } = t;
|
|
161
|
-
if (e.length === 0)
|
|
162
|
-
throw new Error("Reclaim requires at least one input; got none.");
|
|
163
|
-
if (o <= 0n)
|
|
164
|
-
throw new Error(
|
|
165
|
-
`Reclaim fee must be positive, got ${o} sat. Refusing to build a transaction that would not relay.`
|
|
166
|
-
);
|
|
167
|
-
const n = G(a), l = k(
|
|
168
|
-
new Uint8Array(n.scriptPubKey)
|
|
169
|
-
).toLowerCase(), u = new S();
|
|
170
|
-
u.setVersion(J), u.setLocktime(0);
|
|
171
|
-
let c = 0n;
|
|
172
|
-
const r = /* @__PURE__ */ new Set();
|
|
173
|
-
if (e.forEach((i, y) => {
|
|
174
|
-
const v = R.fromHex(
|
|
175
|
-
g(i.depositorSignedPeginTxHex)
|
|
176
|
-
), h = v.getId(), P = v.outs[m];
|
|
177
|
-
if (!P)
|
|
178
|
-
throw new Error(
|
|
179
|
-
`PegIn ${h} has no output at vout ${m} (tx has ${v.outs.length}); there is no depositor-claim reserve to reclaim.`
|
|
180
|
-
);
|
|
181
|
-
const $ = g(i.observed.txid).toLowerCase();
|
|
182
|
-
if ($ !== h)
|
|
183
|
-
throw new Error(
|
|
184
|
-
`Input ${y}: the observation is of ${$}, but this input spends PegIn ${h}. Reclaim refused — the reserve that was looked up is not the one being swept.`
|
|
185
|
-
);
|
|
186
|
-
if (i.observed.vout !== m)
|
|
187
|
-
throw new Error(
|
|
188
|
-
`Input ${y}: the observation is of vout ${i.observed.vout}, but the depositor-claim reserve is at vout ${m}. Reclaim refused.`
|
|
189
|
-
);
|
|
190
|
-
const E = k(
|
|
191
|
-
new Uint8Array(P.script)
|
|
192
|
-
).toLowerCase();
|
|
193
|
-
if (E !== l)
|
|
194
|
-
throw new Error(
|
|
195
|
-
`Input ${y}: PegIn ${h} vout ${m} pays ${E}, but the connected wallet's depositor-claim script is ${l}. Reclaim refused — this reserve belongs to a different wallet.`
|
|
196
|
-
);
|
|
197
|
-
const x = g(
|
|
198
|
-
i.observed.scriptPubKey
|
|
199
|
-
).toLowerCase();
|
|
200
|
-
if (x !== l)
|
|
201
|
-
throw new Error(
|
|
202
|
-
`Input ${y}: the observed UTXO ${h}:${m} pays ${x}, expected ${l}. Reclaim refused — chain state disagrees with the contract's PegIn.`
|
|
203
|
-
);
|
|
204
|
-
const p = BigInt(P.value);
|
|
205
|
-
if (p !== i.observed.value)
|
|
206
|
-
throw new Error(
|
|
207
|
-
`Input ${y}: PegIn ${h} vout ${m} carries ${p} sat, but the observed UTXO carries ${i.observed.value} sat. Reclaim refused.`
|
|
208
|
-
);
|
|
209
|
-
if (p !== i.expectedValue)
|
|
210
|
-
throw new Error(
|
|
211
|
-
`Input ${y}: PegIn ${h} vout ${m} carries ${p} sat, but this vault's parameters compute a depositor-claim value of ${i.expectedValue} sat. Reclaim refused.`
|
|
212
|
-
);
|
|
213
|
-
const w = `${h}:${m}`;
|
|
214
|
-
if (r.has(w))
|
|
215
|
-
throw new Error(
|
|
216
|
-
`Input ${y} repeats outpoint ${w}, which is already being swept by an earlier input. Reclaim refused.`
|
|
217
|
-
);
|
|
218
|
-
r.add(w), c += p, u.addInput({
|
|
219
|
-
hash: h,
|
|
220
|
-
index: m,
|
|
221
|
-
sequence: Z,
|
|
222
|
-
witnessUtxo: { script: P.script, value: P.value },
|
|
223
|
-
tapLeafScript: [
|
|
224
|
-
{
|
|
225
|
-
leafVersion: H,
|
|
226
|
-
script: n.leafScript,
|
|
227
|
-
controlBlock: n.controlBlock
|
|
228
|
-
}
|
|
229
|
-
],
|
|
230
|
-
tapInternalKey: n.internalKey
|
|
231
|
-
});
|
|
232
|
-
}), o >= c)
|
|
233
|
-
throw new Error(
|
|
234
|
-
`Reclaim fee ${o} sat is not less than the swept total ${c} sat. Refusing to build a transaction with no output.`
|
|
235
|
-
);
|
|
236
|
-
const s = c - o;
|
|
237
|
-
if (s <= V)
|
|
238
|
-
throw new Error(
|
|
239
|
-
`Reclaim output ${s} sat is at or below the dust threshold ${V} sat. The reserve is not at risk — it stays where it is until fee rates fall.`
|
|
240
|
-
);
|
|
241
|
-
const f = g(
|
|
242
|
-
U(a)
|
|
243
|
-
);
|
|
244
|
-
return u.addOutput({
|
|
245
|
-
script: d.from(b(f)),
|
|
246
|
-
value: Number(s)
|
|
247
|
-
}), { psbtHex: u.toHex(), outputValue: s, totalInputValue: c };
|
|
248
|
-
}
|
|
249
|
-
function de(t) {
|
|
250
|
-
const { requestedPsbtHex: a, signaturesHex: e, signerXOnlyPubkeyHex: o } = t, n = g(o);
|
|
251
|
-
if (n.length !== B)
|
|
252
|
-
throw new Error(
|
|
253
|
-
`Signer x-only pubkey must be ${B} hex chars (32 bytes), got ${n.length}.`
|
|
254
|
-
);
|
|
255
|
-
const l = d.from(b(n)), u = S.fromHex(a);
|
|
256
|
-
if (e.length !== u.data.inputs.length)
|
|
257
|
-
throw new Error(
|
|
258
|
-
`Cannot finalize: got ${e.length} signature(s) for ${u.data.inputs.length} input(s). Every input must be signed — refusing to broadcast a partially signed transaction.`
|
|
259
|
-
);
|
|
260
|
-
return u.data.inputs.forEach((c, r) => {
|
|
261
|
-
if (c.tapKeySig)
|
|
262
|
-
throw new Error(
|
|
263
|
-
`Cannot finalize: input ${r} of the locally built PSBT carries a key-path signature. These outputs are script-path only.`
|
|
264
|
-
);
|
|
265
|
-
const s = c.tapLeafScript;
|
|
266
|
-
if (!s || s.length !== 1)
|
|
267
|
-
throw new Error(
|
|
268
|
-
`Cannot finalize: input ${r} must have exactly one tapLeafScript, got ${(s == null ? void 0 : s.length) ?? 0}.`
|
|
269
|
-
);
|
|
270
|
-
const f = s[0];
|
|
271
|
-
if (f.leafVersion !== H)
|
|
272
|
-
throw new Error(
|
|
273
|
-
`Cannot finalize: input ${r} tapLeafScript has leaf version 0x${f.leafVersion.toString(16)}, expected 0x${H.toString(16)}.`
|
|
274
|
-
);
|
|
275
|
-
const i = g(e[r]);
|
|
276
|
-
if (i.length !== O)
|
|
277
|
-
throw new Error(
|
|
278
|
-
`Signature for input ${r} must be ${O} hex chars (64 bytes), got ${i.length}.`
|
|
279
|
-
);
|
|
280
|
-
u.updateInput(r, {
|
|
281
|
-
tapScriptSig: [
|
|
282
|
-
{
|
|
283
|
-
pubkey: l,
|
|
284
|
-
leafHash: Y(f.leafVersion, f.script),
|
|
285
|
-
signature: d.from(b(i))
|
|
286
|
-
}
|
|
287
|
-
]
|
|
288
|
-
});
|
|
289
|
-
}), u.finalizeAllInputs(), u.extractTransaction().toHex();
|
|
290
|
-
}
|
|
291
|
-
async function we(t) {
|
|
292
|
-
const a = g(t.noPayoutTxHex), e = R.fromHex(a), { noPayoutScript: o, noPayoutControlBlock: n } = await z(
|
|
293
|
-
t.connectorParams,
|
|
294
|
-
t.challengerPubkey
|
|
295
|
-
), l = b(o), u = b(n), c = new S();
|
|
296
|
-
c.setVersion(e.version), c.setLocktime(e.locktime);
|
|
297
|
-
for (let r = 0; r < e.ins.length; r++) {
|
|
298
|
-
const s = e.ins[r], f = t.prevouts[r];
|
|
299
|
-
if (!f)
|
|
300
|
-
throw new Error(`Missing prevout data for input ${r}`);
|
|
301
|
-
const i = {
|
|
302
|
-
hash: s.hash,
|
|
303
|
-
index: s.index,
|
|
304
|
-
sequence: s.sequence,
|
|
305
|
-
witnessUtxo: {
|
|
306
|
-
script: d.from(b(g(f.script_pubkey))),
|
|
307
|
-
value: f.value
|
|
308
|
-
}
|
|
309
|
-
};
|
|
310
|
-
r === 0 && (i.tapLeafScript = [
|
|
311
|
-
{
|
|
312
|
-
leafVersion: H,
|
|
313
|
-
script: d.from(l),
|
|
314
|
-
controlBlock: d.from(u)
|
|
315
|
-
}
|
|
316
|
-
], i.tapInternalKey = d.from(N)), c.addInput(i);
|
|
317
|
-
}
|
|
318
|
-
for (const r of e.outs)
|
|
319
|
-
c.addOutput({
|
|
320
|
-
script: r.script,
|
|
321
|
-
value: r.value
|
|
322
|
-
});
|
|
323
|
-
return c.toHex();
|
|
324
|
-
}
|
|
325
|
-
function me(t, a, e) {
|
|
326
|
-
const o = R.fromHex(g(t));
|
|
327
|
-
if (o.outs.length !== 1)
|
|
328
|
-
throw new Error(
|
|
329
|
-
`NoPayout transaction must have exactly 1 output, got ${o.outs.length}`
|
|
330
|
-
);
|
|
331
|
-
const n = b(D(a)), { output: l } = M.p2tr({
|
|
332
|
-
internalPubkey: d.from(n),
|
|
333
|
-
network: F(e)
|
|
334
|
-
});
|
|
335
|
-
if (!l)
|
|
336
|
-
throw new Error(
|
|
337
|
-
"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation"
|
|
338
|
-
);
|
|
339
|
-
if (!o.outs[0].script.equals(l))
|
|
340
|
-
throw new Error(
|
|
341
|
-
"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address"
|
|
342
|
-
);
|
|
343
|
-
}
|
|
344
|
-
export {
|
|
345
|
-
he as a,
|
|
346
|
-
pe as b,
|
|
347
|
-
we as c,
|
|
348
|
-
me as d,
|
|
349
|
-
fe as e,
|
|
350
|
-
de as f,
|
|
351
|
-
oe as r
|
|
352
|
-
};
|
|
353
|
-
//# sourceMappingURL=noPayout-DpGRzidi.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"noPayout-DpGRzidi.js","sources":["../src/tbv/core/wasm/value-guards.ts","../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/reclaim.ts","../src/tbv/core/primitives/psbt/finalizeScriptPathWithSignatures.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Runtime guard for satoshi amounts crossing into the WASM FFI boundary.\n *\n * `new BigUint64Array(values)` is the only way satoshi amounts are handed to\n * the constructor, and a runtime cast (`as readonly bigint[]`) lets a caller\n * pass a non-bigint or non-positive element that `BigUint64Array` would either\n * reject cryptically or, in its length-arg form, silently zero-fill. Values\n * above the u64 maximum are worse still: `BigUint64Array` wraps them mod 2^64\n * without complaint, turning an oversized amount into a small one.\n * {@link assertPositiveBigintArray} validates such inputs before the\n * typed-array construction.\n *\n * Mirrors the `assertPositiveBigintArray` half of `value-guards.ts` in\n * `@babylonlabs-io/babylon-tbv-rust-wasm`; that one function is pinned to the\n * engine's source copy by `__tests__/value-guards.test.ts`. The engine's other\n * guard, `assertWasmBigint`, has no counterpart here: the engine applies it to\n * its own WASM return values before they reach this package.\n */\n\n/** Largest value BigUint64Array stores without wrapping mod 2^64 (2^64 − 1). */\nconst U64_MAX = (1n << 64n) - 1n;\n\n/**\n * Assert a value is a non-empty array of strictly-positive `bigint`s and return\n * it narrowed, ready to feed into `new BigUint64Array(...)`.\n *\n * @param values - The candidate array of satoshi amounts.\n * @param label - Human-readable name used in the thrown error.\n * @throws If `values` is not an array, is empty, or contains any element that is\n * not a `bigint`, is not strictly greater than 0, or exceeds the u64 maximum\n * (which `BigUint64Array` would otherwise wrap mod 2^64).\n */\nexport function assertPositiveBigintArray(\n values: unknown,\n label: string,\n): bigint[] {\n if (!Array.isArray(values)) {\n throw new Error(\n `${label} must be an array of positive bigints (got ${typeof values}).`,\n );\n }\n if (values.length === 0) {\n throw new Error(`${label} must not be empty.`);\n }\n values.forEach((value, index) => {\n if (typeof value !== \"bigint\") {\n throw new Error(\n `${label}[${index}] must be a bigint (got ${typeof value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n if (value <= 0n) {\n throw new Error(`${label}[${index}] must be > 0 (got ${value}).`);\n }\n if (value > U64_MAX) {\n throw new Error(\n `${label}[${index}] must fit in a u64 (got ${value}); ` +\n `refusing to feed it into satoshi math.`,\n );\n }\n });\n return values as bigint[];\n}\n","/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n loadRawTbvWasm,\n tapInternalPubkey,\n} from \"../../wasm\";\nimport { assertPositiveBigintArray } from \"../../wasm/value-guards\";\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: `<depositorPubkey> OP_CHECKSIGVERIFY <timelockRefund>\n * OP_CHECKSEQUENCEVERIFY` — btc-vault `connectors/prepegin_htlc.rs`\n * `generate_refund_script`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n const { WasmPrePeginTx } = await loadRawTbvWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: typeof unfundedTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against 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 * Reclaim PSBT Builder Primitive\n *\n * Builds an unsigned PSBT that sweeps the depositor-claim reserve — PegIn\n * vout 1 — back to the depositor's own BIP-86 address.\n *\n * The reserve funds the depositor's `claim_tx`, their recourse if the vault\n * provider fails during peg-out. When the vault provider claims instead and\n * the depositor withdraws normally, nothing ever spends it. This primitive is\n * the only thing in the repository that can.\n *\n * Spend path: the single `<depositor> OP_CHECKSIG` tapleaf (see\n * ./depositorClaim). No timelock, no counterparty signature — the depositor's\n * Schnorr signature alone. That is also why the *caller* must gate: this\n * builder will happily sweep a reserve whose vault is still live, which would\n * permanently void the depositor's pre-signed recourse graph. Eligibility is\n * enforced upstream, in the service.\n *\n * @module primitives/psbt/reclaim\n */\n\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { DUST_THRESHOLD } from \"../../utils/fee/constants\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport {\n PEGIN_DEPOSITOR_CLAIM_VOUT,\n deriveDepositorClaimDescriptor,\n} from \"./depositorClaim\";\n\n/**\n * nVersion for the reclaim transaction. Plain v2, not TRUC: the reserve is only\n * offered once its PegIn is deeply confirmed, so the v2/v3 PegIn's nVersion-3\n * topology limits no longer constrain its children.\n */\nconst RECLAIM_TX_VERSION = 2;\n\n/**\n * nSequence for every reclaim input: RBF-enabled, no relative timelock. The\n * claim leaf carries no CSV, so this is a fee-bumping signal only.\n */\nconst RECLAIM_INPUT_SEQUENCE = 0xfffffffd;\n\n/**\n * Weight units of the reclaim transaction's skeleton — everything except the\n * inputs. Non-witness `version(4) + inCount(1) + outCount(1) + locktime(4) +\n * output(8 + 1 + 34)` = 53 B × 4, plus the 2 WU SegWit marker and flag.\n */\nconst RECLAIM_SKELETON_WEIGHT_UNITS = 214;\n\n/**\n * Weight units each script-path input adds. Non-witness `outpoint(36) +\n * scriptSigLen(1) + sequence(4)` = 41 B × 4 = 164, plus a witness of\n * `stackCount(1) + sig(1 + 64) + leafScript(1 + 34) + controlBlock(1 + 33)` =\n * 135 WU.\n *\n * Exact rather than conservative: every element is fixed-length here — a\n * 64-byte BIP-340 signature under SIGHASH_DEFAULT, the 34-byte leaf, and a\n * 33-byte control block with no merkle path.\n */\nconst RECLAIM_INPUT_WEIGHT_UNITS = 299;\n\n/** Weight units per virtual byte. */\nconst WEIGHT_UNITS_PER_VBYTE = 4;\n\n/**\n * Virtual size of an N-in/1-out reclaim transaction.\n *\n * `REFUND_VSIZE = 160` does not generalise to N inputs, and\n * `computePeginBaseFeeSats` is wrong for this shape entirely — its\n * `P2TR_INPUT_SIZE = 58` is a *key-path* input and under-fees a script-path\n * spend by roughly a quarter.\n *\n * N=1 → 129 vB; each additional input adds 75 vB.\n */\nexport function reclaimVsize(numInputs: number): number {\n if (!Number.isInteger(numInputs) || numInputs < 1) {\n throw new Error(\n `Reclaim input count must be a positive integer, got ${numInputs}.`,\n );\n }\n return Math.ceil(\n (RECLAIM_SKELETON_WEIGHT_UNITS +\n RECLAIM_INPUT_WEIGHT_UNITS * numInputs) /\n WEIGHT_UNITS_PER_VBYTE,\n );\n}\n\n/** Absolute fee in satoshis for an N-in/1-out reclaim at a given rate. */\nexport function estimateReclaimFeeSats(\n feeRateSatsVb: number,\n numInputs: number,\n): bigint {\n if (!Number.isFinite(feeRateSatsVb) || feeRateSatsVb <= 0) {\n throw new Error(\n `Reclaim fee rate must be a positive number, got ${feeRateSatsVb}.`,\n );\n }\n return BigInt(Math.ceil(feeRateSatsVb * reclaimVsize(numInputs)));\n}\n\n/** One depositor-claim reserve to sweep, with the material to bind it. */\nexport interface ReclaimReserve {\n /**\n * The contract's own copy of the depositor-signed PegIn transaction\n * (`VaultProtocolInfo.depositorSignedPeginTx`). Authoritative: its SegWit\n * txid equals the broadcast PegIn's, and its `outs[1]` carries the reserve's\n * script and value at no extra RPC cost.\n */\n depositorSignedPeginTxHex: string;\n /** Independent chain observation of `peginTxid:1` (esplora UTXO lookup). */\n observed: {\n /**\n * The outpoint the caller actually issued its chain lookup against, so the\n * observation below can be tied to the input this builder adds.\n *\n * Without it the script and value binds prove only that *some* UTXO has\n * this shape — the claim script is a pure function of the depositor key and\n * so is byte-identical across every vault they own, and the value is a pure\n * function of protocol parameters. Neither distinguishes one of the\n * depositor's vaults from another.\n *\n * Txid in display order, 64 hex chars, with or without `0x` prefix.\n */\n txid: string;\n /** Vout the lookup was issued against. Must be the claim vout. */\n vout: number;\n /** scriptPubKey hex, with or without `0x` prefix. */\n scriptPubKey: string;\n /** Output value in satoshis. */\n value: bigint;\n };\n /**\n * The reserve value recomputed from this vault's protocol parameters via\n * `computeMinClaimValue`. Bound so a doctored PegIn that agrees with itself\n * and with a compromised indexer still fails.\n */\n expectedValue: bigint;\n}\n\nexport interface BuildReclaimPsbtParams {\n /**\n * The **connected wallet's live** x-only pubkey, 64-char hex. Never the\n * indexer's `depositorBtcPubkey`: re-deriving from the live key is what\n * proves the wallet about to sign is the wallet that can spend, and rejects\n * the wrong-wallet case with an error instead of an unspendable broadcast.\n */\n depositorPubkey: string;\n /**\n * Reserves to sweep. An array so batching several vaults into one\n * transaction is a later change rather than a rewrite; today the app passes\n * exactly one.\n */\n inputs: ReclaimReserve[];\n /** Absolute fee in satoshis. The caller sizes it; see `reclaimVsize`. */\n feeSats: bigint;\n}\n\nexport interface BuildReclaimPsbtResult {\n /** PSBT hex ready for depositor signing. */\n psbtHex: string;\n /** Value of the single output — what the depositor actually receives. */\n outputValue: bigint;\n /** Sum of the swept reserves, before fee. */\n totalInputValue: bigint;\n}\n\n/**\n * Build the N-in/1-out reclaim PSBT.\n *\n * Every input is bound three ways before it reaches the PSBT: the contract's\n * PegIn bytes, the chain observation, and a JS re-derivation from the live\n * wallet key must agree on both script and value. Any disagreement throws.\n * The observation must also name the outpoint it was taken from, since script\n * and value alone repeat across all of a depositor's vaults.\n *\n * Binding the input to the *vault* that was asked for is a further step, and\n * it belongs to the service: it needs the vault id derivation, which is async.\n * See `services/reclaim/buildAndBroadcastReclaim`.\n *\n * @throws If `inputs` is empty, the fee is non-positive, any input fails its\n * outpoint, script or value bind, or the resulting output would be at or\n * below dust.\n */\nexport function buildReclaimPsbt(\n params: BuildReclaimPsbtParams,\n): BuildReclaimPsbtResult {\n const { depositorPubkey, inputs, feeSats } = params;\n\n if (inputs.length === 0) {\n throw new Error(\"Reclaim requires at least one input; got none.\");\n }\n if (feeSats <= 0n) {\n throw new Error(\n `Reclaim fee must be positive, got ${feeSats} sat. Refusing to build a ` +\n `transaction that would not relay.`,\n );\n }\n\n // One derivation, reused for every input's bind and for the destination.\n const descriptor = deriveDepositorClaimDescriptor(depositorPubkey);\n const expectedScriptPubKey = uint8ArrayToHex(\n new Uint8Array(descriptor.scriptPubKey),\n ).toLowerCase();\n\n const psbt = new Psbt();\n psbt.setVersion(RECLAIM_TX_VERSION);\n psbt.setLocktime(0);\n\n let totalInputValue = 0n;\n const seenOutpoints = new Set<string>();\n\n inputs.forEach((input, i) => {\n const peginTx = Transaction.fromHex(\n stripHexPrefix(input.depositorSignedPeginTxHex),\n );\n const peginTxid = peginTx.getId();\n\n const claimOut = peginTx.outs[PEGIN_DEPOSITOR_CLAIM_VOUT];\n if (!claimOut) {\n throw new Error(\n `PegIn ${peginTxid} has no output at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT} (tx has ${peginTx.outs.length}); ` +\n `there is no depositor-claim reserve to reclaim.`,\n );\n }\n\n // Bind 0: the observation is of *this* outpoint. Everything below compares\n // a script and a value, both of which repeat across every vault this\n // depositor owns under the same protocol parameters — so without this the\n // remaining binds cannot tell one of their vaults from another, and a\n // caller that resolved the wrong vault would sweep it with every check\n // passing. The independent source is the PegIn the PSBT is built from; the\n // esplora response cannot serve here because `getUtxoInfo` echoes back the\n // txid and vout it was called with rather than reading them from the body.\n const observedTxid = stripHexPrefix(input.observed.txid).toLowerCase();\n if (observedTxid !== peginTxid) {\n throw new Error(\n `Input ${i}: the observation is of ${observedTxid}, but this input ` +\n `spends PegIn ${peginTxid}. Reclaim refused — the reserve that was ` +\n `looked up is not the one being swept.`,\n );\n }\n if (input.observed.vout !== PEGIN_DEPOSITOR_CLAIM_VOUT) {\n throw new Error(\n `Input ${i}: the observation is of vout ${input.observed.vout}, but ` +\n `the depositor-claim reserve is at vout ` +\n `${PEGIN_DEPOSITOR_CLAIM_VOUT}. Reclaim refused.`,\n );\n }\n\n // Bind 1: the contract's PegIn bytes against the JS re-derivation from the\n // live wallet key. This is the assertion that proves the connected wallet\n // can actually spend the output we are about to sign for.\n const contractScriptPubKey = uint8ArrayToHex(\n new Uint8Array(claimOut.script),\n ).toLowerCase();\n if (contractScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} pays ` +\n `${contractScriptPubKey}, but the connected wallet's depositor-claim ` +\n `script is ${expectedScriptPubKey}. Reclaim refused — this reserve ` +\n `belongs to a different wallet.`,\n );\n }\n\n // Bind 2: the independent chain observation must agree with both.\n const observedScriptPubKey = stripHexPrefix(\n input.observed.scriptPubKey,\n ).toLowerCase();\n if (observedScriptPubKey !== expectedScriptPubKey) {\n throw new Error(\n `Input ${i}: the observed UTXO ${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `pays ${observedScriptPubKey}, expected ${expectedScriptPubKey}. ` +\n `Reclaim refused — chain state disagrees with the contract's PegIn.`,\n );\n }\n\n // Value bind, same three ways.\n const contractValue = BigInt(claimOut.value);\n if (contractValue !== input.observed.value) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but the observed UTXO carries ` +\n `${input.observed.value} sat. Reclaim refused.`,\n );\n }\n if (contractValue !== input.expectedValue) {\n throw new Error(\n `Input ${i}: PegIn ${peginTxid} vout ${PEGIN_DEPOSITOR_CLAIM_VOUT} ` +\n `carries ${contractValue} sat, but this vault's parameters compute a ` +\n `depositor-claim value of ${input.expectedValue} sat. Reclaim refused.`,\n );\n }\n\n // A batch that names the same vault twice would otherwise double-count the\n // swept total and then fail deep inside bitcoinjs. Reject it here, where\n // the message can say which input is the duplicate.\n const outpoint = `${peginTxid}:${PEGIN_DEPOSITOR_CLAIM_VOUT}`;\n if (seenOutpoints.has(outpoint)) {\n throw new Error(\n `Input ${i} repeats outpoint ${outpoint}, which is already being ` +\n `swept by an earlier input. Reclaim refused.`,\n );\n }\n seenOutpoints.add(outpoint);\n\n totalInputValue += contractValue;\n\n psbt.addInput({\n hash: peginTxid,\n index: PEGIN_DEPOSITOR_CLAIM_VOUT,\n sequence: RECLAIM_INPUT_SEQUENCE,\n witnessUtxo: { script: claimOut.script, value: claimOut.value },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: descriptor.leafScript,\n controlBlock: descriptor.controlBlock,\n },\n ],\n tapInternalKey: descriptor.internalKey,\n });\n });\n\n if (feeSats >= totalInputValue) {\n throw new Error(\n `Reclaim fee ${feeSats} sat is not less than the swept total ` +\n `${totalInputValue} sat. Refusing to build a transaction with no output.`,\n );\n }\n\n const outputValue = totalInputValue - feeSats;\n if (outputValue <= DUST_THRESHOLD) {\n throw new Error(\n `Reclaim output ${outputValue} sat is at or below the dust threshold ` +\n `${DUST_THRESHOLD} sat. The reserve is not at risk — it stays where it ` +\n `is until fee rates fall.`,\n );\n }\n\n const destination = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(depositorPubkey),\n );\n psbt.addOutput({\n script: Buffer.from(hexToUint8Array(destination)),\n value: Number(outputValue),\n });\n\n return { psbtHex: psbt.toHex(), outputValue, totalInputValue };\n}\n","/**\n * Finalize a Taproot script-path spend from the PSBT *we* built, using only the\n * verified signatures the wallet returned.\n *\n * Why this exists. The obvious shape — hand the wallet's PSBT to\n * `finalizeAllInputs()` — puts wallet-controlled bytes on the trust path even\n * when the signature itself has been verified.\n * `assertPsbtUnsignedTxMatches` deliberately pins only the unsigned\n * transaction and skips per-input metadata, so `tapLeafScript`, `controlBlock`\n * and `tapKeySig` all survive from the wallet's response untouched. And\n * bitcoinjs-lib checks key-spend first (`src/psbt.js`, `_finalizeTaprootInput`:\n * \"Check key spend first. Increased privacy and reduced block space.\"), so a\n * returned `tapKeySig` wins outright and `tapScriptSig` is never consulted.\n * Every output the depositor-claim reserve and the HTLC refund spend from uses\n * a NUMS internal key, so the resulting key-path witness cannot satisfy the\n * script — the transaction is rejected at broadcast, after a wallet prompt the\n * depositor cannot make sense of.\n *\n * Verifying and then discarding the wallet's PSBT closes that off structurally\n * rather than detecting it afterwards, and it makes the code match what\n * `verifyScriptPathSchnorrSignature` already documents: \"only the 64-byte\n * signature comes from the wallet\".\n *\n * @module tbv/core/primitives/psbt/finalizeScriptPathWithSignatures\n */\n\nimport { Psbt } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport { X_ONLY_PUBKEY_HEX_LEN } from \"../../utils/validation\";\nimport {\n SCHNORR_SIG_HEX_LEN,\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport { computeTapLeafHash } from \"../utils/taproot\";\n\nexport interface FinalizeScriptPathWithSignaturesParams {\n /**\n * Hex of the PSBT built locally and sent to the wallet — the sole source of\n * every per-input field. NOT the wallet-returned PSBT.\n */\n requestedPsbtHex: string;\n /**\n * Verified 64-byte Schnorr signatures, one per input, index-aligned with the\n * PSBT's inputs. Each must already have passed\n * `assertScriptPathSchnorrSignature` — this function does not re-verify them,\n * it only decides which bytes are allowed to reach the witness.\n */\n signaturesHex: readonly string[];\n /** X-only pubkey (64 hex chars) the signatures are attributed to. */\n signerXOnlyPubkeyHex: string;\n}\n\n/**\n * Attach `signaturesHex` to the locally built PSBT's script-path inputs,\n * finalize, and return the extracted transaction hex.\n *\n * @throws If the signature count does not match the input count, any signature\n * or the signer key is malformed, any input does not carry exactly one\n * tapscript leaf at the expected leaf version, any input already carries a\n * key-path signature, or bitcoinjs-lib cannot finalize.\n */\nexport function finalizeScriptPathWithSignatures(\n params: FinalizeScriptPathWithSignaturesParams,\n): string {\n const { requestedPsbtHex, signaturesHex, signerXOnlyPubkeyHex } = params;\n\n const signerXOnly = stripHexPrefix(signerXOnlyPubkeyHex);\n if (signerXOnly.length !== X_ONLY_PUBKEY_HEX_LEN) {\n throw new Error(\n `Signer x-only pubkey must be ${X_ONLY_PUBKEY_HEX_LEN} hex chars ` +\n `(32 bytes), got ${signerXOnly.length}.`,\n );\n }\n const signerPubkey = Buffer.from(hexToUint8Array(signerXOnly));\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (signaturesHex.length !== psbt.data.inputs.length) {\n throw new Error(\n `Cannot finalize: got ${signaturesHex.length} signature(s) for ` +\n `${psbt.data.inputs.length} input(s). Every input must be signed — ` +\n `refusing to broadcast a partially signed transaction.`,\n );\n }\n\n psbt.data.inputs.forEach((input, inputIndex) => {\n // Our own builders never produce a key-path signature for these spends.\n // If one is present the PSBT is not the one we built, which would defeat\n // the whole point of finalizing locally.\n if (input.tapKeySig) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} of the locally built PSBT ` +\n `carries a key-path signature. These outputs are script-path only.`,\n );\n }\n\n const tapLeafScripts = input.tapLeafScript;\n if (!tapLeafScripts || tapLeafScripts.length !== 1) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} must have exactly one ` +\n `tapLeafScript, got ${tapLeafScripts?.length ?? 0}.`,\n );\n }\n const leaf = tapLeafScripts[0];\n if (leaf.leafVersion !== TAPSCRIPT_LEAF_VERSION) {\n throw new Error(\n `Cannot finalize: input ${inputIndex} tapLeafScript has leaf version ` +\n `0x${leaf.leafVersion.toString(16)}, expected ` +\n `0x${TAPSCRIPT_LEAF_VERSION.toString(16)}.`,\n );\n }\n\n const signatureRaw = stripHexPrefix(signaturesHex[inputIndex]);\n if (signatureRaw.length !== SCHNORR_SIG_HEX_LEN) {\n throw new Error(\n `Signature for input ${inputIndex} must be ${SCHNORR_SIG_HEX_LEN} hex ` +\n `chars (64 bytes), got ${signatureRaw.length}.`,\n );\n }\n\n psbt.updateInput(inputIndex, {\n tapScriptSig: [\n {\n pubkey: signerPubkey,\n leafHash: computeTapLeafHash(leaf.leafVersion, leaf.script),\n signature: Buffer.from(hexToUint8Array(signatureRaw)),\n },\n ],\n });\n });\n\n // With no tapKeySig anywhere, bitcoinjs takes the script-path branch for\n // every input and builds `[signature, leafScript, controlBlock]` from the\n // leaf we supplied.\n psbt.finalizeAllInputs();\n\n return psbt.extractTransaction().toHex();\n}\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"../../wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] 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":["U64_MAX","assertPositiveBigintArray","values","label","value","index","buildRefundPsbt","params","WasmPrePeginTx","loadRawTbvWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","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","RECLAIM_TX_VERSION","RECLAIM_INPUT_SEQUENCE","RECLAIM_SKELETON_WEIGHT_UNITS","RECLAIM_INPUT_WEIGHT_UNITS","WEIGHT_UNITS_PER_VBYTE","reclaimVsize","numInputs","estimateReclaimFeeSats","feeRateSatsVb","buildReclaimPsbt","depositorPubkey","inputs","feeSats","descriptor","deriveDepositorClaimDescriptor","expectedScriptPubKey","totalInputValue","seenOutpoints","input","i","peginTx","peginTxid","claimOut","PEGIN_DEPOSITOR_CLAIM_VOUT","observedTxid","contractScriptPubKey","observedScriptPubKey","contractValue","outpoint","outputValue","DUST_THRESHOLD","destination","finalizeScriptPathWithSignatures","requestedPsbtHex","signaturesHex","signerXOnlyPubkeyHex","signerXOnly","X_ONLY_PUBKEY_HEX_LEN","signerPubkey","inputIndex","tapLeafScripts","leaf","signatureRaw","SCHNORR_SIG_HEX_LEN","computeTapLeafHash","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":";;;;;;;AAoBA,MAAMA,KAAW,MAAM,OAAO;AAYvB,SAASC,EACdC,GACAC,GACU;AACV,MAAI,CAAC,MAAM,QAAQD,CAAM;AACvB,UAAM,IAAI;AAAA,MACR,GAAGC,CAAK,8CAA8C,OAAOD,CAAM;AAAA,IAAA;AAGvE,MAAIA,EAAO,WAAW;AACpB,UAAM,IAAI,MAAM,GAAGC,CAAK,qBAAqB;AAE/C,SAAAD,EAAO,QAAQ,CAACE,GAAOC,MAAU;AAC/B,QAAI,OAAOD,KAAU;AACnB,YAAM,IAAI;AAAA,QACR,GAAGD,CAAK,IAAIE,CAAK,2BAA2B,OAAOD,CAAK;AAAA,MAAA;AAI5D,QAAIA,KAAS;AACX,YAAM,IAAI,MAAM,GAAGD,CAAK,IAAIE,CAAK,sBAAsBD,CAAK,IAAI;AAElE,QAAIA,IAAQJ;AACV,YAAM,IAAI;AAAA,QACR,GAAGG,CAAK,IAAIE,CAAK,4BAA4BD,CAAK;AAAA,MAAA;AAAA,EAIxD,CAAC,GACMF;AACT;ACYA,eAAsBI,GACpBC,GACgC;AAChC,QAAM,EAAE,gBAAAC,MAAmB,MAAMC,EAAA,GAE3B,EAAE,gBAAAC,GAAgB,qBAAAC,GAAqB,UAAAC,GAAU,WAAAC,GAAW,UAAAC,MAChEP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