@babylonlabs-io/ts-sdk 1.2.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/tbv/core/primitives/psbt/peginInput.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/clients/index.d.ts +1 -1
- package/dist/tbv/integrations/aave/clients/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/clients/spoke.d.ts +20 -9
- package/dist/tbv/integrations/aave/clients/spoke.d.ts.map +1 -1
- 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.d.ts +3 -3
- package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.js +300 -238
- package/dist/tbv/integrations/aave/index.js.map +1 -1
- package/dist/tbv/integrations/aave/utils/cascadeSimulation.d.ts +1 -1
- package/dist/tbv/integrations/aave/utils/cascadeSimulation.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/utils/index.d.ts +2 -2
- package/dist/tbv/integrations/aave/utils/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/utils/optimalOrder.d.ts +1 -1
- package/dist/tbv/integrations/aave/utils/optimalOrder.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/utils/vaultSplit.d.ts +171 -41
- package/dist/tbv/integrations/aave/utils/vaultSplit.d.ts.map +1 -1
- package/dist/verifyKeyPathSchnorrSignature-BQHNhRj6.js.map +1 -1
- package/dist/verifyKeyPathSchnorrSignature-Gm9EmZkx.cjs.map +1 -1
- package/package.json +2 -1
|
@@ -1,38 +1,106 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Vault Split Utilities for Aave Liquidation Protection
|
|
3
3
|
*
|
|
4
|
-
* BTC vaults are indivisible UTXOs.
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* BTC vaults are indivisible UTXOs. The Babylon Spoke liquidates one whole
|
|
5
|
+
* vault per call, taking the head of the borrower's ordered vault list.
|
|
6
|
+
* Splitting a deposit into 2 vaults (sacrificial + protected) lets a
|
|
7
|
+
* liquidation take the small head vault and leave the rest of the position.
|
|
8
8
|
*
|
|
9
|
-
* The sacrificial vault (index 0) is sized
|
|
10
|
-
*
|
|
11
|
-
*
|
|
9
|
+
* The sacrificial vault (index 0) is sized so that seizing it at the expected
|
|
10
|
+
* liquidation health factor lifts the position back to the split target
|
|
11
|
+
* health factor. The protected vault (index 1) holds the remainder.
|
|
12
12
|
*
|
|
13
|
-
* Seizure formula
|
|
13
|
+
* Seizure formula:
|
|
14
14
|
* ```
|
|
15
15
|
* liq_penalty = LB × CF
|
|
16
16
|
* debt_to_repay = total_debt × (THF - current_HF) / (THF - liq_penalty)
|
|
17
17
|
* target_seizure = debt_to_repay × LB
|
|
18
18
|
* ```
|
|
19
19
|
*/
|
|
20
|
+
/**
|
|
21
|
+
* Split target health factor: the health factor a two-vault position lands
|
|
22
|
+
* on after its sacrificial vault is seized. The sacrificial vault is sized so
|
|
23
|
+
* that seizing it lifts the position back to this value.
|
|
24
|
+
*
|
|
25
|
+
* This is a Babylon sizing parameter, not a contract parameter. The Babylon
|
|
26
|
+
* Spoke sizes each liquidation by the head vault's BTC and never reads the
|
|
27
|
+
* Aave `LiquidationConfig.targetHealthFactor`, so no contract can supply it.
|
|
28
|
+
* At 1.08 the sacrificial vault stays smaller than the protected vault for
|
|
29
|
+
* every collateral factor up to 86%, and after the first liquidation BTC can
|
|
30
|
+
* fall about 7.4% more before the protected vault is at risk. The risk model
|
|
31
|
+
* and the decision are recorded in babylon-toolkit#2577.
|
|
32
|
+
*
|
|
33
|
+
* Changing this value resizes every new split. A change needs sign-off from
|
|
34
|
+
* the risk model owner and two code-owner approvals: this file is the
|
|
35
|
+
* "Multi-vault split transactions" critical path in CLAUDE.md and has its own
|
|
36
|
+
* entry in .github/CODEOWNERS.
|
|
37
|
+
*/
|
|
38
|
+
export declare const SPLIT_TARGET_HEALTH_FACTOR = 1.08;
|
|
39
|
+
/**
|
|
40
|
+
* Health factor at which a liquidation is assumed to land, in WAD.
|
|
41
|
+
*
|
|
42
|
+
* Aave liquidations settle close to 1.0 (median about 0.997 on Aave V3 over
|
|
43
|
+
* a year), so the split is sized for 0.99. The liquidation bonus used for
|
|
44
|
+
* sizing is read from the Spoke's bonus curve at this health factor. Same
|
|
45
|
+
* ownership and review rules as {@link SPLIT_TARGET_HEALTH_FACTOR}.
|
|
46
|
+
*/
|
|
47
|
+
export declare const EXPECTED_HEALTH_FACTOR_AT_LIQUIDATION_WAD = 990000000000000000n;
|
|
48
|
+
/**
|
|
49
|
+
* {@link EXPECTED_HEALTH_FACTOR_AT_LIQUIDATION_WAD} as a plain number (0.99),
|
|
50
|
+
* for the floating-point split formulas.
|
|
51
|
+
*/
|
|
52
|
+
export declare const EXPECTED_HEALTH_FACTOR_AT_LIQUIDATION: number;
|
|
53
|
+
/**
|
|
54
|
+
* Why the split parameters alone refuse a two-vault split. These are the
|
|
55
|
+
* verdicts {@link findSplitSizingViolation} can return; it sees only the
|
|
56
|
+
* parameters, so each one holds at any deposit amount. One of them,
|
|
57
|
+
* `sacrificial-not-smaller`, is also what {@link computeOptimalSplit} reports
|
|
58
|
+
* when rounding the seizure up leaves the sacrificial vault not strictly
|
|
59
|
+
* smaller, so seeing it in an {@link OptimalSplitResult} does not by itself
|
|
60
|
+
* mean the parameters are bad:
|
|
61
|
+
* - `target-not-above-expected-hf`: THF ≤ expected HF, so the seizure formula
|
|
62
|
+
* has no valid target.
|
|
63
|
+
* - `target-not-above-liquidation-penalty`: THF ≤ LB × CF, so one liquidation
|
|
64
|
+
* takes the whole position.
|
|
65
|
+
* - `sacrificial-not-smaller`: the sacrificial vault would not be strictly
|
|
66
|
+
* smaller than the protected vault.
|
|
67
|
+
* - `no-seizure-expected`: the seized fraction is zero (for example CF 0), so
|
|
68
|
+
* a sacrificial vault would be empty and the split would protect nothing.
|
|
69
|
+
*/
|
|
70
|
+
export type SplitParamsViolation = "target-not-above-expected-hf" | "target-not-above-liquidation-penalty" | "sacrificial-not-smaller" | "no-seizure-expected";
|
|
71
|
+
/**
|
|
72
|
+
* Why {@link computeOptimalSplit} refuses a split: the parameter verdicts
|
|
73
|
+
* above, plus one only a deposit amount can reach.
|
|
74
|
+
* - `below-dust`: the vaults would be below the HTLC dust threshold. A
|
|
75
|
+
* non-positive deposit reports this too, but only when the parameters
|
|
76
|
+
* themselves allow a split — otherwise the parameter verdict wins.
|
|
77
|
+
*/
|
|
78
|
+
export type SplitSizingViolation = SplitParamsViolation | "below-dust";
|
|
79
|
+
/**
|
|
80
|
+
* Inputs of the Aave v4 liquidation bonus curve, in their on-chain units.
|
|
81
|
+
*/
|
|
82
|
+
export interface LiquidationBonusCurve {
|
|
83
|
+
/** `LiquidationConfig.healthFactorForMaxBonus`, WAD. Below 1e18. */
|
|
84
|
+
healthFactorForMaxBonus: bigint;
|
|
85
|
+
/** `LiquidationConfig.liquidationBonusFactor`, BPS. At most 10_000. */
|
|
86
|
+
liquidationBonusFactor: bigint;
|
|
87
|
+
/** `DynamicReserveConfig.maxLiquidationBonus`, BPS. At least 10_000. */
|
|
88
|
+
maxLiquidationBonus: bigint;
|
|
89
|
+
}
|
|
20
90
|
/**
|
|
21
91
|
* Parameters for computing the optimal vault split.
|
|
22
92
|
*/
|
|
23
93
|
export interface OptimalSplitParams {
|
|
24
94
|
/** Total deposit amount in satoshis */
|
|
25
95
|
totalBtc: bigint;
|
|
26
|
-
/** Collateral factor (e.g. 0.
|
|
96
|
+
/** Collateral factor (e.g. 0.78 for 78%) */
|
|
27
97
|
CF: number;
|
|
28
|
-
/** Liquidation bonus (e.g. 1.
|
|
98
|
+
/** Liquidation bonus at the expected health factor (e.g. 1.0504) */
|
|
29
99
|
LB: number;
|
|
30
|
-
/**
|
|
100
|
+
/** Split target health factor (e.g. {@link SPLIT_TARGET_HEALTH_FACTOR}) */
|
|
31
101
|
THF: number;
|
|
32
|
-
/** Expected health factor at liquidation (e.g.
|
|
102
|
+
/** Expected health factor at liquidation (e.g. {@link EXPECTED_HEALTH_FACTOR_AT_LIQUIDATION}) */
|
|
33
103
|
expectedHF: number;
|
|
34
|
-
/** Safety margin multiplier for the sacrificial vault (e.g. 1.05 for 5% buffer) */
|
|
35
|
-
safetyMargin: number;
|
|
36
104
|
}
|
|
37
105
|
/**
|
|
38
106
|
* Result of the optimal vault split computation.
|
|
@@ -44,8 +112,14 @@ export interface OptimalSplitResult {
|
|
|
44
112
|
protectedVault: bigint;
|
|
45
113
|
/** Fraction of collateral that would be seized (0–1) */
|
|
46
114
|
seizedFraction: number;
|
|
47
|
-
/**
|
|
115
|
+
/** Target seizure amount in satoshis */
|
|
48
116
|
targetSeizureBtc: bigint;
|
|
117
|
+
/**
|
|
118
|
+
* Why the split is refused, or null when it is valid. Non-null exactly when
|
|
119
|
+
* the split is not usable: both vault amounts are then 0n, and null always
|
|
120
|
+
* means two positive amounts that sum to `totalBtc`.
|
|
121
|
+
*/
|
|
122
|
+
sizingViolation: SplitSizingViolation | null;
|
|
49
123
|
}
|
|
50
124
|
/**
|
|
51
125
|
* Parameters for computing the minimum deposit required for a split.
|
|
@@ -55,9 +129,54 @@ export interface MinDepositForSplitParams {
|
|
|
55
129
|
minPegin: bigint;
|
|
56
130
|
/** Seized fraction (0–1), from computeOptimalSplit or computeSeizedFraction */
|
|
57
131
|
seizedFraction: number;
|
|
58
|
-
/** Safety margin multiplier (e.g. 1.05) */
|
|
59
|
-
safetyMargin: number;
|
|
60
132
|
}
|
|
133
|
+
/**
|
|
134
|
+
* Compute the Aave v4 liquidation bonus at a health factor.
|
|
135
|
+
*
|
|
136
|
+
* Integer-exact port of `LiquidationLogic.calculateLiquidationBonus`
|
|
137
|
+
* (aave-v4 `src/spoke/libraries/LiquidationLogic.sol`), which the Babylon
|
|
138
|
+
* liquidation path calls with the same inputs: at or below
|
|
139
|
+
* `healthFactorForMaxBonus` the bonus is the maximum; above it the bonus falls
|
|
140
|
+
* linearly towards a minimum of
|
|
141
|
+
* `(maxLiquidationBonus − 100%) × liquidationBonusFactor + 100%` at HF 1.0.
|
|
142
|
+
* Every division rounds down, as on-chain.
|
|
143
|
+
*
|
|
144
|
+
* @param curve - Bonus curve inputs in on-chain units
|
|
145
|
+
* @param healthFactorWad - Health factor in WAD, at most 1e18
|
|
146
|
+
* @returns Liquidation bonus in BPS (e.g. 10504n for 105.04%)
|
|
147
|
+
* @throws {RangeError} when an input is outside the range the contract
|
|
148
|
+
* accepts (the contract would revert or was configured out of range)
|
|
149
|
+
*/
|
|
150
|
+
export declare function computeLiquidationBonusBps(curve: LiquidationBonusCurve, healthFactorWad: bigint): bigint;
|
|
151
|
+
/**
|
|
152
|
+
* The liquidation bonus a split is sized against: the Spoke's bonus curve at
|
|
153
|
+
* {@link EXPECTED_HEALTH_FACTOR_AT_LIQUIDATION_WAD}, as a multiplier.
|
|
154
|
+
*
|
|
155
|
+
* Every consumer of the split inputs (the deposit split, the liquidation
|
|
156
|
+
* warnings, the reorder guard, the E2E CLI) must use this one value, or a
|
|
157
|
+
* fresh split falls short of the seizure the warnings expect.
|
|
158
|
+
*
|
|
159
|
+
* @param bonusConfig - `healthFactorForMaxBonus` (WAD) and
|
|
160
|
+
* `liquidationBonusFactor` (BPS) from the Spoke's liquidation config
|
|
161
|
+
* @param maxLiquidationBonusBps - `maxLiquidationBonus` (BPS) of the dynamic
|
|
162
|
+
* config the position's liquidation uses
|
|
163
|
+
* @returns Liquidation bonus multiplier (e.g. 1.0504)
|
|
164
|
+
* @throws {RangeError} when an input is outside the range the contract accepts
|
|
165
|
+
*/
|
|
166
|
+
export declare function computeSplitLiquidationBonus(bonusConfig: Omit<LiquidationBonusCurve, "maxLiquidationBonus">, maxLiquidationBonusBps: number): number;
|
|
167
|
+
/**
|
|
168
|
+
* Check the split sizing parameters before a two-vault split is offered.
|
|
169
|
+
*
|
|
170
|
+
* @param params - Split target health factor, expected health factor at
|
|
171
|
+
* liquidation, collateral factor and liquidation bonus
|
|
172
|
+
* @returns The first violated rule, or null when a split may be offered
|
|
173
|
+
*/
|
|
174
|
+
export declare function findSplitSizingViolation(params: {
|
|
175
|
+
CF: number;
|
|
176
|
+
LB: number;
|
|
177
|
+
THF: number;
|
|
178
|
+
expectedHF: number;
|
|
179
|
+
}): SplitParamsViolation | null;
|
|
61
180
|
/**
|
|
62
181
|
* Compute the fraction of collateral that would be seized during liquidation,
|
|
63
182
|
* returning both the raw (unclamped) and clamped values.
|
|
@@ -71,10 +190,10 @@ export interface MinDepositForSplitParams {
|
|
|
71
190
|
* seized_fraction = CF × (THF - expectedHF) / (THF - liq_penalty) × LB / expectedHF
|
|
72
191
|
* ```
|
|
73
192
|
*
|
|
74
|
-
* @param CF - Collateral factor (e.g. 0.
|
|
75
|
-
* @param LB - Liquidation bonus (e.g. 1.
|
|
76
|
-
* @param THF -
|
|
77
|
-
* @param expectedHF - Expected health factor at liquidation (e.g.
|
|
193
|
+
* @param CF - Collateral factor (e.g. 0.78)
|
|
194
|
+
* @param LB - Liquidation bonus at the expected health factor (e.g. 1.0504, see {@link computeSplitLiquidationBonus})
|
|
195
|
+
* @param THF - Split target health factor (e.g. {@link SPLIT_TARGET_HEALTH_FACTOR})
|
|
196
|
+
* @param expectedHF - Expected health factor at liquidation (e.g. {@link EXPECTED_HEALTH_FACTOR_AT_LIQUIDATION})
|
|
78
197
|
* @returns Both the raw seized fraction and the clamped [0, 1] value
|
|
79
198
|
*/
|
|
80
199
|
export declare function computeSeizedFractionDetailed(CF: number, LB: number, THF: number, expectedHF: number): {
|
|
@@ -84,36 +203,46 @@ export declare function computeSeizedFractionDetailed(CF: number, LB: number, TH
|
|
|
84
203
|
/**
|
|
85
204
|
* Compute the fraction of collateral that would be seized during liquidation.
|
|
86
205
|
*
|
|
87
|
-
* @param CF - Collateral factor (e.g. 0.
|
|
88
|
-
* @param LB - Liquidation bonus (e.g. 1.
|
|
89
|
-
* @param THF -
|
|
90
|
-
* @param expectedHF - Expected health factor at liquidation (e.g.
|
|
206
|
+
* @param CF - Collateral factor (e.g. 0.78)
|
|
207
|
+
* @param LB - Liquidation bonus at the expected health factor (e.g. 1.0504, see {@link computeSplitLiquidationBonus})
|
|
208
|
+
* @param THF - Split target health factor (e.g. {@link SPLIT_TARGET_HEALTH_FACTOR})
|
|
209
|
+
* @param expectedHF - Expected health factor at liquidation (e.g. {@link EXPECTED_HEALTH_FACTOR_AT_LIQUIDATION})
|
|
91
210
|
* @returns Seized fraction clamped to [0, 1]
|
|
92
211
|
*/
|
|
93
212
|
export declare function computeSeizedFraction(CF: number, LB: number, THF: number, expectedHF: number): number;
|
|
94
213
|
/**
|
|
95
214
|
* Compute the optimal split between a sacrificial vault and a protected vault.
|
|
96
215
|
*
|
|
97
|
-
* The sacrificial vault (index 0) is
|
|
98
|
-
*
|
|
216
|
+
* The sacrificial vault (index 0) is the target seizure rounded up to a whole
|
|
217
|
+
* satoshi. The protected vault (index 1) holds the remainder. The split is
|
|
218
|
+
* refused when the parameters fail {@link findSplitSizingViolation}, when
|
|
219
|
+
* rounding the seizure up leaves the sacrificial vault not strictly smaller,
|
|
220
|
+
* or when the vaults would be dust — a non-positive deposit reaches the last
|
|
221
|
+
* of these whenever the parameters themselves allow a split. Both amounts are
|
|
222
|
+
* then 0n and `sizingViolation` says why; a null violation means two positive
|
|
223
|
+
* amounts that sum to `totalBtc`.
|
|
99
224
|
*
|
|
100
|
-
* @param params -
|
|
101
|
-
* @returns Split result with vault sizes, seized fraction,
|
|
225
|
+
* @param params - Total BTC and split sizing parameters
|
|
226
|
+
* @returns Split result with vault sizes, seized fraction, target seizure and
|
|
227
|
+
* any sizing violation
|
|
102
228
|
*
|
|
103
229
|
* @example
|
|
104
230
|
* ```typescript
|
|
105
|
-
* import {
|
|
231
|
+
* import {
|
|
232
|
+
* computeOptimalSplit,
|
|
233
|
+
* EXPECTED_HEALTH_FACTOR_AT_LIQUIDATION,
|
|
234
|
+
* SPLIT_TARGET_HEALTH_FACTOR,
|
|
235
|
+
* } from "@babylonlabs-io/ts-sdk/tbv/integrations/aave";
|
|
106
236
|
*
|
|
107
237
|
* const result = computeOptimalSplit({
|
|
108
238
|
* totalBtc: 1_000_000_000n, // 10 BTC in sats
|
|
109
|
-
* CF: 0.
|
|
110
|
-
* LB: 1.
|
|
111
|
-
* THF:
|
|
112
|
-
* expectedHF:
|
|
113
|
-
* safetyMargin: 1.05,
|
|
239
|
+
* CF: 0.78,
|
|
240
|
+
* LB: 1.0504,
|
|
241
|
+
* THF: SPLIT_TARGET_HEALTH_FACTOR,
|
|
242
|
+
* expectedHF: EXPECTED_HEALTH_FACTOR_AT_LIQUIDATION,
|
|
114
243
|
* });
|
|
115
|
-
* // result.sacrificialVault
|
|
116
|
-
* // result.protectedVault
|
|
244
|
+
* // result.sacrificialVault === 285_716_677n (2.86 BTC)
|
|
245
|
+
* // result.protectedVault === 714_283_323n (7.14 BTC)
|
|
117
246
|
* ```
|
|
118
247
|
*/
|
|
119
248
|
export declare function computeOptimalSplit(params: OptimalSplitParams): OptimalSplitResult;
|
|
@@ -124,9 +253,10 @@ export declare function computeOptimalSplit(params: OptimalSplitParams): Optimal
|
|
|
124
253
|
* the minimum total deposit where both the sacrificial and protected vaults
|
|
125
254
|
* would meet the minimum peg-in requirement.
|
|
126
255
|
*
|
|
127
|
-
* @param params -
|
|
256
|
+
* @param params - Minimum peg-in and seized fraction
|
|
128
257
|
* @returns Minimum total deposit in satoshis. Returns 0n in two cases:
|
|
129
|
-
* - `seizedFraction
|
|
258
|
+
* - `seizedFraction >= 0.5`: split refused (the sacrificial vault would not
|
|
259
|
+
* be smaller than the protected vault)
|
|
130
260
|
* - `seizedFraction <= 0`: split not useful (no seizure expected at this health factor)
|
|
131
261
|
*
|
|
132
262
|
* @example
|
|
@@ -135,9 +265,9 @@ export declare function computeOptimalSplit(params: OptimalSplitParams): Optimal
|
|
|
135
265
|
*
|
|
136
266
|
* const minDeposit = computeMinDepositForSplit({
|
|
137
267
|
* minPegin: 50_000n, // 0.0005 BTC
|
|
138
|
-
* seizedFraction: 0.
|
|
139
|
-
* safetyMargin: 1.05,
|
|
268
|
+
* seizedFraction: 0.2857,
|
|
140
269
|
* });
|
|
270
|
+
* // minDeposit === 175_009n: 50_000 / 0.2857, rounded up
|
|
141
271
|
* ```
|
|
142
272
|
*/
|
|
143
273
|
export declare function computeMinDepositForSplit(params: MinDepositForSplitParams): bigint;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vaultSplit.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/integrations/aave/utils/vaultSplit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;
|
|
1
|
+
{"version":3,"file":"vaultSplit.d.ts","sourceRoot":"","sources":["../../../../../src/tbv/integrations/aave/utils/vaultSplit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAUH;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,0BAA0B,OAAO,CAAC;AAE/C;;;;;;;GAOG;AACH,eAAO,MAAM,yCAAyC,sBAC5B,CAAC;AAE3B;;;GAGG;AACH,eAAO,MAAM,qCAAqC,QACe,CAAC;AASlE;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,MAAM,oBAAoB,GAC5B,8BAA8B,GAC9B,sCAAsC,GACtC,yBAAyB,GACzB,qBAAqB,CAAC;AAE1B;;;;;;GAMG;AACH,MAAM,MAAM,oBAAoB,GAAG,oBAAoB,GAAG,YAAY,CAAC;AAEvE;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,oEAAoE;IACpE,uBAAuB,EAAE,MAAM,CAAC;IAChC,uEAAuE;IACvE,sBAAsB,EAAE,MAAM,CAAC;IAC/B,wEAAwE;IACxE,mBAAmB,EAAE,MAAM,CAAC;CAC7B;AAoBD;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,uCAAuC;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,4CAA4C;IAC5C,EAA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E,cAAc,EAAE,MAAM,CAAC;IAAC,iBAAiB,EAAE,MAAM,CAAA;CAAE,CAsBvD;AAED;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,MAAM,EACV,EAAE,EAAE,MAAM,EACV,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,GACjB,MAAM,CAER;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,kBAAkB,GACzB,kBAAkB,CAuEpB;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,wBAAwB,GAC/B,MAAM,CAoBR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifyKeyPathSchnorrSignature-BQHNhRj6.js","sources":["../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/utils/witness/witnessStack.ts","../src/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.ts","../src/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.ts"],"sourcesContent":["/**\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 { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"../../wasm\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * Vault core (tx-graph) version the Pre-PegIn was built with. Must match\n * the version passed to buildPrePeginPsbt() so the HTLC connector scripts\n * are derived for the same graph.\n */\n vaultCoreVersion: number;\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 // Keep the facade's graph-version and input checks. Do not use its scripts\n // or control block as signing data.\n await getPrePeginHtlcConnectorInfo({\n txGraphVersion: params.vaultCoreVersion,\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 const expectedHtlc = deriveExpectedPrePeginHtlc(params, params.hashlock);\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 if (!expectedHtlc.scriptPubKey.equals(htlcOutput.script)) {\n throw new Error(\n \"PegIn HTLC taptree mismatch: the independent 2-leaf tree does not \" +\n \"reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.\",\n );\n }\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. bitcoinjs\n // re-verifies leaf-in-tree consistency (control block vs tapMerkleRoot)\n // inside addInput — a second independent check.\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: expectedHtlc.hashlockScript,\n controlBlock: expectedHtlc.hashlockControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\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 non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\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(hexToUint8Array(depositorPubkey));\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.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\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 throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n","/**\n * Consensus witness-stack decoding, shared by every module that reads a\n * witness we did not build.\n *\n * Two independent decoders drifted apart before this existed: one accepted\n * non-minimal CompactSize encodings, the other rejected them. vaultd decodes\n * with rust-bitcoin, whose `VarInt::consensus_decode`\n * (0.32.8 `consensus/encode.rs:493-522`) returns `NonMinimalVarInt` for a 0xfd\n * carrying < 0xfd and a 0xfe carrying < 0x10000 — so the strict reading is the\n * only one that matches what the network will accept.\n *\n * @module tbv/core/utils/witness/witnessStack\n */\n\n/** CompactSize discriminators; 0xff (u64) is out of range for a witness. */\nconst COMPACT_SIZE_UINT16_PREFIX = 0xfd;\nconst COMPACT_SIZE_UINT32_PREFIX = 0xfe;\nconst COMPACT_SIZE_UINT16_BYTES = 3;\nconst COMPACT_SIZE_UINT32_BYTES = 5;\nconst COMPACT_SIZE_UINT16_MIN_VALUE = 0xfd;\nconst COMPACT_SIZE_UINT32_MIN_VALUE = 0x10000;\n\n/**\n * Decode a consensus-encoded witness stack: item count, then (len, bytes)*.\n *\n * @param witness - The consensus-encoded witness bytes.\n * @param subject - Names the witness in error messages (e.g. \"finalScriptWitness\").\n * @returns The stack items, as views over `witness`.\n * @throws If the encoding is truncated, non-minimal, out of range, or leaves\n * trailing bytes.\n */\nexport function decodeWitnessStack(\n witness: Uint8Array,\n subject: string,\n): Uint8Array[] {\n let offset = 0;\n\n const readCompactSize = (): number => {\n if (offset >= witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const first = witness[offset];\n if (first < COMPACT_SIZE_UINT16_PREFIX) {\n offset += 1;\n return first;\n }\n if (first === COMPACT_SIZE_UINT16_PREFIX) {\n if (offset + COMPACT_SIZE_UINT16_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value = witness[offset + 1] | (witness[offset + 2] << 8);\n if (value < COMPACT_SIZE_UINT16_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT16_BYTES;\n return value;\n }\n if (first === COMPACT_SIZE_UINT32_PREFIX) {\n if (offset + COMPACT_SIZE_UINT32_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value =\n (witness[offset + 1] |\n (witness[offset + 2] << 8) |\n (witness[offset + 3] << 16) |\n (witness[offset + 4] << 24)) >>>\n 0;\n if (value < COMPACT_SIZE_UINT32_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT32_BYTES;\n return value;\n }\n throw new Error(`${subject} carries an out-of-range item length`);\n };\n\n const count = readCompactSize();\n const items: Uint8Array[] = [];\n for (let i = 0; i < count; i++) {\n const len = readCompactSize();\n if (offset + len > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n items.push(witness.subarray(offset, offset + len));\n offset += len;\n }\n if (offset !== witness.length) {\n throw new Error(`${subject} has trailing bytes`);\n }\n return items;\n}\n","/**\n * Far-side verification of P2WPKH ECDSA signatures a wallet returned, over\n * the PSBT we requested (trusted prevouts) — the Native SegWit sibling of\n * `verifyKeyPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs:945-1000\n * verify_finalized_p2wpkh_spend`. The wallet's success/finalization is\n * never trusted on its own (CLAUDE.md §8): prevout script and value come\n * from the PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport {\n crypto as bcrypto,\n script as bscript,\n payments,\n Psbt,\n Transaction,\n} from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\n\n// P2WPKH scriptPubKey is exactly `OP_0 OP_PUSHBYTES_20 <20-byte key hash>`\n// (BIP-141 witness program v0, 20 bytes).\nconst P2WPKH_SCRIPT_LEN = 22;\nconst OP_0 = 0x00;\nconst OP_PUSHBYTES_20 = 0x14;\nconst P2WPKH_PROGRAM_START = 2;\n\n/** SEC1 compressed pubkey (client.rs:959: \"expected a 33-byte compressed key\"). */\nconst COMPRESSED_PUBKEY_BYTES = 33;\n/** Consensus P2WPKH witness: exactly [signature, pubkey] (client.rs:951-957). */\nconst P2WPKH_WITNESS_ITEMS = 2;\n\n/** Only claim P2WPKH: 22-byte scriptPubKey starting `OP_0 PUSH20`. */\nexport function isP2wpkhScript(\n script: Uint8Array | undefined,\n): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2WPKH_SCRIPT_LEN &&\n script[0] === OP_0 &&\n script[1] === OP_PUSHBYTES_20\n );\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\n/** The `[signature, pubkey]` pair of a finalized P2WPKH witness (client.rs:951-957). */\nfunction decodeP2wpkhWitness(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; pubkey: Uint8Array } {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== P2WPKH_WITNESS_ITEMS) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized P2WPKH witness must have ` +\n `exactly 2 items [signature, pubkey], got ${items.length}.`,\n );\n }\n return { signature: items[0], pubkey: items[1] };\n}\n\nexport interface AssertReturnedP2wpkhSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout script/value). NOT the wallet's. */\n requestedPsbtHex: string;\n /** The wallet-returned PSBT input carrying the signature material. */\n returnedInput: {\n partialSig?: Array<{ pubkey: Uint8Array; signature: Uint8Array }>;\n finalScriptWitness?: Uint8Array;\n };\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that the returned input carries a valid P2WPKH ECDSA signature\n * over the BIP-143 sighash of `requestedPsbtHex` input `inputIndex`:\n * `partialSig` (BIP-174: the value is the exact witness-stack signature\n * bytes, the key its pubkey), or the finalized 2-item witness — and when\n * both are present they must be the same bytes.\n *\n * @throws If the requested input is not a P2WPKH spend, no signature was\n * returned, a finalized witness disagrees with its `partialSig`,\n * or any check of `verify_finalized_p2wpkh_spend` fails.\n */\nexport function assertReturnedP2wpkhSignature(\n params: AssertReturnedP2wpkhSignatureParams,\n): void {\n const { requestedPsbtHex, returnedInput, inputIndex } = params;\n\n const partials = returnedInput.partialSig;\n // Consensus allows exactly one signature in a P2WPKH witness, so a second\n // partialSig entry is ambiguous tampering, not a fallback to pick from.\n if (partials !== undefined && partials.length > 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a P2WPKH input must carry at most one ` +\n `partial signature, got ${partials.length}.`,\n );\n }\n const partial = partials?.[0];\n const witness = returnedInput.finalScriptWitness\n ? decodeP2wpkhWitness(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify (same\n // rationale as the tapKeySig/witness agreement check).\n if (\n partial &&\n witness &&\n (!bytesEqual(partial.signature, witness.signature) ||\n !bytesEqual(partial.pubkey, witness.pubkey))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its partialSig.`,\n );\n }\n\n const material = partial ?? witness;\n if (!material) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no P2WPKH signature ` +\n `(no partialSig, not finalized).`,\n );\n }\n\n assertP2wpkhEcdsaSignature(\n requestedPsbtHex,\n material.signature,\n material.pubkey,\n inputIndex,\n );\n}\n\n/**\n * The crypto core, mirroring `verify_finalized_p2wpkh_spend` check by\n * check: pubkey shape and curve membership, hash160(pubkey) == witness\n * program, strict-DER + SIGHASH_ALL-only signature, ECDSA over the\n * BIP-143 sighash recomputed from the REQUESTED prevout.\n */\nfunction assertP2wpkhEcdsaSignature(\n requestedPsbtHex: string,\n encodedSignature: Uint8Array,\n pubkey: Uint8Array,\n inputIndex: number,\n): void {\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n const prevout = psbt.data.inputs[inputIndex].witnessUtxo;\n if (!prevout || !isP2wpkhScript(prevout.script)) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a P2WPKH input.`,\n );\n }\n\n // Pubkey: exactly 33 bytes (client.rs:959-965) and a parseable curve\n // point, as PublicKey::from_slice (client.rs:966-968).\n if (pubkey.length !== COMPRESSED_PUBKEY_BYTES) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey must be 33 bytes, ` +\n `got ${pubkey.length}.`,\n );\n }\n if (!ecc.isPointCompressed(pubkey)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey is not a valid secp256k1 point.`,\n );\n }\n\n // hash160(pubkey) must equal the prevout's witness program — what\n // consensus checks (client.rs:970-977).\n const program = prevout.script.subarray(\n P2WPKH_PROGRAM_START,\n P2WPKH_SCRIPT_LEN,\n );\n if (!bytesEqual(bcrypto.hash160(Buffer.from(pubkey)), program)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey does not hash to the ` +\n `prevout's witness program.`,\n );\n }\n\n // Strict-DER decode with defined-hashtype gate — the accept set of\n // ecdsa::Signature::from_slice / EcdsaSighashType::from_standard\n // (client.rs:978-980) — then SIGHASH_ALL exactly (client.rs:981-987).\n let decoded: { signature: Buffer; hashType: number };\n try {\n decoded = bscript.signature.decode(Buffer.from(encodedSignature));\n } catch (e) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not DER with a ` +\n `defined sighash byte: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that libsecp's strict consensus\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(decoded.signature, decoded.hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not canonical DER.`,\n );\n }\n if (decoded.hashType !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature has sighash type ` +\n `0x${decoded.hashType.toString(16)} (expected SIGHASH_ALL).`,\n );\n }\n\n // BIP-143 sighash over the REQUESTED prevout value with the standard\n // P2WPKH scriptCode built from the witness program (client.rs:988-991;\n // scriptCode template per bitcoinjs-lib's own P2WPKH signer,\n // `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: Buffer.from(program) }).output;\n if (!scriptCode) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: could not build the P2WPKH scriptCode.`,\n );\n }\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV0(\n inputIndex,\n scriptCode,\n prevout.value,\n decoded.hashType,\n );\n\n // strict=true rejects high-S, as libsecp256k1's verify_ecdsa does\n // (client.rs:992-999; secp256k1 crate `ecdsa/mod.rs:194`). ecc.verify\n // throws on out-of-range r/s — that is a failed verification here.\n let verifies = false;\n try {\n verifies = ecc.verify(sighash, pubkey, decoded.signature, true);\n } catch {\n verifies = false;\n }\n if (!verifies) {\n throw new Error(\n `P2WPKH signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout. The wallet may have signed a different ` +\n `transaction or key.`,\n );\n }\n}\n","/**\n * Far-side verification of Taproot KEY-PATH Schnorr signatures a wallet\n * returned, over the PSBT we requested (trusted prevouts) — the key-path twin\n * of `assertScriptPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs check_signatures_valid` (output key taken\n * from the prevout scriptPubKey, all prevouts committed). The wallet's\n * success/finalization is never trusted on its own (CLAUDE.md §8).\n * `assertReturnedKeyPathSignatures` additionally dispatches P2WPKH-funded\n * inputs to `verifyP2wpkhEcdsaSignature` (client.rs's\n * `verify_finalized_p2wpkh_spend` sibling), so a Native SegWit software\n * wallet's signatures no longer pass through unchecked.\n *\n * Why verify against the *requested* PSBT: `assertPsbtUnsignedTxMatches` pins\n * the unsigned transaction but deliberately skips per-input metadata, so a\n * wallet could rewrite `witnessUtxo` in its response and make a wrong-message\n * signature self-validate. Prevout scripts and values therefore come from the\n * PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\nimport { hexToUint8Array, stripHexPrefix } from \"../utils/bitcoin\";\nimport {\n assertReturnedP2wpkhSignature,\n isP2wpkhScript,\n} from \"./verifyP2wpkhEcdsaSignature\";\n\nconst SCHNORR_SIG_BYTES = 64;\nconst SIGHASH_DEFAULT = Transaction.SIGHASH_DEFAULT; // 0x00\nconst SIGHASH_ALL = Transaction.SIGHASH_ALL; // 0x01\n\n// P2TR scriptPubKey is exactly `OP_1 OP_PUSHBYTES_32 <32-byte output key>`.\nconst P2TR_SCRIPT_LEN = 34;\nconst OP_1 = 0x51;\nconst OP_PUSHBYTES_32 = 0x20;\nconst P2TR_OUTPUT_KEY_OFFSET = 2;\n\nfunction isP2trScript(script: Uint8Array | undefined): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2TR_SCRIPT_LEN &&\n script[0] === OP_1 &&\n script[1] === OP_PUSHBYTES_32\n );\n}\n\n/** BIP-341: 64 bytes ⇒ SIGHASH_DEFAULT; 65 bytes ⇒ the trailing byte is the hash type (we accept ALL only). */\nfunction splitHashType(\n sig: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; hashType: number } {\n if (sig.length === SCHNORR_SIG_BYTES) {\n return { signature: sig, hashType: SIGHASH_DEFAULT };\n }\n if (\n sig.length === SCHNORR_SIG_BYTES + 1 &&\n sig[SCHNORR_SIG_BYTES] === SIGHASH_ALL\n ) {\n return {\n signature: sig.subarray(0, SCHNORR_SIG_BYTES),\n hashType: SIGHASH_ALL,\n };\n }\n throw new Error(\n `Key-path signature for input ${inputIndex} must be 64 bytes (SIGHASH_DEFAULT) or ` +\n `65 bytes ending in 0x01 (SIGHASH_ALL), got ${sig.length}.`,\n );\n}\n\nexport interface AssertKeyPathSchnorrSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout scripts/values). NOT the wallet's. */\n requestedPsbtHex: string;\n /** 64- or 65-byte signature, hex. */\n signatureHex: string;\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that `signatureHex` is a valid BIP-340 Schnorr signature over the\n * Taproot key-path sighash of `requestedPsbtHex` input `inputIndex`, under the\n * tweaked output key taken from that input's prevout scriptPubKey.\n *\n * @throws If the input is not a key-path P2TR spend, the requested PSBT lacks\n * the prevout data needed to recompute the sighash, or the signature\n * does not verify.\n */\nexport function assertKeyPathSchnorrSignature(\n params: AssertKeyPathSchnorrSignatureParams,\n): void {\n const { requestedPsbtHex, signatureHex, inputIndex } = params;\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n\n if (!isKeyPathEligible(psbt.data.inputs[inputIndex])) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a key-path P2TR input.`,\n );\n }\n\n // Taproot's sighash commits to every input's prevout (script + value), so all\n // inputs must carry a witnessUtxo. A missing one is a build error, not a\n // value we can default — fail loudly.\n const prevOutScripts: Buffer[] = [];\n const values: number[] = [];\n for (let i = 0; i < psbt.data.inputs.length; i++) {\n const prevout = psbt.data.inputs[i].witnessUtxo;\n if (!prevout) {\n throw new Error(\n `Cannot verify signature: input ${i} of the requested PSBT has no witnessUtxo ` +\n `(required to recompute the Taproot sighash).`,\n );\n }\n prevOutScripts.push(prevout.script);\n values.push(prevout.value);\n }\n\n const { signature, hashType } = splitHashType(\n hexToUint8Array(stripHexPrefix(signatureHex)),\n inputIndex,\n );\n\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV1(\n inputIndex,\n prevOutScripts,\n values,\n hashType,\n );\n\n // Key-path signatures verify against the TWEAKED output key = the prevout's\n // witness program.\n const outputKey = prevOutScripts[inputIndex].subarray(P2TR_OUTPUT_KEY_OFFSET);\n\n if (!ecc.verifySchnorr(sighash, outputKey, signature)) {\n throw new Error(\n `Key-path Schnorr signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout (output key ${Buffer.from(outputKey).toString(\"hex\")}). ` +\n `The wallet may have signed a different transaction or key.`,\n );\n }\n}\n\n/**\n * A key-path P2TR input: an internal key, no script-path material, and a\n * taproot prevout. Script-path inputs are the script-path verifier's job.\n */\nfunction isKeyPathEligible(input: {\n tapInternalKey?: Uint8Array;\n tapLeafScript?: unknown;\n tapMerkleRoot?: Uint8Array;\n witnessUtxo?: { script: Uint8Array };\n}): boolean {\n return (\n input.tapInternalKey !== undefined &&\n input.tapLeafScript === undefined &&\n input.tapMerkleRoot === undefined &&\n isP2trScript(input.witnessUtxo?.script)\n );\n}\n\n/**\n * The lone stack item of a finalized key-path witness. An annex would add a\n * second item, but Bitcoin Core rejects annexes as nonstandard\n * (`src/policy/policy.cpp:327-329`), so such a spend could never broadcast.\n */\nfunction singleWitnessItem(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): Uint8Array {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized key-path witness must have ` +\n `exactly one item, got ${items.length}.`,\n );\n }\n return items[0];\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\nexport interface AssertReturnedKeyPathSignaturesParams {\n /** PSBT we built locally and asked the wallet to sign. */\n requestedPsbtHex: string;\n /** PSBT the wallet returned after signing. */\n returnedPsbtHex: string;\n}\n\n/**\n * Verify every key-path-eligible and P2WPKH input of the REQUESTED PSBT\n * against what the wallet RETURNED. Key-path: `tapKeySig`, or the single\n * finalized witness item for wallets that auto-finalize — and when both are\n * present they must be the same bytes. P2WPKH: `partialSig`, or the finalized\n * 2-item witness, verified as ECDSA over the BIP-143 sighash\n * ({@link assertReturnedP2wpkhSignature}); a failure throws but the input is\n * NOT counted. Any other input type (script-path, P2WSH, ...) throws — no\n * verifier here covers it, so it cannot be treated as verified.\n *\n * @returns How many inputs were verified KEY-PATH. A caller that knows every\n * input is taproot key-path (e.g. an approval wallet) must assert\n * this equals its input count — P2WPKH inputs never count toward it,\n * so that gate stays exact.\n * @throws If the input counts differ, an input is neither key-path P2TR nor\n * P2WPKH, an eligible input carries no signature, a finalized witness\n * disagrees with its `tapKeySig`/`partialSig`, or any signature does\n * not verify.\n */\nexport function assertReturnedKeyPathSignatures(\n params: AssertReturnedKeyPathSignaturesParams,\n): number {\n const { requestedPsbtHex, returnedPsbtHex } = params;\n\n const requested = Psbt.fromHex(requestedPsbtHex);\n const returned = Psbt.fromHex(returnedPsbtHex);\n\n if (returned.data.inputs.length !== requested.data.inputs.length) {\n throw new Error(\n `Returned PSBT input count ${returned.data.inputs.length} differs from the ` +\n `requested ${requested.data.inputs.length}.`,\n );\n }\n\n let verified = 0;\n requested.data.inputs.forEach((input, inputIndex) => {\n const returnedInput = returned.data.inputs[inputIndex];\n\n if (!isKeyPathEligible(input)) {\n // Native SegWit funding inputs get the ECDSA check.\n if (isP2wpkhScript(input.witnessUtxo?.script)) {\n assertReturnedP2wpkhSignature({\n requestedPsbtHex,\n returnedInput,\n inputIndex,\n });\n return;\n }\n // No verifier exists for any other type — fail closed like btc-vault's\n // check_signatures_valid rather than silently reporting it checked.\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is neither key-path P2TR ` +\n `nor P2WPKH; refusing to treat it as verified.`,\n );\n }\n verified++;\n\n const tapKeySig = returnedInput.tapKeySig;\n const witnessSig = returnedInput.finalScriptWitness\n ? singleWitnessItem(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify. Matches\n // btc-vault `crates/btc-wallet-remote/src/client.rs:1053-1072,1102-1121`,\n // which checks each independently.\n if (tapKeySig && witnessSig && !bytesEqual(tapKeySig, witnessSig)) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its tapKeySig.`,\n );\n }\n\n const sig = tapKeySig ?? witnessSig;\n if (!sig) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no key-path signature ` +\n `(no tapKeySig, not finalized).`,\n );\n }\n\n assertKeyPathSchnorrSignature({\n requestedPsbtHex,\n signatureHex: Buffer.from(sig).toString(\"hex\"),\n inputIndex,\n });\n });\n\n return verified;\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","getPrePeginHtlcConnectorInfo","expectedHtlc","deriveExpectedPrePeginHtlc","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","hexToUint8Array","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","COMPACT_SIZE_UINT16_PREFIX","COMPACT_SIZE_UINT32_PREFIX","COMPACT_SIZE_UINT16_BYTES","COMPACT_SIZE_UINT32_BYTES","COMPACT_SIZE_UINT16_MIN_VALUE","COMPACT_SIZE_UINT32_MIN_VALUE","decodeWitnessStack","witness","subject","offset","readCompactSize","first","value","count","items","i","len","P2WPKH_SCRIPT_LEN","OP_0","OP_PUSHBYTES_20","P2WPKH_PROGRAM_START","COMPRESSED_PUBKEY_BYTES","P2WPKH_WITNESS_ITEMS","isP2wpkhScript","script","bytesEqual","a","b","byte","decodeP2wpkhWitness","finalScriptWitness","inputIndex","assertReturnedP2wpkhSignature","requestedPsbtHex","returnedInput","partials","partial","material","assertP2wpkhEcdsaSignature","encodedSignature","pubkey","prevout","ecc","program","bcrypto","decoded","bscript","scriptCode","payments","sighash","verifies","SCHNORR_SIG_BYTES","SIGHASH_DEFAULT","SIGHASH_ALL","P2TR_SCRIPT_LEN","OP_1","OP_PUSHBYTES_32","P2TR_OUTPUT_KEY_OFFSET","isP2trScript","splitHashType","assertKeyPathSchnorrSignature","signatureHex","isKeyPathEligible","prevOutScripts","values","signature","hashType","outputKey","_a","singleWitnessItem","assertReturnedKeyPathSignatures","returnedPsbtHex","requested","returned","verified","tapKeySig","witnessSig"],"mappings":";;;;;;AA4FA,eAAsBA,GACpBC,GACoC;AACpC,QAAMC,IAAaC,EAAeF,EAAO,UAAU,GAC7CG,IAAsBD,EAAeF,EAAO,mBAAmB;AAIrE,QAAMI,EAA6B;AAAA,IACjC,gBAAgBJ,EAAO;AAAA,IACvB,iBAAiBA,EAAO;AAAA,IACxB,qBAAqBA,EAAO;AAAA,IAC5B,oBAAoBA,EAAO;AAAA,IAC3B,4BAA4BA,EAAO;AAAA,IACnC,UAAUA,EAAO;AAAA,IACjB,gBAAgBA,EAAO;AAAA,IACvB,SAASA,EAAO;AAAA,EAAA,CACjB;AACD,QAAMK,IAAeC,EAA2BN,GAAQA,EAAO,QAAQ,GAEjEO,IAAUC,EAAY,QAAQP,CAAU,GACxCQ,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,IAAgBuC,EAAS,KAAK,OAAO1C,CAAU;AAErD,QAAI,CAAC+B,EAAkBvE,CAAK,GAAG;AAE7B,UAAIgC,GAAe6C,IAAA7E,EAAM,gBAAN,gBAAA6E,EAAmB,MAAM,GAAG;AAC7C,QAAApC,EAA8B;AAAA,UAC5B,kBAAAC;AAAA,UACA,eAAAC;AAAA,UACA,YAAAH;AAAA,QAAA,CACD;AACD;AAAA,MACF;AAGA,YAAM,IAAI;AAAA,QACR,SAASA,CAAU;AAAA,MAAA;AAAA,IAGvB;AACA,IAAA2C;AAEA,UAAMC,IAAYzC,EAAc,WAC1B0C,IAAa1C,EAAc,qBAC7BmC,GAAkBnC,EAAc,oBAAoBH,CAAU,IAC9D;AAMJ,QAAI4C,KAAaC,KAAc,CAACnD,GAAWkD,GAAWC,CAAU;AAC9D,YAAM,IAAI;AAAA,QACR,uBAAuB7C,CAAU;AAAA,MAAA;AAIrC,UAAMhC,IAAM4E,KAAaC;AACzB,QAAI,CAAC7E;AACH,YAAM,IAAI;AAAA,QACR,uBAAuBgC,CAAU;AAAA,MAAA;AAKrC,IAAA6B,GAA8B;AAAA,MAC5B,kBAAA3B;AAAA,MACA,cAAchD,EAAO,KAAKc,CAAG,EAAE,SAAS,KAAK;AAAA,MAC7C,YAAAgC;AAAA,IAAA,CACD;AAAA,EACH,CAAC,GAEM2C;AACT;"}
|
|
1
|
+
{"version":3,"file":"verifyKeyPathSchnorrSignature-BQHNhRj6.js","sources":["../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/utils/witness/witnessStack.ts","../src/tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature.ts","../src/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.ts"],"sourcesContent":["/**\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 { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { Buffer } from \"buffer\";\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"../../wasm\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\nimport { deriveExpectedPrePeginHtlc } from \"./assertWasmPeginSizing\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * Vault core (tx-graph) version the Pre-PegIn was built with. Must match\n * the version passed to buildPrePeginPsbt() so the HTLC connector scripts\n * are derived for the same graph.\n */\n vaultCoreVersion: number;\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 // Keep the facade's graph-version and input checks. Do not use its scripts\n // or control block as signing data.\n await getPrePeginHtlcConnectorInfo({\n txGraphVersion: params.vaultCoreVersion,\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 const expectedHtlc = deriveExpectedPrePeginHtlc(params, params.hashlock);\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 if (!expectedHtlc.scriptPubKey.equals(htlcOutput.script)) {\n throw new Error(\n \"PegIn HTLC taptree mismatch: the independent 2-leaf tree does not \" +\n \"reproduce the funded Pre-PegIn HTLC scriptPubKey; refusing to sign.\",\n );\n }\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. bitcoinjs\n // re-verifies leaf-in-tree consistency (control block vs tapMerkleRoot)\n // inside addInput — a second independent check.\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: expectedHtlc.hashlockScript,\n controlBlock: expectedHtlc.hashlockControlBlock,\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n tapMerkleRoot: expectedHtlc.tapMerkleRoot,\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 non-finalized PSBTs with tapScriptSig entries. Finalized PSBTs are\n * rejected because the witness stack does not reliably identify the depositor\n * signature by public key.\n *\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Signatures with an appended sighash byte\n * are rejected rather than stripped.\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(hexToUint8Array(depositorPubkey));\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 // A wallet that ignores `autoFinalized: false` returns already-finalized\n // inputs (OKX's single-PSBT endpoint does; the wallet-connector routes OKX\n // around it). finalizeAllInputs() throws in that case, so fall back to\n // 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.\n * PegIn input signatures must use implicit Taproot SIGHASH_DEFAULT, which is\n * encoded by omitting the sighash byte. Reject 65-byte signatures instead of\n * stripping the sighash byte because it changes the signed Taproot message.\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 throw new Error(\n `Unexpected sighash byte 0x${sig[64].toString(16).padStart(2, \"0\")} in PegIn input signature. ` +\n \"Expected implicit SIGHASH_DEFAULT as a 64-byte signature.\",\n );\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n","/**\n * Consensus witness-stack decoding, shared by every module that reads a\n * witness we did not build.\n *\n * Two independent decoders drifted apart before this existed: one accepted\n * non-minimal CompactSize encodings, the other rejected them. vaultd decodes\n * with rust-bitcoin, whose `VarInt::consensus_decode`\n * (0.32.8 `consensus/encode.rs:493-522`) returns `NonMinimalVarInt` for a 0xfd\n * carrying < 0xfd and a 0xfe carrying < 0x10000 — so the strict reading is the\n * only one that matches what the network will accept.\n *\n * @module tbv/core/utils/witness/witnessStack\n */\n\n/** CompactSize discriminators; 0xff (u64) is out of range for a witness. */\nconst COMPACT_SIZE_UINT16_PREFIX = 0xfd;\nconst COMPACT_SIZE_UINT32_PREFIX = 0xfe;\nconst COMPACT_SIZE_UINT16_BYTES = 3;\nconst COMPACT_SIZE_UINT32_BYTES = 5;\nconst COMPACT_SIZE_UINT16_MIN_VALUE = 0xfd;\nconst COMPACT_SIZE_UINT32_MIN_VALUE = 0x10000;\n\n/**\n * Decode a consensus-encoded witness stack: item count, then (len, bytes)*.\n *\n * @param witness - The consensus-encoded witness bytes.\n * @param subject - Names the witness in error messages (e.g. \"finalScriptWitness\").\n * @returns The stack items, as views over `witness`.\n * @throws If the encoding is truncated, non-minimal, out of range, or leaves\n * trailing bytes.\n */\nexport function decodeWitnessStack(\n witness: Uint8Array,\n subject: string,\n): Uint8Array[] {\n let offset = 0;\n\n const readCompactSize = (): number => {\n if (offset >= witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const first = witness[offset];\n if (first < COMPACT_SIZE_UINT16_PREFIX) {\n offset += 1;\n return first;\n }\n if (first === COMPACT_SIZE_UINT16_PREFIX) {\n if (offset + COMPACT_SIZE_UINT16_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value = witness[offset + 1] | (witness[offset + 2] << 8);\n if (value < COMPACT_SIZE_UINT16_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT16_BYTES;\n return value;\n }\n if (first === COMPACT_SIZE_UINT32_PREFIX) {\n if (offset + COMPACT_SIZE_UINT32_BYTES > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n const value =\n (witness[offset + 1] |\n (witness[offset + 2] << 8) |\n (witness[offset + 3] << 16) |\n (witness[offset + 4] << 24)) >>>\n 0;\n if (value < COMPACT_SIZE_UINT32_MIN_VALUE) {\n throw new Error(`${subject} has a non-minimal length encoding`);\n }\n offset += COMPACT_SIZE_UINT32_BYTES;\n return value;\n }\n throw new Error(`${subject} carries an out-of-range item length`);\n };\n\n const count = readCompactSize();\n const items: Uint8Array[] = [];\n for (let i = 0; i < count; i++) {\n const len = readCompactSize();\n if (offset + len > witness.length) {\n throw new Error(`${subject} is truncated`);\n }\n items.push(witness.subarray(offset, offset + len));\n offset += len;\n }\n if (offset !== witness.length) {\n throw new Error(`${subject} has trailing bytes`);\n }\n return items;\n}\n","/**\n * Far-side verification of P2WPKH ECDSA signatures a wallet returned, over\n * the PSBT we requested (trusted prevouts) — the Native SegWit sibling of\n * `verifyKeyPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs:945-1000\n * verify_finalized_p2wpkh_spend`. The wallet's success/finalization is\n * never trusted on its own (CLAUDE.md §8): prevout script and value come\n * from the PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyP2wpkhEcdsaSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport {\n crypto as bcrypto,\n script as bscript,\n payments,\n Psbt,\n Transaction,\n} from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\n\n// P2WPKH scriptPubKey is exactly `OP_0 OP_PUSHBYTES_20 <20-byte key hash>`\n// (BIP-141 witness program v0, 20 bytes).\nconst P2WPKH_SCRIPT_LEN = 22;\nconst OP_0 = 0x00;\nconst OP_PUSHBYTES_20 = 0x14;\nconst P2WPKH_PROGRAM_START = 2;\n\n/** SEC1 compressed pubkey (client.rs:959: \"expected a 33-byte compressed key\"). */\nconst COMPRESSED_PUBKEY_BYTES = 33;\n/** Consensus P2WPKH witness: exactly [signature, pubkey] (client.rs:951-957). */\nconst P2WPKH_WITNESS_ITEMS = 2;\n\n/** Only claim P2WPKH: 22-byte scriptPubKey starting `OP_0 PUSH20`. */\nexport function isP2wpkhScript(\n script: Uint8Array | undefined,\n): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2WPKH_SCRIPT_LEN &&\n script[0] === OP_0 &&\n script[1] === OP_PUSHBYTES_20\n );\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\n/** The `[signature, pubkey]` pair of a finalized P2WPKH witness (client.rs:951-957). */\nfunction decodeP2wpkhWitness(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; pubkey: Uint8Array } {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== P2WPKH_WITNESS_ITEMS) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized P2WPKH witness must have ` +\n `exactly 2 items [signature, pubkey], got ${items.length}.`,\n );\n }\n return { signature: items[0], pubkey: items[1] };\n}\n\nexport interface AssertReturnedP2wpkhSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout script/value). NOT the wallet's. */\n requestedPsbtHex: string;\n /** The wallet-returned PSBT input carrying the signature material. */\n returnedInput: {\n partialSig?: Array<{ pubkey: Uint8Array; signature: Uint8Array }>;\n finalScriptWitness?: Uint8Array;\n };\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that the returned input carries a valid P2WPKH ECDSA signature\n * over the BIP-143 sighash of `requestedPsbtHex` input `inputIndex`:\n * `partialSig` (BIP-174: the value is the exact witness-stack signature\n * bytes, the key its pubkey), or the finalized 2-item witness — and when\n * both are present they must be the same bytes.\n *\n * @throws If the requested input is not a P2WPKH spend, no signature was\n * returned, a finalized witness disagrees with its `partialSig`,\n * or any check of `verify_finalized_p2wpkh_spend` fails.\n */\nexport function assertReturnedP2wpkhSignature(\n params: AssertReturnedP2wpkhSignatureParams,\n): void {\n const { requestedPsbtHex, returnedInput, inputIndex } = params;\n\n const partials = returnedInput.partialSig;\n // Consensus allows exactly one signature in a P2WPKH witness, so a second\n // partialSig entry is ambiguous tampering, not a fallback to pick from.\n if (partials !== undefined && partials.length > 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a P2WPKH input must carry at most one ` +\n `partial signature, got ${partials.length}.`,\n );\n }\n const partial = partials?.[0];\n const witness = returnedInput.finalScriptWitness\n ? decodeP2wpkhWitness(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify (same\n // rationale as the tapKeySig/witness agreement check).\n if (\n partial &&\n witness &&\n (!bytesEqual(partial.signature, witness.signature) ||\n !bytesEqual(partial.pubkey, witness.pubkey))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its partialSig.`,\n );\n }\n\n const material = partial ?? witness;\n if (!material) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no P2WPKH signature ` +\n `(no partialSig, not finalized).`,\n );\n }\n\n assertP2wpkhEcdsaSignature(\n requestedPsbtHex,\n material.signature,\n material.pubkey,\n inputIndex,\n );\n}\n\n/**\n * The crypto core, mirroring `verify_finalized_p2wpkh_spend` check by\n * check: pubkey shape and curve membership, hash160(pubkey) == witness\n * program, strict-DER + SIGHASH_ALL-only signature, ECDSA over the\n * BIP-143 sighash recomputed from the REQUESTED prevout.\n */\nfunction assertP2wpkhEcdsaSignature(\n requestedPsbtHex: string,\n encodedSignature: Uint8Array,\n pubkey: Uint8Array,\n inputIndex: number,\n): void {\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n const prevout = psbt.data.inputs[inputIndex].witnessUtxo;\n if (!prevout || !isP2wpkhScript(prevout.script)) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a P2WPKH input.`,\n );\n }\n\n // Pubkey: exactly 33 bytes (client.rs:959-965) and a parseable curve\n // point, as PublicKey::from_slice (client.rs:966-968).\n if (pubkey.length !== COMPRESSED_PUBKEY_BYTES) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey must be 33 bytes, ` +\n `got ${pubkey.length}.`,\n );\n }\n if (!ecc.isPointCompressed(pubkey)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey is not a valid secp256k1 point.`,\n );\n }\n\n // hash160(pubkey) must equal the prevout's witness program — what\n // consensus checks (client.rs:970-977).\n const program = prevout.script.subarray(\n P2WPKH_PROGRAM_START,\n P2WPKH_SCRIPT_LEN,\n );\n if (!bytesEqual(bcrypto.hash160(Buffer.from(pubkey)), program)) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH pubkey does not hash to the ` +\n `prevout's witness program.`,\n );\n }\n\n // Strict-DER decode with defined-hashtype gate — the accept set of\n // ecdsa::Signature::from_slice / EcdsaSighashType::from_standard\n // (client.rs:978-980) — then SIGHASH_ALL exactly (client.rs:981-987).\n let decoded: { signature: Buffer; hashType: number };\n try {\n decoded = bscript.signature.decode(Buffer.from(encodedSignature));\n } catch (e) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not DER with a ` +\n `defined sighash byte: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n // decode tolerates non-minimal integers (bip66.js never bounds lenR/lenS at 33;\n // fromDER truncates, script_signature.js:29-35) that libsecp's strict consensus\n // parse rejects (secp256k1-sys ecdsa_impl.h:127-136) — require the unique\n // minimal encoding by re-encoding and byte-comparing.\n if (\n !bscript.signature\n .encode(decoded.signature, decoded.hashType)\n .equals(Buffer.from(encodedSignature))\n ) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature is not canonical DER.`,\n );\n }\n if (decoded.hashType !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: P2WPKH signature has sighash type ` +\n `0x${decoded.hashType.toString(16)} (expected SIGHASH_ALL).`,\n );\n }\n\n // BIP-143 sighash over the REQUESTED prevout value with the standard\n // P2WPKH scriptCode built from the witness program (client.rs:988-991;\n // scriptCode template per bitcoinjs-lib's own P2WPKH signer,\n // `src/psbt.js:1245-1255`).\n const scriptCode = payments.p2pkh({ hash: Buffer.from(program) }).output;\n if (!scriptCode) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: could not build the P2WPKH scriptCode.`,\n );\n }\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV0(\n inputIndex,\n scriptCode,\n prevout.value,\n decoded.hashType,\n );\n\n // strict=true rejects high-S, as libsecp256k1's verify_ecdsa does\n // (client.rs:992-999; secp256k1 crate `ecdsa/mod.rs:194`). ecc.verify\n // throws on out-of-range r/s — that is a failed verification here.\n let verifies = false;\n try {\n verifies = ecc.verify(sighash, pubkey, decoded.signature, true);\n } catch {\n verifies = false;\n }\n if (!verifies) {\n throw new Error(\n `P2WPKH signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout. The wallet may have signed a different ` +\n `transaction or key.`,\n );\n }\n}\n","/**\n * Far-side verification of Taproot KEY-PATH Schnorr signatures a wallet\n * returned, over the PSBT we requested (trusted prevouts) — the key-path twin\n * of `assertScriptPathSchnorrSignature`. Reference: btc-vault\n * `crates/btc-wallet-remote/src/client.rs check_signatures_valid` (output key taken\n * from the prevout scriptPubKey, all prevouts committed). The wallet's\n * success/finalization is never trusted on its own (CLAUDE.md §8).\n * `assertReturnedKeyPathSignatures` additionally dispatches P2WPKH-funded\n * inputs to `verifyP2wpkhEcdsaSignature` (client.rs's\n * `verify_finalized_p2wpkh_spend` sibling), so a Native SegWit software\n * wallet's signatures no longer pass through unchecked.\n *\n * Why verify against the *requested* PSBT: `assertPsbtUnsignedTxMatches` pins\n * the unsigned transaction but deliberately skips per-input metadata, so a\n * wallet could rewrite `witnessUtxo` in its response and make a wrong-message\n * signature self-validate. Prevout scripts and values therefore come from the\n * PSBT we built; only the signature bytes come from the wallet.\n *\n * @module tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { Buffer } from \"buffer\";\n\nimport { decodeWitnessStack } from \"../../utils/witness/witnessStack\";\nimport { hexToUint8Array, stripHexPrefix } from \"../utils/bitcoin\";\nimport {\n assertReturnedP2wpkhSignature,\n isP2wpkhScript,\n} from \"./verifyP2wpkhEcdsaSignature\";\n\nconst SCHNORR_SIG_BYTES = 64;\nconst SIGHASH_DEFAULT = Transaction.SIGHASH_DEFAULT; // 0x00\nconst SIGHASH_ALL = Transaction.SIGHASH_ALL; // 0x01\n\n// P2TR scriptPubKey is exactly `OP_1 OP_PUSHBYTES_32 <32-byte output key>`.\nconst P2TR_SCRIPT_LEN = 34;\nconst OP_1 = 0x51;\nconst OP_PUSHBYTES_32 = 0x20;\nconst P2TR_OUTPUT_KEY_OFFSET = 2;\n\nfunction isP2trScript(script: Uint8Array | undefined): script is Uint8Array {\n return (\n script !== undefined &&\n script.length === P2TR_SCRIPT_LEN &&\n script[0] === OP_1 &&\n script[1] === OP_PUSHBYTES_32\n );\n}\n\n/** BIP-341: 64 bytes ⇒ SIGHASH_DEFAULT; 65 bytes ⇒ the trailing byte is the hash type (we accept ALL only). */\nfunction splitHashType(\n sig: Uint8Array,\n inputIndex: number,\n): { signature: Uint8Array; hashType: number } {\n if (sig.length === SCHNORR_SIG_BYTES) {\n return { signature: sig, hashType: SIGHASH_DEFAULT };\n }\n if (\n sig.length === SCHNORR_SIG_BYTES + 1 &&\n sig[SCHNORR_SIG_BYTES] === SIGHASH_ALL\n ) {\n return {\n signature: sig.subarray(0, SCHNORR_SIG_BYTES),\n hashType: SIGHASH_ALL,\n };\n }\n throw new Error(\n `Key-path signature for input ${inputIndex} must be 64 bytes (SIGHASH_DEFAULT) or ` +\n `65 bytes ending in 0x01 (SIGHASH_ALL), got ${sig.length}.`,\n );\n}\n\nexport interface AssertKeyPathSchnorrSignatureParams {\n /** Hex of the PSBT we built and sent (trusted prevout scripts/values). NOT the wallet's. */\n requestedPsbtHex: string;\n /** 64- or 65-byte signature, hex. */\n signatureHex: string;\n /** Index of the input the signature is for. */\n inputIndex: number;\n}\n\n/**\n * Assert that `signatureHex` is a valid BIP-340 Schnorr signature over the\n * Taproot key-path sighash of `requestedPsbtHex` input `inputIndex`, under the\n * tweaked output key taken from that input's prevout scriptPubKey.\n *\n * @throws If the input is not a key-path P2TR spend, the requested PSBT lacks\n * the prevout data needed to recompute the sighash, or the signature\n * does not verify.\n */\nexport function assertKeyPathSchnorrSignature(\n params: AssertKeyPathSchnorrSignatureParams,\n): void {\n const { requestedPsbtHex, signatureHex, inputIndex } = params;\n\n const psbt = Psbt.fromHex(requestedPsbtHex);\n\n if (inputIndex < 0 || inputIndex >= psbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${psbt.data.inputs.length} inputs).`,\n );\n }\n\n if (!isKeyPathEligible(psbt.data.inputs[inputIndex])) {\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is not a key-path P2TR input.`,\n );\n }\n\n // Taproot's sighash commits to every input's prevout (script + value), so all\n // inputs must carry a witnessUtxo. A missing one is a build error, not a\n // value we can default — fail loudly.\n const prevOutScripts: Buffer[] = [];\n const values: number[] = [];\n for (let i = 0; i < psbt.data.inputs.length; i++) {\n const prevout = psbt.data.inputs[i].witnessUtxo;\n if (!prevout) {\n throw new Error(\n `Cannot verify signature: input ${i} of the requested PSBT has no witnessUtxo ` +\n `(required to recompute the Taproot sighash).`,\n );\n }\n prevOutScripts.push(prevout.script);\n values.push(prevout.value);\n }\n\n const { signature, hashType } = splitHashType(\n hexToUint8Array(stripHexPrefix(signatureHex)),\n inputIndex,\n );\n\n const tx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());\n const sighash = tx.hashForWitnessV1(\n inputIndex,\n prevOutScripts,\n values,\n hashType,\n );\n\n // Key-path signatures verify against the TWEAKED output key = the prevout's\n // witness program.\n const outputKey = prevOutScripts[inputIndex].subarray(P2TR_OUTPUT_KEY_OFFSET);\n\n if (!ecc.verifySchnorr(sighash, outputKey, signature)) {\n throw new Error(\n `Key-path Schnorr signature for input ${inputIndex} does not verify against the ` +\n `requested PSBT's prevout (output key ${Buffer.from(outputKey).toString(\"hex\")}). ` +\n `The wallet may have signed a different transaction or key.`,\n );\n }\n}\n\n/**\n * A key-path P2TR input: an internal key, no script-path material, and a\n * taproot prevout. Script-path inputs are the script-path verifier's job.\n */\nfunction isKeyPathEligible(input: {\n tapInternalKey?: Uint8Array;\n tapLeafScript?: unknown;\n tapMerkleRoot?: Uint8Array;\n witnessUtxo?: { script: Uint8Array };\n}): boolean {\n return (\n input.tapInternalKey !== undefined &&\n input.tapLeafScript === undefined &&\n input.tapMerkleRoot === undefined &&\n isP2trScript(input.witnessUtxo?.script)\n );\n}\n\n/**\n * The lone stack item of a finalized key-path witness. An annex would add a\n * second item, but Bitcoin Core rejects annexes as nonstandard\n * (`src/policy/policy.cpp:327-329`), so such a spend could never broadcast.\n */\nfunction singleWitnessItem(\n finalScriptWitness: Uint8Array,\n inputIndex: number,\n): Uint8Array {\n const items = decodeWitnessStack(finalScriptWitness, \"finalScriptWitness\");\n if (items.length !== 1) {\n throw new Error(\n `Returned PSBT input ${inputIndex}: a finalized key-path witness must have ` +\n `exactly one item, got ${items.length}.`,\n );\n }\n return items[0];\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\nexport interface AssertReturnedKeyPathSignaturesParams {\n /** PSBT we built locally and asked the wallet to sign. */\n requestedPsbtHex: string;\n /** PSBT the wallet returned after signing. */\n returnedPsbtHex: string;\n}\n\n/**\n * Verify every key-path-eligible and P2WPKH input of the REQUESTED PSBT\n * against what the wallet RETURNED. Key-path: `tapKeySig`, or the single\n * finalized witness item for wallets that auto-finalize — and when both are\n * present they must be the same bytes. P2WPKH: `partialSig`, or the finalized\n * 2-item witness, verified as ECDSA over the BIP-143 sighash\n * ({@link assertReturnedP2wpkhSignature}); a failure throws but the input is\n * NOT counted. Any other input type (script-path, P2WSH, ...) throws — no\n * verifier here covers it, so it cannot be treated as verified.\n *\n * @returns How many inputs were verified KEY-PATH. A caller that knows every\n * input is taproot key-path (e.g. an approval wallet) must assert\n * this equals its input count — P2WPKH inputs never count toward it,\n * so that gate stays exact.\n * @throws If the input counts differ, an input is neither key-path P2TR nor\n * P2WPKH, an eligible input carries no signature, a finalized witness\n * disagrees with its `tapKeySig`/`partialSig`, or any signature does\n * not verify.\n */\nexport function assertReturnedKeyPathSignatures(\n params: AssertReturnedKeyPathSignaturesParams,\n): number {\n const { requestedPsbtHex, returnedPsbtHex } = params;\n\n const requested = Psbt.fromHex(requestedPsbtHex);\n const returned = Psbt.fromHex(returnedPsbtHex);\n\n if (returned.data.inputs.length !== requested.data.inputs.length) {\n throw new Error(\n `Returned PSBT input count ${returned.data.inputs.length} differs from the ` +\n `requested ${requested.data.inputs.length}.`,\n );\n }\n\n let verified = 0;\n requested.data.inputs.forEach((input, inputIndex) => {\n const returnedInput = returned.data.inputs[inputIndex];\n\n if (!isKeyPathEligible(input)) {\n // Native SegWit funding inputs get the ECDSA check.\n if (isP2wpkhScript(input.witnessUtxo?.script)) {\n assertReturnedP2wpkhSignature({\n requestedPsbtHex,\n returnedInput,\n inputIndex,\n });\n return;\n }\n // No verifier exists for any other type — fail closed like btc-vault's\n // check_signatures_valid rather than silently reporting it checked.\n throw new Error(\n `Input ${inputIndex} of the requested PSBT is neither key-path P2TR ` +\n `nor P2WPKH; refusing to treat it as verified.`,\n );\n }\n verified++;\n\n const tapKeySig = returnedInput.tapKeySig;\n const witnessSig = returnedInput.finalScriptWitness\n ? singleWitnessItem(returnedInput.finalScriptWitness, inputIndex)\n : undefined;\n\n // Both fields can be present, and the consumers broadcast the WITNESS\n // bytes — so the two must agree, not just one of them verify. Matches\n // btc-vault `crates/btc-wallet-remote/src/client.rs:1053-1072,1102-1121`,\n // which checks each independently.\n if (tapKeySig && witnessSig && !bytesEqual(tapKeySig, witnessSig)) {\n throw new Error(\n `Returned PSBT input ${inputIndex} finalized witness does not match its tapKeySig.`,\n );\n }\n\n const sig = tapKeySig ?? witnessSig;\n if (!sig) {\n throw new Error(\n `Returned PSBT input ${inputIndex} carries no key-path signature ` +\n `(no tapKeySig, not finalized).`,\n );\n }\n\n assertKeyPathSchnorrSignature({\n requestedPsbtHex,\n signatureHex: Buffer.from(sig).toString(\"hex\"),\n inputIndex,\n });\n });\n\n return verified;\n}\n"],"names":["buildPeginInputPsbt","params","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","getPrePeginHtlcConnectorInfo","expectedHtlc","deriveExpectedPrePeginHtlc","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","depositorPubkey","input","depositorPubkeyBytes","hexToUint8Array","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","COMPACT_SIZE_UINT16_PREFIX","COMPACT_SIZE_UINT32_PREFIX","COMPACT_SIZE_UINT16_BYTES","COMPACT_SIZE_UINT32_BYTES","COMPACT_SIZE_UINT16_MIN_VALUE","COMPACT_SIZE_UINT32_MIN_VALUE","decodeWitnessStack","witness","subject","offset","readCompactSize","first","value","count","items","i","len","P2WPKH_SCRIPT_LEN","OP_0","OP_PUSHBYTES_20","P2WPKH_PROGRAM_START","COMPRESSED_PUBKEY_BYTES","P2WPKH_WITNESS_ITEMS","isP2wpkhScript","script","bytesEqual","a","b","byte","decodeP2wpkhWitness","finalScriptWitness","inputIndex","assertReturnedP2wpkhSignature","requestedPsbtHex","returnedInput","partials","partial","material","assertP2wpkhEcdsaSignature","encodedSignature","pubkey","prevout","ecc","program","bcrypto","decoded","bscript","scriptCode","payments","sighash","verifies","SCHNORR_SIG_BYTES","SIGHASH_DEFAULT","SIGHASH_ALL","P2TR_SCRIPT_LEN","OP_1","OP_PUSHBYTES_32","P2TR_OUTPUT_KEY_OFFSET","isP2trScript","splitHashType","assertKeyPathSchnorrSignature","signatureHex","isKeyPathEligible","prevOutScripts","values","signature","hashType","outputKey","_a","singleWitnessItem","assertReturnedKeyPathSignatures","returnedPsbtHex","requested","returned","verified","tapKeySig","witnessSig"],"mappings":";;;;;;AA4FA,eAAsBA,GACpBC,GACoC;AACpC,QAAMC,IAAaC,EAAeF,EAAO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