@babylonlabs-io/ts-sdk 0.70.1 → 0.71.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/PeginManager-BIKAnZ-X.cjs +2 -0
- package/dist/PeginManager-BIKAnZ-X.cjs.map +1 -0
- package/dist/{PeginManager-BNtg6jgY.js → PeginManager-Byvmccdd.js} +10 -10
- package/dist/PeginManager-Byvmccdd.js.map +1 -0
- package/dist/abortSignals-BPpAUL1Z.js +18 -0
- package/dist/abortSignals-BPpAUL1Z.js.map +1 -0
- package/dist/abortSignals-msbmbqFe.cjs +2 -0
- package/dist/abortSignals-msbmbqFe.cjs.map +1 -0
- package/dist/{bitcoin-Ch_jxnDa.js → bitcoin-C-TuHb-v.js} +21 -22
- package/dist/bitcoin-C-TuHb-v.js.map +1 -0
- package/dist/bitcoin-D-O2GjbC.cjs +2 -0
- package/dist/bitcoin-D-O2GjbC.cjs.map +1 -0
- package/dist/{buildAndBroadcastReclaim-kBHwOL02.js → buildAndBroadcastReclaim-C0TdwO2M.js} +60 -59
- package/dist/{buildAndBroadcastReclaim-kBHwOL02.js.map → buildAndBroadcastReclaim-C0TdwO2M.js.map} +1 -1
- package/dist/buildAndBroadcastReclaim-kRx7-o2y.cjs +2 -0
- package/dist/{buildAndBroadcastReclaim-iNJfx0ZG.cjs.map → buildAndBroadcastReclaim-kRx7-o2y.cjs.map} +1 -1
- package/dist/{challengeAssert-BNQ8sToz.js → challengeAssert-Cp_GeRg8.js} +3 -3
- package/dist/challengeAssert-Cp_GeRg8.js.map +1 -0
- package/dist/challengeAssert-Z7_YULBb.cjs +2 -0
- package/dist/challengeAssert-Z7_YULBb.cjs.map +1 -0
- package/dist/constants-Bh38W9mq.cjs +2 -0
- package/dist/constants-Bh38W9mq.cjs.map +1 -0
- package/dist/constants-CPzppOdq.js +17 -0
- package/dist/constants-CPzppOdq.js.map +1 -0
- package/dist/index-Cs7_Evtk.cjs +2 -0
- package/dist/index-Cs7_Evtk.cjs.map +1 -0
- package/dist/index-LgmJhdEN.js +505 -0
- package/dist/index-LgmJhdEN.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +230 -226
- package/dist/index.js.map +1 -1
- package/dist/mempoolApi-BQllf-ji.cjs +2 -0
- package/dist/{mempoolApi-Q90mz17e.cjs.map → mempoolApi-BQllf-ji.cjs.map} +1 -1
- package/dist/{mempoolApi-CfOFmov6.js → mempoolApi-CRNMOsbC.js} +36 -35
- package/dist/{mempoolApi-CfOFmov6.js.map → mempoolApi-CRNMOsbC.js.map} +1 -1
- package/dist/noPayout--lxo7qe4.js +300 -0
- package/dist/noPayout--lxo7qe4.js.map +1 -0
- package/dist/noPayout-CegnEwfp.cjs +2 -0
- package/dist/noPayout-CegnEwfp.cjs.map +1 -0
- package/dist/{onChainBtcPubkey-C_a2L3kL.cjs → onChainBtcPubkey-B5ZvWCCF.cjs} +2 -2
- package/dist/{onChainBtcPubkey-C_a2L3kL.cjs.map → onChainBtcPubkey-B5ZvWCCF.cjs.map} +1 -1
- package/dist/{onChainBtcPubkey-BAHZyKQL.js → onChainBtcPubkey-DATNfAAl.js} +2 -2
- package/dist/{onChainBtcPubkey-BAHZyKQL.js.map → onChainBtcPubkey-DATNfAAl.js.map} +1 -1
- package/dist/parseFundingOutpoints-BkgGihaY.cjs +2 -0
- package/dist/parseFundingOutpoints-BkgGihaY.cjs.map +1 -0
- package/dist/{parseFundingOutpoints-CO-f6IHK.js → parseFundingOutpoints-DlINgQ3X.js} +30 -29
- package/dist/parseFundingOutpoints-DlINgQ3X.js.map +1 -0
- package/dist/{batchPoll-BM4iQ9jT.js → primeVpAuth-D1qbOkhb.js} +311 -803
- package/dist/primeVpAuth-D1qbOkhb.js.map +1 -0
- package/dist/primeVpAuth-tEXx9TGx.cjs +2 -0
- package/dist/primeVpAuth-tEXx9TGx.cjs.map +1 -0
- package/dist/{reservation-CBAvoF3U.js → reservation-Cj9F0rP9.js} +2 -2
- package/dist/{reservation-CBAvoF3U.js.map → reservation-Cj9F0rP9.js.map} +1 -1
- package/dist/{reservation-CDbInVw0.cjs → reservation-Dr2HLCxx.cjs} +2 -2
- package/dist/{reservation-CDbInVw0.cjs.map → reservation-Dr2HLCxx.cjs.map} +1 -1
- package/dist/{signPsbtsWithFallback-X6ivsbh7.js → signPsbtsWithFallback-BjXdnI0X.js} +18 -19
- package/dist/{signPsbtsWithFallback-X6ivsbh7.js.map → signPsbtsWithFallback-BjXdnI0X.js.map} +1 -1
- package/dist/signPsbtsWithFallback-zOQWokmk.cjs +2 -0
- package/dist/{signPsbtsWithFallback-Bo1PJX90.cjs.map → signPsbtsWithFallback-zOQWokmk.cjs.map} +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +36 -35
- package/dist/tbv/core/clients/index.js.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/serverIdentity.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/auth/verifyDepositorCwt.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.cjs +2 -0
- package/dist/tbv/core/clients/vault-provider/status/index.cjs.map +1 -0
- package/dist/tbv/core/clients/vault-provider/status/index.d.ts +18 -0
- package/dist/tbv/core/clients/vault-provider/status/index.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/status/index.js +17 -0
- package/dist/tbv/core/clients/vault-provider/status/index.js.map +1 -0
- package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -1
- package/dist/tbv/core/deposit-terms/rebuildDepositTermsCore.d.ts +1 -1
- package/dist/tbv/core/deposit-terms/rebuildDepositTermsCore.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +224 -220
- package/dist/tbv/core/index.js.map +1 -1
- 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.d.ts +2 -2
- package/dist/tbv/core/primitives/index.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.js +7 -7
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/noPayout.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/noPayout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/payout.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/peginInput.d.ts +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/primitives/scripts/payout.d.ts +1 -1
- package/dist/tbv/core/primitives/scripts/payout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts +0 -10
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
- package/dist/tbv/core/recovery/reconstructPeginParams.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/signDepositorGraph.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/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +47 -44
- package/dist/tbv/core/utils/index.js.map +1 -1
- package/dist/tbv/core/utils/utxo/reservation.d.ts.map +1 -1
- package/dist/tbv/core/utils/validation.d.ts +4 -0
- package/dist/tbv/core/utils/validation.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/deriveVaultRoot.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/index.cjs +1 -1
- package/dist/tbv/core/vault-secrets/index.d.ts +1 -1
- package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/index.js +2 -2
- package/dist/tbv/core/wasm/__tests__/constants.test.d.ts +2 -0
- package/dist/tbv/core/wasm/__tests__/constants.test.d.ts.map +1 -0
- package/dist/tbv/core/wasm/__tests__/loader.test.d.ts +2 -0
- package/dist/tbv/core/wasm/__tests__/loader.test.d.ts.map +1 -0
- package/dist/tbv/core/wasm/__tests__/value-guards.test.d.ts +2 -0
- package/dist/tbv/core/wasm/__tests__/value-guards.test.d.ts.map +1 -0
- package/dist/tbv/core/wasm/constants.d.ts +11 -0
- package/dist/tbv/core/wasm/constants.d.ts.map +1 -0
- package/dist/tbv/core/wasm/index.cjs +2 -0
- package/dist/tbv/core/wasm/index.cjs.map +1 -0
- package/dist/tbv/core/wasm/index.d.ts +191 -0
- package/dist/tbv/core/wasm/index.d.ts.map +1 -0
- package/dist/tbv/core/wasm/index.js +144 -0
- package/dist/tbv/core/wasm/index.js.map +1 -0
- package/dist/tbv/core/wasm/value-guards.d.ts +30 -0
- package/dist/tbv/core/wasm/value-guards.d.ts.map +1 -0
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +224 -220
- package/dist/tbv/index.js.map +1 -1
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/toRefundInputs-Bdtz8p27.cjs +2 -0
- package/dist/toRefundInputs-Bdtz8p27.cjs.map +1 -0
- package/dist/{toRefundInputs-DPNYBFkP.js → toRefundInputs-CgXMcHrk.js} +7 -7
- package/dist/toRefundInputs-CgXMcHrk.js.map +1 -0
- package/dist/validation-C6XTfZak.cjs +2 -0
- package/dist/validation-C6XTfZak.cjs.map +1 -0
- package/dist/validation-OSC0xTHB.js +17 -0
- package/dist/validation-OSC0xTHB.js.map +1 -0
- package/dist/vaultCoreVersion-DYfw3qed.cjs +2 -0
- package/dist/vaultCoreVersion-DYfw3qed.cjs.map +1 -0
- package/dist/vaultCoreVersion-D_fP9P3C.js +10 -0
- package/dist/vaultCoreVersion-D_fP9P3C.js.map +1 -0
- package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs +2 -0
- package/dist/verifyKeyPathSchnorrSignature-BedSbH2D.cjs.map +1 -0
- package/dist/{verifyKeyPathSchnorrSignature-C6Cmk0R1.js → verifyKeyPathSchnorrSignature-BrgUJmV0.js} +3 -3
- package/dist/verifyKeyPathSchnorrSignature-BrgUJmV0.js.map +1 -0
- package/dist/{verifyScriptPathSchnorrSignature-CQYucnJA.js → verifyScriptPathSchnorrSignature-ZAZfFJ6S.js} +35 -34
- package/dist/verifyScriptPathSchnorrSignature-ZAZfFJ6S.js.map +1 -0
- package/dist/verifyScriptPathSchnorrSignature-mzYCzaSy.cjs +2 -0
- package/dist/verifyScriptPathSchnorrSignature-mzYCzaSy.cjs.map +1 -0
- package/package.json +12 -2
- package/dist/PeginManager-BNtg6jgY.js.map +0 -1
- package/dist/PeginManager-CvI99Uhd.cjs +0 -2
- package/dist/PeginManager-CvI99Uhd.cjs.map +0 -1
- package/dist/batchPoll-BM4iQ9jT.js.map +0 -1
- package/dist/batchPoll-cqpEfBjr.cjs +0 -2
- package/dist/batchPoll-cqpEfBjr.cjs.map +0 -1
- package/dist/bitcoin-Ch_jxnDa.js.map +0 -1
- package/dist/bitcoin-m84N5a8o.cjs +0 -2
- package/dist/bitcoin-m84N5a8o.cjs.map +0 -1
- package/dist/buildAndBroadcastReclaim-iNJfx0ZG.cjs +0 -2
- package/dist/challengeAssert-BNQ8sToz.js.map +0 -1
- package/dist/challengeAssert-BrpC3-cQ.cjs +0 -2
- package/dist/challengeAssert-BrpC3-cQ.cjs.map +0 -1
- package/dist/constants-BCdDRd_Y.cjs +0 -2
- package/dist/constants-BCdDRd_Y.cjs.map +0 -1
- package/dist/constants-DRiWbItj.js +0 -24
- package/dist/constants-DRiWbItj.js.map +0 -1
- package/dist/mempoolApi-Q90mz17e.cjs +0 -2
- package/dist/noPayout-BKP3mRu3.cjs +0 -2
- package/dist/noPayout-BKP3mRu3.cjs.map +0 -1
- package/dist/noPayout-BdATUPjF.js +0 -280
- package/dist/noPayout-BdATUPjF.js.map +0 -1
- package/dist/parseFundingOutpoints-CIO9Ok1L.cjs +0 -2
- package/dist/parseFundingOutpoints-CIO9Ok1L.cjs.map +0 -1
- package/dist/parseFundingOutpoints-CO-f6IHK.js.map +0 -1
- package/dist/signPsbtsWithFallback-Bo1PJX90.cjs +0 -2
- package/dist/toRefundInputs-BJojfg3k.cjs +0 -2
- package/dist/toRefundInputs-BJojfg3k.cjs.map +0 -1
- package/dist/toRefundInputs-DPNYBFkP.js.map +0 -1
- package/dist/validation-CDbOaDj7.cjs +0 -2
- package/dist/validation-CDbOaDj7.cjs.map +0 -1
- package/dist/validation-Dj3dqYtl.js +0 -30
- package/dist/validation-Dj3dqYtl.js.map +0 -1
- package/dist/verifyKeyPathSchnorrSignature-C6Cmk0R1.js.map +0 -1
- package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs +0 -2
- package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-CQYucnJA.js.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-D-ppKNjT.cjs +0 -2
- package/dist/verifyScriptPathSchnorrSignature-D-ppKNjT.cjs.map +0 -1
|
@@ -1,280 +0,0 @@
|
|
|
1
|
-
import { initWasm as N, WasmPrePeginTx as U, assertPositiveBigintArray as _, getPrePeginHtlcConnectorInfo as q, tapInternalPubkey as V, getAssertNoPayoutScriptInfo as M } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
2
|
-
import { Buffer as m } from "buffer";
|
|
3
|
-
import { Transaction as k, Psbt as R, payments as D } from "bitcoinjs-lib";
|
|
4
|
-
import { u as T, T as H, h as g, s as v, d as O, p as F, k as W } from "./bitcoin-Ch_jxnDa.js";
|
|
5
|
-
import { n as G, d as z, P as y } from "./verifyScriptPathSchnorrSignature-CQYucnJA.js";
|
|
6
|
-
import { D as B } from "./fundPeginTransaction-B2wyjqp0.js";
|
|
7
|
-
async function ae(o) {
|
|
8
|
-
await N();
|
|
9
|
-
const { prePeginParams: e, fundedPrePeginTxHex: s, htlcVout: t, refundFee: i, hashlock: c } = o, f = G(
|
|
10
|
-
e.authAnchorHash
|
|
11
|
-
), n = new U(
|
|
12
|
-
e.vaultCoreVersion,
|
|
13
|
-
e.depositorPubkey,
|
|
14
|
-
e.vaultProviderPubkey,
|
|
15
|
-
e.vaultKeeperPubkeys,
|
|
16
|
-
e.universalChallengerPubkeys,
|
|
17
|
-
[...e.hashlocks],
|
|
18
|
-
new BigUint64Array(
|
|
19
|
-
_(e.pegInAmounts, "pegInAmounts")
|
|
20
|
-
),
|
|
21
|
-
e.timelockRefund,
|
|
22
|
-
e.feeRate,
|
|
23
|
-
e.minPeginFeeRate,
|
|
24
|
-
e.numLocalChallengers,
|
|
25
|
-
e.councilQuorum,
|
|
26
|
-
e.councilSize,
|
|
27
|
-
e.network,
|
|
28
|
-
f
|
|
29
|
-
);
|
|
30
|
-
let r = null;
|
|
31
|
-
try {
|
|
32
|
-
const l = n.getHtlcScriptPubKey(t).toLowerCase(), w = n.getHtlcValue(t);
|
|
33
|
-
r = n.fromFundedTransaction(s);
|
|
34
|
-
const u = r.buildRefundTx(i, t), P = await q({
|
|
35
|
-
txGraphVersion: e.vaultCoreVersion,
|
|
36
|
-
depositorPubkey: e.depositorPubkey,
|
|
37
|
-
vaultProviderPubkey: e.vaultProviderPubkey,
|
|
38
|
-
vaultKeeperPubkeys: e.vaultKeeperPubkeys,
|
|
39
|
-
universalChallengerPubkeys: e.universalChallengerPubkeys,
|
|
40
|
-
hashlock: c,
|
|
41
|
-
timelockRefund: e.timelockRefund,
|
|
42
|
-
network: e.network
|
|
43
|
-
}), b = s.startsWith("0x") ? s.slice(2) : s, p = k.fromHex(b), d = p.outs[t];
|
|
44
|
-
if (!d)
|
|
45
|
-
throw new Error(
|
|
46
|
-
`HTLC output at vout ${t} not found in funded Pre-PegIn tx (tx has ${p.outs.length} outputs)`
|
|
47
|
-
);
|
|
48
|
-
const $ = T(
|
|
49
|
-
new Uint8Array(d.script)
|
|
50
|
-
).toLowerCase();
|
|
51
|
-
if ($ !== l)
|
|
52
|
-
throw new Error(
|
|
53
|
-
`HTLC scriptPubKey mismatch at vout ${t}: reconstructed template expects ${l}, funded tx carries ${$}. Refund refused — the (hashlocks, pegInAmounts) vector does not match the on-chain commitment.`
|
|
54
|
-
);
|
|
55
|
-
const x = BigInt(d.value);
|
|
56
|
-
if (x !== w)
|
|
57
|
-
throw new Error(
|
|
58
|
-
`HTLC value mismatch at vout ${t}: reconstructed template expects ${w} sat, funded tx carries ${x} sat. Refund refused — the pegInAmounts vector does not match the on-chain commitment.`
|
|
59
|
-
);
|
|
60
|
-
const a = k.fromHex(u);
|
|
61
|
-
if (a.ins.length !== 1)
|
|
62
|
-
throw new Error(
|
|
63
|
-
`Refund transaction must have exactly 1 input, got ${a.ins.length}`
|
|
64
|
-
);
|
|
65
|
-
const h = a.ins[0], C = p.getId(), S = T(
|
|
66
|
-
new Uint8Array(h.hash).slice().reverse()
|
|
67
|
-
);
|
|
68
|
-
if (S !== C)
|
|
69
|
-
throw new Error(
|
|
70
|
-
`Refund input does not reference the Pre-PegIn transaction. Expected ${C}, got ${S}`
|
|
71
|
-
);
|
|
72
|
-
if (h.index !== t)
|
|
73
|
-
throw new Error(
|
|
74
|
-
`Refund input index ${h.index} does not match expected htlcVout ${t}`
|
|
75
|
-
);
|
|
76
|
-
const I = new R();
|
|
77
|
-
if (I.setVersion(a.version), I.setLocktime(a.locktime), I.addInput({
|
|
78
|
-
hash: h.hash,
|
|
79
|
-
index: h.index,
|
|
80
|
-
sequence: h.sequence,
|
|
81
|
-
witnessUtxo: {
|
|
82
|
-
script: d.script,
|
|
83
|
-
value: d.value
|
|
84
|
-
},
|
|
85
|
-
tapLeafScript: [
|
|
86
|
-
{
|
|
87
|
-
leafVersion: H,
|
|
88
|
-
script: m.from(g(P.refundScript)),
|
|
89
|
-
controlBlock: m.from(
|
|
90
|
-
g(P.refundControlBlock)
|
|
91
|
-
)
|
|
92
|
-
}
|
|
93
|
-
],
|
|
94
|
-
tapInternalKey: m.from(V)
|
|
95
|
-
}), a.outs.length !== 1)
|
|
96
|
-
throw new Error(
|
|
97
|
-
`Refund transaction must have exactly 1 output, got ${a.outs.length}`
|
|
98
|
-
);
|
|
99
|
-
const E = a.outs[0], A = v(
|
|
100
|
-
O(e.depositorPubkey)
|
|
101
|
-
).toLowerCase(), L = T(
|
|
102
|
-
new Uint8Array(E.script)
|
|
103
|
-
).toLowerCase();
|
|
104
|
-
if (L !== A)
|
|
105
|
-
throw new Error(
|
|
106
|
-
`Refund output scriptPubKey ${L} does not match the depositor's BIP-86 address ${A}. Refund refused — the reclaimed funds would not return to the depositor.`
|
|
107
|
-
);
|
|
108
|
-
const K = x - i;
|
|
109
|
-
if (BigInt(E.value) !== K)
|
|
110
|
-
throw new Error(
|
|
111
|
-
`Refund output value ${BigInt(E.value)} sat does not equal the HTLC value ${x} sat minus the requested fee ${i} sat (expected ${K} sat). Refund refused — the reclaimed amount would be burned as excess fee.`
|
|
112
|
-
);
|
|
113
|
-
return I.addOutput({
|
|
114
|
-
script: E.script,
|
|
115
|
-
value: E.value
|
|
116
|
-
}), { psbtHex: I.toHex() };
|
|
117
|
-
} finally {
|
|
118
|
-
r == null || r.free(), n.free();
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
const X = 2, Q = 4294967293, Y = 214, j = 299, J = 4;
|
|
122
|
-
function Z(o) {
|
|
123
|
-
if (!Number.isInteger(o) || o < 1)
|
|
124
|
-
throw new Error(
|
|
125
|
-
`Reclaim input count must be a positive integer, got ${o}.`
|
|
126
|
-
);
|
|
127
|
-
return Math.ceil(
|
|
128
|
-
(Y + j * o) / J
|
|
129
|
-
);
|
|
130
|
-
}
|
|
131
|
-
function ie(o, e) {
|
|
132
|
-
if (!Number.isFinite(o) || o <= 0)
|
|
133
|
-
throw new Error(
|
|
134
|
-
`Reclaim fee rate must be a positive number, got ${o}.`
|
|
135
|
-
);
|
|
136
|
-
return BigInt(Math.ceil(o * Z(e)));
|
|
137
|
-
}
|
|
138
|
-
function ue(o) {
|
|
139
|
-
const { depositorPubkey: e, inputs: s, feeSats: t } = o;
|
|
140
|
-
if (s.length === 0)
|
|
141
|
-
throw new Error("Reclaim requires at least one input; got none.");
|
|
142
|
-
if (t <= 0n)
|
|
143
|
-
throw new Error(
|
|
144
|
-
`Reclaim fee must be positive, got ${t} sat. Refusing to build a transaction that would not relay.`
|
|
145
|
-
);
|
|
146
|
-
const i = z(e), c = T(
|
|
147
|
-
new Uint8Array(i.scriptPubKey)
|
|
148
|
-
).toLowerCase(), f = new R();
|
|
149
|
-
f.setVersion(X), f.setLocktime(0);
|
|
150
|
-
let n = 0n;
|
|
151
|
-
const r = /* @__PURE__ */ new Set();
|
|
152
|
-
if (s.forEach((u, P) => {
|
|
153
|
-
const b = k.fromHex(
|
|
154
|
-
v(u.depositorSignedPeginTxHex)
|
|
155
|
-
), p = b.getId(), d = b.outs[y];
|
|
156
|
-
if (!d)
|
|
157
|
-
throw new Error(
|
|
158
|
-
`PegIn ${p} has no output at vout ${y} (tx has ${b.outs.length}); there is no depositor-claim reserve to reclaim.`
|
|
159
|
-
);
|
|
160
|
-
const $ = T(
|
|
161
|
-
new Uint8Array(d.script)
|
|
162
|
-
).toLowerCase();
|
|
163
|
-
if ($ !== c)
|
|
164
|
-
throw new Error(
|
|
165
|
-
`Input ${P}: PegIn ${p} vout ${y} pays ${$}, but the connected wallet's depositor-claim script is ${c}. Reclaim refused — this reserve belongs to a different wallet.`
|
|
166
|
-
);
|
|
167
|
-
const x = v(
|
|
168
|
-
u.observed.scriptPubKey
|
|
169
|
-
).toLowerCase();
|
|
170
|
-
if (x !== c)
|
|
171
|
-
throw new Error(
|
|
172
|
-
`Input ${P}: the observed UTXO ${p}:${y} pays ${x}, expected ${c}. Reclaim refused — chain state disagrees with the contract's PegIn.`
|
|
173
|
-
);
|
|
174
|
-
const a = BigInt(d.value);
|
|
175
|
-
if (a !== u.observed.value)
|
|
176
|
-
throw new Error(
|
|
177
|
-
`Input ${P}: PegIn ${p} vout ${y} carries ${a} sat, but the observed UTXO carries ${u.observed.value} sat. Reclaim refused.`
|
|
178
|
-
);
|
|
179
|
-
if (a !== u.expectedValue)
|
|
180
|
-
throw new Error(
|
|
181
|
-
`Input ${P}: PegIn ${p} vout ${y} carries ${a} sat, but this vault's parameters compute a depositor-claim value of ${u.expectedValue} sat. Reclaim refused.`
|
|
182
|
-
);
|
|
183
|
-
const h = `${p}:${y}`;
|
|
184
|
-
if (r.has(h))
|
|
185
|
-
throw new Error(
|
|
186
|
-
`Input ${P} repeats outpoint ${h}, which is already being swept by an earlier input. Reclaim refused.`
|
|
187
|
-
);
|
|
188
|
-
r.add(h), n += a, f.addInput({
|
|
189
|
-
hash: p,
|
|
190
|
-
index: y,
|
|
191
|
-
sequence: Q,
|
|
192
|
-
witnessUtxo: { script: d.script, value: d.value },
|
|
193
|
-
tapLeafScript: [
|
|
194
|
-
{
|
|
195
|
-
leafVersion: H,
|
|
196
|
-
script: i.leafScript,
|
|
197
|
-
controlBlock: i.controlBlock
|
|
198
|
-
}
|
|
199
|
-
],
|
|
200
|
-
tapInternalKey: i.internalKey
|
|
201
|
-
});
|
|
202
|
-
}), t >= n)
|
|
203
|
-
throw new Error(
|
|
204
|
-
`Reclaim fee ${t} sat is not less than the swept total ${n} sat. Refusing to build a transaction with no output.`
|
|
205
|
-
);
|
|
206
|
-
const l = n - t;
|
|
207
|
-
if (l <= B)
|
|
208
|
-
throw new Error(
|
|
209
|
-
`Reclaim output ${l} sat is at or below the dust threshold ${B} sat. The reserve is not at risk — it stays where it is until fee rates fall.`
|
|
210
|
-
);
|
|
211
|
-
const w = v(
|
|
212
|
-
O(e)
|
|
213
|
-
);
|
|
214
|
-
return f.addOutput({
|
|
215
|
-
script: m.from(g(w)),
|
|
216
|
-
value: Number(l)
|
|
217
|
-
}), { psbtHex: f.toHex(), outputValue: l, totalInputValue: n };
|
|
218
|
-
}
|
|
219
|
-
async function ce(o) {
|
|
220
|
-
const e = v(o.noPayoutTxHex), s = k.fromHex(e), { noPayoutScript: t, noPayoutControlBlock: i } = await M(
|
|
221
|
-
o.connectorParams,
|
|
222
|
-
o.challengerPubkey
|
|
223
|
-
), c = g(t), f = g(i), n = new R();
|
|
224
|
-
n.setVersion(s.version), n.setLocktime(s.locktime);
|
|
225
|
-
for (let r = 0; r < s.ins.length; r++) {
|
|
226
|
-
const l = s.ins[r], w = o.prevouts[r];
|
|
227
|
-
if (!w)
|
|
228
|
-
throw new Error(`Missing prevout data for input ${r}`);
|
|
229
|
-
const u = {
|
|
230
|
-
hash: l.hash,
|
|
231
|
-
index: l.index,
|
|
232
|
-
sequence: l.sequence,
|
|
233
|
-
witnessUtxo: {
|
|
234
|
-
script: m.from(g(v(w.script_pubkey))),
|
|
235
|
-
value: w.value
|
|
236
|
-
}
|
|
237
|
-
};
|
|
238
|
-
r === 0 && (u.tapLeafScript = [
|
|
239
|
-
{
|
|
240
|
-
leafVersion: H,
|
|
241
|
-
script: m.from(c),
|
|
242
|
-
controlBlock: m.from(f)
|
|
243
|
-
}
|
|
244
|
-
], u.tapInternalKey = m.from(V)), n.addInput(u);
|
|
245
|
-
}
|
|
246
|
-
for (const r of s.outs)
|
|
247
|
-
n.addOutput({
|
|
248
|
-
script: r.script,
|
|
249
|
-
value: r.value
|
|
250
|
-
});
|
|
251
|
-
return n.toHex();
|
|
252
|
-
}
|
|
253
|
-
function le(o, e, s) {
|
|
254
|
-
const t = k.fromHex(v(o));
|
|
255
|
-
if (t.outs.length !== 1)
|
|
256
|
-
throw new Error(
|
|
257
|
-
`NoPayout transaction must have exactly 1 output, got ${t.outs.length}`
|
|
258
|
-
);
|
|
259
|
-
const i = g(F(e)), { output: c } = D.p2tr({
|
|
260
|
-
internalPubkey: m.from(i),
|
|
261
|
-
network: W(s)
|
|
262
|
-
});
|
|
263
|
-
if (!c)
|
|
264
|
-
throw new Error(
|
|
265
|
-
"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation"
|
|
266
|
-
);
|
|
267
|
-
if (!t.outs[0].script.equals(c))
|
|
268
|
-
throw new Error(
|
|
269
|
-
"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address"
|
|
270
|
-
);
|
|
271
|
-
}
|
|
272
|
-
export {
|
|
273
|
-
ue as a,
|
|
274
|
-
ae as b,
|
|
275
|
-
ce as c,
|
|
276
|
-
le as d,
|
|
277
|
-
ie as e,
|
|
278
|
-
Z as r
|
|
279
|
-
};
|
|
280
|
-
//# sourceMappingURL=noPayout-BdATUPjF.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"noPayout-BdATUPjF.js","sources":["../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/reclaim.ts","../src/tbv/core/primitives/psbt/noPayout.ts"],"sourcesContent":["/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n assertPositiveBigintArray,\n getPrePeginHtlcConnectorInfo,\n initWasm,\n tapInternalPubkey,\n WasmPrePeginTx,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n deriveBip86ScriptPubKeyHex,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\nimport { normalizeAuthAnchorHash, type PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<timelockRefund> CSV DROP <depositorPubkey> CHECKSIG`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n await initWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n // The 14th positional arg `auth_anchor_hash` is `Option<String>` in\n // the Rust WASM constructor (the 9th arg `min_pegin_fee_rate` requires\n // the two-rate constructor from btc-vault #1930). Production peg-ins\n // (PeginManager) always commit an OP_RETURN <PUSH32 SHA256(authAnchor)>\n // output at `vout = hashlocks.length`; the unfunded template must\n // include it so `fromFundedTransaction` aligns with the funded tx.\n // Normalize identically to the peg-in primitives (`0x` strip,\n // lowercase, length/charset validation) so a direct primitive caller\n // reusing successful peg-in params doesn't hand unnormalized bytes to\n // WASM. Pass `undefined` for legacy non-auth-anchored Pre-PegIns.\n const normalizedAuthAnchorHash = normalizeAuthAnchorHash(\n prePeginParams.authAnchorHash,\n );\n // Reconstruct the template under the same graph version the Pre-PegIn\n // was originally built with (the vault's stamped vaultCoreVersion).\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.vaultCoreVersion,\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(\n assertPositiveBigintArray(prePeginParams.pegInAmounts, \"pegInAmounts\"),\n ),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.minPeginFeeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n normalizedAuthAnchorHash,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n // Cross-check the reconstructed unfunded template against the funded\n // transaction: the WASM template's HTLC scriptPubKey at `htlcVout`\n // must equal the bytes the funded tx carries at the same output.\n // If they disagree, the template was reconstructed from the wrong\n // (hashlocks, amounts) vector — signing it would produce a refund\n // that does not spend the on-chain HTLC the depositor expects.\n // This is the explicit invariant the audit recommends: never sign a\n // refund whose template doesn't match the on-chain output bytes.\n const expectedHtlcScriptPubKey = unfundedTx\n .getHtlcScriptPubKey(htlcVout)\n .toLowerCase();\n // The reconstructed template's HTLC output value at `htlcVout`,\n // sized by WASM from the supplied `pegInAmounts` via the protocol\n // formula `htlcValue = peginAmount + depositorClaimValue + minPeginFee`.\n // Captured before `fromFundedTransaction` to bind it to the value the\n // funded tx actually carries (see the cross-check below).\n const expectedHtlcValue = unfundedTx.getHtlcValue(htlcVout);\n\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n txGraphVersion: prePeginParams.vaultCoreVersion,\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const actualHtlcScriptPubKey = uint8ArrayToHex(\n new Uint8Array(htlcOutput.script),\n ).toLowerCase();\n if (actualHtlcScriptPubKey !== expectedHtlcScriptPubKey) {\n throw new Error(\n `HTLC scriptPubKey mismatch at vout ${htlcVout}: reconstructed ` +\n `template expects ${expectedHtlcScriptPubKey}, funded tx carries ` +\n `${actualHtlcScriptPubKey}. Refund refused — the (hashlocks, ` +\n `pegInAmounts) vector does not match the on-chain commitment.`,\n );\n }\n\n // Value cross-check (mirrors the script check above): the template's\n // HTLC value — derived by WASM from `pegInAmounts` via the protocol\n // formula — must equal the value the funded tx pays at this output.\n // A caller that hands the full HTLC output value (or any wrong amount)\n // as `pegInAmounts` would inflate the template value and trip this\n // guard, rather than silently signing a refund built from a template\n // that disagrees with the on-chain commitment.\n const actualHtlcValue = BigInt(htlcOutput.value);\n if (actualHtlcValue !== expectedHtlcValue) {\n throw new Error(\n `HTLC value mismatch at vout ${htlcVout}: reconstructed template ` +\n `expects ${expectedHtlcValue} sat, funded tx carries ` +\n `${actualHtlcValue} sat. Refund refused — the pegInAmounts vector ` +\n `does not match the on-chain commitment.`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n // Output side: pin the single refund output to the depositor's own\n // BIP-86 P2TR address, mirroring the input-side pinning above. WASM\n // builds the refund output from the refund leaf's depositor key, so a\n // correct template always pays exactly one output back to the depositor.\n // Asserting it here means a malformed template (or a tampered WASM)\n // cannot redirect the reclaimed funds to a script the depositor does\n // not control.\n if (refundTx.outs.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 output, got ${refundTx.outs.length}`,\n );\n }\n const refundOutput = refundTx.outs[0];\n const expectedDepositorScriptPubKey = stripHexPrefix(\n deriveBip86ScriptPubKeyHex(prePeginParams.depositorPubkey),\n ).toLowerCase();\n const actualRefundOutputScriptPubKey = uint8ArrayToHex(\n new Uint8Array(refundOutput.script),\n ).toLowerCase();\n if (actualRefundOutputScriptPubKey !== expectedDepositorScriptPubKey) {\n throw new Error(\n `Refund output scriptPubKey ${actualRefundOutputScriptPubKey} does not ` +\n `match the depositor's BIP-86 address ${expectedDepositorScriptPubKey}. ` +\n `Refund refused — the reclaimed funds would not return to the depositor.`,\n );\n }\n\n // Value: the single refund output must return the full HTLC value minus\n // exactly the requested fee. The refund is 1-in/1-out (asserted above), so\n // a value below `htlcValue - refundFee` means WASM applied a larger fee\n // than requested — the difference would be burned as miner fee. Pin it so\n // the depositor reclaims the expected amount, not a silently reduced one.\n const expectedRefundOutputValue = actualHtlcValue - refundFee;\n if (BigInt(refundOutput.value) !== expectedRefundOutputValue) {\n throw new Error(\n `Refund output value ${BigInt(refundOutput.value)} sat does not equal ` +\n `the HTLC value ${actualHtlcValue} sat minus the requested fee ` +\n `${refundFee} sat (expected ${expectedRefundOutputValue} sat). ` +\n `Refund refused — the reclaimed amount would be burned as excess fee.`,\n );\n }\n\n psbt.addOutput({\n script: refundOutput.script,\n value: refundOutput.value,\n });\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * 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 /** 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 *\n * @throws If `inputs` is empty, the fee is non-positive, any input fails its\n * script or value bind, or the resulting output would be at or 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 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 * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n type Network,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction, payments } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n getNetwork,\n hexToUint8Array,\n processPublicKeyToXOnly,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n/**\n * Validate that a NoPayout transaction pays to the challenger via the\n * protocol-defined output structure: a single BIP-86 P2TR output derived from\n * the challenger's x-only pubkey.\n *\n * Mirrors the per-role payout output validation now inlined in\n * `buildPayoutPsbt` for the NoPayout path, where the sink is fixed by the\n * protocol rather than read from on-chain registration\n * (see `crates/vault/src/transactions/nopayout.rs::NoPayoutTx::new`).\n *\n * @param noPayoutTxHex - Raw NoPayout transaction hex\n * @param challengerPubkey - Challenger's x-only public key (hex)\n * @param network - Bitcoin network used to derive the P2TR scriptPubKey\n * @throws If the transaction does not have exactly one output\n * @throws If the single output's scriptPubKey does not equal the BIP-86 P2TR\n * scriptPubKey for the challenger\n */\nexport function assertNoPayoutOutputMatchesChallenger(\n noPayoutTxHex: string,\n challengerPubkey: string,\n network: Network,\n): void {\n const tx = Transaction.fromHex(stripHexPrefix(noPayoutTxHex));\n\n if (tx.outs.length !== 1) {\n throw new Error(\n `NoPayout transaction must have exactly 1 output, got ${tx.outs.length}`,\n );\n }\n\n const xOnly = hexToUint8Array(processPublicKeyToXOnly(challengerPubkey));\n const { output: expectedScript } = payments.p2tr({\n internalPubkey: Buffer.from(xOnly),\n network: getNetwork(network),\n });\n if (!expectedScript) {\n throw new Error(\n \"Failed to derive challenger BIP-86 P2TR scriptPubKey for NoPayout output validation\",\n );\n }\n\n if (!tx.outs[0].script.equals(expectedScript)) {\n throw new Error(\n \"NoPayout transaction does not pay to the expected challenger BIP-86 P2TR address\",\n );\n }\n}\n"],"names":["buildRefundPsbt","params","initWasm","prePeginParams","fundedPrePeginTxHex","htlcVout","refundFee","hashlock","normalizedAuthAnchorHash","normalizeAuthAnchorHash","unfundedTx","WasmPrePeginTx","assertPositiveBigintArray","fundedTx","expectedHtlcScriptPubKey","expectedHtlcValue","refundTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","cleanPrePeginHex","prePeginTx","Transaction","htlcOutput","actualHtlcScriptPubKey","uint8ArrayToHex","actualHtlcValue","refundTx","refundInput","prePeginTxid","refundInputTxid","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","hexToUint8Array","tapInternalPubkey","refundOutput","expectedDepositorScriptPubKey","stripHexPrefix","deriveBip86ScriptPubKeyHex","actualRefundOutputScriptPubKey","expectedRefundOutputValue","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","contractScriptPubKey","observedScriptPubKey","contractValue","outpoint","outputValue","DUST_THRESHOLD","destination","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","scriptBytes","controlBlockBytes","prevout","inputData","output","assertNoPayoutOutputMatchesChallenger","challengerPubkey","network","tx","xOnly","processPublicKeyToXOnly","expectedScript","payments","getNetwork"],"mappings":";;;;;;AAyEA,eAAsBA,GACpBC,GACgC;AAChC,QAAMC,EAAA;AAEN,QAAM,EAAE,gBAAAC,GAAgB,qBAAAC,GAAqB,UAAAC,GAAU,WAAAC,GAAW,UAAAC,MAChEN,GAYIO,IAA2BC;AAAA,IAC/BN,EAAe;AAAA,EAAA,GAIXO,IAAa,IAAIC;AAAA,IACrBR,EA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IAG1DL,EAAK,SAASoD,CAAS;AAAA,EACzB;AAGA,aAAWC,KAAUR,EAAW;AAC9B,IAAA7C,EAAK,UAAU;AAAA,MACb,QAAQqD,EAAO;AAAA,MACf,OAAOA,EAAO;AAAA,IAAA,CACf;AAGH,SAAOrD,EAAK,MAAA;AACd;AAmBO,SAASsD,GACdV,GACAW,GACAC,GACM;AACN,QAAMC,IAAKlE,EAAY,QAAQiB,EAAeoC,CAAa,CAAC;AAE5D,MAAIa,EAAG,KAAK,WAAW;AACrB,UAAM,IAAI;AAAA,MACR,wDAAwDA,EAAG,KAAK,MAAM;AAAA,IAAA;AAI1E,QAAMC,IAAQtD,EAAgBuD,EAAwBJ,CAAgB,CAAC,GACjE,EAAE,QAAQK,MAAmBC,EAAS,KAAK;AAAA,IAC/C,gBAAgB1D,EAAO,KAAKuD,CAAK;AAAA,IACjC,SAASI,EAAWN,CAAO;AAAA,EAAA,CAC5B;AACD,MAAI,CAACI;AACH,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAIJ,MAAI,CAACH,EAAG,KAAK,CAAC,EAAE,OAAO,OAAOG,CAAc;AAC1C,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAGN;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const l=require("./bitcoin-m84N5a8o.cjs"),x=require("./sha2-DsrLC4NM.cjs"),y=require("bitcoinjs-lib"),b=require("buffer"),i=32,u=32,c=36,m=32,s=4,v=s+i+s+m;function a(t,e,r){t[e]=r>>>24&255,t[e+1]=r>>>16&255,t[e+2]=r>>>8&255,t[e+3]=r&255}function O(t){if(t.txid.length!==u)throw new Error(`outpoint.txid must be exactly ${u} bytes, got ${t.txid.length}`);if(!Number.isInteger(t.vout)||t.vout<0||t.vout>4294967295)throw new Error(`outpoint.vout must be a u32, got ${t.vout}`);const e=new Uint8Array(c);return e.set(t.txid,0),a(e,u,t.vout),e}function h(t,e){const r=Math.min(t.length,e.length);for(let n=0;n<r;n++)if(t[n]!==e[n])return t[n]-e[n];return t.length-e.length}function f(t){if(t.length===0)throw new Error("buildFundingOutpointsCommitment: outpoints must be non-empty");const e=t.map(O);e.sort(h);for(let n=1;n<e.length;n++)if(h(e[n-1],e[n])===0)throw new Error("buildFundingOutpointsCommitment: duplicate outpoint detected");const r=new Uint8Array(e.length*c);for(let n=0;n<e.length;n++)r.set(e[n],n*c);return x.sha256(r)}function E(t){if(t.depositorBtcPubkey.length!==i)throw new Error(`vaultContext: depositorBtcPubkey must be exactly ${i} bytes, got ${t.depositorBtcPubkey.length}`);const e=f(t.fundingOutpoints),r=new Uint8Array(v);let n=0;return a(r,n,i),n+=s,r.set(t.depositorBtcPubkey,n),n+=i,a(r,n,m),n+=s,r.set(e,n),r}const g="babylon-btc-vault",w=32,d=w*2,_=/^[0-9a-f]+$/;function T(t){return typeof t.deriveContextHash=="function"?{deriveContextHash:(e,r)=>t.deriveContextHash(e,r)}:{}}async function p(t,e){const r=E(e),n=l.uint8ArrayToHex(r),o=await t.deriveContextHash(g,n);if(typeof o!="string")throw new Error(`deriveVaultRoot: wallet must return a string, got ${typeof o}`);if(o.length!==d)throw new Error(`deriveVaultRoot: wallet must return a ${d}-character hex string (${w} bytes), got length ${o.length}`);if(!_.test(o))throw new Error("deriveVaultRoot: wallet must return lowercase hex per derive-context-hash.md §2.1; got value with non-lowercase or non-hex characters");return l.hexToUint8Array(o)}function C(t){if(!t)throw new Error("Pre-pegin transaction hex is empty");const e=t.startsWith("0x")?t.slice(2):t,r=y.Transaction.fromHex(e);if(r.ins.length===0)throw new Error("Pre-pegin transaction has no inputs");return r.ins.map(n=>({txid:Uint8Array.from(b.Buffer.from(n.hash).reverse()),vout:n.index}))}exports.VAULT_APP_NAME=g;exports.buildFundingOutpointsCommitment=f;exports.buildVaultContext=E;exports.deriveVaultRoot=p;exports.forwardDeriveContextHash=T;exports.parseFundingOutpointsFromTx=C;
|
|
2
|
-
//# sourceMappingURL=parseFundingOutpoints-CIO9Ok1L.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"parseFundingOutpoints-CIO9Ok1L.cjs","sources":["../src/tbv/core/vault-secrets/context.ts","../src/tbv/core/vault-secrets/deriveVaultRoot.ts","../src/tbv/core/vault-secrets/parseFundingOutpoints.ts"],"sourcesContent":["/**\n * Canonical `vaultContext` byte encoding per\n * `derive-vault-secrets.md` §2.3.\n *\n * ```\n * vaultContext :=\n * I2OSP(32, 4) || depositorBtcPubkey // 32B x-only\n * || I2OSP(32, 4) || fundingOutpointsCommitment // 32B SHA-256\n * ```\n *\n * `fundingOutpointsCommitment` is SHA-256 over the canonically-sorted\n * funding outpoints of the Pre-PegIn transaction, serialized as\n * `txid (32B display/RPC order) || vout (4B u32 big-endian)` per\n * outpoint. Sorting by 36-byte lex order makes the commitment\n * invariant under tx-level input reordering, so same-inputs RBF and\n * reorg rebroadcasts yield the same context.\n *\n * @module vault-secrets/context\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\n\nconst DEPOSITOR_PUBKEY_SIZE = 32;\nconst TXID_SIZE = 32;\nconst OUTPOINT_SIZE = 36;\nconst COMMITMENT_SIZE = 32;\nconst FIELD_LEN_PREFIX_SIZE = 4;\nconst VAULT_CONTEXT_SIZE =\n FIELD_LEN_PREFIX_SIZE +\n DEPOSITOR_PUBKEY_SIZE +\n FIELD_LEN_PREFIX_SIZE +\n COMMITMENT_SIZE;\n\nexport interface FundingOutpoint {\n /**\n * Bitcoin txid in **display / RPC order** (byte-reversed from the\n * internal little-endian wire form used when hashing a raw tx).\n */\n txid: Uint8Array;\n /** Output index within the referenced transaction (u32). */\n vout: number;\n}\n\nexport interface VaultContextInput {\n /** Depositor's x-only BTC public key (32 bytes). */\n depositorBtcPubkey: Uint8Array;\n /** Funding outpoints of the Pre-PegIn transaction. MUST be non-empty. */\n fundingOutpoints: readonly FundingOutpoint[];\n}\n\nfunction writeUint32BE(out: Uint8Array, offset: number, value: number): void {\n out[offset] = (value >>> 24) & 0xff;\n out[offset + 1] = (value >>> 16) & 0xff;\n out[offset + 2] = (value >>> 8) & 0xff;\n out[offset + 3] = value & 0xff;\n}\n\nfunction serializeOutpoint(outpoint: FundingOutpoint): Uint8Array {\n if (outpoint.txid.length !== TXID_SIZE) {\n throw new Error(\n `outpoint.txid must be exactly ${TXID_SIZE} bytes, got ${outpoint.txid.length}`,\n );\n }\n if (\n !Number.isInteger(outpoint.vout) ||\n outpoint.vout < 0 ||\n outpoint.vout > 0xffffffff\n ) {\n throw new Error(`outpoint.vout must be a u32, got ${outpoint.vout}`);\n }\n const out = new Uint8Array(OUTPOINT_SIZE);\n out.set(outpoint.txid, 0);\n writeUint32BE(out, TXID_SIZE, outpoint.vout);\n return out;\n}\n\nfunction compareBytes(a: Uint8Array, b: Uint8Array): number {\n const len = Math.min(a.length, b.length);\n for (let i = 0; i < len; i++) {\n if (a[i] !== b[i]) return a[i] - b[i];\n }\n return a.length - b.length;\n}\n\n/**\n * Compute SHA-256 over canonically-sorted funding outpoints.\n *\n * Outpoints are serialized as 36-byte `txid || vout_BE`, sorted\n * ascending lexicographically, concatenated, then hashed.\n *\n * @stability frozen — on-chain-binding. Any change to layout, sort\n * order, or serialization is a hard fork; existing deposits would no\n * longer match their committed `depositorWotsPkHash`.\n *\n * @throws If `outpoints` is empty or contains duplicates.\n */\nexport function buildFundingOutpointsCommitment(\n outpoints: readonly FundingOutpoint[],\n): Uint8Array {\n if (outpoints.length === 0) {\n throw new Error(\n \"buildFundingOutpointsCommitment: outpoints must be non-empty\",\n );\n }\n const serialized = outpoints.map(serializeOutpoint);\n serialized.sort(compareBytes);\n\n for (let i = 1; i < serialized.length; i++) {\n if (compareBytes(serialized[i - 1], serialized[i]) === 0) {\n throw new Error(\n \"buildFundingOutpointsCommitment: duplicate outpoint detected\",\n );\n }\n }\n\n const flat = new Uint8Array(serialized.length * OUTPOINT_SIZE);\n for (let i = 0; i < serialized.length; i++) {\n flat.set(serialized[i], i * OUTPOINT_SIZE);\n }\n return sha256(flat);\n}\n\n/**\n * Build the canonical `vaultContext` byte string fed into the wallet's\n * `deriveContextHash` (or a locally-implemented equivalent on the\n * app side).\n *\n * Output length is always 72 bytes.\n *\n * @stability frozen — on-chain-binding. The 72-byte layout is the\n * input to `deriveContextHash`; any change rotates the vault root and\n * therefore every WOTS key, hashlock secret, and auth anchor derived\n * from it. Existing deposits cannot be recovered after a layout change.\n */\nexport function buildVaultContext(input: VaultContextInput): Uint8Array {\n if (input.depositorBtcPubkey.length !== DEPOSITOR_PUBKEY_SIZE) {\n throw new Error(\n `vaultContext: depositorBtcPubkey must be exactly ${DEPOSITOR_PUBKEY_SIZE} bytes, got ${input.depositorBtcPubkey.length}`,\n );\n }\n const commitment = buildFundingOutpointsCommitment(input.fundingOutpoints);\n\n const out = new Uint8Array(VAULT_CONTEXT_SIZE);\n let offset = 0;\n\n writeUint32BE(out, offset, DEPOSITOR_PUBKEY_SIZE);\n offset += FIELD_LEN_PREFIX_SIZE;\n out.set(input.depositorBtcPubkey, offset);\n offset += DEPOSITOR_PUBKEY_SIZE;\n\n writeUint32BE(out, offset, COMMITMENT_SIZE);\n offset += FIELD_LEN_PREFIX_SIZE;\n out.set(commitment, offset);\n\n return out;\n}\n","/**\n * Vault-root derivation via the wallet's `deriveContextHash` API.\n *\n * Implements the canonical root source from `derive-vault-secrets.md`\n * §2.2:\n *\n * ```\n * rootDerivation = deriveContextHash(\"babylon-btc-vault\", hex(vaultContext))\n * ```\n *\n * The 32-byte output is fed directly into the {@link expandAuthAnchor},\n * {@link expandHashlockSecret}, and {@link expandWotsSeed} functions in\n * this module.\n *\n * @module vault-secrets/deriveVaultRoot\n */\n\nimport { hexToUint8Array, uint8ArrayToHex } from \"../primitives/utils/bitcoin\";\n\nimport { buildVaultContext, type VaultContextInput } from \"./context\";\n\n/**\n * The fixed `appName` passed to the wallet's `deriveContextHash` for\n * Babylon vault derivations. The wallet displays this in its approval\n * dialog. Defined by `derive-vault-secrets.md` §2.2 — must not be\n * changed without coordinating a spec revision and a downstream\n * migration plan, as it provides app-level domain separation across\n * applications using the same wallet.\n */\nexport const VAULT_APP_NAME = \"babylon-btc-vault\";\n\n/** Expected length of the wallet output in bytes per spec §2.1. */\nconst ROOT_OUTPUT_BYTES = 32;\n\n/** Expected length of the wallet output in lowercase hex chars. */\nconst ROOT_OUTPUT_HEX_LEN = ROOT_OUTPUT_BYTES * 2;\n\nconst LOWERCASE_HEX_RE = /^[0-9a-f]+$/;\n\n/**\n * Minimal structural shape for the wallet capability needed by this\n * helper. Typed against the method directly so callers can pass any\n * value that implements `deriveContextHash` — `BitcoinWallet` from\n * this SDK, `IBTCProvider` from `@babylonlabs-io/wallet-connector`,\n * or a test mock — without depending on the rest of either interface.\n */\nexport interface DeriveContextHashCapableWallet {\n deriveContextHash(appName: string, context: string): Promise<string>;\n}\n\n/** Forward the deriveContextHash capability only when the wallet actually has it,\n * so seam guards (ensurePrePeginTermsApproval) can fire their typed error instead\n * of a mid-ceremony TypeError. */\nexport function forwardDeriveContextHash(\n wallet: Partial<DeriveContextHashCapableWallet>,\n): Partial<DeriveContextHashCapableWallet> {\n return typeof wallet.deriveContextHash === \"function\"\n ? {\n deriveContextHash: (appName, context) =>\n wallet.deriveContextHash!(appName, context),\n }\n : {};\n}\n\n/**\n * Derive the 32-byte vault root from a wallet by encoding the\n * canonical {@link VaultContextInput} and forwarding to\n * `wallet.deriveContextHash`.\n *\n * Validates the wallet's output strictly: must be exactly 64\n * lowercase hex characters per `derive-context-hash.md` §2.1. A\n * conformant wallet always satisfies this, but we re-check at the\n * SDK boundary so a non-conformant wallet (or a wallet returning a\n * malformed value through a buggy adapter) fails loud here rather\n * than producing silently-wrong derived secrets downstream.\n *\n * The helper itself produces only valid spec inputs (`appName` is\n * the hardcoded `VAULT_APP_NAME`; `context` is hex of the 72-byte\n * `vaultContext`, always 144 chars lowercase), so input-side\n * validation is unnecessary.\n *\n * @param wallet - Any value implementing `deriveContextHash`.\n * @param input - The canonical {@link VaultContextInput} that\n * uniquely identifies the vault. Encoded by\n * {@link buildVaultContext} into a 72-byte structure\n * before being hex-encoded for the wallet.\n * @stability frozen — on-chain-binding. The pair (`VAULT_APP_NAME`,\n * `vaultContext` encoding) is the wallet's input space; changing\n * either rotates the root and invalidates every secret derived from\n * it. `VAULT_APP_NAME` is fixed by `derive-vault-secrets.md` §2.2\n * and must never change without a coordinated spec revision.\n *\n * @returns 32-byte root suitable for {@link expandAuthAnchor},\n * {@link expandHashlockSecret}, {@link expandWotsSeed}.\n * @throws If the wallet returns a non-64-char or non-lowercase-hex\n * string. Errors from the wallet (user rejection,\n * method-not-supported, etc.) propagate unchanged.\n */\nexport async function deriveVaultRoot(\n wallet: DeriveContextHashCapableWallet,\n input: VaultContextInput,\n): Promise<Uint8Array> {\n const vaultContext = buildVaultContext(input);\n const contextHex = uint8ArrayToHex(vaultContext);\n\n const rootHex = await wallet.deriveContextHash(VAULT_APP_NAME, contextHex);\n\n if (typeof rootHex !== \"string\") {\n throw new Error(\n `deriveVaultRoot: wallet must return a string, got ${typeof rootHex}`,\n );\n }\n if (rootHex.length !== ROOT_OUTPUT_HEX_LEN) {\n throw new Error(\n `deriveVaultRoot: wallet must return a ${ROOT_OUTPUT_HEX_LEN}-character hex string (${ROOT_OUTPUT_BYTES} bytes), got length ${rootHex.length}`,\n );\n }\n if (!LOWERCASE_HEX_RE.test(rootHex)) {\n throw new Error(\n \"deriveVaultRoot: wallet must return lowercase hex per derive-context-hash.md §2.1; got value with non-lowercase or non-hex characters\",\n );\n }\n\n return hexToUint8Array(rootHex);\n}\n","/**\n * Parse a Pre-PegIn transaction's inputs into the vault-context\n * `fundingOutpoints` shape consumed by `deriveVaultRoot`. Reverses\n * the prev-txid bytes from wire-internal little-endian to display\n * order so the derivation is byte-for-byte identical to the\n * deposit-time computation.\n *\n * @module vault-secrets/parseFundingOutpoints\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport type { FundingOutpoint } from \"./context\";\n\nexport function parseFundingOutpointsFromTx(\n unsignedTxHex: string,\n): FundingOutpoint[] {\n if (!unsignedTxHex) {\n throw new Error(\"Pre-pegin transaction hex is empty\");\n }\n const cleanHex = unsignedTxHex.startsWith(\"0x\")\n ? unsignedTxHex.slice(2)\n : unsignedTxHex;\n const tx = Transaction.fromHex(cleanHex);\n if (tx.ins.length === 0) {\n throw new Error(\"Pre-pegin transaction has no inputs\");\n }\n return tx.ins.map((input) => ({\n txid: Uint8Array.from(Buffer.from(input.hash).reverse()),\n vout: input.index,\n }));\n}\n"],"names":["DEPOSITOR_PUBKEY_SIZE","TXID_SIZE","OUTPOINT_SIZE","COMMITMENT_SIZE","FIELD_LEN_PREFIX_SIZE","VAULT_CONTEXT_SIZE","writeUint32BE","out","offset","value","serializeOutpoint","outpoint","compareBytes","a","b","len","i","buildFundingOutpointsCommitment","outpoints","serialized","flat","sha256","buildVaultContext","input","commitment","VAULT_APP_NAME","ROOT_OUTPUT_BYTES","ROOT_OUTPUT_HEX_LEN","LOWERCASE_HEX_RE","forwardDeriveContextHash","wallet","appName","context","deriveVaultRoot","vaultContext","contextHex","uint8ArrayToHex","rootHex","hexToUint8Array","parseFundingOutpointsFromTx","unsignedTxHex","cleanHex","tx","Transaction","Buffer"],"mappings":"uIAsBMA,EAAwB,GACxBC,EAAY,GACZC,EAAgB,GAChBC,EAAkB,GAClBC,EAAwB,EACxBC,EACJD,EACAJ,EACAI,EACAD,EAmBF,SAASG,EAAcC,EAAiBC,EAAgBC,EAAqB,CAC3EF,EAAIC,CAAM,EAAKC,IAAU,GAAM,IAC/BF,EAAIC,EAAS,CAAC,EAAKC,IAAU,GAAM,IACnCF,EAAIC,EAAS,CAAC,EAAKC,IAAU,EAAK,IAClCF,EAAIC,EAAS,CAAC,EAAIC,EAAQ,GAC5B,CAEA,SAASC,EAAkBC,EAAuC,CAChE,GAAIA,EAAS,KAAK,SAAWV,EAC3B,MAAM,IAAI,MACR,iCAAiCA,CAAS,eAAeU,EAAS,KAAK,MAAM,EA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KnB,IAAW,CAC5B,KAAM,WAAW,KAAKqB,EAAAA,OAAO,KAAKrB,EAAM,IAAI,EAAE,SAAS,EACvD,KAAMA,EAAM,KAAA,EACZ,CACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"parseFundingOutpoints-CO-f6IHK.js","sources":["../src/tbv/core/vault-secrets/context.ts","../src/tbv/core/vault-secrets/deriveVaultRoot.ts","../src/tbv/core/vault-secrets/parseFundingOutpoints.ts"],"sourcesContent":["/**\n * Canonical `vaultContext` byte encoding per\n * `derive-vault-secrets.md` §2.3.\n *\n * ```\n * vaultContext :=\n * I2OSP(32, 4) || depositorBtcPubkey // 32B x-only\n * || I2OSP(32, 4) || fundingOutpointsCommitment // 32B SHA-256\n * ```\n *\n * `fundingOutpointsCommitment` is SHA-256 over the canonically-sorted\n * funding outpoints of the Pre-PegIn transaction, serialized as\n * `txid (32B display/RPC order) || vout (4B u32 big-endian)` per\n * outpoint. Sorting by 36-byte lex order makes the commitment\n * invariant under tx-level input reordering, so same-inputs RBF and\n * reorg rebroadcasts yield the same context.\n *\n * @module vault-secrets/context\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\n\nconst DEPOSITOR_PUBKEY_SIZE = 32;\nconst TXID_SIZE = 32;\nconst OUTPOINT_SIZE = 36;\nconst COMMITMENT_SIZE = 32;\nconst FIELD_LEN_PREFIX_SIZE = 4;\nconst VAULT_CONTEXT_SIZE =\n FIELD_LEN_PREFIX_SIZE +\n DEPOSITOR_PUBKEY_SIZE +\n FIELD_LEN_PREFIX_SIZE +\n COMMITMENT_SIZE;\n\nexport interface FundingOutpoint {\n /**\n * Bitcoin txid in **display / RPC order** (byte-reversed from the\n * internal little-endian wire form used when hashing a raw tx).\n */\n txid: Uint8Array;\n /** Output index within the referenced transaction (u32). */\n vout: number;\n}\n\nexport interface VaultContextInput {\n /** Depositor's x-only BTC public key (32 bytes). */\n depositorBtcPubkey: Uint8Array;\n /** Funding outpoints of the Pre-PegIn transaction. MUST be non-empty. */\n fundingOutpoints: readonly FundingOutpoint[];\n}\n\nfunction writeUint32BE(out: Uint8Array, offset: number, value: number): void {\n out[offset] = (value >>> 24) & 0xff;\n out[offset + 1] = (value >>> 16) & 0xff;\n out[offset + 2] = (value >>> 8) & 0xff;\n out[offset + 3] = value & 0xff;\n}\n\nfunction serializeOutpoint(outpoint: FundingOutpoint): Uint8Array {\n if (outpoint.txid.length !== TXID_SIZE) {\n throw new Error(\n `outpoint.txid must be exactly ${TXID_SIZE} bytes, got ${outpoint.txid.length}`,\n );\n }\n if (\n !Number.isInteger(outpoint.vout) ||\n outpoint.vout < 0 ||\n outpoint.vout > 0xffffffff\n ) {\n throw new Error(`outpoint.vout must be a u32, got ${outpoint.vout}`);\n }\n const out = new Uint8Array(OUTPOINT_SIZE);\n out.set(outpoint.txid, 0);\n writeUint32BE(out, TXID_SIZE, outpoint.vout);\n return out;\n}\n\nfunction compareBytes(a: Uint8Array, b: Uint8Array): number {\n const len = Math.min(a.length, b.length);\n for (let i = 0; i < len; i++) {\n if (a[i] !== b[i]) return a[i] - b[i];\n }\n return a.length - b.length;\n}\n\n/**\n * Compute SHA-256 over canonically-sorted funding outpoints.\n *\n * Outpoints are serialized as 36-byte `txid || vout_BE`, sorted\n * ascending lexicographically, concatenated, then hashed.\n *\n * @stability frozen — on-chain-binding. Any change to layout, sort\n * order, or serialization is a hard fork; existing deposits would no\n * longer match their committed `depositorWotsPkHash`.\n *\n * @throws If `outpoints` is empty or contains duplicates.\n */\nexport function buildFundingOutpointsCommitment(\n outpoints: readonly FundingOutpoint[],\n): Uint8Array {\n if (outpoints.length === 0) {\n throw new Error(\n \"buildFundingOutpointsCommitment: outpoints must be non-empty\",\n );\n }\n const serialized = outpoints.map(serializeOutpoint);\n serialized.sort(compareBytes);\n\n for (let i = 1; i < serialized.length; i++) {\n if (compareBytes(serialized[i - 1], serialized[i]) === 0) {\n throw new Error(\n \"buildFundingOutpointsCommitment: duplicate outpoint detected\",\n );\n }\n }\n\n const flat = new Uint8Array(serialized.length * OUTPOINT_SIZE);\n for (let i = 0; i < serialized.length; i++) {\n flat.set(serialized[i], i * OUTPOINT_SIZE);\n }\n return sha256(flat);\n}\n\n/**\n * Build the canonical `vaultContext` byte string fed into the wallet's\n * `deriveContextHash` (or a locally-implemented equivalent on the\n * app side).\n *\n * Output length is always 72 bytes.\n *\n * @stability frozen — on-chain-binding. The 72-byte layout is the\n * input to `deriveContextHash`; any change rotates the vault root and\n * therefore every WOTS key, hashlock secret, and auth anchor derived\n * from it. Existing deposits cannot be recovered after a layout change.\n */\nexport function buildVaultContext(input: VaultContextInput): Uint8Array {\n if (input.depositorBtcPubkey.length !== DEPOSITOR_PUBKEY_SIZE) {\n throw new Error(\n `vaultContext: depositorBtcPubkey must be exactly ${DEPOSITOR_PUBKEY_SIZE} bytes, got ${input.depositorBtcPubkey.length}`,\n );\n }\n const commitment = buildFundingOutpointsCommitment(input.fundingOutpoints);\n\n const out = new Uint8Array(VAULT_CONTEXT_SIZE);\n let offset = 0;\n\n writeUint32BE(out, offset, DEPOSITOR_PUBKEY_SIZE);\n offset += FIELD_LEN_PREFIX_SIZE;\n out.set(input.depositorBtcPubkey, offset);\n offset += DEPOSITOR_PUBKEY_SIZE;\n\n writeUint32BE(out, offset, COMMITMENT_SIZE);\n offset += FIELD_LEN_PREFIX_SIZE;\n out.set(commitment, offset);\n\n return out;\n}\n","/**\n * Vault-root derivation via the wallet's `deriveContextHash` API.\n *\n * Implements the canonical root source from `derive-vault-secrets.md`\n * §2.2:\n *\n * ```\n * rootDerivation = deriveContextHash(\"babylon-btc-vault\", hex(vaultContext))\n * ```\n *\n * The 32-byte output is fed directly into the {@link expandAuthAnchor},\n * {@link expandHashlockSecret}, and {@link expandWotsSeed} functions in\n * this module.\n *\n * @module vault-secrets/deriveVaultRoot\n */\n\nimport { hexToUint8Array, uint8ArrayToHex } from \"../primitives/utils/bitcoin\";\n\nimport { buildVaultContext, type VaultContextInput } from \"./context\";\n\n/**\n * The fixed `appName` passed to the wallet's `deriveContextHash` for\n * Babylon vault derivations. The wallet displays this in its approval\n * dialog. Defined by `derive-vault-secrets.md` §2.2 — must not be\n * changed without coordinating a spec revision and a downstream\n * migration plan, as it provides app-level domain separation across\n * applications using the same wallet.\n */\nexport const VAULT_APP_NAME = \"babylon-btc-vault\";\n\n/** Expected length of the wallet output in bytes per spec §2.1. */\nconst ROOT_OUTPUT_BYTES = 32;\n\n/** Expected length of the wallet output in lowercase hex chars. */\nconst ROOT_OUTPUT_HEX_LEN = ROOT_OUTPUT_BYTES * 2;\n\nconst LOWERCASE_HEX_RE = /^[0-9a-f]+$/;\n\n/**\n * Minimal structural shape for the wallet capability needed by this\n * helper. Typed against the method directly so callers can pass any\n * value that implements `deriveContextHash` — `BitcoinWallet` from\n * this SDK, `IBTCProvider` from `@babylonlabs-io/wallet-connector`,\n * or a test mock — without depending on the rest of either interface.\n */\nexport interface DeriveContextHashCapableWallet {\n deriveContextHash(appName: string, context: string): Promise<string>;\n}\n\n/** Forward the deriveContextHash capability only when the wallet actually has it,\n * so seam guards (ensurePrePeginTermsApproval) can fire their typed error instead\n * of a mid-ceremony TypeError. */\nexport function forwardDeriveContextHash(\n wallet: Partial<DeriveContextHashCapableWallet>,\n): Partial<DeriveContextHashCapableWallet> {\n return typeof wallet.deriveContextHash === \"function\"\n ? {\n deriveContextHash: (appName, context) =>\n wallet.deriveContextHash!(appName, context),\n }\n : {};\n}\n\n/**\n * Derive the 32-byte vault root from a wallet by encoding the\n * canonical {@link VaultContextInput} and forwarding to\n * `wallet.deriveContextHash`.\n *\n * Validates the wallet's output strictly: must be exactly 64\n * lowercase hex characters per `derive-context-hash.md` §2.1. A\n * conformant wallet always satisfies this, but we re-check at the\n * SDK boundary so a non-conformant wallet (or a wallet returning a\n * malformed value through a buggy adapter) fails loud here rather\n * than producing silently-wrong derived secrets downstream.\n *\n * The helper itself produces only valid spec inputs (`appName` is\n * the hardcoded `VAULT_APP_NAME`; `context` is hex of the 72-byte\n * `vaultContext`, always 144 chars lowercase), so input-side\n * validation is unnecessary.\n *\n * @param wallet - Any value implementing `deriveContextHash`.\n * @param input - The canonical {@link VaultContextInput} that\n * uniquely identifies the vault. Encoded by\n * {@link buildVaultContext} into a 72-byte structure\n * before being hex-encoded for the wallet.\n * @stability frozen — on-chain-binding. The pair (`VAULT_APP_NAME`,\n * `vaultContext` encoding) is the wallet's input space; changing\n * either rotates the root and invalidates every secret derived from\n * it. `VAULT_APP_NAME` is fixed by `derive-vault-secrets.md` §2.2\n * and must never change without a coordinated spec revision.\n *\n * @returns 32-byte root suitable for {@link expandAuthAnchor},\n * {@link expandHashlockSecret}, {@link expandWotsSeed}.\n * @throws If the wallet returns a non-64-char or non-lowercase-hex\n * string. Errors from the wallet (user rejection,\n * method-not-supported, etc.) propagate unchanged.\n */\nexport async function deriveVaultRoot(\n wallet: DeriveContextHashCapableWallet,\n input: VaultContextInput,\n): Promise<Uint8Array> {\n const vaultContext = buildVaultContext(input);\n const contextHex = uint8ArrayToHex(vaultContext);\n\n const rootHex = await wallet.deriveContextHash(VAULT_APP_NAME, contextHex);\n\n if (typeof rootHex !== \"string\") {\n throw new Error(\n `deriveVaultRoot: wallet must return a string, got ${typeof rootHex}`,\n );\n }\n if (rootHex.length !== ROOT_OUTPUT_HEX_LEN) {\n throw new Error(\n `deriveVaultRoot: wallet must return a ${ROOT_OUTPUT_HEX_LEN}-character hex string (${ROOT_OUTPUT_BYTES} bytes), got length ${rootHex.length}`,\n );\n }\n if (!LOWERCASE_HEX_RE.test(rootHex)) {\n throw new Error(\n \"deriveVaultRoot: wallet must return lowercase hex per derive-context-hash.md §2.1; got value with non-lowercase or non-hex characters\",\n );\n }\n\n return hexToUint8Array(rootHex);\n}\n","/**\n * Parse a Pre-PegIn transaction's inputs into the vault-context\n * `fundingOutpoints` shape consumed by `deriveVaultRoot`. Reverses\n * the prev-txid bytes from wire-internal little-endian to display\n * order so the derivation is byte-for-byte identical to the\n * deposit-time computation.\n *\n * @module vault-secrets/parseFundingOutpoints\n */\n\nimport { Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\n\nimport type { FundingOutpoint } from \"./context\";\n\nexport function parseFundingOutpointsFromTx(\n unsignedTxHex: string,\n): FundingOutpoint[] {\n if (!unsignedTxHex) {\n throw new Error(\"Pre-pegin transaction hex is empty\");\n }\n const cleanHex = unsignedTxHex.startsWith(\"0x\")\n ? unsignedTxHex.slice(2)\n : unsignedTxHex;\n const tx = Transaction.fromHex(cleanHex);\n if (tx.ins.length === 0) {\n throw new Error(\"Pre-pegin transaction has no inputs\");\n }\n return tx.ins.map((input) => ({\n txid: Uint8Array.from(Buffer.from(input.hash).reverse()),\n vout: input.index,\n }));\n}\n"],"names":["DEPOSITOR_PUBKEY_SIZE","TXID_SIZE","OUTPOINT_SIZE","COMMITMENT_SIZE","FIELD_LEN_PREFIX_SIZE","VAULT_CONTEXT_SIZE","writeUint32BE","out","offset","value","serializeOutpoint","outpoint","compareBytes","a","b","len","i","buildFundingOutpointsCommitment","outpoints","serialized","flat","sha256","buildVaultContext","input","commitment","VAULT_APP_NAME","ROOT_OUTPUT_BYTES","ROOT_OUTPUT_HEX_LEN","LOWERCASE_HEX_RE","forwardDeriveContextHash","wallet","appName","context","deriveVaultRoot","vaultContext","contextHex","uint8ArrayToHex","rootHex","hexToUint8Array","parseFundingOutpointsFromTx","unsignedTxHex","cleanHex","tx","Transaction","Buffer"],"mappings":";;;;AAsBA,MAAMA,IAAwB,IACxBC,IAAY,IACZC,IAAgB,IAChBC,IAAkB,IAClBC,IAAwB,GACxBC,IACJD,IACAJ,IACAI,IACAD;AAmBF,SAASG,EAAcC,GAAiBC,GAAgBC,GAAqB;AAC3E,EAAAF,EAAIC,CAAM,IAAKC,MAAU,KAAM,KAC/BF,EAAIC,IAAS,CAAC,IAAKC,MAAU,KAAM,KACnCF,EAAIC,IAAS,CAAC,IAAKC,MAAU,IAAK,KAClCF,EAAIC,IAAS,CAAC,IAAIC,IAA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M,oCAAoC;AAEtD,QAAMC,IAAWD,EAAc,WAAW,IAAI,IAC1CA,EAAc,MAAM,CAAC,IACrBA,GACEE,IAAKC,EAAY,QAAQF,CAAQ;AACvC,MAAIC,EAAG,IAAI,WAAW;AACpB,UAAM,IAAI,MAAM,qCAAqC;AAEvD,SAAOA,EAAG,IAAI,IAAI,CAACnB,OAAW;AAAA,IAC5B,MAAM,WAAW,KAAKqB,EAAO,KAAKrB,EAAM,IAAI,EAAE,SAAS;AAAA,IACvD,MAAMA,EAAM;AAAA,EAAA,EACZ;AACJ;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var H=Object.defineProperty;var B=(t,e,r)=>e in t?H(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var b=(t,e,r)=>B(t,typeof e!="symbol"?e+"":e,r);const E=require("bitcoinjs-lib"),p=require("./bitcoin-m84N5a8o.cjs"),A=require("./sha2-DsrLC4NM.cjs");require("@babylonlabs-io/babylon-tbv-rust-wasm");const u=require("./verifyScriptPathSchnorrSignature-D-ppKNjT.cjs"),y=require("./constants-BCdDRd_Y.cjs"),d=require("./signing-Bnsro0hE.cjs");function O(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const o=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,o.get?o:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const v=O(E),k=106,S=32,P=34;function R(t,e,r){const o=p.stripHexPrefix(t),s=v.Transaction.fromHex(o);if(s.outs.length<=e)throw new Error(`Pre-PegIn auth-anchor OP_RETURN missing: tx has ${s.outs.length} outputs, expected at least ${e+1} (vault outputs + OP_RETURN)`);const c=s.outs[e],i=c.script;if(i.length!==P||i[0]!==k||i[1]!==S)throw new Error(`Pre-PegIn auth-anchor OP_RETURN at vout ${e} has unexpected script encoding (got ${i.length}-byte script with prefix 0x${i.slice(0,Math.min(2,i.length)).toString("hex")}; expected ${P}-byte OP_RETURN + PUSH32 layout)`);const l=i.slice(2).toString("hex").toLowerCase();if(l!==r.toLowerCase())throw new Error(`Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${e}: tx pushes ${l}, expected ${r}`);if(c.value!==0)throw new Error(`Pre-PegIn auth-anchor OP_RETURN at vout ${e} has non-zero value ${c.value}; OP_RETURN outputs must be 0-value`)}function C(t){let e;try{e=v.Transaction.fromHex(p.stripHexPrefix(t))}catch{return}const r=[];for(let o=0;o<e.outs.length;o++){const s=e.outs[o],c=s.script;c.length===P&&c[0]===k&&c[1]===S&&s.value===0&&r.push({vout:o,hash:c.slice(2).toString("hex").toLowerCase()})}return r.length===1?r[0]:void 0}const f=66;function T(t){if(!t.startsWith("0x")&&!t.startsWith("0X"))throw new Error("Expected 0x-prefixed hex string");const e=t.slice(2);if(e.length%2!==0)throw new Error(`Hex string has odd length: ${e.length}`);if(!/^[0-9a-fA-F]*$/.test(e))throw new Error("Hex string contains non-hex characters");const r=new Uint8Array(e.length/2);for(let o=0;o<r.length;o++)r[o]=parseInt(e.slice(o*2,o*2+2),16);return r}function _(t){return`0x${Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}`}function h(t,e){if(t.length!==f)throw new Error(`${e} must be exactly 32 bytes (${f} hex chars with 0x prefix), got ${t.length}`)}function m(t){h(t,"Secret");const e=T(t),r=A.sha256(e);return _(r)}function N(t,e){return h(t,"Secret"),h(e,"Hashlock"),T(e),m(t).toLowerCase()===e.toLowerCase()}function w(t){return typeof t.approveDepositTerms=="function"}async function $(t){const e=t;if(typeof e.getChangeAddress!="function")throw new Error("Approval wallet does not implement getChangeAddress; it must expose its change branch, because the signing device accepts Pre-PegIn change only there.");return e.getChangeAddress()}function D(t){if(!w(t))return{};const e=t.holdsApprovedDepositTerms,r=t.validateDepositTerms,o=t.getChangeAddress;return{approveDepositTerms:s=>t.approveDepositTerms(s),...typeof o=="function"?{getChangeAddress:()=>o.call(t)}:{},...typeof e=="function"?{holdsApprovedDepositTerms:s=>e.call(t,s)}:{},...typeof r=="function"?{validateDepositTerms:s=>r.call(t,s)}:{}}}const x=0;class U{constructor(e){b(this,"config");this.config=e}async signPayoutTransaction(e){const r=await this.config.btcWallet.getPublicKeyHex(),{depositorPubkey:o}=p.validateWalletPubkey(r,e.depositorBtcPubkey),s=await u.buildPayoutPsbt({vaultCoreVersion:e.vaultCoreVersion,payoutTxHex:e.payoutTxHex,peginTxHex:e.peginTxHex,assertTxHex:e.assertTxHex,depositorBtcPubkey:o,vaultProviderBtcPubkey:e.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:e.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:e.universalChallengerBtcPubkeys,timelockPegin:e.timelockPegin,timelockAssert:e.timelockAssert,network:this.config.network,claimerBtcPubkey:e.claimerBtcPubkey,registeredPayoutScriptPubKey:e.registeredPayoutScriptPubKey,commissionBps:e.commissionBps,protocolFeeRate:e.protocolFeeRate,councilMembers:e.councilMembers,councilQuorum:e.councilQuorum,vkClaimerPayoutScriptPubKeys:e.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:e.vpCommissionScriptPubKey}),c=await this.config.btcWallet.signPsbt(s.psbtHex,d.createTaprootScriptPathSignOptions(r,y.DEPOSITOR_SIGNED_INPUT_COUNT));u.assertPsbtUnsignedTxMatches({requestedPsbtHex:s.psbtHex,returnedPsbtHex:c});const i=u.extractPayoutSignature(c,o);return u.assertScriptPathSchnorrSignature({requestedPsbtHex:s.psbtHex,signatureHex:i,signerXOnlyPubkeyHex:o,inputIndex:x}),{signature:i,depositorBtcPubkey:o}}getNetwork(){return this.config.network}supportsBatchSigning(){return typeof this.config.btcWallet.signPsbts=="function"}async signPayoutTransactionsBatch(e){if(!this.supportsBatchSigning())throw new Error("Wallet does not support batch signing (signPsbts method not available)");const r=await this.config.btcWallet.getPublicKeyHex(),o=[],s=[],c=[];for(const n of e){const{depositorPubkey:a}=p.validateWalletPubkey(r,n.depositorBtcPubkey);c.push(a);const g=await u.buildPayoutPsbt({vaultCoreVersion:n.vaultCoreVersion,payoutTxHex:n.payoutTxHex,peginTxHex:n.peginTxHex,assertTxHex:n.assertTxHex,depositorBtcPubkey:a,vaultProviderBtcPubkey:n.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:n.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:n.universalChallengerBtcPubkeys,timelockPegin:n.timelockPegin,timelockAssert:n.timelockAssert,network:this.config.network,claimerBtcPubkey:n.claimerBtcPubkey,registeredPayoutScriptPubKey:n.registeredPayoutScriptPubKey,commissionBps:n.commissionBps,protocolFeeRate:n.protocolFeeRate,councilMembers:n.councilMembers,councilQuorum:n.councilQuorum,vkClaimerPayoutScriptPubKeys:n.vkClaimerPayoutScriptPubKeys,vpCommissionScriptPubKey:n.vpCommissionScriptPubKey});o.push(g.psbtHex),s.push(d.createTaprootScriptPathSignOptions(r,y.DEPOSITOR_SIGNED_INPUT_COUNT))}const i=await this.config.btcWallet.signPsbts(o,s);if(i.length!==e.length)throw new Error(`Expected ${e.length} signed PSBTs but received ${i.length}`);const l=[];for(let n=0;n<e.length;n++){const a=c[n];u.assertPsbtUnsignedTxMatches({requestedPsbtHex:o[n],returnedPsbtHex:i[n]});const g=u.extractPayoutSignature(i[n],a);u.assertScriptPathSchnorrSignature({requestedPsbtHex:o[n],signatureHex:g,signerXOnlyPubkeyHex:a,inputIndex:x}),l.push({payoutSignature:g,depositorBtcPubkey:a})}return l}}async function I(t,e,r){if(e.length===1)return[await t.signPsbt(e[0],r==null?void 0:r[0])];if(typeof t.signPsbts=="function"){const s=await t.signPsbts(e,r);if(s.length!==e.length)throw new Error(`Expected ${e.length} signed PSBTs but received ${s.length}`);return s}const o=[];for(let s=0;s<e.length;s++)o.push(await t.signPsbt(e[s],r==null?void 0:r[s]));return o}exports.PayoutManager=U;exports.assertAuthAnchorOpReturn=R;exports.computeHashlock=m;exports.findAuthAnchorOpReturn=C;exports.forwardDepositApproval=D;exports.requireChangeAddress=$;exports.signPsbtsWithFallback=I;exports.supportsDepositApproval=w;exports.validateSecretAgainstHashlock=N;
|
|
2
|
-
//# sourceMappingURL=signPsbtsWithFallback-Bo1PJX90.cjs.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var te=Object.defineProperty;var re=(e,t,r)=>t in e?te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var K=(e,t,r)=>re(e,typeof t!="symbol"?t+"":t,r);const ne=require("./sha2-DsrLC4NM.cjs"),S=require("./signPsbtsWithFallback-Bo1PJX90.cjs"),q=require("./PeginManager-CvI99Uhd.cjs"),p=require("./bitcoin-m84N5a8o.cjs"),f=require("@babylonlabs-io/babylon-tbv-rust-wasm"),N=require("./parseFundingOutpoints-CIO9Ok1L.cjs"),U=require("bitcoinjs-lib"),H=require("./verifyScriptPathSchnorrSignature-D-ppKNjT.cjs"),z=require("./fundPeginTransaction-BLD8FRL9.cjs"),j=require("./waitForTransactionReceiptSmartAware-Ct7LPwPI.cjs"),M="DepositTermsRejectedError";class L extends Error{constructor(r,n="device-envelope"){super(r);K(this,"reason");this.name=M,this.reason=n}}function oe(e){if(e instanceof L)return!0;if(typeof e!="object"||e===null)return!1;const t=e;return t.name===M&&t.reason==="device-envelope"}async function W(e){const t=e.siblings.length;if(t===0)throw new Error("rebuildDepositTermsCore: at least one sibling is required");for(const[o,b]of e.siblings.entries())if(b.amount<=0n)throw new Error(`rebuildDepositTermsCore: sibling[${o}] has non-positive on-chain pegin amount ${b.amount}; the chain-read vault record is invalid. Resume refused.`);if(e.prepeginMaxFee<=0n)throw new Error(`rebuildDepositTermsCore: prepeginMaxFee must be > 0, got ${e.prepeginMaxFee}`);const r=p.stripHexPrefix(e.prepeginTxid).toLowerCase(),n=p.stripHexPrefix(j.calculateBtcTxHash(e.fundedPrePeginTxHex)).toLowerCase();if(n!==r)throw new Error(`Funded Pre-PegIn tx hashes to ${n}, expected ${r} (on-chain prepeginTxid). Resume refused.`);const h=S.findAuthAnchorOpReturn(p.stripHexPrefix(e.fundedPrePeginTxHex));if(h===void 0)throw new Error("Funded Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN commitment — it either predates auth anchoring or is malformed. The intent resume path requires the anchor to prove sibling completeness. Resume refused.");if(h.vout!==t)throw new Error(`Auth-anchor OP_RETURN at vout ${h.vout} does not match the discovered sibling count ${t}; the discovered sibling set does not cover this transaction's HTLC outputs (a lagging index can cause this — retry later). Resume refused.`);const c=e.vaultKeeperBtcPubkeys.length,u=e.universalChallengerBtcPubkeys.length,l=await f.computeMinClaimValue(e.vaultCoreVersion,c,u,e.councilQuorum,e.councilSize,e.protocolFeeRate),a=await f.computeMinPeginFee(e.vaultCoreVersion,c,u,e.minPeginFeeRate),d=await f.peginP2aAnchorOutput(e.vaultCoreVersion),s=(d==null?void 0:d.value)??0n;if(l<=0n)throw new Error(`WASM returned non-positive depositorClaimValue ${l}; expected > 0. Resume refused.`);if(a<=0n)throw new Error(`WASM returned non-positive peginMaxFee ${a}; expected > 0. Resume refused.`);if(s<0n)throw new Error(`WASM returned negative P2A anchor value ${s}. Resume refused.`);const i=a+s,v=e.minPeginFeeRate*z.MAX_REASONABLE_PEGIN_VBYTES;if(i<=0n||i>v)throw new Error(`WASM implied PegIn reserve ${i} sat is outside (0, ${v}] (minPeginFeeRate=${e.minPeginFeeRate} × ${z.MAX_REASONABLE_PEGIN_VBYTES} vbytes). Resume refused.`);const w=e.siblings.map(o=>o.amount+l+a+s),E=await Promise.all(e.siblings.map(async o=>(await f.getPrePeginHtlcConnectorInfo({txGraphVersion:e.vaultCoreVersion,depositorPubkey:e.depositorBtcPubkey,vaultProviderPubkey:e.vaultProviderBtcPubkey,vaultKeeperPubkeys:[...e.vaultKeeperBtcPubkeys],universalChallengerPubkeys:[...e.universalChallengerBtcPubkeys],hashlock:p.stripHexPrefix(o.hashlock),timelockRefund:e.timelockRefund,network:e.network})).scriptPubKey)),x=U.Transaction.fromHex(p.stripHexPrefix(e.fundedPrePeginTxHex)).outs.map(o=>({value:o.value,script:o.script}));return H.assertEncodedHtlcOutputsMatch(x,w,E),q.buildDepositTerms({vaultCoreVersion:e.vaultCoreVersion,protocolFeeRate:e.protocolFeeRate,timelockPegin:e.timelockPegin,timelockAssert:e.timelockAssert,timelockRefund:e.timelockRefund,prepeginTxid:e.prepeginTxid,prepeginMaxFee:e.prepeginMaxFee,vaultProviderBtcPubkey:e.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:e.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:e.universalChallengerBtcPubkeys,maxAcceptableCommissionBps:e.maxAcceptableCommissionBps,peginAmounts:e.siblings.map(o=>o.amount),depositorClaimValue:l,peginMaxFee:a})}function se(e){const t=(e instanceof Error?e.message:typeof e=="string"?e:"").toLowerCase();return t.includes("wots")&&t.includes("hash")&&t.includes("does not match")}class Q extends Error{constructor(t,r){super(`Re-derived vault root does not match this Pre-PegIn: derived auth-anchor hash ${t}, transaction commits to ${r}. Connect the same wallet, on the same account and the same network, that created the deposit.`),this.derivedAuthAnchorHash=t,this.onChainAuthAnchorHash=r,this.name="VaultRootMismatchError"}}class A extends Error{constructor(t){super(t),this.name="UnanchoredPrePeginError"}}class X extends Error{constructor(t,r,n=[]){super(`No candidate parameter set reproduces this Pre-PegIn's HTLC outputs (${t} candidate(s) tried). `+(n.length>0?`${n.length} version(s) could not be resolved and may hold the answer: ${n.join(" | ")}. `:"")+`Sample rejections: ${r.join(" | ")}`),this.candidatesTried=t,this.sampleRejections=r,this.unresolvedLabels=n,this.name="PeginParamsNotFoundError"}}class J extends Error{constructor(t){super(`${t.length} candidate parameter sets reproduce this Pre-PegIn's HTLC outputs, so the vault's stamped versions cannot be determined: ${t.join(" | ")}. Reconstruction refused.`),this.survivorLabels=t,this.name="PeginParamsAmbiguousError"}}class G extends Error{constructor(t,r){super(`A candidate matched this Pre-PegIn (${t}), but ${r.length} version(s) could not be resolved, so the search space did not provably contain the true parameters: ${r.join(" | ")}. A version sharing the matched timelockRefund and participants is indistinguishable from the true one, so the match cannot be trusted. Reconstruction refused.`),this.matchedLabel=t,this.unresolvedLabels=r,this.name="PeginParamsIncompleteSpaceError"}}class T extends Error{constructor(t){super(`${t}. Reconstruction refused.`),this.name="PeginSizingIntegrityError"}}async function ie(e){const{wallet:t,depositorBtcPubkey:r,fundedPrePeginTxHex:n}=e,h=p.stripHexPrefix(n),c=S.findAuthAnchorOpReturn(h);if(c===void 0)throw new A("Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN, so the number of HTLC outputs it funds cannot be determined. Legacy pre-anchor deposits are not recoverable by this path.");const u=c.vout;if(u===0)throw new A("Pre-PegIn's auth-anchor OP_RETURN is at vout 0, implying zero HTLC outputs; there is nothing to recover.");const l=N.parseFundingOutpointsFromTx(h),a=await N.deriveVaultRoot(t,{depositorBtcPubkey:p.hexToUint8Array(p.processPublicKeyToXOnly(r)),fundingOutpoints:l});try{const s=await f.expandAuthAnchor(a);let i;try{i=p.uint8ArrayToHex(ne.sha256(s))}finally{s.fill(0)}if(i!==c.hash)throw new Q(i,c.hash)}catch(s){throw a.fill(0),s}const{hashlocks:d}=await q.expandPerVaultSecrets(a,u);return{vaultCount:u,hashlocks:d,authAnchorHash:c.hash}}function ae(e){const{vaultCoreVersion:t,offchainParams:r,participantKeySets:n}=e;if(!Number.isInteger(t)||t<1)throw new Error(`buildPeginParamsCandidates: vaultCoreVersion must be a positive integer, got ${t}`);if(r.length===0)throw new Error("buildPeginParamsCandidates: at least one offchain-params version is required");if(n.length===0)throw new Error("buildPeginParamsCandidates: at least one participant key set is required");const h=[];for(const c of r)for(const u of n)h.push({vaultCoreVersion:t,offchainParams:c,participants:u});return h}function Y(e){return`${e.axis} v${e.version} (${e.reason})`}function $(e){const{participants:t}=e;return`core=${e.vaultCoreVersion} offchain=${e.offchainParams.version} keepers=${t.appVaultKeepersVersion} challengers=${t.universalChallengersVersion} vp=${t.vaultProvider}`}const D=5;function ce(e,t){return JSON.stringify({terms:e,peginAmounts:t},(r,n)=>typeof n=="bigint"?`${n}`:n)}function ue(e){const{offchainParams:t,participants:r}=e;return[e.vaultCoreVersion,r.vaultKeeperBtcPubkeys.length,r.universalChallengerBtcPubkeys.length,t.councilQuorum,t.councilSize,t.protocolFeeRate,t.minPeginFeeRate].join("|")}async function le(e){const{offchainParams:t,participants:r}=e,n=r.vaultKeeperBtcPubkeys.length,h=r.universalChallengerBtcPubkeys.length,[c,u,l]=await Promise.all([f.computeMinClaimValue(e.vaultCoreVersion,n,h,t.councilQuorum,t.councilSize,t.protocolFeeRate),f.computeMinPeginFee(e.vaultCoreVersion,n,h,t.minPeginFeeRate),f.peginP2aAnchorOutput(e.vaultCoreVersion)]),a=(l==null?void 0:l.value)??0n;if(c<=0n)throw new T(`WASM returned non-positive depositorClaimValue ${c} for graph version ${e.vaultCoreVersion}`);if(u<=0n)throw new T(`WASM returned non-positive peginMaxFee ${u} for graph version ${e.vaultCoreVersion}`);if(a<0n)throw new T(`WASM returned negative P2A anchor value ${a} for graph version ${e.vaultCoreVersion}`);return{depositorClaimValue:c,peginMaxFee:u,p2aAnchorValue:a}}async function he(e){const{hashlocks:t,fundedPrePeginTxHex:r,depositorBtcPubkey:n,prepeginMaxFee:h,maxAcceptableCommissionBps:c,network:u,candidates:l,unresolvedVersions:a}=e;if(t.length===0)throw new Error("reconstructPeginParams: at least one hashlock is required");if(l.length===0)throw new Error("reconstructPeginParams: candidate space is empty");const d=p.processPublicKeyToXOnly(n),s=p.stripHexPrefix(r),i=S.findAuthAnchorOpReturn(s);if(i===void 0)throw new A("Pre-PegIn carries no single, unambiguous auth-anchor OP_RETURN; the sibling set cannot be proven complete. Reconstruction refused.");if(i.vout!==t.length)throw new Error(`reconstructPeginParams: ${t.length} hashlock(s) supplied but the auth-anchor OP_RETURN sits at vout ${i.vout}, so the transaction funds ${i.vout} HTLC output(s). Reconstruction refused.`);const v=U.Transaction.fromHex(s).outs,w=t.map((m,g)=>BigInt(v[g].value)),E=p.stripHexPrefix(j.calculateBtcTxHash(s)).toLowerCase(),x=new Map,o=[],b=[],F=[];let I=0;for(const m of l)try{const g=ue(m);let P=x.get(g);P===void 0&&(P=await le(m),x.set(g,P));const k=P.depositorClaimValue+P.peginMaxFee+P.p2aAnchorValue,y=w.map(C=>C-k),V=y.findIndex(C=>C<=0n);if(V!==-1)throw new H.HtlcOutputMismatchError(`HTLC output[${V}] value ${w[V]} is not above this candidate's reserve ${k}, so it implies a non-positive pegin amount ${y[V]}.`);const{offchainParams:R,participants:B}=m,_=await W({vaultCoreVersion:m.vaultCoreVersion,siblings:t.map((C,ee)=>({hashlock:C,amount:y[ee]})),fundedPrePeginTxHex:s,depositorBtcPubkey:d,vaultProviderBtcPubkey:B.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:B.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:B.universalChallengerBtcPubkeys,protocolFeeRate:R.protocolFeeRate,minPeginFeeRate:R.minPeginFeeRate,councilQuorum:R.councilQuorum,councilSize:R.councilSize,timelockPegin:R.timelockPegin,timelockAssert:R.timelockAssert,timelockRefund:R.timelockRefund,prepeginTxid:E,prepeginMaxFee:h,maxAcceptableCommissionBps:c,network:u});o.push({candidate:m,terms:_,peginAmounts:y,fingerprint:ce(_,y)})}catch(g){if(g instanceof T)throw g;const P=$(m),k=g instanceof Error?g.message:String(g);g instanceof H.HtlcOutputMismatchError?b.length<D&&b.push(`[${P}] ${k}`):(I++,F.length<D&&F.push(`${P} (${k})`))}const Z=a.length+I,O=[...a.map(Y),...F];if(o.length===0)throw new X(l.length,b,O);if(new Set(o.map(m=>m.fingerprint)).size>1)throw new J(o.map(m=>$(m.candidate)));if(Z>0)throw new G($(o[0].candidate),O);return{candidate:o[0].candidate,terms:o[0].terms,peginAmounts:o[0].peginAmounts,authAnchorHash:i.hash,candidatesTried:l.length,matchedCandidates:o.map(m=>m.candidate)}}function de(e,t){const{htlcVout:r,depositorBtcPubkey:n,applicationEntryPoint:h,fundedPrePeginTxHex:c,hashlocks:u,network:l}=t,{candidate:a,peginAmounts:d}=e,{offchainParams:s,participants:i}=a;if(u.length!==d.length)throw new Error(`toRefundInputs: ${u.length} hashlock(s) but ${d.length} reconstructed amount(s); the reconstruction and the hashlock vector describe different transactions.`);if(!Number.isInteger(r)||r<0||r>=d.length)throw new Error(`toRefundInputs: htlcVout ${r} is outside the reconstructed batch of ${d.length} vault(s).`);const v=d.map((x,o)=>({hashlock:p.ensureHexPrefix(u[o]),amount:x,htlcVout:o})),w={vaultCoreVersion:a.vaultCoreVersion,hashlock:v[r].hashlock,htlcVout:r,offchainParamsVersion:s.version,appVaultKeepersVersion:i.appVaultKeepersVersion,universalChallengersVersion:i.universalChallengersVersion,vaultProvider:i.vaultProvider,applicationEntryPoint:h,amount:d[r],unsignedPrePeginTxHex:c,depositorBtcPubkey:n,batch:v},E={vaultProviderPubkey:i.vaultProviderBtcPubkey,vaultKeeperPubkeys:i.vaultKeeperBtcPubkeys,universalChallengerPubkeys:i.universalChallengerBtcPubkeys,timelockRefund:s.timelockRefund,feeRate:s.protocolFeeRate,minPeginFeeRate:s.minPeginFeeRate,numLocalChallengers:i.vaultKeeperBtcPubkeys.length,councilQuorum:s.councilQuorum,councilSize:s.councilSize,network:l};return{vault:w,context:E}}exports.DEPOSIT_TERMS_REJECTED_ERROR_NAME=M;exports.DepositTermsRejectedError=L;exports.PeginParamsAmbiguousError=J;exports.PeginParamsIncompleteSpaceError=G;exports.PeginParamsNotFoundError=X;exports.PeginSizingIntegrityError=T;exports.UnanchoredPrePeginError=A;exports.VaultRootMismatchError=Q;exports.buildPeginParamsCandidates=ae;exports.deriveHashlocksFromPrePegin=ie;exports.describePeginParamsCandidate=$;exports.describeUnresolvedVersion=Y;exports.isDepositTermsRejectedError=oe;exports.isWotsMismatchError=se;exports.rebuildDepositTermsCore=W;exports.reconstructPeginParams=he;exports.toRefundInputs=de;
|
|
2
|
-
//# sourceMappingURL=toRefundInputs-BJojfg3k.cjs.map
|