@babylonlabs-io/ts-sdk 0.31.0 → 0.32.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-DmVq6ffv.cjs → PeginManager-CTRPJo8m.cjs} +2 -2
- package/dist/{PeginManager-DmVq6ffv.cjs.map → PeginManager-CTRPJo8m.cjs.map} +1 -1
- package/dist/{PeginManager-c44Uvd1N.js → PeginManager-DUR1BTKM.js} +6 -6
- package/dist/{PeginManager-c44Uvd1N.js.map → PeginManager-DUR1BTKM.js.map} +1 -1
- package/dist/{bitcoin-B-Y0DlqR.js → bitcoin-0_T6KJON.js} +32 -28
- package/dist/bitcoin-0_T6KJON.js.map +1 -0
- package/dist/bitcoin-EYBKDtEW.cjs +2 -0
- package/dist/bitcoin-EYBKDtEW.cjs.map +1 -0
- package/dist/{buildAndBroadcastRefund-CLLaz8D3.cjs → buildAndBroadcastRefund-CIHhUmRv.cjs} +2 -2
- package/dist/{buildAndBroadcastRefund-CLLaz8D3.cjs.map → buildAndBroadcastRefund-CIHhUmRv.cjs.map} +1 -1
- package/dist/{buildAndBroadcastRefund-BRQaCQrJ.js → buildAndBroadcastRefund-DwrX_IBf.js} +3 -3
- package/dist/{buildAndBroadcastRefund-BRQaCQrJ.js.map → buildAndBroadcastRefund-DwrX_IBf.js.map} +1 -1
- package/dist/challengeAssert-DSlCIBoT.js +304 -0
- package/dist/challengeAssert-DSlCIBoT.js.map +1 -0
- package/dist/challengeAssert-DuhkzZG-.cjs +2 -0
- package/dist/challengeAssert-DuhkzZG-.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +7 -7
- package/dist/{noPayout-CwgYkZYs.cjs → noPayout-CDhbGn_B.cjs} +2 -2
- package/dist/{noPayout-CwgYkZYs.cjs.map → noPayout-CDhbGn_B.cjs.map} +1 -1
- package/dist/{noPayout-B8JiTaYt.js → noPayout-DohtepqZ.js} +2 -2
- package/dist/{noPayout-B8JiTaYt.js.map → noPayout-DohtepqZ.js.map} +1 -1
- package/dist/{psbtInputFields-CB8hqjQ5.cjs → psbtInputFields-BLi7Ta-T.cjs} +2 -2
- package/dist/{psbtInputFields-CB8hqjQ5.cjs.map → psbtInputFields-BLi7Ta-T.cjs.map} +1 -1
- package/dist/{psbtInputFields-DeTFSJOq.js → psbtInputFields-DPCFHgGd.js} +2 -2
- package/dist/{psbtInputFields-DeTFSJOq.js.map → psbtInputFields-DPCFHgGd.js.map} +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +7 -7
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.js +3 -3
- package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts +10 -7
- package/dist/tbv/core/primitives/psbt/challengeAssert.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/constants.d.ts +26 -0
- package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -0
- package/dist/tbv/core/primitives/psbt/depositorPayout.d.ts +13 -6
- package/dist/tbv/core/primitives/psbt/depositorPayout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts +13 -0
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +1 -1
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +2 -2
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +7 -7
- package/dist/testing/index.cjs +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/{vault-registry-reader-DdruADqa.cjs → vault-registry-reader-BBS1_AON.cjs} +2 -2
- package/dist/{vault-registry-reader-DdruADqa.cjs.map → vault-registry-reader-BBS1_AON.cjs.map} +1 -1
- package/dist/{vault-registry-reader-BywZhqJL.js → vault-registry-reader-CG6bea1S.js} +2 -2
- package/dist/{vault-registry-reader-BywZhqJL.js.map → vault-registry-reader-CG6bea1S.js.map} +1 -1
- package/package.json +1 -1
- package/dist/bitcoin-B-Y0DlqR.js.map +0 -1
- package/dist/bitcoin-DIN0OupO.cjs +0 -2
- package/dist/bitcoin-DIN0OupO.cjs.map +0 -1
- package/dist/challengeAssert-mYikGC34.js +0 -269
- package/dist/challengeAssert-mYikGC34.js.map +0 -1
- package/dist/challengeAssert-yYFflBOx.cjs +0 -2
- package/dist/challengeAssert-yYFflBOx.cjs.map +0 -1
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { p as B, s as d, u as S, h as P, T as I, c as v } from "./bitcoin-0_T6KJON.js";
|
|
2
|
+
import { createPrePeginTransaction as L, buildPeginTxFromPrePegin as O, getPrePeginHtlcConnectorInfo as _, tapInternalPubkey as A, getPeginPayoutScriptInfo as V, getChallengeAssertScriptInfo as R } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
3
|
+
import { c as z } from "./fundPeginTransaction-oV-dNJOU.js";
|
|
4
|
+
import { Buffer as l } from "buffer";
|
|
5
|
+
import { Transaction as h, Psbt as k } from "bitcoinjs-lib";
|
|
6
|
+
function w(e) {
|
|
7
|
+
return B(e).toLowerCase();
|
|
8
|
+
}
|
|
9
|
+
function G(e, t, s) {
|
|
10
|
+
const r = /* @__PURE__ */ new Set();
|
|
11
|
+
r.add(w(e));
|
|
12
|
+
for (const n of t)
|
|
13
|
+
r.add(w(n));
|
|
14
|
+
return r.delete(w(s)), r.size;
|
|
15
|
+
}
|
|
16
|
+
const m = 64, K = /^[0-9a-fA-F]+$/;
|
|
17
|
+
async function Q(e) {
|
|
18
|
+
const t = $(e.authAnchorHash), s = await L({
|
|
19
|
+
depositorPubkey: e.depositorPubkey,
|
|
20
|
+
vaultProviderPubkey: e.vaultProviderPubkey,
|
|
21
|
+
vaultKeeperPubkeys: e.vaultKeeperPubkeys,
|
|
22
|
+
universalChallengerPubkeys: e.universalChallengerPubkeys,
|
|
23
|
+
hashlocks: [...e.hashlocks],
|
|
24
|
+
timelockRefund: e.timelockRefund,
|
|
25
|
+
pegInAmounts: [...e.pegInAmounts],
|
|
26
|
+
feeRate: e.feeRate,
|
|
27
|
+
numLocalChallengers: e.numLocalChallengers,
|
|
28
|
+
councilQuorum: e.councilQuorum,
|
|
29
|
+
councilSize: e.councilSize,
|
|
30
|
+
network: e.network,
|
|
31
|
+
authAnchorHash: t
|
|
32
|
+
}), n = z(s.txHex).outputs.reduce(
|
|
33
|
+
(u, o) => u + BigInt(o.value),
|
|
34
|
+
0n
|
|
35
|
+
), i = t !== void 0 ? s.htlcValues.length : null;
|
|
36
|
+
return {
|
|
37
|
+
psbtHex: s.txHex,
|
|
38
|
+
totalOutputValue: n,
|
|
39
|
+
htlcValues: s.htlcValues,
|
|
40
|
+
htlcScriptPubKeys: s.htlcScriptPubKeys,
|
|
41
|
+
htlcAddresses: s.htlcAddresses,
|
|
42
|
+
peginAmounts: s.peginAmounts,
|
|
43
|
+
depositorClaimValue: s.depositorClaimValue,
|
|
44
|
+
authAnchorVout: i
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function $(e) {
|
|
48
|
+
if (e === void 0) return;
|
|
49
|
+
const t = e.startsWith("0x") || e.startsWith("0X") ? e.slice(2) : e;
|
|
50
|
+
if (t.length !== m || !K.test(t))
|
|
51
|
+
throw new Error(
|
|
52
|
+
`authAnchorHash must be 32-byte hex (${m} chars, no 0x prefix); got length ${t.length}`
|
|
53
|
+
);
|
|
54
|
+
return t.toLowerCase();
|
|
55
|
+
}
|
|
56
|
+
async function Y(e) {
|
|
57
|
+
const t = await O(
|
|
58
|
+
{
|
|
59
|
+
depositorPubkey: e.prePeginParams.depositorPubkey,
|
|
60
|
+
vaultProviderPubkey: e.prePeginParams.vaultProviderPubkey,
|
|
61
|
+
vaultKeeperPubkeys: e.prePeginParams.vaultKeeperPubkeys,
|
|
62
|
+
universalChallengerPubkeys: e.prePeginParams.universalChallengerPubkeys,
|
|
63
|
+
hashlocks: [...e.prePeginParams.hashlocks],
|
|
64
|
+
timelockRefund: e.prePeginParams.timelockRefund,
|
|
65
|
+
pegInAmounts: [...e.prePeginParams.pegInAmounts],
|
|
66
|
+
feeRate: e.prePeginParams.feeRate,
|
|
67
|
+
numLocalChallengers: e.prePeginParams.numLocalChallengers,
|
|
68
|
+
councilQuorum: e.prePeginParams.councilQuorum,
|
|
69
|
+
councilSize: e.prePeginParams.councilSize,
|
|
70
|
+
network: e.prePeginParams.network,
|
|
71
|
+
authAnchorHash: $(
|
|
72
|
+
e.prePeginParams.authAnchorHash
|
|
73
|
+
)
|
|
74
|
+
},
|
|
75
|
+
e.timelockPegin,
|
|
76
|
+
e.fundedPrePeginTxHex,
|
|
77
|
+
e.htlcVout
|
|
78
|
+
);
|
|
79
|
+
return {
|
|
80
|
+
txHex: t.txHex,
|
|
81
|
+
txid: t.txid,
|
|
82
|
+
vaultScriptPubKey: t.vaultScriptPubKey,
|
|
83
|
+
vaultValue: t.vaultValue
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
async function j(e) {
|
|
87
|
+
const t = d(e.peginTxHex), s = d(e.fundedPrePeginTxHex), r = await _({
|
|
88
|
+
depositorPubkey: e.depositorPubkey,
|
|
89
|
+
vaultProviderPubkey: e.vaultProviderPubkey,
|
|
90
|
+
vaultKeeperPubkeys: e.vaultKeeperPubkeys,
|
|
91
|
+
universalChallengerPubkeys: e.universalChallengerPubkeys,
|
|
92
|
+
hashlock: e.hashlock,
|
|
93
|
+
timelockRefund: e.timelockRefund,
|
|
94
|
+
network: e.network
|
|
95
|
+
}), n = h.fromHex(t), i = h.fromHex(s);
|
|
96
|
+
if (n.ins.length !== 1)
|
|
97
|
+
throw new Error(
|
|
98
|
+
`PegIn transaction must have exactly 1 input, got ${n.ins.length}`
|
|
99
|
+
);
|
|
100
|
+
const u = n.ins[0], o = i.getId(), c = S(
|
|
101
|
+
new Uint8Array(u.hash).slice().reverse()
|
|
102
|
+
);
|
|
103
|
+
if (c !== o)
|
|
104
|
+
throw new Error(
|
|
105
|
+
`PegIn input does not reference the Pre-PegIn transaction. Expected ${o}, got ${c}`
|
|
106
|
+
);
|
|
107
|
+
const a = i.outs[u.index];
|
|
108
|
+
if (!a)
|
|
109
|
+
throw new Error(
|
|
110
|
+
`Pre-PegIn output ${u.index} not found (Pre-PegIn has ${i.outs.length} outputs)`
|
|
111
|
+
);
|
|
112
|
+
const g = P(r.hashlockScript), x = P(r.hashlockControlBlock), p = new k();
|
|
113
|
+
p.setVersion(n.version), p.setLocktime(n.locktime), p.addInput({
|
|
114
|
+
hash: u.hash,
|
|
115
|
+
index: u.index,
|
|
116
|
+
sequence: u.sequence,
|
|
117
|
+
witnessUtxo: {
|
|
118
|
+
script: a.script,
|
|
119
|
+
value: a.value
|
|
120
|
+
},
|
|
121
|
+
tapLeafScript: [
|
|
122
|
+
{
|
|
123
|
+
leafVersion: I,
|
|
124
|
+
script: l.from(g),
|
|
125
|
+
controlBlock: l.from(x)
|
|
126
|
+
}
|
|
127
|
+
],
|
|
128
|
+
tapInternalKey: l.from(A)
|
|
129
|
+
// sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot
|
|
130
|
+
});
|
|
131
|
+
for (const f of n.outs)
|
|
132
|
+
p.addOutput({
|
|
133
|
+
script: f.script,
|
|
134
|
+
value: f.value
|
|
135
|
+
});
|
|
136
|
+
return { psbtHex: p.toHex() };
|
|
137
|
+
}
|
|
138
|
+
function J(e, t) {
|
|
139
|
+
const r = k.fromHex(e).data.inputs[0];
|
|
140
|
+
if (!r)
|
|
141
|
+
throw new Error("PegIn PSBT has no inputs");
|
|
142
|
+
if (r.tapScriptSig && r.tapScriptSig.length > 0) {
|
|
143
|
+
const n = l.from(
|
|
144
|
+
P(t)
|
|
145
|
+
);
|
|
146
|
+
for (const i of r.tapScriptSig)
|
|
147
|
+
if (i.pubkey.equals(n))
|
|
148
|
+
return N(i.signature);
|
|
149
|
+
throw new Error(
|
|
150
|
+
`No PegIn input signature found for depositor pubkey: ${t}`
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
throw r.finalScriptWitness && r.finalScriptWitness.length > 0 ? new Error(
|
|
154
|
+
"PegIn input PSBT is already finalized. Cannot reliably extract the depositor signature from the witness stack. Ensure the wallet returns a non-finalized PSBT with tapScriptSig entries."
|
|
155
|
+
) : new Error(
|
|
156
|
+
"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT"
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
function M(e) {
|
|
160
|
+
const t = k.fromHex(e);
|
|
161
|
+
try {
|
|
162
|
+
t.finalizeAllInputs();
|
|
163
|
+
} catch (s) {
|
|
164
|
+
if (!t.data.inputs.every(
|
|
165
|
+
(n) => n.finalScriptWitness || n.finalScriptSig
|
|
166
|
+
))
|
|
167
|
+
throw new Error(
|
|
168
|
+
`PSBT finalization failed and wallet did not auto-finalize: ${s}`
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
return t.extractTransaction().toHex();
|
|
172
|
+
}
|
|
173
|
+
function N(e) {
|
|
174
|
+
if (e.length === 64)
|
|
175
|
+
return S(new Uint8Array(e));
|
|
176
|
+
if (e.length === 65) {
|
|
177
|
+
const t = e[64];
|
|
178
|
+
if (t !== h.SIGHASH_ALL)
|
|
179
|
+
throw new Error(
|
|
180
|
+
`Unexpected sighash type 0x${t.toString(16).padStart(2, "0")} in PegIn input signature. Expected SIGHASH_DEFAULT (64-byte sig) or SIGHASH_ALL (0x01).`
|
|
181
|
+
);
|
|
182
|
+
return S(new Uint8Array(e.subarray(0, 64)));
|
|
183
|
+
}
|
|
184
|
+
throw new Error(`Unexpected PegIn input signature length: ${e.length}`);
|
|
185
|
+
}
|
|
186
|
+
const E = 2, b = 0, T = 0;
|
|
187
|
+
async function Z(e) {
|
|
188
|
+
const t = h.fromHex(d(e.payoutTxHex)), s = h.fromHex(d(e.peginTxHex)), r = h.fromHex(d(e.assertTxHex));
|
|
189
|
+
if (t.ins.length !== E)
|
|
190
|
+
throw new Error(
|
|
191
|
+
`Depositor Payout transaction must have exactly ${E} inputs, got ${t.ins.length}`
|
|
192
|
+
);
|
|
193
|
+
const n = t.ins[0], i = t.ins[1], u = v(n), o = s.getId();
|
|
194
|
+
if (u !== o || n.index !== b)
|
|
195
|
+
throw new Error(
|
|
196
|
+
`Depositor Payout input 0 must spend PegIn:${b}. Expected ${o}:${b}, got ${u}:${n.index}`
|
|
197
|
+
);
|
|
198
|
+
const c = v(i), a = r.getId();
|
|
199
|
+
if (c !== a || i.index !== T)
|
|
200
|
+
throw new Error(
|
|
201
|
+
`Depositor Payout input 1 must spend Assert:${T}. Expected ${a}:${T}, got ${c}:${i.index}`
|
|
202
|
+
);
|
|
203
|
+
const g = s.outs[n.index], x = r.outs[i.index], { payoutScript: p, payoutControlBlock: f } = await V(
|
|
204
|
+
e.connectorParams
|
|
205
|
+
), C = P(p), U = P(f), y = new k();
|
|
206
|
+
y.setVersion(t.version), y.setLocktime(t.locktime), y.addInput({
|
|
207
|
+
hash: n.hash,
|
|
208
|
+
index: n.index,
|
|
209
|
+
sequence: n.sequence,
|
|
210
|
+
witnessUtxo: {
|
|
211
|
+
script: g.script,
|
|
212
|
+
value: g.value
|
|
213
|
+
},
|
|
214
|
+
tapLeafScript: [
|
|
215
|
+
{
|
|
216
|
+
leafVersion: I,
|
|
217
|
+
script: l.from(C),
|
|
218
|
+
controlBlock: l.from(U)
|
|
219
|
+
}
|
|
220
|
+
],
|
|
221
|
+
tapInternalKey: l.from(A)
|
|
222
|
+
}), y.addInput({
|
|
223
|
+
hash: i.hash,
|
|
224
|
+
index: i.index,
|
|
225
|
+
sequence: i.sequence,
|
|
226
|
+
witnessUtxo: {
|
|
227
|
+
script: x.script,
|
|
228
|
+
value: x.value
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
for (const H of t.outs)
|
|
232
|
+
y.addOutput({
|
|
233
|
+
script: H.script,
|
|
234
|
+
value: H.value
|
|
235
|
+
});
|
|
236
|
+
return y.toHex();
|
|
237
|
+
}
|
|
238
|
+
async function ee(e) {
|
|
239
|
+
const t = h.fromHex(
|
|
240
|
+
d(e.challengeAssertTxHex)
|
|
241
|
+
), s = h.fromHex(d(e.assertTxHex)), r = s.getId();
|
|
242
|
+
if (e.connectorParamsPerInput.length !== t.ins.length)
|
|
243
|
+
throw new Error(
|
|
244
|
+
`Expected ${t.ins.length} connector params, got ${e.connectorParamsPerInput.length}`
|
|
245
|
+
);
|
|
246
|
+
const n = /* @__PURE__ */ new Set();
|
|
247
|
+
for (let o = 0; o < t.ins.length; o++) {
|
|
248
|
+
const c = t.ins[o], a = v(c);
|
|
249
|
+
if (a !== r)
|
|
250
|
+
throw new Error(
|
|
251
|
+
`ChallengeAssert input ${o} must spend an Assert output. Expected txid ${r}, got ${a}`
|
|
252
|
+
);
|
|
253
|
+
if (!s.outs[c.index])
|
|
254
|
+
throw new Error(
|
|
255
|
+
`Assert output ${c.index} not found for ChallengeAssert input ${o} (txid: ${r})`
|
|
256
|
+
);
|
|
257
|
+
if (n.has(c.index))
|
|
258
|
+
throw new Error(
|
|
259
|
+
`ChallengeAssert input ${o} duplicates Assert output index ${c.index}`
|
|
260
|
+
);
|
|
261
|
+
n.add(c.index);
|
|
262
|
+
}
|
|
263
|
+
const i = await Promise.all(
|
|
264
|
+
e.connectorParamsPerInput.map((o) => R(o))
|
|
265
|
+
), u = new k();
|
|
266
|
+
u.setVersion(t.version), u.setLocktime(t.locktime);
|
|
267
|
+
for (let o = 0; o < t.ins.length; o++) {
|
|
268
|
+
const c = t.ins[o], a = s.outs[c.index], { script: g, controlBlock: x } = i[o], p = P(g), f = P(x);
|
|
269
|
+
u.addInput({
|
|
270
|
+
hash: c.hash,
|
|
271
|
+
index: c.index,
|
|
272
|
+
sequence: c.sequence,
|
|
273
|
+
witnessUtxo: {
|
|
274
|
+
script: a.script,
|
|
275
|
+
value: a.value
|
|
276
|
+
},
|
|
277
|
+
tapLeafScript: [
|
|
278
|
+
{
|
|
279
|
+
leafVersion: I,
|
|
280
|
+
script: l.from(p),
|
|
281
|
+
controlBlock: l.from(f)
|
|
282
|
+
}
|
|
283
|
+
],
|
|
284
|
+
tapInternalKey: l.from(A)
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
for (const o of t.outs)
|
|
288
|
+
u.addOutput({
|
|
289
|
+
script: o.script,
|
|
290
|
+
value: o.value
|
|
291
|
+
});
|
|
292
|
+
return u.toHex();
|
|
293
|
+
}
|
|
294
|
+
export {
|
|
295
|
+
Y as a,
|
|
296
|
+
Q as b,
|
|
297
|
+
G as c,
|
|
298
|
+
j as d,
|
|
299
|
+
J as e,
|
|
300
|
+
M as f,
|
|
301
|
+
Z as g,
|
|
302
|
+
ee as h
|
|
303
|
+
};
|
|
304
|
+
//# sourceMappingURL=challengeAssert-DSlCIBoT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"challengeAssert-DSlCIBoT.js","sources":["../src/tbv/core/primitives/challengers.ts","../src/tbv/core/primitives/psbt/pegin.ts","../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/primitives/psbt/constants.ts","../src/tbv/core/primitives/psbt/depositorPayout.ts","../src/tbv/core/primitives/psbt/challengeAssert.ts"],"sourcesContent":["/**\n * Challenger counting utilities.\n *\n * Used for UI-level validation (e.g. computing minimum deposit amounts)\n * where the depositor's identity is known. The transaction builders use\n * `vaultKeeperBtcPubkeys.length` to match the VP's current validation.\n */\n\nimport { processPublicKeyToXOnly } from \"./utils/bitcoin\";\n\n/**\n * Normalize a public key to lowercase x-only hex for reliable comparison.\n *\n * Handles `0x` prefixes, compressed (33-byte), and uncompressed (65-byte) keys.\n */\nfunction normalizeKey(key: string): string {\n return processPublicKeyToXOnly(key).toLowerCase();\n}\n\n/**\n * Compute the number of local challengers for a vault.\n *\n * Mirrors the VP's `compute_num_challengers()` logic:\n * local challengers = {vault_provider} ∪ {vault_keepers} − {depositor}\n *\n * Keys are normalized to x-only lowercase hex before comparison, so\n * `0x`-prefixed, compressed, or mixed-case keys are handled correctly.\n *\n * @param vaultProviderPubkey - Vault provider BTC public key\n * @param vaultKeeperPubkeys - Vault keeper BTC public keys\n * @param depositorPubkey - Depositor (claimer) BTC public key\n * @returns Number of local challengers\n */\nexport function computeNumLocalChallengers(\n vaultProviderPubkey: string,\n vaultKeeperPubkeys: string[],\n depositorPubkey: string,\n): number {\n const localSet = new Set<string>();\n localSet.add(normalizeKey(vaultProviderPubkey));\n for (const vk of vaultKeeperPubkeys) {\n localSet.add(normalizeKey(vk));\n }\n localSet.delete(normalizeKey(depositorPubkey));\n return localSet.size;\n}\n","/**\n * Pre-PegIn PSBT Builder Primitive\n *\n * This module provides pure functions for building unfunded Pre-PegIn transactions\n * and deriving PegIn transactions from them, using the WASM implementation from\n * @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * Pre-PegIn Flow:\n * 1. buildPrePeginPsbt() — creates unfunded Pre-PegIn tx (HTLC output)\n * 2. [caller funds Pre-PegIn tx and computes txid]\n * 3. buildPeginTxFromFundedPrePegin() — derives PegIn tx spending the HTLC\n * 4. buildPeginInputPsbt() — PSBT for depositor to sign PegIn HTLC leaf 0 input\n *\n * @module primitives/psbt/pegin\n */\n\nimport {\n buildPeginTxFromPrePegin,\n createPrePeginTransaction,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\nimport { parseUnfundedWasmTransaction } from \"../../utils/transaction/fundPeginTransaction\";\n\n/**\n * Parameters for building an unfunded Pre-PegIn PSBT\n */\nexport interface PrePeginParams {\n /** Depositor's BTC public key (x-only, 64-char hex without 0x prefix) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Array of vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Array of universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment(s) (64 hex chars = 32 bytes each) */\n hashlocks: readonly string[];\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Amounts to peg in (satoshis), one per deposit */\n pegInAmounts: readonly bigint[];\n /** Fee rate in sat/vB from contract offchain params */\n feeRate: bigint;\n /** Number of local challengers (from contract params) */\n numLocalChallengers: number;\n /** M in M-of-N council multisig (from contract params) */\n councilQuorum: number;\n /** N in M-of-N council multisig (from contract params) */\n councilSize: number;\n /** Bitcoin network */\n network: Network;\n /**\n * Optional 32-byte `SHA256(auth_anchor)` commitment (64-char hex, no\n * `0x` prefix). If provided, the Pre-PegIn tx will include an\n * `OP_RETURN <PUSH32 authAnchorHash>` output at vout =\n * `hashlocks.length`, binding the depositor's bearer-token\n * `auth_anchor` preimage to this Pre-PegIn.\n */\n authAnchorHash?: string;\n}\n\n/**\n * Byte length of an `auth_anchor_hash` commitment when encoded as a\n * lowercase hex string (32 bytes → 64 hex chars).\n */\nconst AUTH_ANCHOR_HASH_HEX_LEN = 64;\n\nconst HEX_PATTERN = /^[0-9a-fA-F]+$/;\n\n/**\n * Result of building an unfunded Pre-PegIn transaction\n */\nexport interface PrePeginPsbtResult {\n /**\n * Unfunded transaction hex (no inputs, HTLC outputs + optional\n * auth-anchor OP_RETURN + CPFP anchor).\n *\n * The caller is responsible for:\n * - Selecting UTXOs covering totalOutputValue + network fees\n * - Funding the transaction (add inputs and change output)\n * - Calling buildPeginTxFromFundedPrePegin() with the funded tx hex\n */\n psbtHex: string;\n /** Sum of all unfunded outputs — use this for UTXO selection */\n totalOutputValue: bigint;\n /** HTLC output values in satoshis, one per deposit (each includes peginAmount + depositorClaimValue + minPeginFee) */\n htlcValues: readonly bigint[];\n /** HTLC output scriptPubKeys (hex encoded), one per deposit */\n htlcScriptPubKeys: readonly string[];\n /** HTLC Taproot addresses, one per deposit */\n htlcAddresses: readonly string[];\n /** Pegin amounts in satoshis, one per deposit */\n peginAmounts: readonly bigint[];\n /** Depositor claim value computed by WASM from contract parameters */\n depositorClaimValue: bigint;\n /**\n * Vout index of the auth-anchor `OP_RETURN` output if one was\n * included (i.e. `authAnchorHash` was provided), or `null` if not.\n * Always equals `htlcValues.length` when present.\n */\n authAnchorVout: number | null;\n}\n\n/**\n * Parameters for building the PegIn transaction from a funded Pre-PegIn tx\n */\nexport interface BuildPeginTxParams {\n /** Same PrePeginParams used to create the Pre-PegIn transaction */\n prePeginParams: PrePeginParams;\n /** CSV timelock in blocks for the PegIn vault output */\n timelockPegin: number;\n /** Hex-encoded funded Pre-PegIn transaction */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output to spend */\n htlcVout: number;\n}\n\n/**\n * Result of building the PegIn transaction\n */\nexport interface PeginTxResult {\n /** PegIn transaction hex (1 input spending HTLC, 1 vault output) */\n txHex: string;\n /** PegIn transaction ID */\n txid: string;\n /** Vault output scriptPubKey (hex encoded) */\n vaultScriptPubKey: string;\n /** Vault output value in satoshis */\n vaultValue: bigint;\n}\n\n/**\n * Build unfunded Pre-PegIn transaction using WASM.\n *\n * Creates a Bitcoin transaction template with no inputs, an HTLC output, and a\n * CPFP anchor output. The HTLC value is computed internally from the contract\n * parameters — the caller does not need to compute depositorClaimValue separately.\n *\n * @param params - Pre-PegIn parameters\n * @returns Unfunded Pre-PegIn transaction details with HTLC output information\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPrePeginPsbt(\n params: PrePeginParams,\n): Promise<PrePeginPsbtResult> {\n const authAnchorHash = normalizeAuthAnchorHash(params.authAnchorHash);\n\n const result = await createPrePeginTransaction({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlocks: [...params.hashlocks],\n timelockRefund: params.timelockRefund,\n pegInAmounts: [...params.pegInAmounts],\n feeRate: params.feeRate,\n numLocalChallengers: params.numLocalChallengers,\n councilQuorum: params.councilQuorum,\n councilSize: params.councilSize,\n network: params.network,\n authAnchorHash,\n });\n\n // Parse the unfunded tx to sum all output values\n // (HTLCs + optional OP_RETURN + CPFP anchor). This is the amount\n // UTXOs must cover before adding network fees.\n const parsed = parseUnfundedWasmTransaction(result.txHex);\n const totalOutputValue = parsed.outputs.reduce(\n (sum, o) => sum + BigInt(o.value),\n 0n,\n );\n\n // The WASM places the OP_RETURN commitment immediately after the\n // HTLC outputs when authAnchorHash is provided.\n const authAnchorVout =\n authAnchorHash !== undefined ? result.htlcValues.length : null;\n\n return {\n psbtHex: result.txHex,\n totalOutputValue,\n htlcValues: result.htlcValues,\n htlcScriptPubKeys: result.htlcScriptPubKeys,\n htlcAddresses: result.htlcAddresses,\n peginAmounts: result.peginAmounts,\n depositorClaimValue: result.depositorClaimValue,\n authAnchorVout,\n };\n}\n\n/**\n * Validate and normalize an `authAnchorHash` hex string before passing\n * it to the WASM boundary. WASM expects exactly 64 lowercase hex chars.\n */\nfunction normalizeAuthAnchorHash(\n value: string | undefined,\n): string | undefined {\n if (value === undefined) return undefined;\n const cleaned =\n value.startsWith(\"0x\") || value.startsWith(\"0X\") ? value.slice(2) : value;\n if (\n cleaned.length !== AUTH_ANCHOR_HASH_HEX_LEN ||\n !HEX_PATTERN.test(cleaned)\n ) {\n throw new Error(\n `authAnchorHash must be 32-byte hex (${AUTH_ANCHOR_HASH_HEX_LEN} chars, no 0x prefix); got length ${cleaned.length}`,\n );\n }\n return cleaned.toLowerCase();\n}\n\n/**\n * Build the PegIn transaction from a funded Pre-PegIn transaction.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output at htlcVout via the\n * hashlock + all-party script (leaf 0).\n *\n * @param params - Build parameters including Pre-PegIn params and funded tx hex\n * @returns PegIn transaction details\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPeginTxFromFundedPrePegin(\n params: BuildPeginTxParams,\n): Promise<PeginTxResult> {\n // WASM reconstructs the Pre-PegIn template from these params to\n // decode the funded tx. Must pass `authAnchorHash` (normalized\n // identically to buildPrePeginPsbt) so the reconstruction matches\n // the original outputs, including the OP_RETURN at vout =\n // hashlocks.length.\n const result = await buildPeginTxFromPrePegin(\n {\n depositorPubkey: params.prePeginParams.depositorPubkey,\n vaultProviderPubkey: params.prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: params.prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys:\n params.prePeginParams.universalChallengerPubkeys,\n hashlocks: [...params.prePeginParams.hashlocks],\n timelockRefund: params.prePeginParams.timelockRefund,\n pegInAmounts: [...params.prePeginParams.pegInAmounts],\n feeRate: params.prePeginParams.feeRate,\n numLocalChallengers: params.prePeginParams.numLocalChallengers,\n councilQuorum: params.prePeginParams.councilQuorum,\n councilSize: params.prePeginParams.councilSize,\n network: params.prePeginParams.network,\n authAnchorHash: normalizeAuthAnchorHash(\n params.prePeginParams.authAnchorHash,\n ),\n },\n params.timelockPegin,\n params.fundedPrePeginTxHex,\n params.htlcVout,\n );\n\n return {\n txHex: result.txHex,\n txid: result.txid,\n vaultScriptPubKey: result.vaultScriptPubKey,\n vaultValue: result.vaultValue,\n };\n}\n","/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, stripHexPrefix, uint8ArrayToHex } from \"../utils/bitcoin\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const hashlockScript = hexToUint8Array(htlcConnector.hashlockScript);\n const hashlockControlBlock = hexToUint8Array(htlcConnector.hashlockControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hashlockScript),\n controlBlock: Buffer.from(hashlockControlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports both non-finalized PSBTs (tapScriptSig) and finalized PSBTs (witness).\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(\n hexToUint8Array(depositorPubkey),\n );\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present.\n * Accepts 64-byte sigs (implicit SIGHASH_DEFAULT) and 65-byte sigs with\n * SIGHASH_ALL (0x01). Rejects all other sighash types including 0x00, which\n * is consensus-invalid per BIP-342 when explicitly appended.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n const sighashByte = sig[64];\n // Only accept SIGHASH_ALL (0x01). Per BIP-342, SIGHASH_DEFAULT is signaled\n // by omitting the sighash byte (64-byte sig). A 65-byte sig with byte 64\n // set to 0x00 is consensus-invalid: Bitcoin Core rejects it with\n // SCRIPT_ERR_SCHNORR_SIG_HASHTYPE. Accepting 0x00 here would let\n // extractPeginInputSignature succeed (stripping the byte) while\n // finalizePeginInputPsbt passes the raw 65-byte sig into the witness,\n // producing a BTC transaction that can never confirm.\n if (sighashByte !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Unexpected sighash type 0x${sighashByte.toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n `Expected SIGHASH_DEFAULT (64-byte sig) or SIGHASH_ALL (0x01).`,\n );\n }\n return uint8ArrayToHex(new Uint8Array(sig.subarray(0, 64)));\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n\n","/**\n * Protocol invariants for depositor graph transactions.\n *\n * These indices and counts encode the on-chain vault protocol layout\n * (which output of PegIn/Assert each child transaction spends, and how\n * many inputs each transaction has). Consumed by the PSBT builders and\n * the depositor graph signing service; a drift between copies of these\n * values would silently change validation behaviour.\n *\n * @module primitives/psbt/constants\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md\n */\n\n/**\n * Depositor Payout transaction input count.\n * Input 0: PegIn:0 (signed). Input 1: Assert:0 (in sighash, not signed).\n */\nexport const DEPOSITOR_PAYOUT_INPUT_COUNT = 2;\n\n/** PegIn vault output index spent by the depositor's Payout input 0. */\nexport const PEGIN_VAULT_OUTPUT_INDEX = 0;\n\n/** Payout input index bound to the graph Assert tx (NOT signed). */\nexport const PAYOUT_ASSERT_INPUT_INDEX = 1;\n\n/** Assert output index spent by the depositor's Payout input 1 (NOT signed). */\nexport const ASSERT_PAYOUT_OUTPUT_INDEX = 0;\n\n/** Assert output index spent by NoPayout input 0 (signed). */\nexport const ASSERT_NOPAYOUT_OUTPUT_INDEX = 0;\n","/**\n * Depositor Payout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's own Payout transaction\n * (depositor-as-claimer path). The depositor signs input 0 using the\n * payout taproot script from WasmPeginPayoutConnector (PegIn vault UTXO).\n *\n * Input 0 spends PegIn:0 (the vault UTXO) — the same connector used for\n * VP/VK payout signing. The VP verifies this signature using the\n * PeginPayoutConnector's payout script.\n *\n * @module primitives/psbt/depositorPayout\n * @see btc-vault crates/vault/src/sign.rs — verify_depositor_signature / get_payout_tap_leaf_hash\n */\n\nimport {\n type PayoutConnectorParams,\n getPeginPayoutScriptInfo,\n tapInternalPubkey,\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 hexToUint8Array,\n inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport {\n ASSERT_PAYOUT_OUTPUT_INDEX,\n DEPOSITOR_PAYOUT_INPUT_COUNT,\n PEGIN_VAULT_OUTPUT_INDEX,\n} from \"./constants\";\n\n/**\n * Parameters for building a depositor Payout PSBT\n */\nexport interface DepositorPayoutParams {\n /** Payout transaction hex (unsigned) */\n payoutTxHex: string;\n /** Authoritative PegIn transaction hex — input 0 must spend PegIn:0 */\n peginTxHex: string;\n /** Authoritative Assert transaction hex — input 1 must spend Assert:0 */\n assertTxHex: string;\n /** Parameters for the PeginPayout connector (depositor, VP, VKs, UCs, timelock) */\n connectorParams: PayoutConnectorParams;\n}\n\n/**\n * Build unsigned depositor Payout PSBT.\n *\n * The depositor's payout transaction has 2 inputs:\n * - Input 0: PegIn:0 (vault UTXO) — depositor signs using PeginPayoutConnector payout script\n * - Input 1: Assert:0 — NOT signed by depositor\n *\n * Both inputs must be present in the PSBT because Taproot SIGHASH_DEFAULT\n * commits to all input prevouts. Prevout script_pubkey/value are derived\n * from the authoritative parent transactions, not trusted from external input.\n *\n * @param params - Depositor payout parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not reference peginTxHex at output index 0\n * @throws If input 1 does not reference assertTxHex at output index 0\n */\nexport async function buildDepositorPayoutPsbt(\n params: DepositorPayoutParams,\n): Promise<string> {\n const payoutTx = Transaction.fromHex(stripHexPrefix(params.payoutTxHex));\n const peginTx = Transaction.fromHex(stripHexPrefix(params.peginTxHex));\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n\n if (payoutTx.ins.length !== DEPOSITOR_PAYOUT_INPUT_COUNT) {\n throw new Error(\n `Depositor Payout transaction must have exactly ${DEPOSITOR_PAYOUT_INPUT_COUNT} inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n const input0Txid = inputTxidHex(input0);\n const peginTxid = peginTx.getId();\n if (input0Txid !== peginTxid || input0.index !== PEGIN_VAULT_OUTPUT_INDEX) {\n throw new Error(\n `Depositor Payout input 0 must spend PegIn:${PEGIN_VAULT_OUTPUT_INDEX}. ` +\n `Expected ${peginTxid}:${PEGIN_VAULT_OUTPUT_INDEX}, got ${input0Txid}:${input0.index}`,\n );\n }\n\n const input1Txid = inputTxidHex(input1);\n const assertTxid = assertTx.getId();\n if (input1Txid !== assertTxid || input1.index !== ASSERT_PAYOUT_OUTPUT_INDEX) {\n throw new Error(\n `Depositor Payout input 1 must spend Assert:${ASSERT_PAYOUT_OUTPUT_INDEX}. ` +\n `Expected ${assertTxid}:${ASSERT_PAYOUT_OUTPUT_INDEX}, got ${input1Txid}:${input1.index}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n const assertPrevOut = assertTx.outs[input1.index];\n\n const { payoutScript, payoutControlBlock } = await getPeginPayoutScriptInfo(\n params.connectorParams,\n );\n const scriptBytes = hexToUint8Array(payoutScript);\n const controlBlock = hexToUint8Array(payoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n });\n\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n","/**\n * ChallengeAssert PSBT Builder\n *\n * Builds an unsigned PSBT for a ChallengeAssert transaction\n * (depositor-as-claimer path, per challenger). The ChallengeAssert tx has\n * NUM_UTXOS_FOR_CHALLENGE_ASSERT (3) inputs, each spending a different Assert\n * output segment. The depositor signs ALL inputs, each with its own taproot\n * script derived from the per-segment connector params.\n *\n * @module primitives/psbt/challengeAssert\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — ChallengeAssert connector (NUM_UTXOS_FOR_CHALLENGE_ASSERT=3)\n */\n\nimport {\n type ChallengeAssertConnectorParams,\n getChallengeAssertScriptInfo,\n tapInternalPubkey,\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 hexToUint8Array,\n inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a ChallengeAssert PSBT\n */\nexport interface ChallengeAssertParams {\n /** ChallengeAssert transaction hex (unsigned) */\n challengeAssertTxHex: string;\n /** Authoritative Assert transaction hex — every input must spend an Assert output */\n assertTxHex: string;\n /** Per-input connector params (one per input/segment, determines the taproot script) */\n connectorParamsPerInput: ChallengeAssertConnectorParams[];\n}\n\n/**\n * Build unsigned ChallengeAssert PSBT.\n *\n * The ChallengeAssert transaction has 3 inputs (one per Assert output segment).\n * Each input has its own taproot script derived from its connector params.\n * The depositor signs all inputs. Every prevout is derived from the\n * authoritative Assert transaction, never trusted from external input.\n *\n * @param params - ChallengeAssert parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the number of connector params does not match the number of inputs\n * @throws If any input does not reference assertTxHex\n * @throws If any referenced Assert output is missing\n * @throws If two inputs reference the same Assert output index\n */\nexport async function buildChallengeAssertPsbt(\n params: ChallengeAssertParams,\n): Promise<string> {\n const challengeAssertTx = Transaction.fromHex(\n stripHexPrefix(params.challengeAssertTxHex),\n );\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n const assertTxid = assertTx.getId();\n\n if (params.connectorParamsPerInput.length !== challengeAssertTx.ins.length) {\n throw new Error(\n `Expected ${challengeAssertTx.ins.length} connector params, got ${params.connectorParamsPerInput.length}`,\n );\n }\n\n const seenAssertOutputs = new Set<number>();\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const inputTxid = inputTxidHex(input);\n if (inputTxid !== assertTxid) {\n throw new Error(\n `ChallengeAssert input ${i} must spend an Assert output. ` +\n `Expected txid ${assertTxid}, got ${inputTxid}`,\n );\n }\n if (!assertTx.outs[input.index]) {\n throw new Error(\n `Assert output ${input.index} not found for ChallengeAssert input ${i} (txid: ${assertTxid})`,\n );\n }\n if (seenAssertOutputs.has(input.index)) {\n throw new Error(\n `ChallengeAssert input ${i} duplicates Assert output index ${input.index}`,\n );\n }\n seenAssertOutputs.add(input.index);\n }\n\n const scriptInfos = await Promise.all(\n params.connectorParamsPerInput.map((cp) => getChallengeAssertScriptInfo(cp)),\n );\n\n const psbt = new Psbt();\n psbt.setVersion(challengeAssertTx.version);\n psbt.setLocktime(challengeAssertTx.locktime);\n\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const assertPrevOut = assertTx.outs[input.index];\n\n const { script, controlBlock } = scriptInfos[i];\n const scriptBytes = hexToUint8Array(script);\n const controlBlockBytes = hexToUint8Array(controlBlock);\n\n psbt.addInput({\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n }\n\n for (const output of challengeAssertTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n"],"names":["normalizeKey","key","processPublicKeyToXOnly","computeNumLocalChallengers","vaultProviderPubkey","vaultKeeperPubkeys","depositorPubkey","localSet","vk","AUTH_ANCHOR_HASH_HEX_LEN","HEX_PATTERN","buildPrePeginPsbt","params","authAnchorHash","normalizeAuthAnchorHash","result","createPrePeginTransaction","totalOutputValue","parseUnfundedWasmTransaction","sum","authAnchorVout","value","cleaned","buildPeginTxFromFundedPrePegin","buildPeginTxFromPrePegin","buildPeginInputPsbt","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","hashlockScript","hexToUint8Array","hashlockControlBlock","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","sighashByte","DEPOSITOR_PAYOUT_INPUT_COUNT","PEGIN_VAULT_OUTPUT_INDEX","ASSERT_PAYOUT_OUTPUT_INDEX","buildDepositorPayoutPsbt","payoutTx","assertTx","input0","input1","input0Txid","inputTxidHex","peginTxid","input1Txid","assertTxid","peginPrevOut","assertPrevOut","payoutScript","payoutControlBlock","getPeginPayoutScriptInfo","scriptBytes","controlBlock","buildChallengeAssertPsbt","challengeAssertTx","seenAssertOutputs","i","inputTxid","scriptInfos","cp","getChallengeAssertScriptInfo","script","controlBlockBytes"],"mappings":";;;;;AAeA,SAASA,EAAaC,GAAqB;AACzC,SAAOC,EAAwBD,CAAG,EAAE,YAAA;AACtC;AAgBO,SAASE,EACdC,GACAC,GACAC,GACQ;AACR,QAAMC,wBAAe,IAAA;AACrB,EAAAA,EAAS,IAAIP,EAAaI,CAAmB,CAAC;AAC9C,aAAWI,KAAMH;AACf,IAAAE,EAAS,IAAIP,EAAaQ,CAAE,CAAC;AAE/B,SAAAD,EAAS,OAAOP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,EAAc;AAAA,MAAA;AAAA,MAEvB,eAAe;AAAA,QACb;AAAA,UACE,aAAa7B;AAAA,UACb,QAAQC,EAAO,KAAKgC,CAAW;AAAA,UAC/B,cAAchC,EAAO,KAAK2C,CAAiB;AAAA,QAAA;AAAA,MAC7C;AAAA,MAEF,gBAAgB3C,EAAO,KAAKC,CAAiB;AAAA,IAAA,CAC9C;AAAA,EACH;AAEA,aAAWC,KAAUiC,EAAkB;AACrC,IAAAtC,EAAK,UAAU;AAAA,MACb,QAAQK,EAAO;AAAA,MACf,OAAOA,EAAO;AAAA,IAAA,CACf;AAGH,SAAOL,EAAK,MAAA;AACd;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const o=require("./bitcoin-EYBKDtEW.cjs"),d=require("@babylonlabs-io/babylon-tbv-rust-wasm"),m=require("./fundPeginTransaction-DaWoYCgO.cjs"),p=require("buffer"),l=require("bitcoinjs-lib");function T(e){return o.processPublicKeyToXOnly(e).toLowerCase()}function E(e,t,s){const i=new Set;i.add(T(e));for(const n of t)i.add(T(n));return i.delete(T(s)),i.size}const A=64,$=/^[0-9a-fA-F]+$/;async function C(e){const t=H(e.authAnchorHash),s=await d.createPrePeginTransaction({depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlocks:[...e.hashlocks],timelockRefund:e.timelockRefund,pegInAmounts:[...e.pegInAmounts],feeRate:e.feeRate,numLocalChallengers:e.numLocalChallengers,councilQuorum:e.councilQuorum,councilSize:e.councilSize,network:e.network,authAnchorHash:t}),n=m.parseUnfundedWasmTransaction(s.txHex).outputs.reduce((c,r)=>c+BigInt(r.value),0n),u=t!==void 0?s.htlcValues.length:null;return{psbtHex:s.txHex,totalOutputValue:n,htlcValues:s.htlcValues,htlcScriptPubKeys:s.htlcScriptPubKeys,htlcAddresses:s.htlcAddresses,peginAmounts:s.peginAmounts,depositorClaimValue:s.depositorClaimValue,authAnchorVout:u}}function H(e){if(e===void 0)return;const t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length!==A||!$.test(t))throw new Error(`authAnchorHash must be 32-byte hex (${A} chars, no 0x prefix); got length ${t.length}`);return t.toLowerCase()}async function B(e){const t=await d.buildPeginTxFromPrePegin({depositorPubkey:e.prePeginParams.depositorPubkey,vaultProviderPubkey:e.prePeginParams.vaultProviderPubkey,vaultKeeperPubkeys:e.prePeginParams.vaultKeeperPubkeys,universalChallengerPubkeys:e.prePeginParams.universalChallengerPubkeys,hashlocks:[...e.prePeginParams.hashlocks],timelockRefund:e.prePeginParams.timelockRefund,pegInAmounts:[...e.prePeginParams.pegInAmounts],feeRate:e.prePeginParams.feeRate,numLocalChallengers:e.prePeginParams.numLocalChallengers,councilQuorum:e.prePeginParams.councilQuorum,councilSize:e.prePeginParams.councilSize,network:e.prePeginParams.network,authAnchorHash:H(e.prePeginParams.authAnchorHash)},e.timelockPegin,e.fundedPrePeginTxHex,e.htlcVout);return{txHex:t.txHex,txid:t.txid,vaultScriptPubKey:t.vaultScriptPubKey,vaultValue:t.vaultValue}}async function U(e){const t=o.stripHexPrefix(e.peginTxHex),s=o.stripHexPrefix(e.fundedPrePeginTxHex),i=await d.getPrePeginHtlcConnectorInfo({depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlock:e.hashlock,timelockRefund:e.timelockRefund,network:e.network}),n=l.Transaction.fromHex(t),u=l.Transaction.fromHex(s);if(n.ins.length!==1)throw new Error(`PegIn transaction must have exactly 1 input, got ${n.ins.length}`);const c=n.ins[0],r=u.getId(),a=o.uint8ArrayToHex(new Uint8Array(c.hash).slice().reverse());if(a!==r)throw new Error(`PegIn input does not reference the Pre-PegIn transaction. Expected ${r}, got ${a}`);const P=u.outs[c.index];if(!P)throw new Error(`Pre-PegIn output ${c.index} not found (Pre-PegIn has ${u.outs.length} outputs)`);const x=o.hexToUint8Array(i.hashlockScript),f=o.hexToUint8Array(i.hashlockControlBlock),h=new l.Psbt;h.setVersion(n.version),h.setLocktime(n.locktime),h.addInput({hash:c.hash,index:c.index,sequence:c.sequence,witnessUtxo:{script:P.script,value:P.value},tapLeafScript:[{leafVersion:o.TAPSCRIPT_LEAF_VERSION,script:p.Buffer.from(x),controlBlock:p.Buffer.from(f)}],tapInternalKey:p.Buffer.from(d.tapInternalPubkey)});for(const g of n.outs)h.addOutput({script:g.script,value:g.value});return{psbtHex:h.toHex()}}function L(e,t){const i=l.Psbt.fromHex(e).data.inputs[0];if(!i)throw new Error("PegIn PSBT has no inputs");if(i.tapScriptSig&&i.tapScriptSig.length>0){const n=p.Buffer.from(o.hexToUint8Array(t));for(const u of i.tapScriptSig)if(u.pubkey.equals(n))return O(u.signature);throw new Error(`No PegIn input signature found for depositor pubkey: ${t}`)}throw i.finalScriptWitness&&i.finalScriptWitness.length>0?new Error("PegIn input PSBT is already finalized. Cannot reliably extract the depositor signature from the witness stack. Ensure the wallet returns a non-finalized PSBT with tapScriptSig entries."):new Error("No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT")}function _(e){const t=l.Psbt.fromHex(e);try{t.finalizeAllInputs()}catch(s){if(!t.data.inputs.every(n=>n.finalScriptWitness||n.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${s}`)}return t.extractTransaction().toHex()}function O(e){if(e.length===64)return o.uint8ArrayToHex(new Uint8Array(e));if(e.length===65){const t=e[64];if(t!==l.Transaction.SIGHASH_ALL)throw new Error(`Unexpected sighash type 0x${t.toString(16).padStart(2,"0")} in PegIn input signature. Expected SIGHASH_DEFAULT (64-byte sig) or SIGHASH_ALL (0x01).`);return o.uint8ArrayToHex(new Uint8Array(e.subarray(0,64)))}throw new Error(`Unexpected PegIn input signature length: ${e.length}`)}const S=2,b=0,k=0;async function R(e){const t=l.Transaction.fromHex(o.stripHexPrefix(e.payoutTxHex)),s=l.Transaction.fromHex(o.stripHexPrefix(e.peginTxHex)),i=l.Transaction.fromHex(o.stripHexPrefix(e.assertTxHex));if(t.ins.length!==S)throw new Error(`Depositor Payout transaction must have exactly ${S} inputs, got ${t.ins.length}`);const n=t.ins[0],u=t.ins[1],c=o.inputTxidHex(n),r=s.getId();if(c!==r||n.index!==b)throw new Error(`Depositor Payout input 0 must spend PegIn:${b}. Expected ${r}:${b}, got ${c}:${n.index}`);const a=o.inputTxidHex(u),P=i.getId();if(a!==P||u.index!==k)throw new Error(`Depositor Payout input 1 must spend Assert:${k}. Expected ${P}:${k}, got ${a}:${u.index}`);const x=s.outs[n.index],f=i.outs[u.index],{payoutScript:h,payoutControlBlock:g}=await d.getPeginPayoutScriptInfo(e.connectorParams),I=o.hexToUint8Array(h),v=o.hexToUint8Array(g),y=new l.Psbt;y.setVersion(t.version),y.setLocktime(t.locktime),y.addInput({hash:n.hash,index:n.index,sequence:n.sequence,witnessUtxo:{script:x.script,value:x.value},tapLeafScript:[{leafVersion:o.TAPSCRIPT_LEAF_VERSION,script:p.Buffer.from(I),controlBlock:p.Buffer.from(v)}],tapInternalKey:p.Buffer.from(d.tapInternalPubkey)}),y.addInput({hash:u.hash,index:u.index,sequence:u.sequence,witnessUtxo:{script:f.script,value:f.value}});for(const w of t.outs)y.addOutput({script:w.script,value:w.value});return y.toHex()}async function V(e){const t=l.Transaction.fromHex(o.stripHexPrefix(e.challengeAssertTxHex)),s=l.Transaction.fromHex(o.stripHexPrefix(e.assertTxHex)),i=s.getId();if(e.connectorParamsPerInput.length!==t.ins.length)throw new Error(`Expected ${t.ins.length} connector params, got ${e.connectorParamsPerInput.length}`);const n=new Set;for(let r=0;r<t.ins.length;r++){const a=t.ins[r],P=o.inputTxidHex(a);if(P!==i)throw new Error(`ChallengeAssert input ${r} must spend an Assert output. Expected txid ${i}, got ${P}`);if(!s.outs[a.index])throw new Error(`Assert output ${a.index} not found for ChallengeAssert input ${r} (txid: ${i})`);if(n.has(a.index))throw new Error(`ChallengeAssert input ${r} duplicates Assert output index ${a.index}`);n.add(a.index)}const u=await Promise.all(e.connectorParamsPerInput.map(r=>d.getChallengeAssertScriptInfo(r))),c=new l.Psbt;c.setVersion(t.version),c.setLocktime(t.locktime);for(let r=0;r<t.ins.length;r++){const a=t.ins[r],P=s.outs[a.index],{script:x,controlBlock:f}=u[r],h=o.hexToUint8Array(x),g=o.hexToUint8Array(f);c.addInput({hash:a.hash,index:a.index,sequence:a.sequence,witnessUtxo:{script:P.script,value:P.value},tapLeafScript:[{leafVersion:o.TAPSCRIPT_LEAF_VERSION,script:p.Buffer.from(h),controlBlock:p.Buffer.from(g)}],tapInternalKey:p.Buffer.from(d.tapInternalPubkey)})}for(const r of t.outs)c.addOutput({script:r.script,value:r.value});return c.toHex()}exports.buildChallengeAssertPsbt=V;exports.buildDepositorPayoutPsbt=R;exports.buildPeginInputPsbt=U;exports.buildPeginTxFromFundedPrePegin=B;exports.buildPrePeginPsbt=C;exports.computeNumLocalChallengers=E;exports.extractPeginInputSignature=L;exports.finalizePeginInputPsbt=_;
|
|
2
|
+
//# sourceMappingURL=challengeAssert-DuhkzZG-.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"challengeAssert-DuhkzZG-.cjs","sources":["../src/tbv/core/primitives/challengers.ts","../src/tbv/core/primitives/psbt/pegin.ts","../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/primitives/psbt/constants.ts","../src/tbv/core/primitives/psbt/depositorPayout.ts","../src/tbv/core/primitives/psbt/challengeAssert.ts"],"sourcesContent":["/**\n * Challenger counting utilities.\n *\n * Used for UI-level validation (e.g. computing minimum deposit amounts)\n * where the depositor's identity is known. The transaction builders use\n * `vaultKeeperBtcPubkeys.length` to match the VP's current validation.\n */\n\nimport { processPublicKeyToXOnly } from \"./utils/bitcoin\";\n\n/**\n * Normalize a public key to lowercase x-only hex for reliable comparison.\n *\n * Handles `0x` prefixes, compressed (33-byte), and uncompressed (65-byte) keys.\n */\nfunction normalizeKey(key: string): string {\n return processPublicKeyToXOnly(key).toLowerCase();\n}\n\n/**\n * Compute the number of local challengers for a vault.\n *\n * Mirrors the VP's `compute_num_challengers()` logic:\n * local challengers = {vault_provider} ∪ {vault_keepers} − {depositor}\n *\n * Keys are normalized to x-only lowercase hex before comparison, so\n * `0x`-prefixed, compressed, or mixed-case keys are handled correctly.\n *\n * @param vaultProviderPubkey - Vault provider BTC public key\n * @param vaultKeeperPubkeys - Vault keeper BTC public keys\n * @param depositorPubkey - Depositor (claimer) BTC public key\n * @returns Number of local challengers\n */\nexport function computeNumLocalChallengers(\n vaultProviderPubkey: string,\n vaultKeeperPubkeys: string[],\n depositorPubkey: string,\n): number {\n const localSet = new Set<string>();\n localSet.add(normalizeKey(vaultProviderPubkey));\n for (const vk of vaultKeeperPubkeys) {\n localSet.add(normalizeKey(vk));\n }\n localSet.delete(normalizeKey(depositorPubkey));\n return localSet.size;\n}\n","/**\n * Pre-PegIn PSBT Builder Primitive\n *\n * This module provides pure functions for building unfunded Pre-PegIn transactions\n * and deriving PegIn transactions from them, using the WASM implementation from\n * @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * Pre-PegIn Flow:\n * 1. buildPrePeginPsbt() — creates unfunded Pre-PegIn tx (HTLC output)\n * 2. [caller funds Pre-PegIn tx and computes txid]\n * 3. buildPeginTxFromFundedPrePegin() — derives PegIn tx spending the HTLC\n * 4. buildPeginInputPsbt() — PSBT for depositor to sign PegIn HTLC leaf 0 input\n *\n * @module primitives/psbt/pegin\n */\n\nimport {\n buildPeginTxFromPrePegin,\n createPrePeginTransaction,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\nimport { parseUnfundedWasmTransaction } from \"../../utils/transaction/fundPeginTransaction\";\n\n/**\n * Parameters for building an unfunded Pre-PegIn PSBT\n */\nexport interface PrePeginParams {\n /** Depositor's BTC public key (x-only, 64-char hex without 0x prefix) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Array of vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Array of universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment(s) (64 hex chars = 32 bytes each) */\n hashlocks: readonly string[];\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Amounts to peg in (satoshis), one per deposit */\n pegInAmounts: readonly bigint[];\n /** Fee rate in sat/vB from contract offchain params */\n feeRate: bigint;\n /** Number of local challengers (from contract params) */\n numLocalChallengers: number;\n /** M in M-of-N council multisig (from contract params) */\n councilQuorum: number;\n /** N in M-of-N council multisig (from contract params) */\n councilSize: number;\n /** Bitcoin network */\n network: Network;\n /**\n * Optional 32-byte `SHA256(auth_anchor)` commitment (64-char hex, no\n * `0x` prefix). If provided, the Pre-PegIn tx will include an\n * `OP_RETURN <PUSH32 authAnchorHash>` output at vout =\n * `hashlocks.length`, binding the depositor's bearer-token\n * `auth_anchor` preimage to this Pre-PegIn.\n */\n authAnchorHash?: string;\n}\n\n/**\n * Byte length of an `auth_anchor_hash` commitment when encoded as a\n * lowercase hex string (32 bytes → 64 hex chars).\n */\nconst AUTH_ANCHOR_HASH_HEX_LEN = 64;\n\nconst HEX_PATTERN = /^[0-9a-fA-F]+$/;\n\n/**\n * Result of building an unfunded Pre-PegIn transaction\n */\nexport interface PrePeginPsbtResult {\n /**\n * Unfunded transaction hex (no inputs, HTLC outputs + optional\n * auth-anchor OP_RETURN + CPFP anchor).\n *\n * The caller is responsible for:\n * - Selecting UTXOs covering totalOutputValue + network fees\n * - Funding the transaction (add inputs and change output)\n * - Calling buildPeginTxFromFundedPrePegin() with the funded tx hex\n */\n psbtHex: string;\n /** Sum of all unfunded outputs — use this for UTXO selection */\n totalOutputValue: bigint;\n /** HTLC output values in satoshis, one per deposit (each includes peginAmount + depositorClaimValue + minPeginFee) */\n htlcValues: readonly bigint[];\n /** HTLC output scriptPubKeys (hex encoded), one per deposit */\n htlcScriptPubKeys: readonly string[];\n /** HTLC Taproot addresses, one per deposit */\n htlcAddresses: readonly string[];\n /** Pegin amounts in satoshis, one per deposit */\n peginAmounts: readonly bigint[];\n /** Depositor claim value computed by WASM from contract parameters */\n depositorClaimValue: bigint;\n /**\n * Vout index of the auth-anchor `OP_RETURN` output if one was\n * included (i.e. `authAnchorHash` was provided), or `null` if not.\n * Always equals `htlcValues.length` when present.\n */\n authAnchorVout: number | null;\n}\n\n/**\n * Parameters for building the PegIn transaction from a funded Pre-PegIn tx\n */\nexport interface BuildPeginTxParams {\n /** Same PrePeginParams used to create the Pre-PegIn transaction */\n prePeginParams: PrePeginParams;\n /** CSV timelock in blocks for the PegIn vault output */\n timelockPegin: number;\n /** Hex-encoded funded Pre-PegIn transaction */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output to spend */\n htlcVout: number;\n}\n\n/**\n * Result of building the PegIn transaction\n */\nexport interface PeginTxResult {\n /** PegIn transaction hex (1 input spending HTLC, 1 vault output) */\n txHex: string;\n /** PegIn transaction ID */\n txid: string;\n /** Vault output scriptPubKey (hex encoded) */\n vaultScriptPubKey: string;\n /** Vault output value in satoshis */\n vaultValue: bigint;\n}\n\n/**\n * Build unfunded Pre-PegIn transaction using WASM.\n *\n * Creates a Bitcoin transaction template with no inputs, an HTLC output, and a\n * CPFP anchor output. The HTLC value is computed internally from the contract\n * parameters — the caller does not need to compute depositorClaimValue separately.\n *\n * @param params - Pre-PegIn parameters\n * @returns Unfunded Pre-PegIn transaction details with HTLC output information\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPrePeginPsbt(\n params: PrePeginParams,\n): Promise<PrePeginPsbtResult> {\n const authAnchorHash = normalizeAuthAnchorHash(params.authAnchorHash);\n\n const result = await createPrePeginTransaction({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlocks: [...params.hashlocks],\n timelockRefund: params.timelockRefund,\n pegInAmounts: [...params.pegInAmounts],\n feeRate: params.feeRate,\n numLocalChallengers: params.numLocalChallengers,\n councilQuorum: params.councilQuorum,\n councilSize: params.councilSize,\n network: params.network,\n authAnchorHash,\n });\n\n // Parse the unfunded tx to sum all output values\n // (HTLCs + optional OP_RETURN + CPFP anchor). This is the amount\n // UTXOs must cover before adding network fees.\n const parsed = parseUnfundedWasmTransaction(result.txHex);\n const totalOutputValue = parsed.outputs.reduce(\n (sum, o) => sum + BigInt(o.value),\n 0n,\n );\n\n // The WASM places the OP_RETURN commitment immediately after the\n // HTLC outputs when authAnchorHash is provided.\n const authAnchorVout =\n authAnchorHash !== undefined ? result.htlcValues.length : null;\n\n return {\n psbtHex: result.txHex,\n totalOutputValue,\n htlcValues: result.htlcValues,\n htlcScriptPubKeys: result.htlcScriptPubKeys,\n htlcAddresses: result.htlcAddresses,\n peginAmounts: result.peginAmounts,\n depositorClaimValue: result.depositorClaimValue,\n authAnchorVout,\n };\n}\n\n/**\n * Validate and normalize an `authAnchorHash` hex string before passing\n * it to the WASM boundary. WASM expects exactly 64 lowercase hex chars.\n */\nfunction normalizeAuthAnchorHash(\n value: string | undefined,\n): string | undefined {\n if (value === undefined) return undefined;\n const cleaned =\n value.startsWith(\"0x\") || value.startsWith(\"0X\") ? value.slice(2) : value;\n if (\n cleaned.length !== AUTH_ANCHOR_HASH_HEX_LEN ||\n !HEX_PATTERN.test(cleaned)\n ) {\n throw new Error(\n `authAnchorHash must be 32-byte hex (${AUTH_ANCHOR_HASH_HEX_LEN} chars, no 0x prefix); got length ${cleaned.length}`,\n );\n }\n return cleaned.toLowerCase();\n}\n\n/**\n * Build the PegIn transaction from a funded Pre-PegIn transaction.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output at htlcVout via the\n * hashlock + all-party script (leaf 0).\n *\n * @param params - Build parameters including Pre-PegIn params and funded tx hex\n * @returns PegIn transaction details\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPeginTxFromFundedPrePegin(\n params: BuildPeginTxParams,\n): Promise<PeginTxResult> {\n // WASM reconstructs the Pre-PegIn template from these params to\n // decode the funded tx. Must pass `authAnchorHash` (normalized\n // identically to buildPrePeginPsbt) so the reconstruction matches\n // the original outputs, including the OP_RETURN at vout =\n // hashlocks.length.\n const result = await buildPeginTxFromPrePegin(\n {\n depositorPubkey: params.prePeginParams.depositorPubkey,\n vaultProviderPubkey: params.prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: params.prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys:\n params.prePeginParams.universalChallengerPubkeys,\n hashlocks: [...params.prePeginParams.hashlocks],\n timelockRefund: params.prePeginParams.timelockRefund,\n pegInAmounts: [...params.prePeginParams.pegInAmounts],\n feeRate: params.prePeginParams.feeRate,\n numLocalChallengers: params.prePeginParams.numLocalChallengers,\n councilQuorum: params.prePeginParams.councilQuorum,\n councilSize: params.prePeginParams.councilSize,\n network: params.prePeginParams.network,\n authAnchorHash: normalizeAuthAnchorHash(\n params.prePeginParams.authAnchorHash,\n ),\n },\n params.timelockPegin,\n params.fundedPrePeginTxHex,\n params.htlcVout,\n );\n\n return {\n txHex: result.txHex,\n txid: result.txid,\n vaultScriptPubKey: result.vaultScriptPubKey,\n vaultValue: result.vaultValue,\n };\n}\n","/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, stripHexPrefix, uint8ArrayToHex } from \"../utils/bitcoin\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const hashlockScript = hexToUint8Array(htlcConnector.hashlockScript);\n const hashlockControlBlock = hexToUint8Array(htlcConnector.hashlockControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hashlockScript),\n controlBlock: Buffer.from(hashlockControlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports both non-finalized PSBTs (tapScriptSig) and finalized PSBTs (witness).\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(\n hexToUint8Array(depositorPubkey),\n );\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present.\n * Accepts 64-byte sigs (implicit SIGHASH_DEFAULT) and 65-byte sigs with\n * SIGHASH_ALL (0x01). Rejects all other sighash types including 0x00, which\n * is consensus-invalid per BIP-342 when explicitly appended.\n * @internal\n */\nexport function extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n const sighashByte = sig[64];\n // Only accept SIGHASH_ALL (0x01). Per BIP-342, SIGHASH_DEFAULT is signaled\n // by omitting the sighash byte (64-byte sig). A 65-byte sig with byte 64\n // set to 0x00 is consensus-invalid: Bitcoin Core rejects it with\n // SCRIPT_ERR_SCHNORR_SIG_HASHTYPE. Accepting 0x00 here would let\n // extractPeginInputSignature succeed (stripping the byte) while\n // finalizePeginInputPsbt passes the raw 65-byte sig into the witness,\n // producing a BTC transaction that can never confirm.\n if (sighashByte !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Unexpected sighash type 0x${sighashByte.toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n `Expected SIGHASH_DEFAULT (64-byte sig) or SIGHASH_ALL (0x01).`,\n );\n }\n return uint8ArrayToHex(new Uint8Array(sig.subarray(0, 64)));\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n\n","/**\n * Protocol invariants for depositor graph transactions.\n *\n * These indices and counts encode the on-chain vault protocol layout\n * (which output of PegIn/Assert each child transaction spends, and how\n * many inputs each transaction has). Consumed by the PSBT builders and\n * the depositor graph signing service; a drift between copies of these\n * values would silently change validation behaviour.\n *\n * @module primitives/psbt/constants\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md\n */\n\n/**\n * Depositor Payout transaction input count.\n * Input 0: PegIn:0 (signed). Input 1: Assert:0 (in sighash, not signed).\n */\nexport const DEPOSITOR_PAYOUT_INPUT_COUNT = 2;\n\n/** PegIn vault output index spent by the depositor's Payout input 0. */\nexport const PEGIN_VAULT_OUTPUT_INDEX = 0;\n\n/** Payout input index bound to the graph Assert tx (NOT signed). */\nexport const PAYOUT_ASSERT_INPUT_INDEX = 1;\n\n/** Assert output index spent by the depositor's Payout input 1 (NOT signed). */\nexport const ASSERT_PAYOUT_OUTPUT_INDEX = 0;\n\n/** Assert output index spent by NoPayout input 0 (signed). */\nexport const ASSERT_NOPAYOUT_OUTPUT_INDEX = 0;\n","/**\n * Depositor Payout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's own Payout transaction\n * (depositor-as-claimer path). The depositor signs input 0 using the\n * payout taproot script from WasmPeginPayoutConnector (PegIn vault UTXO).\n *\n * Input 0 spends PegIn:0 (the vault UTXO) — the same connector used for\n * VP/VK payout signing. The VP verifies this signature using the\n * PeginPayoutConnector's payout script.\n *\n * @module primitives/psbt/depositorPayout\n * @see btc-vault crates/vault/src/sign.rs — verify_depositor_signature / get_payout_tap_leaf_hash\n */\n\nimport {\n type PayoutConnectorParams,\n getPeginPayoutScriptInfo,\n tapInternalPubkey,\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 hexToUint8Array,\n inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\nimport {\n ASSERT_PAYOUT_OUTPUT_INDEX,\n DEPOSITOR_PAYOUT_INPUT_COUNT,\n PEGIN_VAULT_OUTPUT_INDEX,\n} from \"./constants\";\n\n/**\n * Parameters for building a depositor Payout PSBT\n */\nexport interface DepositorPayoutParams {\n /** Payout transaction hex (unsigned) */\n payoutTxHex: string;\n /** Authoritative PegIn transaction hex — input 0 must spend PegIn:0 */\n peginTxHex: string;\n /** Authoritative Assert transaction hex — input 1 must spend Assert:0 */\n assertTxHex: string;\n /** Parameters for the PeginPayout connector (depositor, VP, VKs, UCs, timelock) */\n connectorParams: PayoutConnectorParams;\n}\n\n/**\n * Build unsigned depositor Payout PSBT.\n *\n * The depositor's payout transaction has 2 inputs:\n * - Input 0: PegIn:0 (vault UTXO) — depositor signs using PeginPayoutConnector payout script\n * - Input 1: Assert:0 — NOT signed by depositor\n *\n * Both inputs must be present in the PSBT because Taproot SIGHASH_DEFAULT\n * commits to all input prevouts. Prevout script_pubkey/value are derived\n * from the authoritative parent transactions, not trusted from external input.\n *\n * @param params - Depositor payout parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not reference peginTxHex at output index 0\n * @throws If input 1 does not reference assertTxHex at output index 0\n */\nexport async function buildDepositorPayoutPsbt(\n params: DepositorPayoutParams,\n): Promise<string> {\n const payoutTx = Transaction.fromHex(stripHexPrefix(params.payoutTxHex));\n const peginTx = Transaction.fromHex(stripHexPrefix(params.peginTxHex));\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n\n if (payoutTx.ins.length !== DEPOSITOR_PAYOUT_INPUT_COUNT) {\n throw new Error(\n `Depositor Payout transaction must have exactly ${DEPOSITOR_PAYOUT_INPUT_COUNT} inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n const input0Txid = inputTxidHex(input0);\n const peginTxid = peginTx.getId();\n if (input0Txid !== peginTxid || input0.index !== PEGIN_VAULT_OUTPUT_INDEX) {\n throw new Error(\n `Depositor Payout input 0 must spend PegIn:${PEGIN_VAULT_OUTPUT_INDEX}. ` +\n `Expected ${peginTxid}:${PEGIN_VAULT_OUTPUT_INDEX}, got ${input0Txid}:${input0.index}`,\n );\n }\n\n const input1Txid = inputTxidHex(input1);\n const assertTxid = assertTx.getId();\n if (input1Txid !== assertTxid || input1.index !== ASSERT_PAYOUT_OUTPUT_INDEX) {\n throw new Error(\n `Depositor Payout input 1 must spend Assert:${ASSERT_PAYOUT_OUTPUT_INDEX}. ` +\n `Expected ${assertTxid}:${ASSERT_PAYOUT_OUTPUT_INDEX}, got ${input1Txid}:${input1.index}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n const assertPrevOut = assertTx.outs[input1.index];\n\n const { payoutScript, payoutControlBlock } = await getPeginPayoutScriptInfo(\n params.connectorParams,\n );\n const scriptBytes = hexToUint8Array(payoutScript);\n const controlBlock = hexToUint8Array(payoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n });\n\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n","/**\n * ChallengeAssert PSBT Builder\n *\n * Builds an unsigned PSBT for a ChallengeAssert transaction\n * (depositor-as-claimer path, per challenger). The ChallengeAssert tx has\n * NUM_UTXOS_FOR_CHALLENGE_ASSERT (3) inputs, each spending a different Assert\n * output segment. The depositor signs ALL inputs, each with its own taproot\n * script derived from the per-segment connector params.\n *\n * @module primitives/psbt/challengeAssert\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — ChallengeAssert connector (NUM_UTXOS_FOR_CHALLENGE_ASSERT=3)\n */\n\nimport {\n type ChallengeAssertConnectorParams,\n getChallengeAssertScriptInfo,\n tapInternalPubkey,\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 hexToUint8Array,\n inputTxidHex,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a ChallengeAssert PSBT\n */\nexport interface ChallengeAssertParams {\n /** ChallengeAssert transaction hex (unsigned) */\n challengeAssertTxHex: string;\n /** Authoritative Assert transaction hex — every input must spend an Assert output */\n assertTxHex: string;\n /** Per-input connector params (one per input/segment, determines the taproot script) */\n connectorParamsPerInput: ChallengeAssertConnectorParams[];\n}\n\n/**\n * Build unsigned ChallengeAssert PSBT.\n *\n * The ChallengeAssert transaction has 3 inputs (one per Assert output segment).\n * Each input has its own taproot script derived from its connector params.\n * The depositor signs all inputs. Every prevout is derived from the\n * authoritative Assert transaction, never trusted from external input.\n *\n * @param params - ChallengeAssert parameters\n * @returns Unsigned PSBT hex ready for signing\n *\n * @throws If the number of connector params does not match the number of inputs\n * @throws If any input does not reference assertTxHex\n * @throws If any referenced Assert output is missing\n * @throws If two inputs reference the same Assert output index\n */\nexport async function buildChallengeAssertPsbt(\n params: ChallengeAssertParams,\n): Promise<string> {\n const challengeAssertTx = Transaction.fromHex(\n stripHexPrefix(params.challengeAssertTxHex),\n );\n const assertTx = Transaction.fromHex(stripHexPrefix(params.assertTxHex));\n const assertTxid = assertTx.getId();\n\n if (params.connectorParamsPerInput.length !== challengeAssertTx.ins.length) {\n throw new Error(\n `Expected ${challengeAssertTx.ins.length} connector params, got ${params.connectorParamsPerInput.length}`,\n );\n }\n\n const seenAssertOutputs = new Set<number>();\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const inputTxid = inputTxidHex(input);\n if (inputTxid !== assertTxid) {\n throw new Error(\n `ChallengeAssert input ${i} must spend an Assert output. ` +\n `Expected txid ${assertTxid}, got ${inputTxid}`,\n );\n }\n if (!assertTx.outs[input.index]) {\n throw new Error(\n `Assert output ${input.index} not found for ChallengeAssert input ${i} (txid: ${assertTxid})`,\n );\n }\n if (seenAssertOutputs.has(input.index)) {\n throw new Error(\n `ChallengeAssert input ${i} duplicates Assert output index ${input.index}`,\n );\n }\n seenAssertOutputs.add(input.index);\n }\n\n const scriptInfos = await Promise.all(\n params.connectorParamsPerInput.map((cp) => getChallengeAssertScriptInfo(cp)),\n );\n\n const psbt = new Psbt();\n psbt.setVersion(challengeAssertTx.version);\n psbt.setLocktime(challengeAssertTx.locktime);\n\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const assertPrevOut = assertTx.outs[input.index];\n\n const { script, controlBlock } = scriptInfos[i];\n const scriptBytes = hexToUint8Array(script);\n const controlBlockBytes = hexToUint8Array(controlBlock);\n\n psbt.addInput({\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: assertPrevOut.script,\n value: assertPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n }\n\n for (const output of challengeAssertTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n"],"names":["normalizeKey","key","processPublicKeyToXOnly","computeNumLocalChallengers","vaultProviderPubkey","vaultKeeperPubkeys","depositorPubkey","localSet","vk","AUTH_ANCHOR_HASH_HEX_LEN","HEX_PATTERN","buildPrePeginPsbt","params","authAnchorHash","normalizeAuthAnchorHash","result","createPrePeginTransaction","totalOutputValue","parseUnfundedWasmTransaction","sum","o","authAnchorVout","value","cleaned","buildPeginTxFromFundedPrePegin","buildPeginTxFromPrePegin","buildPeginInputPsbt","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","hashlockScript","hexToUint8Array","hashlockControlBlock","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","sighashByte","DEPOSITOR_PAYOUT_INPUT_COUNT","PEGIN_VAULT_OUTPUT_INDEX","ASSERT_PAYOUT_OUTPUT_INDEX","buildDepositorPayoutPsbt","payoutTx","assertTx","input0","input1","input0Txid","inputTxidHex","peginTxid","input1Txid","assertTxid","peginPrevOut","assertPrevOut","payoutScript","payoutControlBlock","getPeginPayoutScriptInfo","scriptBytes","controlBlock","buildChallengeAssertPsbt","challengeAssertTx","seenAssertOutputs","i","inputTxid","scriptInfos","cp","getChallengeAssertScriptInfo","script","controlBlockBytes"],"mappings":"0MAeA,SAASA,EAAaC,EAAqB,CACzC,OAAOC,EAAAA,wBAAwBD,CAAG,EAAE,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B,IAAI/B,EAAM,KAAK,EACnC,MAAM,IAAI,MACR,yBAAyBgC,CAAC,mCAAmChC,EAAM,KAAK,EAAA,EAG5E+B,EAAkB,IAAI/B,EAAM,KAAK,CACnC,CAEA,MAAMkC,EAAc,MAAM,QAAQ,IAChCzE,EAAO,wBAAwB,IAAK0E,GAAOC,EAAAA,6BAA6BD,CAAE,CAAC,CAAA,EAGvE3C,EAAO,IAAIC,OACjBD,EAAK,WAAWsC,EAAkB,OAAO,EACzCtC,EAAK,YAAYsC,EAAkB,QAAQ,EAE3C,QAASE,EAAI,EAAGA,EAAIF,EAAkB,IAAI,OAAQE,IAAK,CACrD,MAAMhC,EAAQ8B,EAAkB,IAAIE,CAAC,EAC/BT,EAAgBT,EAAS,KAAKd,EAAM,KAAK,EAEzC,CAAE,OAAAqC,EAAQ,aAAAT,GAAiBM,EAAYF,CAAC,EACxCL,EAAcrC,EAAAA,gBAAgB+C,CAAM,EACpCC,EAAoBhD,EAAAA,gBAAgBsC,CAAY,EAEtDpC,EAAK,SAAS,CACZ,KAAMQ,EAAM,KACZ,MAAOA,EAAM,MACb,SAAUA,EAAM,SAChB,YAAa,CACX,OAAQuB,EAAc,OACtB,MAAOA,EAAc,KAAA,EAEvB,cAAe,CACb,CACE,YAAa7B,EAAAA,uBACb,OAAQC,EAAAA,OAAO,KAAKgC,CAAW,EAC/B,aAAchC,EAAAA,OAAO,KAAK2C,CAAiB,CAAA,CAC7C,EAEF,eAAgB3C,EAAAA,OAAO,KAAKC,EAAAA,iBAAiB,CAAA,CAC9C,CACH,CAEA,UAAWC,KAAUiC,EAAkB,KACrCtC,EAAK,UAAU,CACb,OAAQK,EAAO,OACf,MAAOA,EAAO,KAAA,CACf,EAGH,OAAOL,EAAK,MAAA,CACd"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./challengeAssert-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./challengeAssert-DuhkzZG-.cjs"),P=require("@babylonlabs-io/babylon-tbv-rust-wasm"),u=require("./noPayout-CDhbGn_B.cjs"),o=require("./bitcoin-EYBKDtEW.cjs"),l=require("./signing-DHSXjhLM.cjs"),d=require("./validation-u8W7Lp2x.cjs"),e=require("./buildAndBroadcastRefund-CIHhUmRv.cjs"),c=require("./shared/index.cjs"),a=require("./fundPeginTransaction-DaWoYCgO.cjs"),i=require("./psbtInputFields-BLi7Ta-T.cjs"),r=require("./PeginManager-CTRPJo8m.cjs"),t=require("./vault-registry-reader-BBS1_AON.cjs"),s=require("./types-jmEyzzhY.cjs");exports.buildChallengeAssertPsbt=n.buildChallengeAssertPsbt;exports.buildDepositorPayoutPsbt=n.buildDepositorPayoutPsbt;exports.buildPeginInputPsbt=n.buildPeginInputPsbt;exports.buildPeginTxFromFundedPrePegin=n.buildPeginTxFromFundedPrePegin;exports.buildPrePeginPsbt=n.buildPrePeginPsbt;exports.computeNumLocalChallengers=n.computeNumLocalChallengers;exports.extractPeginInputSignature=n.extractPeginInputSignature;exports.finalizePeginInputPsbt=n.finalizePeginInputPsbt;Object.defineProperty(exports,"computeMinClaimValue",{enumerable:!0,get:()=>P.computeMinClaimValue});Object.defineProperty(exports,"deriveVaultId",{enumerable:!0,get:()=>P.deriveVaultId});exports.assertPayoutOutputMatchesRegistered=u.assertPayoutOutputMatchesRegistered;exports.buildNoPayoutPsbt=u.buildNoPayoutPsbt;exports.buildPayoutPsbt=u.buildPayoutPsbt;exports.buildRefundPsbt=u.buildRefundPsbt;exports.createPayoutScript=u.createPayoutScript;exports.extractPayoutSignature=u.extractPayoutSignature;exports.deriveNativeSegwitAddress=o.deriveNativeSegwitAddress;exports.deriveTaprootAddress=o.deriveTaprootAddress;exports.ensureHexPrefix=o.ensureHexPrefix;exports.formatSatoshisToBtc=o.formatSatoshisToBtc;exports.getNetwork=o.getNetwork;exports.hexToUint8Array=o.hexToUint8Array;exports.isAddressFromPublicKey=o.isAddressFromPublicKey;exports.isValidHex=o.isValidHex;exports.processPublicKeyToXOnly=o.processPublicKeyToXOnly;exports.stripHexPrefix=o.stripHexPrefix;exports.toXOnly=o.toXOnly;exports.uint8ArrayToHex=o.uint8ArrayToHex;exports.validateWalletPubkey=o.validateWalletPubkey;exports.ContractStatus=l.ContractStatus;exports.PeginAction=l.PeginAction;exports.canPerformAction=l.canPerformAction;exports.createTaprootScriptPathSignOptions=l.createTaprootScriptPathSignOptions;exports.getPeginProtocolState=l.getPeginProtocolState;exports.BITCOIN_ADDRESS_RE=d.BITCOIN_ADDRESS_RE;exports.HEX_RE=d.HEX_RE;exports.KNOWN_SCRIPT_PREFIXES=d.KNOWN_SCRIPT_PREFIXES;exports.MAX_REASONABLE_FEE_SATS=d.MAX_REASONABLE_FEE_SATS;exports.TXID_RE=d.TXID_RE;exports.BIP68NotMatureError=e.BIP68NotMatureError;exports.ClaimerPegoutStatusValue=e.ClaimerPegoutStatusValue;exports.PayoutManager=e.PayoutManager;exports.REFUND_VSIZE=e.REFUND_VSIZE;exports.activateVault=e.activateVault;exports.buildAndBroadcastRefund=e.buildAndBroadcastRefund;exports.computeHashlock=e.computeHashlock;exports.estimateRefundFeeSats=e.estimateRefundFeeSats;exports.isDepositAmountValid=e.isDepositAmountValid;exports.isPegoutTerminalStatus=e.isPegoutTerminalStatus;exports.isRecognizedPegoutStatus=e.isRecognizedPegoutStatus;exports.pollAndSignPayouts=e.pollAndSignPayouts;exports.signDepositorGraph=e.signDepositorGraph;exports.submitWotsPublicKey=e.submitWotsPublicKey;exports.validateDepositAmount=e.validateDepositAmount;exports.validateMultiVaultDepositInputs=e.validateMultiVaultDepositInputs;exports.validateProviderSelection=e.validateProviderSelection;exports.validateRemainingCapacity=e.validateRemainingCapacity;exports.validateSecretAgainstHashlock=e.validateSecretAgainstHashlock;exports.validateVaultAmounts=e.validateVaultAmounts;exports.validateVaultProviderPubkey=e.validateVaultProviderPubkey;exports.waitForPeginStatus=e.waitForPeginStatus;exports.BitcoinNetworks=c.BitcoinNetworks;exports.BTC_DUST_SAT=a.BTC_DUST_SAT;exports.DUST_THRESHOLD=a.DUST_THRESHOLD;exports.FEE_SAFETY_MARGIN=a.FEE_SAFETY_MARGIN;exports.LOW_RATE_ESTIMATION_ACCURACY_BUFFER=a.LOW_RATE_ESTIMATION_ACCURACY_BUFFER;exports.MAX_NON_LEGACY_OUTPUT_SIZE=a.MAX_NON_LEGACY_OUTPUT_SIZE;exports.P2TR_INPUT_SIZE=a.P2TR_INPUT_SIZE;exports.PEGIN_AUTH_ANCHOR_OUTPUTS=a.PEGIN_AUTH_ANCHOR_OUTPUTS;exports.PEGIN_FIXED_OUTPUTS=a.PEGIN_FIXED_OUTPUTS;exports.SPLIT_TX_FEE_SAFETY_MULTIPLIER=a.SPLIT_TX_FEE_SAFETY_MULTIPLIER;exports.TX_BUFFER_SIZE_OVERHEAD=a.TX_BUFFER_SIZE_OVERHEAD;exports.WALLET_RELAY_FEE_RATE_THRESHOLD=a.WALLET_RELAY_FEE_RATE_THRESHOLD;exports.fundPeginTransaction=a.fundPeginTransaction;exports.parseUnfundedWasmTransaction=a.parseUnfundedWasmTransaction;exports.peginOutputCount=a.peginOutputCount;exports.rateBasedTxBufferFee=a.rateBasedTxBufferFee;exports.BitcoinScriptType=i.BitcoinScriptType;exports.UtxoNotAvailableError=i.UtxoNotAvailableError;exports.assertUtxosAvailable=i.assertUtxosAvailable;exports.calculateBtcTxHash=i.calculateBtcTxHash;exports.collectReservedUtxoRefs=i.collectReservedUtxoRefs;exports.extractInputsFromTransaction=i.extractInputsFromTransaction;exports.getDustThreshold=i.getDustThreshold;exports.getPsbtInputFields=i.getPsbtInputFields;exports.getScriptType=i.getScriptType;exports.selectUtxosForDeposit=i.selectUtxosForDeposit;exports.selectUtxosForPegin=i.selectUtxosForPegin;exports.shouldAddChangeOutput=i.shouldAddChangeOutput;exports.validateUtxosAvailable=i.validateUtxosAvailable;exports.CONTRACT_ERRORS=r.CONTRACT_ERRORS;exports.PeginManager=r.PeginManager;exports.VAULT_APP_NAME=r.VAULT_APP_NAME;exports.buildFundingOutpointsCommitment=r.buildFundingOutpointsCommitment;exports.buildVaultContext=r.buildVaultContext;exports.computeWotsBlockPublicKeysHash=r.computeWotsBlockPublicKeysHash;exports.deriveVaultRoot=r.deriveVaultRoot;exports.deriveWotsBlocksFromSeed=r.deriveWotsBlocksFromSeed;exports.expandAuthAnchor=r.expandAuthAnchor;exports.expandHashlockSecret=r.expandHashlockSecret;exports.expandWotsSeed=r.expandWotsSeed;exports.extractErrorData=r.extractErrorData;exports.getContractErrorMessage=r.getContractErrorMessage;exports.handleContractError=r.handleContractError;exports.isKnownContractError=r.isKnownContractError;exports.isWotsMismatchError=r.isWotsMismatchError;exports.ApplicationRegistryABI=t.ApplicationRegistryABI;exports.MEMPOOL_API_URLS=t.MEMPOOL_API_URLS;exports.ProtocolParamsABI=t.ProtocolParamsABI;exports.ServerIdentityError=t.ServerIdentityError;exports.VaultProviderRpcClient=t.VaultProviderRpcClient;exports.ViemProtocolParamsReader=t.ViemProtocolParamsReader;exports.ViemUniversalChallengerReader=t.ViemUniversalChallengerReader;exports.ViemVaultKeeperReader=t.ViemVaultKeeperReader;exports.ViemVaultRegistryReader=t.ViemVaultRegistryReader;exports.VpResponseValidationError=t.VpResponseValidationError;exports.VpTokenProvider=t.VpTokenProvider;exports.getAddressTxs=t.getAddressTxs;exports.getAddressUtxos=t.getAddressUtxos;exports.getMempoolApiUrl=t.getMempoolApiUrl;exports.getNetworkFees=t.getNetworkFees;exports.getTxHex=t.getTxHex;exports.getTxInfo=t.getTxInfo;exports.getUtxoInfo=t.getUtxoInfo;exports.pushTx=t.pushTx;exports.resolveProtocolAddresses=t.resolveProtocolAddresses;exports.validateRequestDepositorClaimerArtifactsResponse=t.validateRequestDepositorClaimerArtifactsResponse;exports.verifyServerIdentity=t.verifyServerIdentity;exports.BTCVaultRegistryABI=s.BTCVaultRegistryABI;exports.DaemonStatus=s.DaemonStatus;exports.JSON_RPC_ERROR_CODES=s.JSON_RPC_ERROR_CODES;exports.JsonRpcClient=s.JsonRpcClient;exports.JsonRpcError=s.JsonRpcError;exports.POST_WOTS_STATUSES=s.POST_WOTS_STATUSES;exports.PRE_DEPOSITOR_SIGNATURES_STATES=s.PRE_DEPOSITOR_SIGNATURES_STATES;exports.RpcErrorCode=s.RpcErrorCode;exports.VP_TERMINAL_STATUSES=s.VP_TERMINAL_STATUSES;exports.VP_TRANSIENT_STATUSES=s.VP_TRANSIENT_STATUSES;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import { h as e, g as t, d as r, a as o, b as i, c as n, e as l, f as u } from "./challengeAssert-
|
|
1
|
+
import { h as e, g as t, d as r, a as o, b as i, c as n, e as l, f as u } from "./challengeAssert-DSlCIBoT.js";
|
|
2
2
|
import { computeMinClaimValue as P, deriveVaultId as c } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
3
|
-
import { a as p, d as S, c as E, b as A, f as R, e as _ } from "./noPayout-
|
|
4
|
-
import { d as m, a as x, e as b, f as I, g as f, h as v, i as C, b as U, p as O, s as V, t as h, u as N, v as y } from "./bitcoin-
|
|
3
|
+
import { a as p, d as S, c as E, b as A, f as R, e as _ } from "./noPayout-DohtepqZ.js";
|
|
4
|
+
import { d as m, a as x, e as b, f as I, g as f, h as v, i as C, b as U, p as O, s as V, t as h, u as N, v as y } from "./bitcoin-0_T6KJON.js";
|
|
5
5
|
import { C as B, P as D, a as M, c as H, g as L } from "./signing-BZigafm0.js";
|
|
6
6
|
import { B as W, H as X, K, M as w, T as G } from "./validation-CxqROCno.js";
|
|
7
|
-
import { B as J, C as Z, P as j, R as z, a as q, m as Q, h as $, n as aa, i as sa, l as ea, k as ta, p as ra, b as oa, s as ia, v as na, g as la, d as ua, c as da, j as Pa, e as ca, f as Ta, w as pa } from "./buildAndBroadcastRefund-
|
|
7
|
+
import { B as J, C as Z, P as j, R as z, a as q, m as Q, h as $, n as aa, i as sa, l as ea, k as ta, p as ra, b as oa, s as ia, v as na, g as la, d as ua, c as da, j as Pa, e as ca, f as Ta, w as pa } from "./buildAndBroadcastRefund-DwrX_IBf.js";
|
|
8
8
|
import { BitcoinNetworks as Ea } from "./shared/index.js";
|
|
9
9
|
import { B as Ra, D as _a, F as ga, L as ma, M as xa, P as ba, b as Ia, a as fa, S as va, T as Ca, W as Ua, f as Oa, c as Va, p as ha, r as Na } from "./fundPeginTransaction-oV-dNJOU.js";
|
|
10
|
-
import { B as Fa, U as Ba, a as Da, f as Ma, c as Ha, e as La, g as ka, i as Wa, h as Xa, s as Ka, b as wa, d as Ga, v as Ya } from "./psbtInputFields-
|
|
11
|
-
import { C as Za, P as ja, V as za, k as qa, l as Qa, c as $a, m as as, d as ss, b as es, f as ts, j as rs, e as os, g as is, h as ns, i as ls, a as us } from "./PeginManager-
|
|
12
|
-
import { A as Ps, M as cs, P as Ts, S as ps, V as Ss, k as Es, l as As, m as Rs, n as _s, h as gs, j as ms, g as xs, a as bs, b as Is, c as fs, d as vs, e as Cs, f as Us, p as Os, r as Vs, v as hs, i as Ns } from "./vault-registry-reader-
|
|
10
|
+
import { B as Fa, U as Ba, a as Da, f as Ma, c as Ha, e as La, g as ka, i as Wa, h as Xa, s as Ka, b as wa, d as Ga, v as Ya } from "./psbtInputFields-DPCFHgGd.js";
|
|
11
|
+
import { C as Za, P as ja, V as za, k as qa, l as Qa, c as $a, m as as, d as ss, b as es, f as ts, j as rs, e as os, g as is, h as ns, i as ls, a as us } from "./PeginManager-DUR1BTKM.js";
|
|
12
|
+
import { A as Ps, M as cs, P as Ts, S as ps, V as Ss, k as Es, l as As, m as Rs, n as _s, h as gs, j as ms, g as xs, a as bs, b as Is, c as fs, d as vs, e as Cs, f as Us, p as Os, r as Vs, v as hs, i as Ns } from "./vault-registry-reader-CG6bea1S.js";
|
|
13
13
|
import { B as Fs, D as Bs, b as Ds, J as Ms, a as Hs, d as Ls, P as ks, R as Ws, c as Xs, V as Ks } from "./types-CnG3JsRs.js";
|
|
14
14
|
export {
|
|
15
15
|
Ps as ApplicationRegistryABI,
|