@babylonlabs-io/ts-sdk 0.26.2 → 0.27.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/{bitcoin-nOOgeRyl.js → bitcoin-B-Y0DlqR.js} +63 -60
- package/dist/bitcoin-B-Y0DlqR.js.map +1 -0
- package/dist/bitcoin-DIN0OupO.cjs +2 -0
- package/dist/bitcoin-DIN0OupO.cjs.map +1 -0
- package/dist/buildAndBroadcastRefund-BEASMFsz.cjs +2 -0
- package/dist/buildAndBroadcastRefund-BEASMFsz.cjs.map +1 -0
- package/dist/buildAndBroadcastRefund-BzYJv-Fv.js +862 -0
- package/dist/buildAndBroadcastRefund-BzYJv-Fv.js.map +1 -0
- package/dist/challengeAssert-BM8m9gPM.cjs +2 -0
- package/dist/challengeAssert-BM8m9gPM.cjs.map +1 -0
- package/dist/{challengeAssert-CH32j5cZ.js → challengeAssert-j2Vwqo0-.js} +135 -120
- package/dist/challengeAssert-j2Vwqo0-.js.map +1 -0
- package/dist/context-BSdcD4J_.cjs +2 -0
- package/dist/context-BSdcD4J_.cjs.map +1 -0
- package/dist/{errors-CQjAF9QE.js → context-CClNOyD3.js} +442 -324
- package/dist/context-CClNOyD3.js.map +1 -0
- package/dist/fundPeginTransaction-DaWoYCgO.cjs +2 -0
- package/dist/fundPeginTransaction-DaWoYCgO.cjs.map +1 -0
- package/dist/fundPeginTransaction-oV-dNJOU.js +76 -0
- package/dist/fundPeginTransaction-oV-dNJOU.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +100 -91
- package/dist/{payout-DzGsAnhf.js → payout-B_fvQU3q.js} +2 -2
- package/dist/{payout-DzGsAnhf.js.map → payout-B_fvQU3q.js.map} +1 -1
- package/dist/{payout-RFIh7GLN.cjs → payout-DP6KMFP1.cjs} +2 -2
- package/dist/{payout-RFIh7GLN.cjs.map → payout-DP6KMFP1.cjs.map} +1 -1
- package/dist/psbtInputFields-C3dqKWjQ.js +258 -0
- package/dist/psbtInputFields-C3dqKWjQ.js.map +1 -0
- package/dist/psbtInputFields-DhGm77bP.cjs +2 -0
- package/dist/psbtInputFields-DhGm77bP.cjs.map +1 -0
- package/dist/sha2-1XZuToHP.cjs +2 -0
- package/dist/sha2-1XZuToHP.cjs.map +1 -0
- package/dist/sha2-ZzfZqQSw.js +1123 -0
- package/dist/sha2-ZzfZqQSw.js.map +1 -0
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +27 -24
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/bip322Verify.test.d.ts +17 -0
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/bip322Verify.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/cbor.test.d.ts +15 -0
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/cbor.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/goldenVectors.d.ts +44 -0
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/goldenVectors.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/serverIdentity.test.d.ts +2 -0
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/serverIdentity.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/tokenProvider.test.d.ts +2 -0
- package/dist/tbv/core/clients/vault-provider/auth/__tests__/tokenProvider.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/bip322Verify.d.ts +56 -0
- package/dist/tbv/core/clients/vault-provider/auth/bip322Verify.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/cbor.d.ts +44 -0
- package/dist/tbv/core/clients/vault-provider/auth/cbor.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/index.d.ts +10 -0
- package/dist/tbv/core/clients/vault-provider/auth/index.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/serverIdentity.d.ts +68 -0
- package/dist/tbv/core/clients/vault-provider/auth/serverIdentity.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts +81 -0
- package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts.map +1 -0
- package/dist/tbv/core/clients/vault-provider/index.d.ts +2 -1
- package/dist/tbv/core/clients/vault-provider/index.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts +66 -1
- package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts.map +1 -1
- package/dist/tbv/core/clients/vault-provider/validators.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.d.ts +3 -0
- package/dist/tbv/core/index.d.ts.map +1 -1
- package/dist/tbv/core/index.js +96 -87
- package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.js +3 -3
- package/dist/tbv/core/primitives/psbt/pegin.d.ts +17 -2
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts +19 -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/fee/__tests__/constants.test.d.ts +2 -0
- package/dist/tbv/core/utils/fee/__tests__/constants.test.d.ts.map +1 -0
- package/dist/tbv/core/utils/fee/constants.d.ts +30 -9
- package/dist/tbv/core/utils/fee/constants.d.ts.map +1 -1
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +28 -27
- package/dist/tbv/core/utils/utxo/availability.d.ts.map +1 -1
- package/dist/tbv/core/utils/utxo/selectUtxos.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/__tests__/context.golden.test.d.ts +34 -0
- package/dist/tbv/core/vault-secrets/__tests__/context.golden.test.d.ts.map +1 -0
- package/dist/tbv/core/vault-secrets/__tests__/context.test.d.ts +6 -0
- package/dist/tbv/core/vault-secrets/__tests__/context.test.d.ts.map +1 -0
- package/dist/tbv/core/vault-secrets/__tests__/expand.test.d.ts +10 -0
- package/dist/tbv/core/vault-secrets/__tests__/expand.test.d.ts.map +1 -0
- package/dist/tbv/core/vault-secrets/__tests__/info.test.d.ts +8 -0
- package/dist/tbv/core/vault-secrets/__tests__/info.test.d.ts.map +1 -0
- package/dist/tbv/core/vault-secrets/context.d.ts +52 -0
- package/dist/tbv/core/vault-secrets/context.d.ts.map +1 -0
- package/dist/tbv/core/vault-secrets/expand.d.ts +43 -0
- package/dist/tbv/core/vault-secrets/expand.d.ts.map +1 -0
- package/dist/tbv/core/vault-secrets/index.d.ts +16 -0
- package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -0
- package/dist/tbv/core/vault-secrets/info.d.ts +55 -0
- package/dist/tbv/core/vault-secrets/info.d.ts.map +1 -0
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +96 -87
- package/dist/tbv/integrations/aave/index.cjs +1 -1
- package/dist/tbv/integrations/aave/index.cjs.map +1 -1
- package/dist/tbv/integrations/aave/index.js +164 -159
- package/dist/tbv/integrations/aave/index.js.map +1 -1
- package/dist/tbv/integrations/aave/utils/vaultSplit.d.ts.map +1 -1
- package/dist/vault-registry-reader-BizmBSBV.cjs +2 -0
- package/dist/vault-registry-reader-BizmBSBV.cjs.map +1 -0
- package/dist/{index-D7s2ilf8.js → vault-registry-reader-CpCOte7w.js} +522 -268
- package/dist/vault-registry-reader-CpCOte7w.js.map +1 -0
- package/package.json +8 -3
- package/dist/bitcoin-CNnPFU6Y.cjs +0 -2
- package/dist/bitcoin-CNnPFU6Y.cjs.map +0 -1
- package/dist/bitcoin-nOOgeRyl.js.map +0 -1
- package/dist/buildAndBroadcastRefund-Ccp-2GWW.js +0 -1334
- package/dist/buildAndBroadcastRefund-Ccp-2GWW.js.map +0 -1
- package/dist/buildAndBroadcastRefund-Mr3ck5ek.cjs +0 -2
- package/dist/buildAndBroadcastRefund-Mr3ck5ek.cjs.map +0 -1
- package/dist/challengeAssert-CH32j5cZ.js.map +0 -1
- package/dist/challengeAssert-X7V3Ik_Q.cjs +0 -2
- package/dist/challengeAssert-X7V3Ik_Q.cjs.map +0 -1
- package/dist/errors-BBrP8sLT.cjs +0 -2
- package/dist/errors-BBrP8sLT.cjs.map +0 -1
- package/dist/errors-CQjAF9QE.js.map +0 -1
- package/dist/fundPeginTransaction-BLYXxLBv.js +0 -70
- package/dist/fundPeginTransaction-BLYXxLBv.js.map +0 -1
- package/dist/fundPeginTransaction-DxNOeyNI.cjs +0 -2
- package/dist/fundPeginTransaction-DxNOeyNI.cjs.map +0 -1
- package/dist/index-CIuXb72l.cjs +0 -2
- package/dist/index-CIuXb72l.cjs.map +0 -1
- package/dist/index-D7s2ilf8.js.map +0 -1
- package/dist/psbtInputFields-1dXR4hLk.js +0 -237
- package/dist/psbtInputFields-1dXR4hLk.js.map +0 -1
- package/dist/psbtInputFields-tnAR8tG5.cjs +0 -2
- package/dist/psbtInputFields-tnAR8tG5.cjs.map +0 -1
- package/dist/types-WrGfwlJd.js +0 -608
- package/dist/types-WrGfwlJd.js.map +0 -1
- package/dist/types-xU3SBcpH.cjs +0 -2
- package/dist/types-xU3SBcpH.cjs.map +0 -1
|
@@ -1,20 +1,21 @@
|
|
|
1
|
-
import { p as
|
|
2
|
-
import { createPrePeginTransaction as
|
|
3
|
-
import {
|
|
4
|
-
import { Buffer as
|
|
5
|
-
import { Transaction as
|
|
1
|
+
import { p as H, s as f, u as v, h as p, T as y } from "./bitcoin-B-Y0DlqR.js";
|
|
2
|
+
import { createPrePeginTransaction as I, buildPeginTxFromPrePegin as A, getPrePeginHtlcConnectorInfo as T, tapInternalPubkey as k, getPeginPayoutScriptInfo as E, getAssertNoPayoutScriptInfo as B, getChallengeAssertScriptInfo as C } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
3
|
+
import { c as L } from "./fundPeginTransaction-oV-dNJOU.js";
|
|
4
|
+
import { Buffer as a } from "buffer";
|
|
5
|
+
import { Transaction as g, Psbt as d } from "bitcoinjs-lib";
|
|
6
6
|
function b(e) {
|
|
7
|
-
return
|
|
7
|
+
return H(e).toLowerCase();
|
|
8
8
|
}
|
|
9
|
-
function
|
|
9
|
+
function q(e, n, t) {
|
|
10
10
|
const s = /* @__PURE__ */ new Set();
|
|
11
11
|
s.add(b(e));
|
|
12
|
-
for (const o of
|
|
12
|
+
for (const o of n)
|
|
13
13
|
s.add(b(o));
|
|
14
|
-
return s.delete(b(
|
|
14
|
+
return s.delete(b(t)), s.size;
|
|
15
15
|
}
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
const S = 64, V = /^[0-9a-fA-F]+$/;
|
|
17
|
+
async function N(e) {
|
|
18
|
+
const n = m(e.authAnchorHash), t = await I({
|
|
18
19
|
depositorPubkey: e.depositorPubkey,
|
|
19
20
|
vaultProviderPubkey: e.vaultProviderPubkey,
|
|
20
21
|
vaultKeeperPubkeys: e.vaultKeeperPubkeys,
|
|
@@ -26,23 +27,34 @@ async function U(e) {
|
|
|
26
27
|
numLocalChallengers: e.numLocalChallengers,
|
|
27
28
|
councilQuorum: e.councilQuorum,
|
|
28
29
|
councilSize: e.councilSize,
|
|
29
|
-
network: e.network
|
|
30
|
-
|
|
31
|
-
|
|
30
|
+
network: e.network,
|
|
31
|
+
authAnchorHash: n
|
|
32
|
+
}), o = L(t.txHex).outputs.reduce(
|
|
33
|
+
(c, u) => c + BigInt(u.value),
|
|
32
34
|
0n
|
|
33
|
-
);
|
|
35
|
+
), r = n !== void 0 ? t.htlcValues.length : null;
|
|
34
36
|
return {
|
|
35
37
|
psbtHex: t.txHex,
|
|
36
|
-
totalOutputValue:
|
|
38
|
+
totalOutputValue: o,
|
|
37
39
|
htlcValues: t.htlcValues,
|
|
38
40
|
htlcScriptPubKeys: t.htlcScriptPubKeys,
|
|
39
41
|
htlcAddresses: t.htlcAddresses,
|
|
40
42
|
peginAmounts: t.peginAmounts,
|
|
41
|
-
depositorClaimValue: t.depositorClaimValue
|
|
43
|
+
depositorClaimValue: t.depositorClaimValue,
|
|
44
|
+
authAnchorVout: r
|
|
42
45
|
};
|
|
43
46
|
}
|
|
44
|
-
|
|
45
|
-
|
|
47
|
+
function m(e) {
|
|
48
|
+
if (e === void 0) return;
|
|
49
|
+
const n = e.startsWith("0x") || e.startsWith("0X") ? e.slice(2) : e;
|
|
50
|
+
if (n.length !== S || !V.test(n))
|
|
51
|
+
throw new Error(
|
|
52
|
+
`authAnchorHash must be 32-byte hex (${S} chars, no 0x prefix); got length ${n.length}`
|
|
53
|
+
);
|
|
54
|
+
return n.toLowerCase();
|
|
55
|
+
}
|
|
56
|
+
async function O(e) {
|
|
57
|
+
const n = await A(
|
|
46
58
|
{
|
|
47
59
|
depositorPubkey: e.prePeginParams.depositorPubkey,
|
|
48
60
|
vaultProviderPubkey: e.prePeginParams.vaultProviderPubkey,
|
|
@@ -55,21 +67,24 @@ async function q(e) {
|
|
|
55
67
|
numLocalChallengers: e.prePeginParams.numLocalChallengers,
|
|
56
68
|
councilQuorum: e.prePeginParams.councilQuorum,
|
|
57
69
|
councilSize: e.prePeginParams.councilSize,
|
|
58
|
-
network: e.prePeginParams.network
|
|
70
|
+
network: e.prePeginParams.network,
|
|
71
|
+
authAnchorHash: m(
|
|
72
|
+
e.prePeginParams.authAnchorHash
|
|
73
|
+
)
|
|
59
74
|
},
|
|
60
75
|
e.timelockPegin,
|
|
61
76
|
e.fundedPrePeginTxHex,
|
|
62
77
|
e.htlcVout
|
|
63
78
|
);
|
|
64
79
|
return {
|
|
65
|
-
txHex:
|
|
66
|
-
txid:
|
|
67
|
-
vaultScriptPubKey:
|
|
68
|
-
vaultValue:
|
|
80
|
+
txHex: n.txHex,
|
|
81
|
+
txid: n.txid,
|
|
82
|
+
vaultScriptPubKey: n.vaultScriptPubKey,
|
|
83
|
+
vaultValue: n.vaultValue
|
|
69
84
|
};
|
|
70
85
|
}
|
|
71
|
-
async function
|
|
72
|
-
const
|
|
86
|
+
async function F(e) {
|
|
87
|
+
const n = f(e.peginTxHex), t = f(e.fundedPrePeginTxHex), s = await T({
|
|
73
88
|
depositorPubkey: e.depositorPubkey,
|
|
74
89
|
vaultProviderPubkey: e.vaultProviderPubkey,
|
|
75
90
|
vaultKeeperPubkeys: e.vaultKeeperPubkeys,
|
|
@@ -77,40 +92,40 @@ async function O(e) {
|
|
|
77
92
|
hashlock: e.hashlock,
|
|
78
93
|
timelockRefund: e.timelockRefund,
|
|
79
94
|
network: e.network
|
|
80
|
-
}), o =
|
|
95
|
+
}), o = g.fromHex(n), r = g.fromHex(t);
|
|
81
96
|
if (o.ins.length !== 1)
|
|
82
97
|
throw new Error(
|
|
83
98
|
`PegIn transaction must have exactly 1 input, got ${o.ins.length}`
|
|
84
99
|
);
|
|
85
|
-
const
|
|
86
|
-
new Uint8Array(
|
|
100
|
+
const c = o.ins[0], u = r.getId(), i = v(
|
|
101
|
+
new Uint8Array(c.hash).slice().reverse()
|
|
87
102
|
);
|
|
88
103
|
if (i !== u)
|
|
89
104
|
throw new Error(
|
|
90
105
|
`PegIn input does not reference the Pre-PegIn transaction. Expected ${u}, got ${i}`
|
|
91
106
|
);
|
|
92
|
-
const
|
|
93
|
-
if (!
|
|
107
|
+
const l = r.outs[c.index];
|
|
108
|
+
if (!l)
|
|
94
109
|
throw new Error(
|
|
95
|
-
`Pre-PegIn output ${
|
|
110
|
+
`Pre-PegIn output ${c.index} not found (Pre-PegIn has ${r.outs.length} outputs)`
|
|
96
111
|
);
|
|
97
|
-
const
|
|
112
|
+
const h = p(s.hashlockScript), P = p(s.hashlockControlBlock), x = new d();
|
|
98
113
|
x.setVersion(o.version), x.setLocktime(o.locktime), x.addInput({
|
|
99
|
-
hash:
|
|
100
|
-
index:
|
|
101
|
-
sequence:
|
|
114
|
+
hash: c.hash,
|
|
115
|
+
index: c.index,
|
|
116
|
+
sequence: c.sequence,
|
|
102
117
|
witnessUtxo: {
|
|
103
|
-
script:
|
|
104
|
-
value:
|
|
118
|
+
script: l.script,
|
|
119
|
+
value: l.value
|
|
105
120
|
},
|
|
106
121
|
tapLeafScript: [
|
|
107
122
|
{
|
|
108
123
|
leafVersion: y,
|
|
109
|
-
script:
|
|
110
|
-
controlBlock:
|
|
124
|
+
script: a.from(h),
|
|
125
|
+
controlBlock: a.from(P)
|
|
111
126
|
}
|
|
112
127
|
],
|
|
113
|
-
tapInternalKey:
|
|
128
|
+
tapInternalKey: a.from(k)
|
|
114
129
|
// sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot
|
|
115
130
|
});
|
|
116
131
|
for (const w of o.outs)
|
|
@@ -120,19 +135,19 @@ async function O(e) {
|
|
|
120
135
|
});
|
|
121
136
|
return { psbtHex: x.toHex() };
|
|
122
137
|
}
|
|
123
|
-
function
|
|
138
|
+
function W(e, n) {
|
|
124
139
|
const s = d.fromHex(e).data.inputs[0];
|
|
125
140
|
if (!s)
|
|
126
141
|
throw new Error("PegIn PSBT has no inputs");
|
|
127
142
|
if (s.tapScriptSig && s.tapScriptSig.length > 0) {
|
|
128
|
-
const o =
|
|
129
|
-
p(
|
|
143
|
+
const o = a.from(
|
|
144
|
+
p(n)
|
|
130
145
|
);
|
|
131
146
|
for (const r of s.tapScriptSig)
|
|
132
147
|
if (r.pubkey.equals(o))
|
|
133
|
-
return
|
|
148
|
+
return $(r.signature);
|
|
134
149
|
throw new Error(
|
|
135
|
-
`No PegIn input signature found for depositor pubkey: ${
|
|
150
|
+
`No PegIn input signature found for depositor pubkey: ${n}`
|
|
136
151
|
);
|
|
137
152
|
}
|
|
138
153
|
throw s.finalScriptWitness && s.finalScriptWitness.length > 0 ? new Error(
|
|
@@ -141,134 +156,134 @@ function _(e, t) {
|
|
|
141
156
|
"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT"
|
|
142
157
|
);
|
|
143
158
|
}
|
|
144
|
-
function
|
|
145
|
-
const
|
|
159
|
+
function D(e) {
|
|
160
|
+
const n = d.fromHex(e);
|
|
146
161
|
try {
|
|
147
|
-
|
|
148
|
-
} catch (
|
|
149
|
-
if (!
|
|
162
|
+
n.finalizeAllInputs();
|
|
163
|
+
} catch (t) {
|
|
164
|
+
if (!n.data.inputs.every(
|
|
150
165
|
(o) => o.finalScriptWitness || o.finalScriptSig
|
|
151
166
|
))
|
|
152
167
|
throw new Error(
|
|
153
|
-
`PSBT finalization failed and wallet did not auto-finalize: ${
|
|
168
|
+
`PSBT finalization failed and wallet did not auto-finalize: ${t}`
|
|
154
169
|
);
|
|
155
170
|
}
|
|
156
|
-
return
|
|
171
|
+
return n.extractTransaction().toHex();
|
|
157
172
|
}
|
|
158
|
-
function
|
|
173
|
+
function $(e) {
|
|
159
174
|
if (e.length === 64)
|
|
160
175
|
return v(new Uint8Array(e));
|
|
161
176
|
if (e.length === 65) {
|
|
162
|
-
const
|
|
163
|
-
if (
|
|
177
|
+
const n = e[64];
|
|
178
|
+
if (n !== g.SIGHASH_ALL)
|
|
164
179
|
throw new Error(
|
|
165
|
-
`Unexpected sighash type 0x${
|
|
180
|
+
`Unexpected sighash type 0x${n.toString(16).padStart(2, "0")} in PegIn input signature. Expected SIGHASH_DEFAULT (64-byte sig) or SIGHASH_ALL (0x01).`
|
|
166
181
|
);
|
|
167
182
|
return v(new Uint8Array(e.subarray(0, 64)));
|
|
168
183
|
}
|
|
169
184
|
throw new Error(`Unexpected PegIn input signature length: ${e.length}`);
|
|
170
185
|
}
|
|
171
|
-
async function
|
|
172
|
-
const
|
|
186
|
+
async function Q(e) {
|
|
187
|
+
const n = f(e.payoutTxHex), t = g.fromHex(n), { payoutScript: s, payoutControlBlock: o } = await E(
|
|
173
188
|
e.connectorParams
|
|
174
|
-
), r = p(s),
|
|
175
|
-
u.setVersion(
|
|
176
|
-
for (let i = 0; i <
|
|
177
|
-
const
|
|
178
|
-
if (!
|
|
189
|
+
), r = p(s), c = p(o), u = new d();
|
|
190
|
+
u.setVersion(t.version), u.setLocktime(t.locktime);
|
|
191
|
+
for (let i = 0; i < t.ins.length; i++) {
|
|
192
|
+
const l = t.ins[i], h = e.prevouts[i];
|
|
193
|
+
if (!h)
|
|
179
194
|
throw new Error(`Missing prevout data for input ${i}`);
|
|
180
|
-
const
|
|
181
|
-
hash:
|
|
182
|
-
index:
|
|
183
|
-
sequence:
|
|
195
|
+
const P = {
|
|
196
|
+
hash: l.hash,
|
|
197
|
+
index: l.index,
|
|
198
|
+
sequence: l.sequence,
|
|
184
199
|
witnessUtxo: {
|
|
185
|
-
script:
|
|
186
|
-
value:
|
|
200
|
+
script: a.from(p(f(h.script_pubkey))),
|
|
201
|
+
value: h.value
|
|
187
202
|
}
|
|
188
203
|
};
|
|
189
|
-
i === 0 && (
|
|
204
|
+
i === 0 && (P.tapLeafScript = [
|
|
190
205
|
{
|
|
191
206
|
leafVersion: y,
|
|
192
|
-
script:
|
|
193
|
-
controlBlock:
|
|
207
|
+
script: a.from(r),
|
|
208
|
+
controlBlock: a.from(c)
|
|
194
209
|
}
|
|
195
|
-
],
|
|
210
|
+
], P.tapInternalKey = a.from(k)), u.addInput(P);
|
|
196
211
|
}
|
|
197
|
-
for (const i of
|
|
212
|
+
for (const i of t.outs)
|
|
198
213
|
u.addOutput({
|
|
199
214
|
script: i.script,
|
|
200
215
|
value: i.value
|
|
201
216
|
});
|
|
202
217
|
return u.toHex();
|
|
203
218
|
}
|
|
204
|
-
async function
|
|
205
|
-
const
|
|
219
|
+
async function X(e) {
|
|
220
|
+
const n = f(e.noPayoutTxHex), t = g.fromHex(n), { noPayoutScript: s, noPayoutControlBlock: o } = await B(
|
|
206
221
|
e.connectorParams,
|
|
207
222
|
e.challengerPubkey
|
|
208
|
-
), r = p(s),
|
|
209
|
-
u.setVersion(
|
|
210
|
-
for (let i = 0; i <
|
|
211
|
-
const
|
|
212
|
-
if (!
|
|
223
|
+
), r = p(s), c = p(o), u = new d();
|
|
224
|
+
u.setVersion(t.version), u.setLocktime(t.locktime);
|
|
225
|
+
for (let i = 0; i < t.ins.length; i++) {
|
|
226
|
+
const l = t.ins[i], h = e.prevouts[i];
|
|
227
|
+
if (!h)
|
|
213
228
|
throw new Error(`Missing prevout data for input ${i}`);
|
|
214
|
-
const
|
|
215
|
-
hash:
|
|
216
|
-
index:
|
|
217
|
-
sequence:
|
|
229
|
+
const P = {
|
|
230
|
+
hash: l.hash,
|
|
231
|
+
index: l.index,
|
|
232
|
+
sequence: l.sequence,
|
|
218
233
|
witnessUtxo: {
|
|
219
|
-
script:
|
|
220
|
-
value:
|
|
234
|
+
script: a.from(p(f(h.script_pubkey))),
|
|
235
|
+
value: h.value
|
|
221
236
|
}
|
|
222
237
|
};
|
|
223
|
-
i === 0 && (
|
|
238
|
+
i === 0 && (P.tapLeafScript = [
|
|
224
239
|
{
|
|
225
240
|
leafVersion: y,
|
|
226
|
-
script:
|
|
227
|
-
controlBlock:
|
|
241
|
+
script: a.from(r),
|
|
242
|
+
controlBlock: a.from(c)
|
|
228
243
|
}
|
|
229
|
-
],
|
|
244
|
+
], P.tapInternalKey = a.from(k)), u.addInput(P);
|
|
230
245
|
}
|
|
231
|
-
for (const i of
|
|
246
|
+
for (const i of t.outs)
|
|
232
247
|
u.addOutput({
|
|
233
248
|
script: i.script,
|
|
234
249
|
value: i.value
|
|
235
250
|
});
|
|
236
251
|
return u.toHex();
|
|
237
252
|
}
|
|
238
|
-
async function
|
|
239
|
-
const
|
|
240
|
-
if (e.connectorParamsPerInput.length !==
|
|
253
|
+
async function G(e) {
|
|
254
|
+
const n = f(e.challengeAssertTxHex), t = g.fromHex(n);
|
|
255
|
+
if (e.connectorParamsPerInput.length !== t.ins.length)
|
|
241
256
|
throw new Error(
|
|
242
|
-
`Expected ${
|
|
257
|
+
`Expected ${t.ins.length} connector params, got ${e.connectorParamsPerInput.length}`
|
|
243
258
|
);
|
|
244
259
|
const s = await Promise.all(
|
|
245
|
-
e.connectorParamsPerInput.map((r) =>
|
|
260
|
+
e.connectorParamsPerInput.map((r) => C(r))
|
|
246
261
|
), o = new d();
|
|
247
|
-
o.setVersion(
|
|
248
|
-
for (let r = 0; r <
|
|
249
|
-
const
|
|
262
|
+
o.setVersion(t.version), o.setLocktime(t.locktime);
|
|
263
|
+
for (let r = 0; r < t.ins.length; r++) {
|
|
264
|
+
const c = t.ins[r], u = e.prevouts[r];
|
|
250
265
|
if (!u)
|
|
251
266
|
throw new Error(`Missing prevout data for input ${r}`);
|
|
252
|
-
const { script: i, controlBlock:
|
|
267
|
+
const { script: i, controlBlock: l } = s[r], h = p(i), P = p(l);
|
|
253
268
|
o.addInput({
|
|
254
|
-
hash:
|
|
255
|
-
index:
|
|
256
|
-
sequence:
|
|
269
|
+
hash: c.hash,
|
|
270
|
+
index: c.index,
|
|
271
|
+
sequence: c.sequence,
|
|
257
272
|
witnessUtxo: {
|
|
258
|
-
script:
|
|
273
|
+
script: a.from(p(f(u.script_pubkey))),
|
|
259
274
|
value: u.value
|
|
260
275
|
},
|
|
261
276
|
tapLeafScript: [
|
|
262
277
|
{
|
|
263
278
|
leafVersion: y,
|
|
264
|
-
script:
|
|
265
|
-
controlBlock:
|
|
279
|
+
script: a.from(h),
|
|
280
|
+
controlBlock: a.from(P)
|
|
266
281
|
}
|
|
267
282
|
],
|
|
268
|
-
tapInternalKey:
|
|
283
|
+
tapInternalKey: a.from(k)
|
|
269
284
|
});
|
|
270
285
|
}
|
|
271
|
-
for (const r of
|
|
286
|
+
for (const r of t.outs)
|
|
272
287
|
o.addOutput({
|
|
273
288
|
script: r.script,
|
|
274
289
|
value: r.value
|
|
@@ -276,14 +291,14 @@ async function D(e) {
|
|
|
276
291
|
return o.toHex();
|
|
277
292
|
}
|
|
278
293
|
export {
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
294
|
+
O as a,
|
|
295
|
+
N as b,
|
|
296
|
+
q as c,
|
|
297
|
+
F as d,
|
|
298
|
+
W as e,
|
|
299
|
+
D as f,
|
|
300
|
+
Q as g,
|
|
301
|
+
X as h,
|
|
302
|
+
G as i
|
|
288
303
|
};
|
|
289
|
-
//# sourceMappingURL=challengeAssert-
|
|
304
|
+
//# sourceMappingURL=challengeAssert-j2Vwqo0-.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"challengeAssert-j2Vwqo0-.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/depositorPayout.ts","../src/tbv/core/primitives/psbt/noPayout.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 * 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 stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a depositor Payout PSBT\n */\nexport interface DepositorPayoutParams {\n /** Payout transaction hex (unsigned) from VP */\n payoutTxHex: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\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 * @param params - Depositor payout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildDepositorPayoutPsbt(\n params: DepositorPayoutParams,\n): Promise<string> {\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const payoutTx = Transaction.fromHex(payoutTxHex);\n\n // Get payout script and control block from WASM (PeginPayoutConnector)\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 // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < payoutTx.ins.length; i++) {\n const input = payoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\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","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n getAssertNoPayoutScriptInfo,\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 stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n","/**\n * 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 stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a ChallengeAssert PSBT\n */\nexport interface ChallengeAssertParams {\n /** ChallengeAssert transaction hex (unsigned) from VP */\n challengeAssertTxHex: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP (flat, one per input) */\n prevouts: Array<{ script_pubkey: string; value: number }>;\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.\n *\n * @param params - ChallengeAssert parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildChallengeAssertPsbt(\n params: ChallengeAssertParams,\n): Promise<string> {\n const challengeAssertTxHex = stripHexPrefix(params.challengeAssertTxHex);\n const challengeAssertTx = Transaction.fromHex(challengeAssertTxHex);\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 // Get script and control block for each input from WASM\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 // Add all inputs — depositor signs every input\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const { 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: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.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 // Add outputs\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","buildDepositorPayoutPsbt","payoutTxHex","payoutTx","payoutScript","payoutControlBlock","getPeginPayoutScriptInfo","scriptBytes","controlBlock","prevout","inputData","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","controlBlockBytes","buildChallengeAssertPsbt","challengeAssertTxHex","challengeAssertTx","scriptInfos","cp","getChallengeAssertScriptInfo","i","script"],"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,EAAaM,CAAe,CAAC,GACtCC,EAAS;AAClB;ACqBA,MAAME,IAA2B,IAE3BC,IAAc;AA2EpB,eAAsBC,EACpBC,GAC6B;AAC7B,QAAMC,IAAiBC,EAAwBF,EAAO,cAAc,GAE9DG,IAAS,MAAMC,EAA0B;AAAA,IAC7C,iBAAiBJ,EAAO;AAAA,IACxB,qBAAqBA,EAAO;AAAA,IAC5B,oBAAoBA,EAAO;AAAA,IAC3B,4BAA4BA,EAAO;AAAA,IACnC,WAAW,CAAC,GAAGA,EAAO,SAAS;AAAA,IAC/B,gBAAgBA,EAAO;AAAA,IACvB,cAAc,CAAC,GAAGA,EAAO,YAAY;AAAA,IACrC,SAASA,EAAO;AAAA,IAChB,qBAAqBA,EAAO;AAAA,IAC5B,eAAeA,EAAO;AAAA,IACtB,aAAaA,EAAO;AAAA,IACpB,SAASA,EAAO;AAAA,IAChB,gBAAAC;AAAA,EAAA,CACD,GAMKI,IADSC,EAA6BH,EAAO,KAAK,E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C,EAAK,YAAYoC,EAAkB,QAAQ;AAG3C,WAASI,IAAI,GAAGA,IAAIJ,EAAkB,IAAI,QAAQI,KAAK;AACrD,UAAMhC,IAAQ4B,EAAkB,IAAII,CAAC,GAC/Bf,IAAUxD,EAAO,SAASuE,CAAC;AAEjC,QAAI,CAACf;AACH,YAAM,IAAI,MAAM,kCAAkCe,CAAC,EAAE;AAGvD,UAAM,EAAE,QAAAC,GAAQ,cAAAjB,MAAiBa,EAAYG,CAAC,GACxCjB,IAAczB,EAAgB2C,CAAM,GACpCR,IAAoBnC,EAAgB0B,CAAY;AAEtD,IAAAxB,EAAK,SAAS;AAAA,MACZ,MAAMQ,EAAM;AAAA,MACZ,OAAOA,EAAM;AAAA,MACb,UAAUA,EAAM;AAAA,MAChB,aAAa;AAAA,QACX,QAAQL,EAAO,KAAKL,EAAgBb,EAAewC,EAAQ,aAAa,CAAC,CAAC;AAAA,QAC1E,OAAOA,EAAQ;AAAA,MAAA;AAAA,MAEjB,eAAe;AAAA,QACb;AAAA,UACE,aAAavB;AAAA,UACb,QAAQC,EAAO,KAAKoB,CAAW;AAAA,UAC/B,cAAcpB,EAAO,KAAK8B,CAAiB;AAAA,QAAA;AAAA,MAC7C;AAAA,MAEF,gBAAgB9B,EAAO,KAAKC,CAAiB;AAAA,IAAA,CAC9C;AAAA,EACH;AAGA,aAAWC,KAAU+B,EAAkB;AACrC,IAAApC,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";var Xt=Object.defineProperty;var qt=(e,t,n)=>t in e?Xt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var x=(e,t,n)=>qt(e,typeof t!="symbol"?t+"":t,n);const F=require("bitcoinjs-lib"),et=require("buffer"),B=require("viem"),jt=require("./signing-DHSXjhLM.cjs"),ht=require("@babylonlabs-io/babylon-tbv-rust-wasm"),S=require("./challengeAssert-BM8m9gPM.cjs"),k=require("./bitcoin-DIN0OupO.cjs"),dt=require("./validation-u8W7Lp2x.cjs"),O=require("./psbtInputFields-DhGm77bP.cjs"),ft=require("./fundPeginTransaction-DaWoYCgO.cjs"),It=require("./vault-registry-reader-BizmBSBV.cjs"),c=require("./sha2-1XZuToHP.cjs");function Zt(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Gt=Zt(F),C={"0x04aabf33":"Vault already exists: This Bitcoin transaction has already been registered. Please select different UTXOs or use a different amount to create a unique transaction.","0x4fec082d":"Script mismatch: The Bitcoin transaction's taproot output does not match the expected vault script. This may be caused by incorrect vault participants or key configuration.","0x6cc363a5":"Invalid BTC proof of possession: The signature could not be verified. Please ensure you're signing with the correct Bitcoin wallet.","0x6c3f2bf6":"Invalid BTC public key: The Bitcoin public key format is invalid.","0x2c5211c6":"Invalid amount: The deposit amount is invalid or below the minimum required.","0x0405f772":"Application not registered: The application controller is not registered in the system.","0x24e165cc":"Invalid provider status: The vault provider is not in a valid state to accept deposits.","0xd92e233d":"Zero address: One of the required addresses is the zero address.","0x65aa7007":"BTC key mismatch: The Bitcoin public key does not match the expected key.","0x82b42900":"Unauthorized: You must be the depositor or vault provider to submit this transaction.","0x8baa579f":"Invalid signature: The BTC proof of possession signature could not be verified.","0x2f9d01e9":"Invalid BTC transaction: The Bitcoin transaction format is invalid.","0x5a3c6b3e":"Vault provider not registered: The selected vault provider is not registered.","0x979f4518":"Invalid pegin fee: The ETH fee sent does not match the required amount. This may indicate a fee rate change during the transaction.","0x5fad9694":"This pre-pegin output has already been used to activate another vault.","0x7ed061c9":"This pegin transaction has already been used to activate another vault."};function N(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.data=="string"&&t.data.startsWith("0x"))return t.data;if(typeof t.details=="string"&&t.details.startsWith("0x"))return t.details;let n=t.cause,s=0;const o=5;for(;n&&typeof n=="object"&&s<o;){const a=n;if(typeof a.data=="string"&&a.data.startsWith("0x"))return a.data;n=a.cause,s++}const i=(typeof t.message=="string"?t.message:"").match(/\b(0x[a-fA-F0-9]{8})\b/);if(i)return i[1]}function zt(e){const t=N(e);if(t){const n=t.substring(0,10);return C[t]??C[n]}}function Yt(e){const t=N(e);if(t===void 0)return!1;const n=t.substring(0,10);return t in C||n in C}function A(e){console.error("[Contract Error] Raw error:",e);const t=N(e);if(console.error("[Contract Error] Extracted error data:",t),t){const s=t.substring(0,10),o=C[t]??C[s];if(o)throw console.error("[Contract Error] Known error:",o),new Error(o)}const n=(e==null?void 0:e.message)||"";if(n.includes("gas limit too high")||n.includes("21000000")||n.includes("Internal JSON-RPC error")){const s=t?` (error code: ${t})`:"";throw console.error("[Contract Error] Transaction rejected. Error code:",t,"Message:",n),new Error(`Transaction failed: The contract rejected this transaction${s}. Possible causes: (1) Vault already exists for this transaction, (2) Invalid signature, (3) Unauthorized caller. Please check your transaction parameters and try again.`)}throw e instanceof Error?(console.error("[Contract Error] Unhandled error:",e.message),e):new Error(`Contract call failed: ${String(e)}`)}const Jt=0,Qt=/^0x[0-9a-f]+$/i,te=/^[0-9a-f]+$/i,ee=/^[A-Za-z0-9+/]+={0,2}$/;function R(e){if(typeof e!="string"||e.length===0)throw new Error("BTC wallet returned empty public key");return k.processPublicKeyToXOnly(e).toLowerCase()}function ne(e){if(typeof e!="string"||e.length===0)throw new Error("BTC wallet returned empty BIP-322 signature");if(e.startsWith("0x")||e.startsWith("0X")){if(!Qt.test(e)||e.length<4||e.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return e.toLowerCase()}if(te.test(e)){if(e.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return`0x${e.toLowerCase()}`}if(!ee.test(e)||e.length%4!==0)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");const t=et.Buffer.from(e,"base64");if(t.length===0||t.toString("base64")!==e)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");return`0x${t.toString("hex")}`}function se(e,t,n,s){const o=n==null?void 0:n[`${e}:${t}`];return o?Promise.resolve({txid:e,vout:t,value:o.value,scriptPubKey:o.scriptPubKey}):It.getUtxoInfo(e,t,s)}const gt=12e4;class oe{constructor(t){x(this,"config");this.config=t}async preparePegin(t){const n=await this.config.btcWallet.getPublicKeyHex(),s=R(n),o=k.stripHexPrefix(t.vaultProviderBtcPubkey),r=t.vaultKeeperBtcPubkeys.map(k.stripHexPrefix),i=t.universalChallengerBtcPubkeys.map(k.stripHexPrefix);if(t.hashlocks.length!==t.amounts.length)throw new Error(`hashlocks.length (${t.hashlocks.length}) must equal amounts.length (${t.amounts.length})`);if(t.hashlocks.length===0)throw new Error("hashlocks must contain at least one entry");const a=r.length,d={depositorPubkey:s,vaultProviderPubkey:o,vaultKeeperPubkeys:r,universalChallengerPubkeys:i,hashlocks:t.hashlocks,timelockRefund:t.timelockRefund,pegInAmounts:t.amounts,feeRate:t.protocolFeeRate,numLocalChallengers:a,councilQuorum:t.councilQuorum,councilSize:t.councilSize,network:this.config.btcNetwork},h=await S.buildPrePeginPsbt(d),l=O.selectUtxosForPegin([...t.availableUTXOs],h.totalOutputValue,t.mempoolFeeRate,ft.peginOutputCount(h.htlcValues.length,d.authAnchorHash)),b=k.getNetwork(this.config.btcNetwork),u=ft.fundPeginTransaction({unfundedTxHex:h.psbtHex,selectedUTXOs:l.selectedUTXOs,changeAddress:t.changeAddress,changeAmount:l.changeAmount,network:b}),w=k.stripHexPrefix(O.calculateBtcTxHash(u)),g=[],P=[],E=[];for(let p=0;p<t.hashlocks.length;p++){const m=await S.buildPeginTxFromFundedPrePegin({prePeginParams:d,timelockPegin:t.timelockPegin,fundedPrePeginTxHex:u,htlcVout:p}),I=await S.buildPeginInputPsbt({peginTxHex:m.txHex,fundedPrePeginTxHex:u,depositorPubkey:s,vaultProviderPubkey:o,vaultKeeperPubkeys:r,universalChallengerPubkeys:i,hashlock:t.hashlocks[p],timelockRefund:t.timelockRefund,network:this.config.btcNetwork});g.push(m),P.push(I.psbtHex),E.push(jt.createTaprootScriptPathSignOptions(n,1))}const y=await this.signPsbtsWithFallback(P,E),f=[];for(let p=0;p<y.length;p++){const m=S.extractPeginInputSignature(y[p],s),I=S.finalizePeginInputPsbt(y[p]);f.push({htlcVout:p,htlcValue:h.htlcValues[p],peginTxHex:I,peginTxid:g[p].txid,peginInputSignature:m,vaultScriptPubKey:g[p].vaultScriptPubKey})}return{fundedPrePeginTxHex:u,prePeginTxid:w,perVault:f,selectedUTXOs:l.selectedUTXOs,fee:l.fee,changeAmount:l.changeAmount}}async signPsbtsWithFallback(t,n){if(typeof this.config.btcWallet.signPsbts=="function"){const o=await this.config.btcWallet.signPsbts(t,n);if(o.length!==t.length)throw new Error(`Expected ${t.length} signed PSBTs but received ${o.length}`);return o}const s=[];for(let o=0;o<t.length;o++){const r=await this.config.btcWallet.signPsbt(t[o],n[o]);s.push(r)}return s}async signAndBroadcast(t){const{fundedPrePeginTxHex:n,depositorBtcPubkey:s}=t,o=n.startsWith("0x")?n.slice(2):n,r=F.Transaction.fromHex(o);if(r.ins.length===0)throw new Error("Transaction has no inputs");const i=new F.Psbt;i.setVersion(r.version),i.setLocktime(r.locktime);const a=et.Buffer.from(R(s),"hex"),d=this.config.mempoolApiUrl,h=r.ins.map(f=>{const p=et.Buffer.from(f.hash).reverse().toString("hex"),m=f.index;return se(p,m,t.localPrevouts,d).then(I=>({input:f,utxoData:I,txid:p,vout:m}))}),l=await Promise.all(h),b=l.reduce((f,p)=>f+BigInt(p.utxoData.value),0n),u=r.outs.reduce((f,p)=>f+BigInt(p.value),0n);if(b<u)throw new Error(`UTXO value mismatch: total input value (${b} sat) is less than total output value (${u} sat). This may indicate the mempool API returned manipulated UTXO data.`);const w=b-u;if(w>dt.MAX_REASONABLE_FEE_SATS)throw new Error(`Implied transaction fee (${w} sat) exceeds maximum reasonable fee (${dt.MAX_REASONABLE_FEE_SATS} sat). This may indicate manipulated UTXO data.`);for(const{input:f,utxoData:p,txid:m,vout:I}of l){const T=O.getPsbtInputFields({value:p.value,scriptPubKey:p.scriptPubKey},a);i.addInput({hash:f.hash,index:f.index,sequence:f.sequence,...T})}for(const f of r.outs)i.addOutput({script:f.script,value:f.value});const g=await this.config.btcWallet.signPsbt(i.toHex()),P=F.Psbt.fromHex(g);try{P.finalizeAllInputs()}catch(f){if(!P.data.inputs.every(m=>m.finalScriptWitness||m.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${f}`)}const E=P.extractTransaction().toHex();return await It.pushTx(E,d)}async registerPeginOnChain(t){const{unsignedPrePeginTx:n,depositorSignedPeginTx:s,vaultProvider:o,hashlock:r,htlcVout:i,depositorPayoutBtcAddress:a,depositorWotsPkHash:d,popSignature:h}=t;if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const l=this.config.ethWallet.account.address;if(!B.isAddressEqual(h.depositorEthAddress,l))throw new Error(`Proof of possession was signed for ${h.depositorEthAddress} but the Ethereum wallet is currently connected to ${l}. Reconnect the original account or call signProofOfPossession() again.`);await this.assertPopMatchesBtcWallet(h);const b=h.btcPopSignature,u=k.ensureHexPrefix(h.depositorBtcPubkey),w=k.ensureHexPrefix(n),g=k.ensureHexPrefix(s),P=await this.resolvePayoutScriptPubKey(a),E=O.calculateBtcTxHash(g),y=await ht.deriveVaultId(k.stripHexPrefix(E),k.stripHexPrefix(l)),f=k.ensureHexPrefix(y);if(await this.checkVaultExists(f))throw new Error(`Vault already exists (ID: ${f}, peginTxHash: ${E}). Vault IDs are derived from the pegin transaction hash and depositor address. To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`);const m=B.createPublicClient({chain:this.config.ethChain,transport:B.http()});let I;try{I=await m.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:c.BTCVaultRegistryABI,functionName:"getPegInFee",args:[o]})}catch{throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.")}const T=B.encodeFunctionData({abi:c.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[l,u,b,w,g,o,r,i,P,d]});let H;try{H=await m.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:T,value:I,account:this.config.ethWallet.account.address})}catch(K){A(K)}let v;try{v=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:T,value:I,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:H})}catch(K){A(K)}const D=await m.waitForTransactionReceipt({hash:v,timeout:gt});return D.status==="reverted"&&A(new Error(`Transaction reverted. Hash: ${v}. Check the transaction on block explorer for details.`)),{ethTxHash:D.transactionHash,vaultId:f,peginTxHash:E}}async registerPeginBatchOnChain(t){const{vaultProvider:n,unsignedPrePeginTx:s,requests:o,popSignature:r}=t;if(o.length===0)throw new Error("Batch pegin requires at least one request");if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const i=this.config.ethWallet.account.address;if(!B.isAddressEqual(r.depositorEthAddress,i))throw new Error(`Proof of possession was signed for ${r.depositorEthAddress} but the Ethereum wallet is currently connected to ${i}. Reconnect the original account or call signProofOfPossession() again.`);await this.assertPopMatchesBtcWallet(r);const a=r.btcPopSignature,d=[];for(const m of o)d.push(await this.resolvePayoutScriptPubKey(m.depositorPayoutBtcAddress));const h=[];for(const m of o){const I=k.ensureHexPrefix(m.depositorSignedPeginTx),T=O.calculateBtcTxHash(I),H=await ht.deriveVaultId(k.stripHexPrefix(T),k.stripHexPrefix(i)),v=k.ensureHexPrefix(H);if(await this.checkVaultExists(v))throw new Error(`Vault already exists (ID: ${v}, peginTxHash: ${T}). To create a new vault, use different UTXOs or a different amount.`);h.push({vaultId:v,peginTxHash:T})}const l=B.createPublicClient({chain:this.config.ethChain,transport:B.http()});let b;try{b=await l.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:c.BTCVaultRegistryABI,functionName:"getPegInFee",args:[n]})}catch{throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.")}const u=b*BigInt(o.length),w=k.ensureHexPrefix(r.depositorBtcPubkey),g=k.ensureHexPrefix(s),P=o.map((m,I)=>({depositorBtcPubKey:w,btcPopSignature:a,unsignedPrePeginTx:g,depositorSignedPeginTx:k.ensureHexPrefix(m.depositorSignedPeginTx),hashlock:m.hashlock,htlcVout:m.htlcVout,referralCode:Jt,depositorPayoutBtcAddress:d[I],depositorWotsPkHash:m.depositorWotsPkHash})),E=B.encodeFunctionData({abi:c.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[i,n,P]});let y;try{y=await l.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:E,value:u,account:this.config.ethWallet.account.address})}catch(m){A(m)}let f;try{f=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:E,value:u,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:y})}catch(m){A(m)}const p=await l.waitForTransactionReceipt({hash:f,timeout:gt});return p.status==="reverted"&&A(new Error(`Batch transaction reverted. Hash: ${f}. Check the transaction on block explorer for details.`)),{ethTxHash:p.transactionHash,vaults:h}}async checkVaultExists(t){try{return(await B.createPublicClient({chain:this.config.ethChain,transport:B.http()}).readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:c.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]}))[0]!==B.zeroAddress}catch{return!1}}async resolvePayoutScriptPubKey(t){let n;if(t)n=t;else{n=await this.config.btcWallet.getAddress();const o=await this.config.btcWallet.getPublicKeyHex();if(!k.isAddressFromPublicKey(n,o,this.config.btcNetwork))throw new Error("The BTC address from your wallet does not match the wallet's public key. Please ensure your wallet is using a supported address type (Taproot or Native SegWit).")}const s=k.getNetwork(this.config.btcNetwork);try{return`0x${Gt.address.toOutputScript(n,s).toString("hex")}`}catch{throw new Error(`Invalid BTC payout address: "${n}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`)}}async signProofOfPossession(){if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const t=this.config.ethWallet.account.address,n=R(await this.config.btcWallet.getPublicKeyHex()),s=this.config.vaultContracts.btcVaultRegistry,o=`${t.toLowerCase()}:${this.config.ethChain.id}:pegin:${s.toLowerCase()}`,r=await this.config.btcWallet.signMessage(o,"bip322-simple");return{btcPopSignature:ne(r),depositorEthAddress:t,depositorBtcPubkey:n}}async assertPopMatchesBtcWallet(t){const n=R(await this.config.btcWallet.getPublicKeyHex()),s=R(t.depositorBtcPubkey);if(n!==s)throw new Error(`Proof of possession was signed with BTC pubkey ${s} but the BTC wallet is currently connected to ${n}. Reconnect the original wallet or call signProofOfPossession() again.`)}getNetwork(){return this.config.btcNetwork}getVaultContractAddress(){return this.config.vaultContracts.btcVaultRegistry}}class _t{constructor(t,n){x(this,"oHash");x(this,"iHash");x(this,"blockLen");x(this,"outputLen");x(this,"finished",!1);x(this,"destroyed",!1);if(c.ahash(t),c.abytes(n,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(n.length>s?t.create().update(n).digest():n);for(let r=0;r<o.length;r++)o[r]^=54;this.iHash.update(o),this.oHash=t.create();for(let r=0;r<o.length;r++)o[r]^=106;this.oHash.update(o),c.clean(o)}update(t){return c.aexists(this),this.iHash.update(t),this}digestInto(t){c.aexists(this),c.abytes(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:s,finished:o,destroyed:r,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=r,t.blockLen=i,t.outputLen=a,t.oHash=n._cloneInto(t.oHash),t.iHash=s._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const V=(e,t,n)=>new _t(e,t).update(n).digest();V.create=(e,t)=>new _t(e,t);const re=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Bt=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),ie=Bt.map(e=>(9*e+5)%16),Ht=(()=>{const n=[[Bt],[ie]];for(let s=0;s<4;s++)for(let o of n)o.push(o[s].map(r=>re[r]));return n})(),vt=Ht[0],At=Ht[1],Ct=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),ae=vt.map((e,t)=>e.map(n=>Ct[t][n])),ce=At.map((e,t)=>e.map(n=>Ct[t][n])),le=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),ue=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function pt(e,t,n,s){return e===0?t^n^s:e===1?t&n|~t&s:e===2?(t|~n)^s:e===3?t&s|n&~s:t^(n|~s)}const U=new Uint32Array(16);class he extends c.HashMD{constructor(){super(64,20,8,!0);x(this,"h0",1732584193);x(this,"h1",-271733879);x(this,"h2",-1732584194);x(this,"h3",271733878);x(this,"h4",-1009589776)}get(){const{h0:n,h1:s,h2:o,h3:r,h4:i}=this;return[n,s,o,r,i]}set(n,s,o,r,i){this.h0=n|0,this.h1=s|0,this.h2=o|0,this.h3=r|0,this.h4=i|0}process(n,s){for(let g=0;g<16;g++,s+=4)U[g]=n.getUint32(s,!0);let o=this.h0|0,r=o,i=this.h1|0,a=i,d=this.h2|0,h=d,l=this.h3|0,b=l,u=this.h4|0,w=u;for(let g=0;g<5;g++){const P=4-g,E=le[g],y=ue[g],f=vt[g],p=At[g],m=ae[g],I=ce[g];for(let T=0;T<16;T++){const H=c.rotl(o+pt(g,i,d,l)+U[f[T]]+E,m[T])+u|0;o=u,u=l,l=c.rotl(d,10)|0,d=i,i=H}for(let T=0;T<16;T++){const H=c.rotl(r+pt(P,a,h,b)+U[p[T]]+y,I[T])+w|0;r=w,w=b,b=c.rotl(h,10)|0,h=a,a=H}}this.set(this.h1+d+b|0,this.h2+l+w|0,this.h3+u+r|0,this.h4+o+a|0,this.h0+i+h|0)}roundClean(){c.clean(U)}destroy(){this.destroyed=!0,c.clean(this.buffer),this.set(0,0,0,0,0)}}const de=c.createHasher(()=>new he),fe=BigInt(0),$=BigInt(1),ge=BigInt(2),pe=BigInt(7),me=BigInt(256),be=BigInt(113),St=[],Ot=[],Rt=[];for(let e=0,t=$,n=1,s=0;e<24;e++){[n,s]=[s,(2*n+3*s)%5],St.push(2*(5*s+n)),Ot.push((e+1)*(e+2)/2%64);let o=fe;for(let r=0;r<7;r++)t=(t<<$^(t>>pe)*be)%me,t&ge&&(o^=$<<($<<BigInt(r))-$);Rt.push(o)}const $t=c.split(Rt,!0),ye=$t[0],we=$t[1],mt=(e,t,n)=>n>32?c.rotlBH(e,t,n):c.rotlSH(e,t,n),bt=(e,t,n)=>n>32?c.rotlBL(e,t,n):c.rotlSL(e,t,n);function xe(e,t=24){const n=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let i=0;i<10;i++)n[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,d=(i+2)%10,h=n[d],l=n[d+1],b=mt(h,l,1)^n[a],u=bt(h,l,1)^n[a+1];for(let w=0;w<50;w+=10)e[i+w]^=b,e[i+w+1]^=u}let o=e[2],r=e[3];for(let i=0;i<24;i++){const a=Ot[i],d=mt(o,r,a),h=bt(o,r,a),l=St[i];o=e[l],r=e[l+1],e[l]=d,e[l+1]=h}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)n[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~n[(a+2)%10]&n[(a+4)%10]}e[0]^=ye[s],e[1]^=we[s]}c.clean(n)}class it{constructor(t,n,s,o=!1,r=24){x(this,"state");x(this,"pos",0);x(this,"posOut",0);x(this,"finished",!1);x(this,"state32");x(this,"destroyed",!1);x(this,"blockLen");x(this,"suffix");x(this,"outputLen");x(this,"enableXOF",!1);x(this,"rounds");if(this.blockLen=t,this.suffix=n,this.outputLen=s,this.enableXOF=o,this.rounds=r,c.anumber(s,"outputLen"),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=c.u32(this.state)}clone(){return this._cloneInto()}keccak(){c.swap32IfBE(this.state32),xe(this.state32,this.rounds),c.swap32IfBE(this.state32),this.posOut=0,this.pos=0}update(t){c.aexists(this),c.abytes(t);const{blockLen:n,state:s}=this,o=t.length;for(let r=0;r<o;){const i=Math.min(n-this.pos,o-r);for(let a=0;a<i;a++)s[this.pos++]^=t[r++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:n,pos:s,blockLen:o}=this;t[s]^=n,(n&128)!==0&&s===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){c.aexists(this,!1),c.abytes(t),this.finish();const n=this.state,{blockLen:s}=this;for(let o=0,r=t.length;o<r;){this.posOut>=s&&this.keccak();const i=Math.min(s-this.posOut,r-o);t.set(n.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return c.anumber(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(c.aoutput(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,c.clean(this.state)}_cloneInto(t){const{blockLen:n,suffix:s,outputLen:o,rounds:r,enableXOF:i}=this;return t||(t=new it(n,s,o,i,r)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=r,t.suffix=s,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}}const Pe=(e,t,n,s={})=>c.createHasher(()=>new it(t,e,n),s),ke=Pe(1,136,32);function Ee(e,t,n,s){c.ahash(e);const o=c.checkOpts({dkLen:32,asyncTick:10},s),{c:r,dkLen:i,asyncTick:a}=o;if(c.anumber(r,"c"),c.anumber(i,"dkLen"),c.anumber(a,"asyncTick"),r<1)throw new Error("iterations (c) must be >= 1");const d=c.kdfInputToBytes(t,"password"),h=c.kdfInputToBytes(n,"salt"),l=new Uint8Array(i),b=V.create(e,d),u=b._cloneInto().update(h);return{c:r,dkLen:i,asyncTick:a,DK:l,PRF:b,PRFSalt:u}}function Te(e,t,n,s,o){return e.destroy(),t.destroy(),s&&s.destroy(),c.clean(o),n}function Ie(e,t,n,s){const{c:o,dkLen:r,DK:i,PRF:a,PRFSalt:d}=Ee(e,t,n,s);let h;const l=new Uint8Array(4),b=c.createView(l),u=new Uint8Array(a.outputLen);for(let w=1,g=0;g<r;w++,g+=a.outputLen){const P=i.subarray(g,g+a.outputLen);b.setInt32(0,w,!1),(h=d._cloneInto(h)).update(l).digestInto(u),P.set(u.subarray(0,P.length));for(let E=1;E<o;E++){a._cloneInto(h).update(u).digestInto(u);for(let y=0;y<P.length;y++)P[y]^=u[y]}}return Te(a,d,i,h,u)}function Lt(e){if(typeof e!="string")throw new TypeError("invalid mnemonic type: "+typeof e);return e.normalize("NFKD")}function _e(e){const t=Lt(e),n=t.split(" ");if(![12,15,18,21,24].includes(n.length))throw new Error("Invalid mnemonic");return{nfkd:t,words:n}}const Be=e=>Lt("mnemonic"+e);function He(e,t=""){return Ie(c.sha512,_e(e).nfkd,Be(t),{c:2048,dkLen:64})}const X=32,q=64,ve=4,_=20,nt=4,Ut=2,Ae=0,Ce=1,W=[64,64];function st(...e){const t=e.reduce((o,r)=>o+r.length,0),n=new Uint8Array(t);let s=0;for(const o of e)n.set(o,s),s+=o.length;return n}function j(e){return new TextEncoder().encode(e)}function Z(e){const t=new Uint8Array(ve);return new DataView(t.buffer).setUint32(0,e.length,!1),st(t,e)}function yt(e){return e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e}const Se=e=>Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("");function Oe(e,t){return V(c.sha512,e,t)}function at(e){return de(c.sha256(e))}function Wt(e){return(1<<e)-1}function Re(e){let t=1;for(;t*t<e+1;)t++;return Math.max(t,2)}function $e(e){const t=nt,n=Wt(t),s=e*n;return{d:t,n:e,checksum_radix:Re(s)}}function G(e,t){const n=[];let s=t;for(;s>0;)n.push(s&255),s>>>=8;const o=new Uint8Array(e.length+n.length);o.set(e);for(let r=0;r<n.length;r++)o[e.length+r]=n[r];return at(o)}function z(e,t){let n=e;for(let s=0;s<t;s++)n=at(n);return n}function Le(e,t){const n=Wt(t.d),s=t.checksum_radix-1,o=Math.floor(t.n*n/t.checksum_radix),r=[];for(let l=0;l<t.n;l++){const b=G(e,l+Ut),u=z(b,n);r.push(Array.from(u))}const i=G(e,Ae),a=z(i,s),d=G(e,Ce),h=z(d,o);return{config:t,message_terminals:r,checksum_major_terminal:Array.from(h),checksum_minor_terminal:Array.from(a)}}function Ft(e){const t=He(e),n=new Uint8Array(t);return t.fill(0),n}async function Mt(e,t,n,s){if(e.length!==q)throw new Error(`WOTS seed must be exactly ${q} bytes, got ${e.length}`);const o=yt(t).toLowerCase(),r=yt(n).toLowerCase(),i=e.slice(X,q),a=e.slice(0,X),d=st(a,st(Z(j(o)),Z(j(r)),Z(j(s.toLowerCase())))),h=Oe(i,d),l=h.slice(0,X);try{const b=[];for(let u=0;u<W.length;u++){const w=W[u],g=$e(w),P=new Uint8Array(l.length+1);P.set(l),P[l.length]=u;const E=at(P);try{const y=Le(E,g);if(y.config.d!==nt)throw new Error(`Block ${u}: expected d=${nt}, got d=${y.config.d}`);if(y.config.n!==w)throw new Error(`Block ${u}: expected n=${w}, got n=${y.config.n}`);if(y.message_terminals.length!==w)throw new Error(`Block ${u}: expected ${w} message terminals, got ${y.message_terminals.length}`);for(let f=0;f<y.message_terminals.length;f++)if(y.message_terminals[f].length!==_)throw new Error(`Block ${u} terminal ${f}: expected ${_} bytes, got ${y.message_terminals[f].length}`);if(y.checksum_minor_terminal.length!==_)throw new Error(`Block ${u} checksum_minor: expected ${_} bytes`);if(y.checksum_major_terminal.length!==_)throw new Error(`Block ${u} checksum_major: expected ${_} bytes`);b.push(y)}finally{P.fill(0),E.fill(0)}}if(b.length!==W.length)throw new Error(`Expected ${W.length} blocks, got ${b.length}`);return b}finally{d.fill(0),i.fill(0),a.fill(0),h.fill(0),l.fill(0),e.fill(0)}}function Y(e,t,n){if(e.length!==_)throw new Error(`Block ${t} ${n}: expected ${_} bytes, got ${e.length}`);for(let s=0;s<e.length;s++){const o=e[s];if(!Number.isInteger(o)||o<0||o>255)throw new Error(`Block ${t} ${n}[${s}]: invalid byte value ${o}`)}}function Nt(e){if(e.length===0)throw new Error("Public keys array must not be empty");for(let r=0;r<e.length;r++){const i=e[r];Y(i.checksum_minor_terminal,r,"checksum_minor_terminal"),Y(i.checksum_major_terminal,r,"checksum_major_terminal");for(let a=0;a<i.message_terminals.length;a++)Y(i.message_terminals[a],r,`message_terminal[${a}]`)}let t=0;for(const r of e)t+=Ut+r.message_terminals.length;const n=new Uint8Array(t*_);let s=0;for(const r of e){n.set(r.checksum_minor_terminal,s),s+=_,n.set(r.checksum_major_terminal,s),s+=_;for(const i of r.message_terminals)n.set(i,s),s+=_}const o=ke(n);return`0x${Se(o)}`}async function Ue(e,t,n,s){const o=Ft(e);try{const r=await Mt(o,t,n,s);return Nt(r)}finally{o.fill(0)}}function We(e){const t=(e instanceof Error?e.message:typeof e=="string"?e:"").toLowerCase();return t.includes("wots")&&t.includes("hash")&&t.includes("does not match")}const J=Uint8Array.of(0),wt=Uint8Array.of();function ct(e,t,n,s=32){c.ahash(e),c.anumber(s,"length");const o=e.outputLen;if(s>255*o)throw new Error("Length must be <= 255*HashLen");const r=Math.ceil(s/o);n===void 0?n=wt:c.abytes(n,void 0,"info");const i=new Uint8Array(r*o),a=V.create(e,t),d=a._cloneInto(),h=new Uint8Array(a.outputLen);for(let l=0;l<r;l++)J[0]=l+1,d.update(l===0?wt:h).update(n).update(J).digestInto(h),i.set(h,o*l),a._cloneInto(d);return a.destroy(),d.destroy(),c.clean(h,J),i.slice(0,s)}const Q=new TextEncoder().encode("babylonvault"),xt=255,Pt=65535,kt=2,Fe="hashlock",Me="auth-anchor",Ne="wots-seed";function Vt(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw new Error(`i2osp4: value must be a u32, got ${e}`);const t=new Uint8Array(4);return t[0]=e>>>24&255,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t}function lt(e,t=new Uint8Array(0)){const n=new TextEncoder().encode(e);if(n.length===0||n.length>xt)throw new Error(`info: label length must be in [1, ${xt}], got ${n.length}`);if(t.length>Pt)throw new Error(`info: ctx length must be in [0, ${Pt}], got ${t.length}`);const s=Q.length+1+n.length+kt+t.length,o=new Uint8Array(s);let r=0;return o.set(Q,r),r+=Q.length,o[r]=n.length,r+=1,o.set(n,r),r+=n.length,o[r]=t.length>>>8&255,o[r+1]=t.length&255,r+=kt,o.set(t,r),o}const Et=32,Ve=32,De=32,Ke=64;function ut(e){if(e.length!==Et)throw new Error(`vault-secrets: root must be exactly ${Et} bytes, got ${e.length}`)}function Xe(e){return ut(e),ct(c.sha256,e,lt(Me),Ve)}function qe(e,t){return ut(e),ct(c.sha256,e,lt(Fe,Vt(t)),De)}function je(e,t){return ut(e),ct(c.sha256,e,lt(Ne,Vt(t)),Ke)}const L=32,tt=32,ot=36,Dt=32,M=4,Ze=M+L+M+Dt;function rt(e,t,n){e[t]=n>>>24&255,e[t+1]=n>>>16&255,e[t+2]=n>>>8&255,e[t+3]=n&255}function Ge(e){if(e.txid.length!==tt)throw new Error(`outpoint.txid must be exactly ${tt} bytes, got ${e.txid.length}`);if(!Number.isInteger(e.vout)||e.vout<0||e.vout>4294967295)throw new Error(`outpoint.vout must be a u32, got ${e.vout}`);const t=new Uint8Array(ot);return t.set(e.txid,0),rt(t,tt,e.vout),t}function Tt(e,t){const n=Math.min(e.length,t.length);for(let s=0;s<n;s++)if(e[s]!==t[s])return e[s]-t[s];return e.length-t.length}function Kt(e){if(e.length===0)throw new Error("buildFundingOutpointsCommitment: outpoints must be non-empty");const t=e.map(Ge);t.sort(Tt);for(let s=1;s<t.length;s++)if(Tt(t[s-1],t[s])===0)throw new Error("buildFundingOutpointsCommitment: duplicate outpoint detected");const n=new Uint8Array(t.length*ot);for(let s=0;s<t.length;s++)n.set(t[s],s*ot);return c.sha256(n)}function ze(e){if(e.depositorBtcPubkey.length!==L)throw new Error(`vaultContext: depositorBtcPubkey must be exactly ${L} bytes, got ${e.depositorBtcPubkey.length}`);const t=Kt(e.fundingOutpoints),n=new Uint8Array(Ze);let s=0;return rt(n,s,L),s+=M,n.set(e.depositorBtcPubkey,s),s+=L,rt(n,s,Dt),s+=M,n.set(t,s),n}exports.CONTRACT_ERRORS=C;exports.PeginManager=oe;exports.buildFundingOutpointsCommitment=Kt;exports.buildVaultContext=ze;exports.computeWotsBlockPublicKeysHash=Nt;exports.deriveWotsBlockPublicKeys=Mt;exports.deriveWotsPkHash=Ue;exports.expandAuthAnchor=Xe;exports.expandHashlockSecret=qe;exports.expandWotsSeed=je;exports.extractErrorData=N;exports.getContractErrorMessage=zt;exports.handleContractError=A;exports.isKnownContractError=Yt;exports.isWotsMismatchError=We;exports.mnemonicToWotsSeed=Ft;
|
|
2
|
+
//# sourceMappingURL=context-BSdcD4J_.cjs.map
|