@babylonlabs-io/ts-sdk 0.39.2 → 0.39.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{PayoutManager-D29D-K-V.js → PayoutManager-2XpjdLxE.js} +75 -97
- package/dist/PayoutManager-2XpjdLxE.js.map +1 -0
- package/dist/PayoutManager-DnKRzWWb.cjs +2 -0
- package/dist/PayoutManager-DnKRzWWb.cjs.map +1 -0
- package/dist/{PeginManager-DXrfY4d6.js → PeginManager-CBQnWvX8.js} +3 -3
- package/dist/{PeginManager-DXrfY4d6.js.map → PeginManager-CBQnWvX8.js.map} +1 -1
- package/dist/{PeginManager-zkTJOy_U.cjs → PeginManager-CPw28lAE.cjs} +2 -2
- package/dist/{PeginManager-zkTJOy_U.cjs.map → PeginManager-CPw28lAE.cjs.map} +1 -1
- package/dist/assertPsbtUnsignedTxMatches-CsawQGjC.js +402 -0
- package/dist/assertPsbtUnsignedTxMatches-CsawQGjC.js.map +1 -0
- package/dist/assertPsbtUnsignedTxMatches-u9yeeUFY.cjs +2 -0
- package/dist/assertPsbtUnsignedTxMatches-u9yeeUFY.cjs.map +1 -0
- package/dist/{buildAndBroadcastRefund-CjWAle7m.js → buildAndBroadcastRefund-BRMB7XyC.js} +254 -271
- package/dist/buildAndBroadcastRefund-BRMB7XyC.js.map +1 -0
- package/dist/buildAndBroadcastRefund-MoSpjUKJ.cjs +2 -0
- package/dist/buildAndBroadcastRefund-MoSpjUKJ.cjs.map +1 -0
- package/dist/{challengeAssert-CNRdpCzm.cjs → challengeAssert-BobHj1La.cjs} +2 -2
- package/dist/{challengeAssert-CNRdpCzm.cjs.map → challengeAssert-BobHj1La.cjs.map} +1 -1
- package/dist/{challengeAssert-CBp4mEs0.js → challengeAssert-D8-RwiDv.js} +7 -7
- package/dist/{challengeAssert-CBp4mEs0.js.map → challengeAssert-D8-RwiDv.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +172 -173
- package/dist/{noPayout-qbaSEKGC.js → noPayout-C5b34rs1.js} +2 -2
- package/dist/{noPayout-qbaSEKGC.js.map → noPayout-C5b34rs1.js.map} +1 -1
- package/dist/{noPayout-jtZsoOzY.cjs → noPayout-CtmOEauj.cjs} +2 -2
- package/dist/{noPayout-jtZsoOzY.cjs.map → noPayout-CtmOEauj.cjs.map} +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +174 -175
- package/dist/tbv/core/managers/PayoutManager.d.ts +9 -15
- package/dist/tbv/core/managers/PayoutManager.d.ts.map +1 -1
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +2 -2
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.d.ts +1 -1
- package/dist/tbv/core/primitives/index.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.js +19 -20
- package/dist/tbv/core/primitives/psbt/constants.d.ts +16 -0
- package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/noPayout.d.ts +3 -2
- package/dist/tbv/core/primitives/psbt/noPayout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/payout.d.ts +24 -15
- package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts +2 -0
- package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +2 -2
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +174 -175
- package/package.json +1 -1
- package/dist/PayoutManager-D29D-K-V.js.map +0 -1
- package/dist/PayoutManager-DERMRuUU.cjs +0 -2
- package/dist/PayoutManager-DERMRuUU.cjs.map +0 -1
- package/dist/assertPsbtUnsignedTxMatches-fNkAaZZm.cjs +0 -2
- package/dist/assertPsbtUnsignedTxMatches-fNkAaZZm.cjs.map +0 -1
- package/dist/assertPsbtUnsignedTxMatches-mTAnLhCz.js +0 -340
- package/dist/assertPsbtUnsignedTxMatches-mTAnLhCz.js.map +0 -1
- package/dist/buildAndBroadcastRefund-CjWAle7m.js.map +0 -1
- package/dist/buildAndBroadcastRefund-CzKOUR75.cjs +0 -2
- package/dist/buildAndBroadcastRefund-CzKOUR75.cjs.map +0 -1
|
@@ -1,90 +1,90 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var
|
|
1
|
+
var m = Object.defineProperty;
|
|
2
|
+
var v = (e, t, s) => t in e ? m(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s;
|
|
3
|
+
var g = (e, t, s) => v(e, typeof t != "symbol" ? t + "" : t, s);
|
|
4
4
|
import * as w from "bitcoinjs-lib";
|
|
5
|
-
import { s as
|
|
6
|
-
import { s as
|
|
7
|
-
import { c as
|
|
5
|
+
import { s as k, v as p } from "./bitcoin-B5aNKtsk.js";
|
|
6
|
+
import { s as E } from "./sha2-BYVxyZzX.js";
|
|
7
|
+
import { c as b } from "./signing-DaLvGwQe.js";
|
|
8
8
|
import "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
9
|
-
import {
|
|
10
|
-
const
|
|
11
|
-
function
|
|
12
|
-
const o =
|
|
13
|
-
if (
|
|
9
|
+
import { c as x, d as y, e as d } from "./assertPsbtUnsignedTxMatches-CsawQGjC.js";
|
|
10
|
+
const H = 106, B = 32, l = 34;
|
|
11
|
+
function W(e, t, s) {
|
|
12
|
+
const o = k(e), c = w.Transaction.fromHex(o);
|
|
13
|
+
if (c.outs.length <= t)
|
|
14
14
|
throw new Error(
|
|
15
|
-
`Pre-PegIn auth-anchor OP_RETURN missing: tx has ${
|
|
15
|
+
`Pre-PegIn auth-anchor OP_RETURN missing: tx has ${c.outs.length} outputs, expected at least ${t + 1} (vault outputs + OP_RETURN)`
|
|
16
16
|
);
|
|
17
|
-
const n =
|
|
18
|
-
if (i.length !== l || i[0] !==
|
|
17
|
+
const n = c.outs[t], i = n.script;
|
|
18
|
+
if (i.length !== l || i[0] !== H || i[1] !== B)
|
|
19
19
|
throw new Error(
|
|
20
20
|
`Pre-PegIn auth-anchor OP_RETURN at vout ${t} has unexpected script encoding (got ${i.length}-byte script with prefix 0x${i.slice(0, Math.min(2, i.length)).toString("hex")}; expected ${l}-byte OP_RETURN + PUSH32 layout)`
|
|
21
21
|
);
|
|
22
|
-
const
|
|
23
|
-
if (
|
|
22
|
+
const a = i.slice(2).toString("hex").toLowerCase();
|
|
23
|
+
if (a !== s.toLowerCase())
|
|
24
24
|
throw new Error(
|
|
25
|
-
`Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${t}: tx pushes ${
|
|
25
|
+
`Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${t}: tx pushes ${a}, expected ${s}`
|
|
26
26
|
);
|
|
27
27
|
if (n.value !== 0)
|
|
28
28
|
throw new Error(
|
|
29
29
|
`Pre-PegIn auth-anchor OP_RETURN at vout ${t} has non-zero value ${n.value}; OP_RETURN outputs must be 0-value`
|
|
30
30
|
);
|
|
31
31
|
}
|
|
32
|
-
function
|
|
32
|
+
function L(e) {
|
|
33
33
|
let t;
|
|
34
34
|
try {
|
|
35
|
-
t = w.Transaction.fromHex(
|
|
35
|
+
t = w.Transaction.fromHex(k(e));
|
|
36
36
|
} catch {
|
|
37
37
|
return;
|
|
38
38
|
}
|
|
39
|
-
const
|
|
39
|
+
const s = [];
|
|
40
40
|
for (let o = 0; o < t.outs.length; o++) {
|
|
41
|
-
const
|
|
42
|
-
n.length === l && n[0] ===
|
|
41
|
+
const c = t.outs[o], n = c.script;
|
|
42
|
+
n.length === l && n[0] === H && n[1] === B && c.value === 0 && s.push({
|
|
43
43
|
vout: o,
|
|
44
44
|
hash: n.slice(2).toString("hex").toLowerCase()
|
|
45
45
|
});
|
|
46
46
|
}
|
|
47
|
-
return
|
|
47
|
+
return s.length === 1 ? s[0] : void 0;
|
|
48
48
|
}
|
|
49
49
|
const f = 66;
|
|
50
|
-
function
|
|
51
|
-
if (!
|
|
50
|
+
function T(e) {
|
|
51
|
+
if (!e.startsWith("0x") && !e.startsWith("0X"))
|
|
52
52
|
throw new Error("Expected 0x-prefixed hex string");
|
|
53
|
-
const t =
|
|
53
|
+
const t = e.slice(2);
|
|
54
54
|
if (t.length % 2 !== 0)
|
|
55
55
|
throw new Error(`Hex string has odd length: ${t.length}`);
|
|
56
56
|
if (!/^[0-9a-fA-F]*$/.test(t))
|
|
57
57
|
throw new Error("Hex string contains non-hex characters");
|
|
58
|
-
const
|
|
59
|
-
for (let o = 0; o <
|
|
60
|
-
|
|
61
|
-
return
|
|
58
|
+
const s = new Uint8Array(t.length / 2);
|
|
59
|
+
for (let o = 0; o < s.length; o++)
|
|
60
|
+
s[o] = parseInt(t.slice(o * 2, o * 2 + 2), 16);
|
|
61
|
+
return s;
|
|
62
62
|
}
|
|
63
|
-
function
|
|
64
|
-
return `0x${Array.from(
|
|
63
|
+
function S(e) {
|
|
64
|
+
return `0x${Array.from(e).map((t) => t.toString(16).padStart(2, "0")).join("")}`;
|
|
65
65
|
}
|
|
66
|
-
function
|
|
67
|
-
if (
|
|
66
|
+
function h(e, t) {
|
|
67
|
+
if (e.length !== f)
|
|
68
68
|
throw new Error(
|
|
69
|
-
`${t} must be exactly 32 bytes (${f} hex chars with 0x prefix), got ${
|
|
69
|
+
`${t} must be exactly 32 bytes (${f} hex chars with 0x prefix), got ${e.length}`
|
|
70
70
|
);
|
|
71
71
|
}
|
|
72
|
-
function
|
|
73
|
-
|
|
74
|
-
const t =
|
|
75
|
-
return
|
|
72
|
+
function R(e) {
|
|
73
|
+
h(e, "Secret");
|
|
74
|
+
const t = T(e), s = E(t);
|
|
75
|
+
return S(s);
|
|
76
76
|
}
|
|
77
|
-
function
|
|
78
|
-
return
|
|
77
|
+
function A(e, t) {
|
|
78
|
+
return h(e, "Secret"), h(t, "Hashlock"), T(t), R(e).toLowerCase() === t.toLowerCase();
|
|
79
79
|
}
|
|
80
|
-
class
|
|
80
|
+
class I {
|
|
81
81
|
/**
|
|
82
82
|
* Creates a new PayoutManager instance.
|
|
83
83
|
*
|
|
84
84
|
* @param config - Manager configuration including wallet
|
|
85
85
|
*/
|
|
86
86
|
constructor(t) {
|
|
87
|
-
|
|
87
|
+
g(this, "config");
|
|
88
88
|
this.config = t;
|
|
89
89
|
}
|
|
90
90
|
/**
|
|
@@ -110,14 +110,10 @@ class C {
|
|
|
110
110
|
* @throws Error if wallet operations fail or signature extraction fails
|
|
111
111
|
*/
|
|
112
112
|
async signPayoutTransaction(t) {
|
|
113
|
-
this.
|
|
114
|
-
|
|
115
|
-
t.registeredPayoutScriptPubKey
|
|
116
|
-
);
|
|
117
|
-
const e = await this.config.btcWallet.getPublicKeyHex(), { depositorPubkey: o } = p(
|
|
118
|
-
e,
|
|
113
|
+
const s = await this.config.btcWallet.getPublicKeyHex(), { depositorPubkey: o } = p(
|
|
114
|
+
s,
|
|
119
115
|
t.depositorBtcPubkey
|
|
120
|
-
),
|
|
116
|
+
), c = await x({
|
|
121
117
|
payoutTxHex: t.payoutTxHex,
|
|
122
118
|
peginTxHex: t.peginTxHex,
|
|
123
119
|
assertTxHex: t.assertTxHex,
|
|
@@ -126,13 +122,16 @@ class C {
|
|
|
126
122
|
vaultKeeperBtcPubkeys: t.vaultKeeperBtcPubkeys,
|
|
127
123
|
universalChallengerBtcPubkeys: t.universalChallengerBtcPubkeys,
|
|
128
124
|
timelockPegin: t.timelockPegin,
|
|
129
|
-
network: this.config.network
|
|
125
|
+
network: this.config.network,
|
|
126
|
+
claimerBtcPubkey: t.claimerBtcPubkey,
|
|
127
|
+
registeredPayoutScriptPubKey: t.registeredPayoutScriptPubKey,
|
|
128
|
+
commissionBps: t.commissionBps
|
|
130
129
|
}), n = await this.config.btcWallet.signPsbt(
|
|
131
|
-
|
|
132
|
-
|
|
130
|
+
c.psbtHex,
|
|
131
|
+
b(s, 1)
|
|
133
132
|
);
|
|
134
|
-
return
|
|
135
|
-
requestedPsbtHex:
|
|
133
|
+
return y({
|
|
134
|
+
requestedPsbtHex: c.psbtHex,
|
|
136
135
|
returnedPsbtHex: n
|
|
137
136
|
}), {
|
|
138
137
|
signature: d(n, o),
|
|
@@ -169,18 +168,14 @@ class C {
|
|
|
169
168
|
throw new Error(
|
|
170
169
|
"Wallet does not support batch signing (signPsbts method not available)"
|
|
171
170
|
);
|
|
172
|
-
const
|
|
171
|
+
const s = await this.config.btcWallet.getPublicKeyHex(), o = [], c = [], n = [];
|
|
173
172
|
for (const r of t) {
|
|
174
|
-
this.validatePayoutOutputs(
|
|
175
|
-
r.payoutTxHex,
|
|
176
|
-
r.registeredPayoutScriptPubKey
|
|
177
|
-
);
|
|
178
173
|
const { depositorPubkey: u } = p(
|
|
179
|
-
|
|
174
|
+
s,
|
|
180
175
|
r.depositorBtcPubkey
|
|
181
176
|
);
|
|
182
177
|
n.push(u);
|
|
183
|
-
const
|
|
178
|
+
const P = await x({
|
|
184
179
|
payoutTxHex: r.payoutTxHex,
|
|
185
180
|
peginTxHex: r.peginTxHex,
|
|
186
181
|
assertTxHex: r.assertTxHex,
|
|
@@ -189,62 +184,45 @@ class C {
|
|
|
189
184
|
vaultKeeperBtcPubkeys: r.vaultKeeperBtcPubkeys,
|
|
190
185
|
universalChallengerBtcPubkeys: r.universalChallengerBtcPubkeys,
|
|
191
186
|
timelockPegin: r.timelockPegin,
|
|
192
|
-
network: this.config.network
|
|
187
|
+
network: this.config.network,
|
|
188
|
+
claimerBtcPubkey: r.claimerBtcPubkey,
|
|
189
|
+
registeredPayoutScriptPubKey: r.registeredPayoutScriptPubKey,
|
|
190
|
+
commissionBps: r.commissionBps
|
|
193
191
|
});
|
|
194
|
-
o.push(
|
|
192
|
+
o.push(P.psbtHex), c.push(b(s, 1));
|
|
195
193
|
}
|
|
196
194
|
const i = await this.config.btcWallet.signPsbts(
|
|
197
195
|
o,
|
|
198
|
-
|
|
196
|
+
c
|
|
199
197
|
);
|
|
200
198
|
if (i.length !== t.length)
|
|
201
199
|
throw new Error(
|
|
202
200
|
`Expected ${t.length} signed PSBTs but received ${i.length}`
|
|
203
201
|
);
|
|
204
|
-
const
|
|
202
|
+
const a = [];
|
|
205
203
|
for (let r = 0; r < t.length; r++) {
|
|
206
204
|
const u = n[r];
|
|
207
|
-
|
|
205
|
+
y({
|
|
208
206
|
requestedPsbtHex: o[r],
|
|
209
207
|
returnedPsbtHex: i[r]
|
|
210
208
|
});
|
|
211
|
-
const
|
|
209
|
+
const P = d(
|
|
212
210
|
i[r],
|
|
213
211
|
u
|
|
214
212
|
);
|
|
215
|
-
|
|
216
|
-
payoutSignature:
|
|
213
|
+
a.push({
|
|
214
|
+
payoutSignature: P,
|
|
217
215
|
depositorBtcPubkey: u
|
|
218
216
|
});
|
|
219
217
|
}
|
|
220
|
-
return
|
|
221
|
-
}
|
|
222
|
-
/**
|
|
223
|
-
* Validates that the payout transaction's largest output pays to the
|
|
224
|
-
* registered depositor payout address (scriptPubKey).
|
|
225
|
-
*
|
|
226
|
-
* This prevents two attack vectors from a malicious vault provider:
|
|
227
|
-
* 1. Substituting a completely different payout address
|
|
228
|
-
* 2. Including a dust output to the correct address while routing
|
|
229
|
-
* the actual funds to an attacker-controlled address
|
|
230
|
-
*
|
|
231
|
-
* @param payoutTxHex - Raw payout transaction hex
|
|
232
|
-
* @param registeredPayoutScriptPubKey - On-chain registered scriptPubKey (hex, with or without 0x prefix)
|
|
233
|
-
* @throws Error if scriptPubKey is invalid hex
|
|
234
|
-
* @throws Error if the largest output does not pay to the registered address
|
|
235
|
-
*/
|
|
236
|
-
validatePayoutOutputs(t, e) {
|
|
237
|
-
S(
|
|
238
|
-
t,
|
|
239
|
-
e
|
|
240
|
-
);
|
|
218
|
+
return a;
|
|
241
219
|
}
|
|
242
220
|
}
|
|
243
221
|
export {
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
222
|
+
I as P,
|
|
223
|
+
W as a,
|
|
224
|
+
R as c,
|
|
225
|
+
L as f,
|
|
226
|
+
A as v
|
|
249
227
|
};
|
|
250
|
-
//# sourceMappingURL=PayoutManager-
|
|
228
|
+
//# sourceMappingURL=PayoutManager-2XpjdLxE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PayoutManager-2XpjdLxE.js","sources":["../src/tbv/core/managers/pegin/assertAuthAnchorOpReturn.ts","../src/tbv/core/services/htlc/index.ts","../src/tbv/core/managers/PayoutManager.ts"],"sourcesContent":["/**\n * Structural verifier for the auth-anchor OP_RETURN in a funded\n * Pre-PegIn transaction.\n *\n * @module managers/pegin/assertAuthAnchorOpReturn\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\n\n/** OP_RETURN opcode. */\nconst OP_RETURN = 0x6a;\n/** Push-32-bytes opcode (raw push, not OP_PUSHDATA1). */\nconst OP_PUSH32 = 0x20;\n/** Encoded length of a standard OP_RETURN script with a 32-byte payload. */\nconst OP_RETURN_PUSH32_SCRIPT_LEN = 1 + 1 + 32;\n\n/**\n * Verify the broadcast Pre-PegIn carries the expected OP_RETURN\n * commitment to the auth anchor.\n *\n * The OP_RETURN sits at `vout = vaultCount` (right after the per-vault\n * HTLC outputs and before the depositor-claim/change outputs) and\n * pushes the 32-byte `SHA256(authAnchor)`. The script encoding is\n * exactly `OP_RETURN || PUSH32 || <32 bytes>` (34 bytes). A\n * non-conformant WASM build that omitted the OP_RETURN, swapped its\n * position, or changed its push payload would let the depositor\n * obtain a valid bearer token for a Pre-PegIn whose on-chain\n * commitment doesn't actually bind the anchor — degrading the auth\n * from on-chain-bound to a shared secret. Fail closed.\n *\n * @throws If the OP_RETURN is missing, mis-located, mis-encoded, or\n * pushes a payload other than `expectedAuthAnchorHashHex`.\n */\nexport function assertAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n vaultCount: number,\n expectedAuthAnchorHashHex: string,\n): void {\n const cleanHex = stripHexPrefix(fundedPrePeginTxHex);\n const tx = bitcoin.Transaction.fromHex(cleanHex);\n\n if (tx.outs.length <= vaultCount) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN missing: tx has ${tx.outs.length} ` +\n `outputs, expected at least ${vaultCount + 1} (vault outputs + OP_RETURN)`,\n );\n }\n\n const opReturnOutput = tx.outs[vaultCount];\n const script = opReturnOutput.script;\n if (\n script.length !== OP_RETURN_PUSH32_SCRIPT_LEN ||\n script[0] !== OP_RETURN ||\n script[1] !== OP_PUSH32\n ) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has unexpected ` +\n `script encoding (got ${script.length}-byte script with prefix ` +\n `0x${script.slice(0, Math.min(2, script.length)).toString(\"hex\")}; ` +\n `expected ${OP_RETURN_PUSH32_SCRIPT_LEN}-byte OP_RETURN + PUSH32 layout)`,\n );\n }\n\n const pushedHex = script.slice(2).toString(\"hex\").toLowerCase();\n if (pushedHex !== expectedAuthAnchorHashHex.toLowerCase()) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${vaultCount}: ` +\n `tx pushes ${pushedHex}, expected ${expectedAuthAnchorHashHex}`,\n );\n }\n\n if (opReturnOutput.value !== 0) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has non-zero ` +\n `value ${opReturnOutput.value}; OP_RETURN outputs must be 0-value`,\n );\n }\n}\n\n/**\n * Best-effort reader for the auth-anchor OP_RETURN payload at `vout` of\n * a funded Pre-PegIn transaction.\n *\n * Returns the 32-byte payload as lowercase hex (no `0x` prefix) if the\n * output at `vout` is exactly `OP_RETURN || PUSH32 || <32 bytes>` with\n * a zero value. Returns `undefined` for any structural mismatch —\n * missing output, wrong script shape, non-zero value — so legacy\n * non-auth-anchored Pre-PegIns parse as \"no anchor\" rather than\n * raising.\n *\n * Used by the refund flow to reconstruct the unfunded WASM template\n * with the same output shape as the on-chain funded transaction.\n * Assertion semantics (compare against an expected value, throw on\n * mismatch) live in {@link assertAuthAnchorOpReturn}.\n */\nexport function readAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n vout: number,\n): string | undefined {\n let tx: bitcoin.Transaction;\n try {\n tx = bitcoin.Transaction.fromHex(stripHexPrefix(fundedPrePeginTxHex));\n } catch {\n // Best-effort: unparseable hex is also \"no extractable anchor\".\n // The same hex flows into the refund PSBT primitive immediately\n // after, where Transaction.fromHex will surface a real parse error.\n return undefined;\n }\n\n if (tx.outs.length <= vout) return undefined;\n\n const output = tx.outs[vout];\n const script = output.script;\n if (\n script.length !== OP_RETURN_PUSH32_SCRIPT_LEN ||\n script[0] !== OP_RETURN ||\n script[1] !== OP_PUSH32\n ) {\n return undefined;\n }\n if (output.value !== 0) return undefined;\n\n return script.slice(2).toString(\"hex\").toLowerCase();\n}\n\n/**\n * Scan a funded Pre-PegIn transaction for its auth-anchor commitment\n * (an `OP_RETURN || PUSH32 || <32 bytes>` output with value 0).\n *\n * Returns `{ vout, hash }` when exactly one such output is found.\n * Returns `undefined` when:\n * - the hex is unparseable,\n * - no matching output exists (legacy non-auth-anchored Pre-PegIn),\n * - more than one matching output exists (ambiguous / malformed).\n *\n * Used by the refund orchestrator to (a) locate the on-chain anchor\n * regardless of how many HTLCs preceded it and (b) detect multi-vault\n * funded transactions structurally: the single-vault refund path\n * reconstructs only one hashlock and expects the anchor at vout 1, so\n * any other vout signals a layout this call cannot safely refund.\n */\nexport function findAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n): { vout: number; hash: string } | undefined {\n let tx: bitcoin.Transaction;\n try {\n tx = bitcoin.Transaction.fromHex(stripHexPrefix(fundedPrePeginTxHex));\n } catch {\n return undefined;\n }\n\n const hits: { vout: number; hash: string }[] = [];\n for (let i = 0; i < tx.outs.length; i++) {\n const output = tx.outs[i];\n const script = output.script;\n if (\n script.length === OP_RETURN_PUSH32_SCRIPT_LEN &&\n script[0] === OP_RETURN &&\n script[1] === OP_PUSH32 &&\n output.value === 0\n ) {\n hits.push({\n vout: i,\n hash: script.slice(2).toString(\"hex\").toLowerCase(),\n });\n }\n }\n\n return hits.length === 1 ? hits[0] : undefined;\n}\n","/**\n * HTLC Secret / Hashlock Utilities\n *\n * Pure functions for computing and validating SHA-256 hashlocks used in the\n * vault deposit protocol's HTLC (Hash Time Lock Contract).\n *\n * The SDK does NOT generate secrets — that is the caller's responsibility.\n * Today callers use `crypto.getRandomValues(32)`; when the `deriveContextHash`\n * wallet API ships, callers will use `wallet.deriveContextHash(\"babylon-btc-vault\", ctx)`.\n * These utilities work identically regardless of how the secret was produced.\n *\n * On-chain contract validation (BTCVaultRegistry.activateVaultWithSecret):\n * if (sha256(abi.encodePacked(s)) != hashlock) revert InvalidSecret();\n *\n * @module htlc\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport type { Hex } from \"viem\";\n\n/** Expected hex length for a 0x-prefixed bytes32 value. */\nconst HEX_BYTES32_LENGTH = 66; // \"0x\" + 64 hex chars\n\n/**\n * Decode a 0x-prefixed hex string to bytes, with strict validation.\n * @throws if the input is not a valid 0x-prefixed hex string\n */\nfunction hexToBytes(hex: Hex): Uint8Array {\n if (!hex.startsWith(\"0x\") && !hex.startsWith(\"0X\")) {\n throw new Error(\"Expected 0x-prefixed hex string\");\n }\n const clean = hex.slice(2);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has odd length: ${clean.length}`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error(\"Hex string contains non-hex characters\");\n }\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Encode a Uint8Array as a 0x-prefixed lowercase hex string.\n */\nfunction bytesToHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\n/**\n * Validate that a value is a 0x-prefixed bytes32 (exactly 32 bytes).\n * @throws if the value is not exactly 32 bytes\n */\nfunction assertBytes32(value: Hex, label: string): void {\n if (value.length !== HEX_BYTES32_LENGTH) {\n throw new Error(\n `${label} must be exactly 32 bytes (${HEX_BYTES32_LENGTH} hex chars with 0x prefix), got ${value.length}`,\n );\n }\n}\n\n/**\n * Compute the SHA-256 hashlock from a secret preimage.\n *\n * Matches the on-chain validation: `sha256(abi.encodePacked(s))` where `s` is a `bytes32`.\n * `abi.encodePacked(bytes32)` is just the raw 32 bytes — no ABI padding.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @returns 0x-prefixed bytes32 SHA-256 hash\n * @throws if secret is not exactly 32 bytes\n */\nexport function computeHashlock(secret: Hex): Hex {\n assertBytes32(secret, \"Secret\");\n const secretBytes = hexToBytes(secret);\n const hash = sha256(secretBytes);\n return bytesToHex(hash);\n}\n\n/**\n * Validate that a secret's SHA-256 hash matches the expected hashlock.\n *\n * Use this for client-side pre-validation before sending the activation\n * transaction to avoid wasting gas on a contract revert.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @param hashlock - 0x-prefixed bytes32 expected hashlock from the vault\n * @returns true if SHA-256(secret) matches the hashlock\n * @throws if secret or hashlock is not exactly 32 bytes\n */\nexport function validateSecretAgainstHashlock(\n secret: Hex,\n hashlock: Hex,\n): boolean {\n assertBytes32(secret, \"Secret\");\n assertBytes32(hashlock, \"Hashlock\");\n // Validate hashlock is valid hex (secret is validated inside computeHashlock)\n hexToBytes(hashlock);\n\n const computed = computeHashlock(secret);\n return computed.toLowerCase() === hashlock.toLowerCase();\n}\n","/**\n * Payout Manager\n *\n * High-level manager that orchestrates the payout signing flow by coordinating\n * SDK primitives ({@link buildPayoutPsbt}, {@link extractPayoutSignature})\n * with a user-provided Bitcoin wallet.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @see {@link PeginManager} - For Steps 1–4 of the peg-in flow\n * @see {@link buildPayoutPsbt} - Lower-level primitive for custom implementations\n * @see {@link extractPayoutSignature} - Extract signatures from signed PSBTs\n *\n * @module managers/PayoutManager\n */\n\nimport type {\n BitcoinWallet,\n SignPsbtOptions,\n} from \"../../../shared/wallets\";\nimport { createTaprootScriptPathSignOptions } from \"../utils/signing\";\nimport {\n assertPsbtUnsignedTxMatches,\n buildPayoutPsbt,\n extractPayoutSignature,\n validateWalletPubkey,\n type Network,\n} from \"../primitives\";\n\n/**\n * Configuration for the PayoutManager.\n */\nexport interface PayoutManagerConfig {\n /**\n * Bitcoin network to use for transactions.\n */\n network: Network;\n\n /**\n * Bitcoin wallet for signing payout transactions.\n */\n btcWallet: BitcoinWallet;\n}\n\n/**\n * Base parameters shared by both payout transaction types.\n */\ninterface SignPayoutBaseParams {\n /**\n * Peg-in transaction hex.\n * The original transaction that created the vault output being spent.\n */\n peginTxHex: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex).\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex).\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex).\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex). This MUST be the\n * key registered on-chain for the vault — typically read from\n * `BTCVaultRegistry.getBtcVaultBasicInfo(...).depositorBtcPubKey`.\n *\n * Required: omitting it would degrade `validateWalletPubkey` to a\n * self-comparison, allowing the wrong wallet to produce a signature\n * over a script tree that doesn't match the on-chain UTXO.\n */\n depositorBtcPubkey: string;\n\n /**\n * The on-chain registered depositor payout scriptPubKey (hex, with or without 0x prefix).\n * Used to validate that the VP-provided payout transaction actually pays to the\n * correct depositor payout address before signing.\n */\n registeredPayoutScriptPubKey: string;\n\n /**\n * The claimer's x-only BTC public key for this payout (64-char hex, no prefix).\n * Forwarded to {@link buildPayoutPsbt} for per-role output validation.\n */\n claimerBtcPubkey: string;\n\n /**\n * VP commission in basis points (`1..=9999`). Forwarded to {@link buildPayoutPsbt}.\n */\n commissionBps: number;\n}\n\n/**\n * Parameters for signing a Payout transaction.\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface SignPayoutParams extends SignPayoutBaseParams {\n /**\n * Payout transaction hex (unsigned).\n * This is the transaction from the vault provider that needs depositor signature.\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex.\n * Payout input 1 references Assert output 0.\n */\n assertTxHex: string;\n}\n\n/**\n * Result of signing a payout transaction.\n */\nexport interface PayoutSignatureResult {\n /**\n * 64-byte Schnorr signature (128 hex characters).\n */\n signature: string;\n\n /**\n * Depositor's BTC public key used for signing.\n */\n depositorBtcPubkey: string;\n}\n\n/**\n * High-level manager for payout transaction signing.\n *\n * @remarks\n * After registering your peg-in on Ethereum (Step 3), the vault provider prepares\n * claim/payout transaction pairs. You must sign each payout transaction using this\n * manager and submit the signatures to the vault provider's RPC API.\n *\n * **What happens internally:**\n * 1. Validates your wallet's public key matches the vault's depositor\n * 2. Builds an unsigned PSBT with taproot script path spend info\n * 3. Signs input 0 (the vault UTXO) with your wallet\n * 4. Extracts the 64-byte Schnorr signature\n *\n * **Note:** The payout transaction has 2 inputs. PayoutManager only signs input 0\n * (from the peg-in tx). Input 1 (from the assert tx) is signed by the vault provider.\n *\n * @see {@link PeginManager} - For the complete peg-in flow context\n * @see {@link buildPayoutPsbt} - Lower-level primitive used internally\n * @see {@link extractPayoutSignature} - Signature extraction primitive\n */\nexport class PayoutManager {\n private readonly config: PayoutManagerConfig;\n\n /**\n * Creates a new PayoutManager instance.\n *\n * @param config - Manager configuration including wallet\n */\n constructor(config: PayoutManagerConfig) {\n this.config = config;\n }\n\n /**\n * Signs a Payout transaction and extracts the Schnorr signature.\n *\n * Flow:\n * 1. Vault provider submits Claim transaction\n * 2. Claimer submits Assert transaction to prove validity\n * 3. Payout can be executed (references Assert tx)\n *\n * This method orchestrates the following steps:\n * 1. Get wallet's public key and convert to x-only format\n * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)\n * 3. Build unsigned PSBT using primitives\n * 4. Sign PSBT via btcWallet.signPsbt()\n * 5. Extract 64-byte Schnorr signature using primitives\n *\n * The returned signature can be submitted to the vault provider API.\n *\n * @param params - Payout signing parameters\n * @returns Signature result with 64-byte Schnorr signature and depositor pubkey\n * @throws Error if wallet pubkey doesn't match depositor pubkey\n * @throws Error if wallet operations fail or signature extraction fails\n */\n async signPayoutTransaction(\n params: SignPayoutParams,\n ): Promise<PayoutSignatureResult> {\n // Validate wallet pubkey matches depositor and get both formats\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n params.depositorBtcPubkey,\n );\n\n // Build unsigned PSBT for Payout (uses Assert tx). Per-role output\n // validation happens inside buildPayoutPsbt against the resolved input\n // values.\n const payoutPsbt = await buildPayoutPsbt({\n payoutTxHex: params.payoutTxHex,\n peginTxHex: params.peginTxHex,\n assertTxHex: params.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: params.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: params.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: this.config.network,\n claimerBtcPubkey: params.claimerBtcPubkey,\n registeredPayoutScriptPubKey: params.registeredPayoutScriptPubKey,\n commissionBps: params.commissionBps,\n });\n\n // Sign PSBT via wallet (Taproot script-path spend, input 0 only)\n const signedPsbtHex = await this.config.btcWallet.signPsbt(\n payoutPsbt.psbtHex,\n createTaprootScriptPathSignOptions(walletPubkeyRaw, 1),\n );\n\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: payoutPsbt.psbtHex,\n returnedPsbtHex: signedPsbtHex,\n });\n\n // Extract Schnorr signature\n const signature = extractPayoutSignature(signedPsbtHex, depositorPubkey);\n\n return {\n signature,\n depositorBtcPubkey: depositorPubkey,\n };\n }\n\n /**\n * Gets the configured Bitcoin network.\n *\n * @returns The Bitcoin network (mainnet, testnet, signet, regtest)\n */\n getNetwork(): Network {\n return this.config.network;\n }\n\n /**\n * Checks if the wallet supports batch signing (signPsbts).\n *\n * @returns true if batch signing is supported\n */\n supportsBatchSigning(): boolean {\n return typeof this.config.btcWallet.signPsbts === \"function\";\n }\n\n /**\n * Batch signs multiple payout transactions (1 per claimer).\n * This allows signing all transactions with a single wallet interaction.\n *\n * @param transactions - Array of payout params to sign\n * @returns Array of signature results matching input order\n * @throws Error if wallet doesn't support batch signing\n * @throws Error if any signing operation fails\n */\n async signPayoutTransactionsBatch(\n transactions: SignPayoutParams[],\n ): Promise<\n Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }>\n > {\n if (!this.supportsBatchSigning()) {\n throw new Error(\n \"Wallet does not support batch signing (signPsbts method not available)\",\n );\n }\n\n // Get wallet pubkey once\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n\n // Build all PSBTs (1 per claimer)\n const psbtsToSign: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n const depositorPubkeys: string[] = [];\n\n for (const tx of transactions) {\n // Validate wallet pubkey matches depositor\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n tx.depositorBtcPubkey,\n );\n depositorPubkeys.push(depositorPubkey);\n\n // Build Payout PSBT (output validation runs inside buildPayoutPsbt\n // against resolved input values).\n const payoutPsbt = await buildPayoutPsbt({\n payoutTxHex: tx.payoutTxHex,\n peginTxHex: tx.peginTxHex,\n assertTxHex: tx.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: tx.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: tx.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: tx.universalChallengerBtcPubkeys,\n timelockPegin: tx.timelockPegin,\n network: this.config.network,\n claimerBtcPubkey: tx.claimerBtcPubkey,\n registeredPayoutScriptPubKey: tx.registeredPayoutScriptPubKey,\n commissionBps: tx.commissionBps,\n });\n psbtsToSign.push(payoutPsbt.psbtHex);\n signOptions.push(createTaprootScriptPathSignOptions(walletPubkeyRaw, 1));\n }\n\n // Batch sign all PSBTs with single wallet interaction\n const signedPsbts = await this.config.btcWallet.signPsbts!(\n psbtsToSign,\n signOptions,\n );\n\n // Validate that wallet returned the expected number of signed PSBTs\n if (signedPsbts.length !== transactions.length) {\n throw new Error(\n `Expected ${transactions.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n\n // Extract signatures from signed PSBTs\n const results: Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }> = [];\n\n for (let i = 0; i < transactions.length; i++) {\n const depositorPubkey = depositorPubkeys[i];\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: psbtsToSign[i],\n returnedPsbtHex: signedPsbts[i],\n });\n const payoutSignature = extractPayoutSignature(\n signedPsbts[i],\n depositorPubkey,\n );\n\n results.push({\n payoutSignature,\n depositorBtcPubkey: depositorPubkey,\n });\n }\n\n return results;\n }\n\n}\n"],"names":["OP_RETURN","OP_PUSH32","OP_RETURN_PUSH32_SCRIPT_LEN","assertAuthAnchorOpReturn","fundedPrePeginTxHex","vaultCount","expectedAuthAnchorHashHex","cleanHex","stripHexPrefix","tx","bitcoin","opReturnOutput","script","pushedHex","findAuthAnchorOpReturn","hits","i","output","HEX_BYTES32_LENGTH","hexToBytes","hex","clean","bytes","bytesToHex","b","assertBytes32","value","label","computeHashlock","secret","secretBytes","hash","sha256","validateSecretAgainstHashlock","hashlock","PayoutManager","config","__publicField","params","walletPubkeyRaw","depositorPubkey","validateWalletPubkey","payoutPsbt","buildPayoutPsbt","signedPsbtHex","createTaprootScriptPathSignOptions","assertPsbtUnsignedTxMatches","extractPayoutSignature","transactions","psbtsToSign","signOptions","depositorPubkeys","signedPsbts","results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AAU;AAAA,MAC9CH;AAAA,MACAC;AAAA,IAAA;AAIF,QAAIE,EAAY,WAAWJ,EAAa;AACtC,YAAM,IAAI;AAAA,QACR,YAAYA,EAAa,MAAM,8BAA8BI,EAAY,MAAM;AAAA,MAAA;AAKnF,UAAMC,IAGD,CAAA;AAEL,aAASrC,IAAI,GAAGA,IAAIgC,EAAa,QAAQhC,KAAK;AAC5C,YAAMwB,IAAkBW,EAAiBnC,CAAC;AAC1C,MAAA8B,EAA4B;AAAA,QAC1B,kBAAkBG,EAAYjC,CAAC;AAAA,QAC/B,iBAAiBoC,EAAYpC,CAAC;AAAA,MAAA,CAC/B;AACD,YAAMsC,IAAkBP;AAAA,QACtBK,EAAYpC,CAAC;AAAA,QACbwB;AAAA,MAAA;AAGF,MAAAa,EAAQ,KAAK;AAAA,QACX,iBAAAC;AAAA,QACA,oBAAoBd;AAAA,MAAA,CACrB;AAAA,IACH;AAEA,WAAOa;AAAA,EACT;AAEF;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var T=Object.defineProperty;var B=(e,t,s)=>t in e?T(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var b=(e,t,s)=>B(e,typeof t!="symbol"?t+"":t,s);const S=require("bitcoinjs-lib"),g=require("./bitcoin-CHfKAhcI.cjs"),v=require("./sha2-DsrLC4NM.cjs"),y=require("./signing-Bnsro0hE.cjs");require("@babylonlabs-io/babylon-tbv-rust-wasm");const u=require("./assertPsbtUnsignedTxMatches-u9yeeUFY.cjs");function R(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const s in e)if(s!=="default"){const n=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,n.get?n:{enumerable:!0,get:()=>e[s]})}}return t.default=e,Object.freeze(t)}const d=R(S),f=106,w=32,h=34;function m(e,t,s){const n=g.stripHexPrefix(e),c=d.Transaction.fromHex(n);if(c.outs.length<=t)throw new Error(`Pre-PegIn auth-anchor OP_RETURN missing: tx has ${c.outs.length} outputs, expected at least ${t+1} (vault outputs + OP_RETURN)`);const o=c.outs[t],i=o.script;if(i.length!==h||i[0]!==f||i[1]!==w)throw new Error(`Pre-PegIn auth-anchor OP_RETURN at vout ${t} has unexpected script encoding (got ${i.length}-byte script with prefix 0x${i.slice(0,Math.min(2,i.length)).toString("hex")}; expected ${h}-byte OP_RETURN + PUSH32 layout)`);const a=i.slice(2).toString("hex").toLowerCase();if(a!==s.toLowerCase())throw new Error(`Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${t}: tx pushes ${a}, expected ${s}`);if(o.value!==0)throw new Error(`Pre-PegIn auth-anchor OP_RETURN at vout ${t} has non-zero value ${o.value}; OP_RETURN outputs must be 0-value`)}function E(e){let t;try{t=d.Transaction.fromHex(g.stripHexPrefix(e))}catch{return}const s=[];for(let n=0;n<t.outs.length;n++){const c=t.outs[n],o=c.script;o.length===h&&o[0]===f&&o[1]===w&&c.value===0&&s.push({vout:n,hash:o.slice(2).toString("hex").toLowerCase()})}return s.length===1?s[0]:void 0}const x=66;function k(e){if(!e.startsWith("0x")&&!e.startsWith("0X"))throw new Error("Expected 0x-prefixed hex string");const t=e.slice(2);if(t.length%2!==0)throw new Error(`Hex string has odd length: ${t.length}`);if(!/^[0-9a-fA-F]*$/.test(t))throw new Error("Hex string contains non-hex characters");const s=new Uint8Array(t.length/2);for(let n=0;n<s.length;n++)s[n]=parseInt(t.slice(n*2,n*2+2),16);return s}function O(e){return`0x${Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}`}function p(e,t){if(e.length!==x)throw new Error(`${t} must be exactly 32 bytes (${x} hex chars with 0x prefix), got ${e.length}`)}function H(e){p(e,"Secret");const t=k(e),s=v.sha256(t);return O(s)}function $(e,t){return p(e,"Secret"),p(t,"Hashlock"),k(t),H(e).toLowerCase()===t.toLowerCase()}class _{constructor(t){b(this,"config");this.config=t}async signPayoutTransaction(t){const s=await this.config.btcWallet.getPublicKeyHex(),{depositorPubkey:n}=g.validateWalletPubkey(s,t.depositorBtcPubkey),c=await u.buildPayoutPsbt({payoutTxHex:t.payoutTxHex,peginTxHex:t.peginTxHex,assertTxHex:t.assertTxHex,depositorBtcPubkey:n,vaultProviderBtcPubkey:t.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:t.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:t.universalChallengerBtcPubkeys,timelockPegin:t.timelockPegin,network:this.config.network,claimerBtcPubkey:t.claimerBtcPubkey,registeredPayoutScriptPubKey:t.registeredPayoutScriptPubKey,commissionBps:t.commissionBps}),o=await this.config.btcWallet.signPsbt(c.psbtHex,y.createTaprootScriptPathSignOptions(s,1));return u.assertPsbtUnsignedTxMatches({requestedPsbtHex:c.psbtHex,returnedPsbtHex:o}),{signature:u.extractPayoutSignature(o,n),depositorBtcPubkey:n}}getNetwork(){return this.config.network}supportsBatchSigning(){return typeof this.config.btcWallet.signPsbts=="function"}async signPayoutTransactionsBatch(t){if(!this.supportsBatchSigning())throw new Error("Wallet does not support batch signing (signPsbts method not available)");const s=await this.config.btcWallet.getPublicKeyHex(),n=[],c=[],o=[];for(const r of t){const{depositorPubkey:l}=g.validateWalletPubkey(s,r.depositorBtcPubkey);o.push(l);const P=await u.buildPayoutPsbt({payoutTxHex:r.payoutTxHex,peginTxHex:r.peginTxHex,assertTxHex:r.assertTxHex,depositorBtcPubkey:l,vaultProviderBtcPubkey:r.vaultProviderBtcPubkey,vaultKeeperBtcPubkeys:r.vaultKeeperBtcPubkeys,universalChallengerBtcPubkeys:r.universalChallengerBtcPubkeys,timelockPegin:r.timelockPegin,network:this.config.network,claimerBtcPubkey:r.claimerBtcPubkey,registeredPayoutScriptPubKey:r.registeredPayoutScriptPubKey,commissionBps:r.commissionBps});n.push(P.psbtHex),c.push(y.createTaprootScriptPathSignOptions(s,1))}const i=await this.config.btcWallet.signPsbts(n,c);if(i.length!==t.length)throw new Error(`Expected ${t.length} signed PSBTs but received ${i.length}`);const a=[];for(let r=0;r<t.length;r++){const l=o[r];u.assertPsbtUnsignedTxMatches({requestedPsbtHex:n[r],returnedPsbtHex:i[r]});const P=u.extractPayoutSignature(i[r],l);a.push({payoutSignature:P,depositorBtcPubkey:l})}return a}}exports.PayoutManager=_;exports.assertAuthAnchorOpReturn=m;exports.computeHashlock=H;exports.findAuthAnchorOpReturn=E;exports.validateSecretAgainstHashlock=$;
|
|
2
|
+
//# sourceMappingURL=PayoutManager-DnKRzWWb.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PayoutManager-DnKRzWWb.cjs","sources":["../src/tbv/core/managers/pegin/assertAuthAnchorOpReturn.ts","../src/tbv/core/services/htlc/index.ts","../src/tbv/core/managers/PayoutManager.ts"],"sourcesContent":["/**\n * Structural verifier for the auth-anchor OP_RETURN in a funded\n * Pre-PegIn transaction.\n *\n * @module managers/pegin/assertAuthAnchorOpReturn\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\n\nimport { stripHexPrefix } from \"../../primitives/utils/bitcoin\";\n\n/** OP_RETURN opcode. */\nconst OP_RETURN = 0x6a;\n/** Push-32-bytes opcode (raw push, not OP_PUSHDATA1). */\nconst OP_PUSH32 = 0x20;\n/** Encoded length of a standard OP_RETURN script with a 32-byte payload. */\nconst OP_RETURN_PUSH32_SCRIPT_LEN = 1 + 1 + 32;\n\n/**\n * Verify the broadcast Pre-PegIn carries the expected OP_RETURN\n * commitment to the auth anchor.\n *\n * The OP_RETURN sits at `vout = vaultCount` (right after the per-vault\n * HTLC outputs and before the depositor-claim/change outputs) and\n * pushes the 32-byte `SHA256(authAnchor)`. The script encoding is\n * exactly `OP_RETURN || PUSH32 || <32 bytes>` (34 bytes). A\n * non-conformant WASM build that omitted the OP_RETURN, swapped its\n * position, or changed its push payload would let the depositor\n * obtain a valid bearer token for a Pre-PegIn whose on-chain\n * commitment doesn't actually bind the anchor — degrading the auth\n * from on-chain-bound to a shared secret. Fail closed.\n *\n * @throws If the OP_RETURN is missing, mis-located, mis-encoded, or\n * pushes a payload other than `expectedAuthAnchorHashHex`.\n */\nexport function assertAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n vaultCount: number,\n expectedAuthAnchorHashHex: string,\n): void {\n const cleanHex = stripHexPrefix(fundedPrePeginTxHex);\n const tx = bitcoin.Transaction.fromHex(cleanHex);\n\n if (tx.outs.length <= vaultCount) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN missing: tx has ${tx.outs.length} ` +\n `outputs, expected at least ${vaultCount + 1} (vault outputs + OP_RETURN)`,\n );\n }\n\n const opReturnOutput = tx.outs[vaultCount];\n const script = opReturnOutput.script;\n if (\n script.length !== OP_RETURN_PUSH32_SCRIPT_LEN ||\n script[0] !== OP_RETURN ||\n script[1] !== OP_PUSH32\n ) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has unexpected ` +\n `script encoding (got ${script.length}-byte script with prefix ` +\n `0x${script.slice(0, Math.min(2, script.length)).toString(\"hex\")}; ` +\n `expected ${OP_RETURN_PUSH32_SCRIPT_LEN}-byte OP_RETURN + PUSH32 layout)`,\n );\n }\n\n const pushedHex = script.slice(2).toString(\"hex\").toLowerCase();\n if (pushedHex !== expectedAuthAnchorHashHex.toLowerCase()) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${vaultCount}: ` +\n `tx pushes ${pushedHex}, expected ${expectedAuthAnchorHashHex}`,\n );\n }\n\n if (opReturnOutput.value !== 0) {\n throw new Error(\n `Pre-PegIn auth-anchor OP_RETURN at vout ${vaultCount} has non-zero ` +\n `value ${opReturnOutput.value}; OP_RETURN outputs must be 0-value`,\n );\n }\n}\n\n/**\n * Best-effort reader for the auth-anchor OP_RETURN payload at `vout` of\n * a funded Pre-PegIn transaction.\n *\n * Returns the 32-byte payload as lowercase hex (no `0x` prefix) if the\n * output at `vout` is exactly `OP_RETURN || PUSH32 || <32 bytes>` with\n * a zero value. Returns `undefined` for any structural mismatch —\n * missing output, wrong script shape, non-zero value — so legacy\n * non-auth-anchored Pre-PegIns parse as \"no anchor\" rather than\n * raising.\n *\n * Used by the refund flow to reconstruct the unfunded WASM template\n * with the same output shape as the on-chain funded transaction.\n * Assertion semantics (compare against an expected value, throw on\n * mismatch) live in {@link assertAuthAnchorOpReturn}.\n */\nexport function readAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n vout: number,\n): string | undefined {\n let tx: bitcoin.Transaction;\n try {\n tx = bitcoin.Transaction.fromHex(stripHexPrefix(fundedPrePeginTxHex));\n } catch {\n // Best-effort: unparseable hex is also \"no extractable anchor\".\n // The same hex flows into the refund PSBT primitive immediately\n // after, where Transaction.fromHex will surface a real parse error.\n return undefined;\n }\n\n if (tx.outs.length <= vout) return undefined;\n\n const output = tx.outs[vout];\n const script = output.script;\n if (\n script.length !== OP_RETURN_PUSH32_SCRIPT_LEN ||\n script[0] !== OP_RETURN ||\n script[1] !== OP_PUSH32\n ) {\n return undefined;\n }\n if (output.value !== 0) return undefined;\n\n return script.slice(2).toString(\"hex\").toLowerCase();\n}\n\n/**\n * Scan a funded Pre-PegIn transaction for its auth-anchor commitment\n * (an `OP_RETURN || PUSH32 || <32 bytes>` output with value 0).\n *\n * Returns `{ vout, hash }` when exactly one such output is found.\n * Returns `undefined` when:\n * - the hex is unparseable,\n * - no matching output exists (legacy non-auth-anchored Pre-PegIn),\n * - more than one matching output exists (ambiguous / malformed).\n *\n * Used by the refund orchestrator to (a) locate the on-chain anchor\n * regardless of how many HTLCs preceded it and (b) detect multi-vault\n * funded transactions structurally: the single-vault refund path\n * reconstructs only one hashlock and expects the anchor at vout 1, so\n * any other vout signals a layout this call cannot safely refund.\n */\nexport function findAuthAnchorOpReturn(\n fundedPrePeginTxHex: string,\n): { vout: number; hash: string } | undefined {\n let tx: bitcoin.Transaction;\n try {\n tx = bitcoin.Transaction.fromHex(stripHexPrefix(fundedPrePeginTxHex));\n } catch {\n return undefined;\n }\n\n const hits: { vout: number; hash: string }[] = [];\n for (let i = 0; i < tx.outs.length; i++) {\n const output = tx.outs[i];\n const script = output.script;\n if (\n script.length === OP_RETURN_PUSH32_SCRIPT_LEN &&\n script[0] === OP_RETURN &&\n script[1] === OP_PUSH32 &&\n output.value === 0\n ) {\n hits.push({\n vout: i,\n hash: script.slice(2).toString(\"hex\").toLowerCase(),\n });\n }\n }\n\n return hits.length === 1 ? hits[0] : undefined;\n}\n","/**\n * HTLC Secret / Hashlock Utilities\n *\n * Pure functions for computing and validating SHA-256 hashlocks used in the\n * vault deposit protocol's HTLC (Hash Time Lock Contract).\n *\n * The SDK does NOT generate secrets — that is the caller's responsibility.\n * Today callers use `crypto.getRandomValues(32)`; when the `deriveContextHash`\n * wallet API ships, callers will use `wallet.deriveContextHash(\"babylon-btc-vault\", ctx)`.\n * These utilities work identically regardless of how the secret was produced.\n *\n * On-chain contract validation (BTCVaultRegistry.activateVaultWithSecret):\n * if (sha256(abi.encodePacked(s)) != hashlock) revert InvalidSecret();\n *\n * @module htlc\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport type { Hex } from \"viem\";\n\n/** Expected hex length for a 0x-prefixed bytes32 value. */\nconst HEX_BYTES32_LENGTH = 66; // \"0x\" + 64 hex chars\n\n/**\n * Decode a 0x-prefixed hex string to bytes, with strict validation.\n * @throws if the input is not a valid 0x-prefixed hex string\n */\nfunction hexToBytes(hex: Hex): Uint8Array {\n if (!hex.startsWith(\"0x\") && !hex.startsWith(\"0X\")) {\n throw new Error(\"Expected 0x-prefixed hex string\");\n }\n const clean = hex.slice(2);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has odd length: ${clean.length}`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error(\"Hex string contains non-hex characters\");\n }\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Encode a Uint8Array as a 0x-prefixed lowercase hex string.\n */\nfunction bytesToHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\")}`;\n}\n\n/**\n * Validate that a value is a 0x-prefixed bytes32 (exactly 32 bytes).\n * @throws if the value is not exactly 32 bytes\n */\nfunction assertBytes32(value: Hex, label: string): void {\n if (value.length !== HEX_BYTES32_LENGTH) {\n throw new Error(\n `${label} must be exactly 32 bytes (${HEX_BYTES32_LENGTH} hex chars with 0x prefix), got ${value.length}`,\n );\n }\n}\n\n/**\n * Compute the SHA-256 hashlock from a secret preimage.\n *\n * Matches the on-chain validation: `sha256(abi.encodePacked(s))` where `s` is a `bytes32`.\n * `abi.encodePacked(bytes32)` is just the raw 32 bytes — no ABI padding.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @returns 0x-prefixed bytes32 SHA-256 hash\n * @throws if secret is not exactly 32 bytes\n */\nexport function computeHashlock(secret: Hex): Hex {\n assertBytes32(secret, \"Secret\");\n const secretBytes = hexToBytes(secret);\n const hash = sha256(secretBytes);\n return bytesToHex(hash);\n}\n\n/**\n * Validate that a secret's SHA-256 hash matches the expected hashlock.\n *\n * Use this for client-side pre-validation before sending the activation\n * transaction to avoid wasting gas on a contract revert.\n *\n * @param secret - 0x-prefixed bytes32 secret (66 hex chars)\n * @param hashlock - 0x-prefixed bytes32 expected hashlock from the vault\n * @returns true if SHA-256(secret) matches the hashlock\n * @throws if secret or hashlock is not exactly 32 bytes\n */\nexport function validateSecretAgainstHashlock(\n secret: Hex,\n hashlock: Hex,\n): boolean {\n assertBytes32(secret, \"Secret\");\n assertBytes32(hashlock, \"Hashlock\");\n // Validate hashlock is valid hex (secret is validated inside computeHashlock)\n hexToBytes(hashlock);\n\n const computed = computeHashlock(secret);\n return computed.toLowerCase() === hashlock.toLowerCase();\n}\n","/**\n * Payout Manager\n *\n * High-level manager that orchestrates the payout signing flow by coordinating\n * SDK primitives ({@link buildPayoutPsbt}, {@link extractPayoutSignature})\n * with a user-provided Bitcoin wallet.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @see {@link PeginManager} - For Steps 1–4 of the peg-in flow\n * @see {@link buildPayoutPsbt} - Lower-level primitive for custom implementations\n * @see {@link extractPayoutSignature} - Extract signatures from signed PSBTs\n *\n * @module managers/PayoutManager\n */\n\nimport type {\n BitcoinWallet,\n SignPsbtOptions,\n} from \"../../../shared/wallets\";\nimport { createTaprootScriptPathSignOptions } from \"../utils/signing\";\nimport {\n assertPsbtUnsignedTxMatches,\n buildPayoutPsbt,\n extractPayoutSignature,\n validateWalletPubkey,\n type Network,\n} from \"../primitives\";\n\n/**\n * Configuration for the PayoutManager.\n */\nexport interface PayoutManagerConfig {\n /**\n * Bitcoin network to use for transactions.\n */\n network: Network;\n\n /**\n * Bitcoin wallet for signing payout transactions.\n */\n btcWallet: BitcoinWallet;\n}\n\n/**\n * Base parameters shared by both payout transaction types.\n */\ninterface SignPayoutBaseParams {\n /**\n * Peg-in transaction hex.\n * The original transaction that created the vault output being spent.\n */\n peginTxHex: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex).\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex).\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex).\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex). This MUST be the\n * key registered on-chain for the vault — typically read from\n * `BTCVaultRegistry.getBtcVaultBasicInfo(...).depositorBtcPubKey`.\n *\n * Required: omitting it would degrade `validateWalletPubkey` to a\n * self-comparison, allowing the wrong wallet to produce a signature\n * over a script tree that doesn't match the on-chain UTXO.\n */\n depositorBtcPubkey: string;\n\n /**\n * The on-chain registered depositor payout scriptPubKey (hex, with or without 0x prefix).\n * Used to validate that the VP-provided payout transaction actually pays to the\n * correct depositor payout address before signing.\n */\n registeredPayoutScriptPubKey: string;\n\n /**\n * The claimer's x-only BTC public key for this payout (64-char hex, no prefix).\n * Forwarded to {@link buildPayoutPsbt} for per-role output validation.\n */\n claimerBtcPubkey: string;\n\n /**\n * VP commission in basis points (`1..=9999`). Forwarded to {@link buildPayoutPsbt}.\n */\n commissionBps: number;\n}\n\n/**\n * Parameters for signing a Payout transaction.\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface SignPayoutParams extends SignPayoutBaseParams {\n /**\n * Payout transaction hex (unsigned).\n * This is the transaction from the vault provider that needs depositor signature.\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex.\n * Payout input 1 references Assert output 0.\n */\n assertTxHex: string;\n}\n\n/**\n * Result of signing a payout transaction.\n */\nexport interface PayoutSignatureResult {\n /**\n * 64-byte Schnorr signature (128 hex characters).\n */\n signature: string;\n\n /**\n * Depositor's BTC public key used for signing.\n */\n depositorBtcPubkey: string;\n}\n\n/**\n * High-level manager for payout transaction signing.\n *\n * @remarks\n * After registering your peg-in on Ethereum (Step 3), the vault provider prepares\n * claim/payout transaction pairs. You must sign each payout transaction using this\n * manager and submit the signatures to the vault provider's RPC API.\n *\n * **What happens internally:**\n * 1. Validates your wallet's public key matches the vault's depositor\n * 2. Builds an unsigned PSBT with taproot script path spend info\n * 3. Signs input 0 (the vault UTXO) with your wallet\n * 4. Extracts the 64-byte Schnorr signature\n *\n * **Note:** The payout transaction has 2 inputs. PayoutManager only signs input 0\n * (from the peg-in tx). Input 1 (from the assert tx) is signed by the vault provider.\n *\n * @see {@link PeginManager} - For the complete peg-in flow context\n * @see {@link buildPayoutPsbt} - Lower-level primitive used internally\n * @see {@link extractPayoutSignature} - Signature extraction primitive\n */\nexport class PayoutManager {\n private readonly config: PayoutManagerConfig;\n\n /**\n * Creates a new PayoutManager instance.\n *\n * @param config - Manager configuration including wallet\n */\n constructor(config: PayoutManagerConfig) {\n this.config = config;\n }\n\n /**\n * Signs a Payout transaction and extracts the Schnorr signature.\n *\n * Flow:\n * 1. Vault provider submits Claim transaction\n * 2. Claimer submits Assert transaction to prove validity\n * 3. Payout can be executed (references Assert tx)\n *\n * This method orchestrates the following steps:\n * 1. Get wallet's public key and convert to x-only format\n * 2. Validate wallet pubkey matches on-chain depositor pubkey (if provided)\n * 3. Build unsigned PSBT using primitives\n * 4. Sign PSBT via btcWallet.signPsbt()\n * 5. Extract 64-byte Schnorr signature using primitives\n *\n * The returned signature can be submitted to the vault provider API.\n *\n * @param params - Payout signing parameters\n * @returns Signature result with 64-byte Schnorr signature and depositor pubkey\n * @throws Error if wallet pubkey doesn't match depositor pubkey\n * @throws Error if wallet operations fail or signature extraction fails\n */\n async signPayoutTransaction(\n params: SignPayoutParams,\n ): Promise<PayoutSignatureResult> {\n // Validate wallet pubkey matches depositor and get both formats\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n params.depositorBtcPubkey,\n );\n\n // Build unsigned PSBT for Payout (uses Assert tx). Per-role output\n // validation happens inside buildPayoutPsbt against the resolved input\n // values.\n const payoutPsbt = await buildPayoutPsbt({\n payoutTxHex: params.payoutTxHex,\n peginTxHex: params.peginTxHex,\n assertTxHex: params.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: params.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: params.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: this.config.network,\n claimerBtcPubkey: params.claimerBtcPubkey,\n registeredPayoutScriptPubKey: params.registeredPayoutScriptPubKey,\n commissionBps: params.commissionBps,\n });\n\n // Sign PSBT via wallet (Taproot script-path spend, input 0 only)\n const signedPsbtHex = await this.config.btcWallet.signPsbt(\n payoutPsbt.psbtHex,\n createTaprootScriptPathSignOptions(walletPubkeyRaw, 1),\n );\n\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: payoutPsbt.psbtHex,\n returnedPsbtHex: signedPsbtHex,\n });\n\n // Extract Schnorr signature\n const signature = extractPayoutSignature(signedPsbtHex, depositorPubkey);\n\n return {\n signature,\n depositorBtcPubkey: depositorPubkey,\n };\n }\n\n /**\n * Gets the configured Bitcoin network.\n *\n * @returns The Bitcoin network (mainnet, testnet, signet, regtest)\n */\n getNetwork(): Network {\n return this.config.network;\n }\n\n /**\n * Checks if the wallet supports batch signing (signPsbts).\n *\n * @returns true if batch signing is supported\n */\n supportsBatchSigning(): boolean {\n return typeof this.config.btcWallet.signPsbts === \"function\";\n }\n\n /**\n * Batch signs multiple payout transactions (1 per claimer).\n * This allows signing all transactions with a single wallet interaction.\n *\n * @param transactions - Array of payout params to sign\n * @returns Array of signature results matching input order\n * @throws Error if wallet doesn't support batch signing\n * @throws Error if any signing operation fails\n */\n async signPayoutTransactionsBatch(\n transactions: SignPayoutParams[],\n ): Promise<\n Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }>\n > {\n if (!this.supportsBatchSigning()) {\n throw new Error(\n \"Wallet does not support batch signing (signPsbts method not available)\",\n );\n }\n\n // Get wallet pubkey once\n const walletPubkeyRaw = await this.config.btcWallet.getPublicKeyHex();\n\n // Build all PSBTs (1 per claimer)\n const psbtsToSign: string[] = [];\n const signOptions: SignPsbtOptions[] = [];\n const depositorPubkeys: string[] = [];\n\n for (const tx of transactions) {\n // Validate wallet pubkey matches depositor\n const { depositorPubkey } = validateWalletPubkey(\n walletPubkeyRaw,\n tx.depositorBtcPubkey,\n );\n depositorPubkeys.push(depositorPubkey);\n\n // Build Payout PSBT (output validation runs inside buildPayoutPsbt\n // against resolved input values).\n const payoutPsbt = await buildPayoutPsbt({\n payoutTxHex: tx.payoutTxHex,\n peginTxHex: tx.peginTxHex,\n assertTxHex: tx.assertTxHex,\n depositorBtcPubkey: depositorPubkey,\n vaultProviderBtcPubkey: tx.vaultProviderBtcPubkey,\n vaultKeeperBtcPubkeys: tx.vaultKeeperBtcPubkeys,\n universalChallengerBtcPubkeys: tx.universalChallengerBtcPubkeys,\n timelockPegin: tx.timelockPegin,\n network: this.config.network,\n claimerBtcPubkey: tx.claimerBtcPubkey,\n registeredPayoutScriptPubKey: tx.registeredPayoutScriptPubKey,\n commissionBps: tx.commissionBps,\n });\n psbtsToSign.push(payoutPsbt.psbtHex);\n signOptions.push(createTaprootScriptPathSignOptions(walletPubkeyRaw, 1));\n }\n\n // Batch sign all PSBTs with single wallet interaction\n const signedPsbts = await this.config.btcWallet.signPsbts!(\n psbtsToSign,\n signOptions,\n );\n\n // Validate that wallet returned the expected number of signed PSBTs\n if (signedPsbts.length !== transactions.length) {\n throw new Error(\n `Expected ${transactions.length} signed PSBTs but received ${signedPsbts.length}`,\n );\n }\n\n // Extract signatures from signed PSBTs\n const results: Array<{\n payoutSignature: string;\n depositorBtcPubkey: string;\n }> = [];\n\n for (let i = 0; i < transactions.length; i++) {\n const depositorPubkey = depositorPubkeys[i];\n assertPsbtUnsignedTxMatches({\n requestedPsbtHex: psbtsToSign[i],\n returnedPsbtHex: signedPsbts[i],\n });\n const payoutSignature = extractPayoutSignature(\n signedPsbts[i],\n depositorPubkey,\n );\n\n results.push({\n payoutSignature,\n depositorBtcPubkey: depositorPubkey,\n });\n }\n\n return results;\n }\n\n}\n"],"names":["OP_RETURN","OP_PUSH32","OP_RETURN_PUSH32_SCRIPT_LEN","assertAuthAnchorOpReturn","fundedPrePeginTxHex","vaultCount","expectedAuthAnchorHashHex","cleanHex","stripHexPrefix","tx","bitcoin","opReturnOutput","script","pushedHex","findAuthAnchorOpReturn","hits","i","output","HEX_BYTES32_LENGTH","hexToBytes","hex","clean","bytes","bytesToHex","b","assertBytes32","value","label","computeHashlock","secret","secretBytes","hash","sha256","validateSecretAgainstHashlock","hashlock","PayoutManager","config","__publicField","params","walletPubkeyRaw","depositorPubkey","validateWalletPubkey","payoutPsbt","buildPayoutPsbt","signedPsbtHex","createTaprootScriptPathSignOptions","assertPsbtUnsignedTxMatches","extractPayoutSignature","transactions","psbtsToSign","signOptions","depositorPubkeys","signedPsbts","results","payoutSignature"],"mappings":"osBAYMA,EAAY,IAEZC,EAAY,GAEZC,EAA8B,GAmB7B,SAASC,EACdC,EACAC,EACAC,EACM,CACN,MAAMC,EAAWC,EAAAA,eAAeJ,CAAmB,EAC7CK,EAAKC,EAAQ,YAAY,QAAQH,CAAQ,EAE/C,GAAIE,EAAG,KAAK,QAAUJ,EACpB,MAAM,IAAI,MACR,mDAAmDI,EAAG,KAAK,MAAM,+BACjCJ,EAAa,CAAC,8BAAA,EAIlD,MAAMM,EAAiBF,EAAG,KAAKJ,CAAU,EACnCO,EAASD,EAAe,OAC9B,GACEC,EAAO,SAAWV,GAClBU,EAAO,CAAC,IAAMZ,GACdY,EAAO,CAAC,IAAMX,EAEd,MAAM,IAAI,MACR,2CAA2CI,CAAU,wCAC3BO,EAAO,MAAM,8BAChCA,EAAO,MAAM,EAAG,KAAK,IAAI,EAAGA,EAAO,MAAM,CAAC,EAAE,SAAS,KAAK,CAAC,cACpDV,CAA2B,kCAAA,EAI7C,MAAMW,EAAYD,EAAO,MAAM,CAAC,EAAE,SAAS,KAAK,EAAE,YAAA,EAClD,GAAIC,IAAcP,EAA0B,cAC1C,MAAM,IAAI,MACR,4DAA4DD,CAAU,eACvDQ,CAAS,cAAcP,CAAyB,EAAA,EAInE,GAAIK,EAAe,QAAU,EAC3B,MAAM,IAAI,MACR,2CAA2CN,CAAU,uBAC1CM,EAAe,KAAK,qCAAA,CAGrC,CAgEO,SAASG,EACdV,EAC4C,CAC5C,IAAIK,EACJ,GAAI,CACFA,EAAKC,EAAQ,YAAY,QAAQF,EAAAA,eAAeJ,CAAmB,CAAC,CACtE,MAAQ,CACN,MACF,CAEA,MAAMW,EAAyC,CAAA,EAC/C,QAASC,EAAI,EAAGA,EAAIP,EAAG,KAAK,OAAQO,IAAK,CACvC,MAAMC,EAASR,EAAG,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ddress as Jt } fro
|
|
|
9
9
|
import { B as I } from "./BTCVaultRegistry.abi-Cq9-JlqT.js";
|
|
10
10
|
import { h as H } from "./errors-CznAK5NB.js";
|
|
11
11
|
import { expandWotsSeed as te, expandHashlockSecret as ee, expandAuthAnchor as ne, deriveVaultId as pt } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
12
|
-
import { b as mt, a as se,
|
|
12
|
+
import { b as mt, a as se, d as bt } from "./assertPsbtUnsignedTxMatches-CsawQGjC.js";
|
|
13
13
|
import { b as oe, e as re, f as ie } from "./peginInput-BPRB9tUi.js";
|
|
14
14
|
import { u as K, h as et, e as v, p as ae, i as wt, s as T, j as Pt, X as ce } from "./bitcoin-B5aNKtsk.js";
|
|
15
15
|
import { c as le } from "./signing-DaLvGwQe.js";
|
|
16
16
|
import { M as yt } from "./validation-CxqROCno.js";
|
|
17
|
-
import { c as ue, a as he } from "./PayoutManager-
|
|
17
|
+
import { c as ue, a as he } from "./PayoutManager-2XpjdLxE.js";
|
|
18
18
|
import { s as de, f as z, i as ge, w as xt } from "./waitForTransactionReceiptSmartAware-CmgFXFza.js";
|
|
19
19
|
import { p as fe, f as pe } from "./fundPeginTransaction-t-6TsHAY.js";
|
|
20
20
|
import { p as me, f as be } from "./mempoolApi-CAIge7Nj.js";
|
|
@@ -1288,4 +1288,4 @@ export {
|
|
|
1288
1288
|
Un as e,
|
|
1289
1289
|
Ie as f
|
|
1290
1290
|
};
|
|
1291
|
-
//# sourceMappingURL=PeginManager-
|
|
1291
|
+
//# sourceMappingURL=PeginManager-CBQnWvX8.js.map
|