@bitgo-beta/babylonlabs-io-btc-staking-ts 0.4.0-beta.142 → 0.4.0-beta.1421
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/README.md +1 -1
- package/dist/index.cjs +2160 -1458
- package/dist/index.cjs.map +7 -0
- package/dist/index.d.cts +752 -496
- package/dist/index.d.ts +1235 -0
- package/dist/index.js +2135 -1431
- package/dist/index.js.map +7 -0
- package/package.json +14 -6
package/dist/index.js
CHANGED
|
@@ -1,231 +1,3 @@
|
|
|
1
|
-
// src/staking/stakingScript.ts
|
|
2
|
-
import { opcodes, script } from "bitcoinjs-lib";
|
|
3
|
-
|
|
4
|
-
// src/constants/keys.ts
|
|
5
|
-
var NO_COORD_PK_BYTE_LENGTH = 32;
|
|
6
|
-
|
|
7
|
-
// src/staking/stakingScript.ts
|
|
8
|
-
var MAGIC_BYTES_LEN = 4;
|
|
9
|
-
var StakingScriptData = class {
|
|
10
|
-
constructor(stakerKey, finalityProviderKeys, covenantKeys, covenantThreshold, stakingTimelock, unbondingTimelock) {
|
|
11
|
-
if (!stakerKey || !finalityProviderKeys || !covenantKeys || !covenantThreshold || !stakingTimelock || !unbondingTimelock) {
|
|
12
|
-
throw new Error("Missing required input values");
|
|
13
|
-
}
|
|
14
|
-
this.stakerKey = stakerKey;
|
|
15
|
-
this.finalityProviderKeys = finalityProviderKeys;
|
|
16
|
-
this.covenantKeys = covenantKeys;
|
|
17
|
-
this.covenantThreshold = covenantThreshold;
|
|
18
|
-
this.stakingTimeLock = stakingTimelock;
|
|
19
|
-
this.unbondingTimeLock = unbondingTimelock;
|
|
20
|
-
if (!this.validate()) {
|
|
21
|
-
throw new Error("Invalid script data provided");
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
/**
|
|
25
|
-
* Validates the staking script.
|
|
26
|
-
* @returns {boolean} Returns true if the staking script is valid, otherwise false.
|
|
27
|
-
*/
|
|
28
|
-
validate() {
|
|
29
|
-
if (this.stakerKey.length != NO_COORD_PK_BYTE_LENGTH) {
|
|
30
|
-
return false;
|
|
31
|
-
}
|
|
32
|
-
if (this.finalityProviderKeys.some(
|
|
33
|
-
(finalityProviderKey) => finalityProviderKey.length != NO_COORD_PK_BYTE_LENGTH
|
|
34
|
-
)) {
|
|
35
|
-
return false;
|
|
36
|
-
}
|
|
37
|
-
if (this.covenantKeys.some((covenantKey) => covenantKey.length != NO_COORD_PK_BYTE_LENGTH)) {
|
|
38
|
-
return false;
|
|
39
|
-
}
|
|
40
|
-
const allPks = [
|
|
41
|
-
this.stakerKey,
|
|
42
|
-
...this.finalityProviderKeys,
|
|
43
|
-
...this.covenantKeys
|
|
44
|
-
];
|
|
45
|
-
const allPksSet = new Set(allPks);
|
|
46
|
-
if (allPks.length !== allPksSet.size) {
|
|
47
|
-
return false;
|
|
48
|
-
}
|
|
49
|
-
if (this.covenantThreshold <= 0 || this.covenantThreshold > this.covenantKeys.length) {
|
|
50
|
-
return false;
|
|
51
|
-
}
|
|
52
|
-
if (this.stakingTimeLock <= 0 || this.stakingTimeLock > 65535) {
|
|
53
|
-
return false;
|
|
54
|
-
}
|
|
55
|
-
if (this.unbondingTimeLock <= 0 || this.unbondingTimeLock > 65535) {
|
|
56
|
-
return false;
|
|
57
|
-
}
|
|
58
|
-
return true;
|
|
59
|
-
}
|
|
60
|
-
// The staking script allows for multiple finality provider public keys
|
|
61
|
-
// to support (re)stake to multiple finality providers
|
|
62
|
-
// Covenant members are going to have multiple keys
|
|
63
|
-
/**
|
|
64
|
-
* Builds a timelock script.
|
|
65
|
-
* @param timelock - The timelock value to encode in the script.
|
|
66
|
-
* @returns {Buffer} containing the compiled timelock script.
|
|
67
|
-
*/
|
|
68
|
-
buildTimelockScript(timelock) {
|
|
69
|
-
return script.compile([
|
|
70
|
-
this.stakerKey,
|
|
71
|
-
opcodes.OP_CHECKSIGVERIFY,
|
|
72
|
-
script.number.encode(timelock),
|
|
73
|
-
opcodes.OP_CHECKSEQUENCEVERIFY
|
|
74
|
-
]);
|
|
75
|
-
}
|
|
76
|
-
/**
|
|
77
|
-
* Builds the staking timelock script.
|
|
78
|
-
* Only holder of private key for given pubKey can spend after relative lock time
|
|
79
|
-
* Creates the timelock script in the form:
|
|
80
|
-
* <stakerPubKey>
|
|
81
|
-
* OP_CHECKSIGVERIFY
|
|
82
|
-
* <stakingTimeBlocks>
|
|
83
|
-
* OP_CHECKSEQUENCEVERIFY
|
|
84
|
-
* @returns {Buffer} The staking timelock script.
|
|
85
|
-
*/
|
|
86
|
-
buildStakingTimelockScript() {
|
|
87
|
-
return this.buildTimelockScript(this.stakingTimeLock);
|
|
88
|
-
}
|
|
89
|
-
/**
|
|
90
|
-
* Builds the unbonding timelock script.
|
|
91
|
-
* Creates the unbonding timelock script in the form:
|
|
92
|
-
* <stakerPubKey>
|
|
93
|
-
* OP_CHECKSIGVERIFY
|
|
94
|
-
* <unbondingTimeBlocks>
|
|
95
|
-
* OP_CHECKSEQUENCEVERIFY
|
|
96
|
-
* @returns {Buffer} The unbonding timelock script.
|
|
97
|
-
*/
|
|
98
|
-
buildUnbondingTimelockScript() {
|
|
99
|
-
return this.buildTimelockScript(this.unbondingTimeLock);
|
|
100
|
-
}
|
|
101
|
-
/**
|
|
102
|
-
* Builds the unbonding script in the form:
|
|
103
|
-
* buildSingleKeyScript(stakerPk, true) ||
|
|
104
|
-
* buildMultiKeyScript(covenantPks, covenantThreshold, false)
|
|
105
|
-
* || means combining the scripts
|
|
106
|
-
* @returns {Buffer} The unbonding script.
|
|
107
|
-
*/
|
|
108
|
-
buildUnbondingScript() {
|
|
109
|
-
return Buffer.concat([
|
|
110
|
-
this.buildSingleKeyScript(this.stakerKey, true),
|
|
111
|
-
this.buildMultiKeyScript(
|
|
112
|
-
this.covenantKeys,
|
|
113
|
-
this.covenantThreshold,
|
|
114
|
-
false
|
|
115
|
-
)
|
|
116
|
-
]);
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* Builds the slashing script for staking in the form:
|
|
120
|
-
* buildSingleKeyScript(stakerPk, true) ||
|
|
121
|
-
* buildMultiKeyScript(finalityProviderPKs, 1, true) ||
|
|
122
|
-
* buildMultiKeyScript(covenantPks, covenantThreshold, false)
|
|
123
|
-
* || means combining the scripts
|
|
124
|
-
* The slashing script is a combination of single-key and multi-key scripts.
|
|
125
|
-
* The single-key script is used for staker key verification.
|
|
126
|
-
* The multi-key script is used for finality provider key verification and covenant key verification.
|
|
127
|
-
* @returns {Buffer} The slashing script as a Buffer.
|
|
128
|
-
*/
|
|
129
|
-
buildSlashingScript() {
|
|
130
|
-
return Buffer.concat([
|
|
131
|
-
this.buildSingleKeyScript(this.stakerKey, true),
|
|
132
|
-
this.buildMultiKeyScript(
|
|
133
|
-
this.finalityProviderKeys,
|
|
134
|
-
// The threshold is always 1 as we only need one
|
|
135
|
-
// finalityProvider signature to perform slashing
|
|
136
|
-
// (only one finalityProvider performs an offence)
|
|
137
|
-
1,
|
|
138
|
-
// OP_VERIFY/OP_CHECKSIGVERIFY is added at the end
|
|
139
|
-
true
|
|
140
|
-
),
|
|
141
|
-
this.buildMultiKeyScript(
|
|
142
|
-
this.covenantKeys,
|
|
143
|
-
this.covenantThreshold,
|
|
144
|
-
// No need to add verify since covenants are at the end of the script
|
|
145
|
-
false
|
|
146
|
-
)
|
|
147
|
-
]);
|
|
148
|
-
}
|
|
149
|
-
/**
|
|
150
|
-
* Builds the staking scripts.
|
|
151
|
-
* @returns {StakingScripts} The staking scripts.
|
|
152
|
-
*/
|
|
153
|
-
buildScripts() {
|
|
154
|
-
return {
|
|
155
|
-
timelockScript: this.buildStakingTimelockScript(),
|
|
156
|
-
unbondingScript: this.buildUnbondingScript(),
|
|
157
|
-
slashingScript: this.buildSlashingScript(),
|
|
158
|
-
unbondingTimelockScript: this.buildUnbondingTimelockScript()
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
// buildSingleKeyScript and buildMultiKeyScript allow us to reuse functionality
|
|
162
|
-
// for creating Bitcoin scripts for the unbonding script and the slashing script
|
|
163
|
-
/**
|
|
164
|
-
* Builds a single key script in the form:
|
|
165
|
-
* buildSingleKeyScript creates a single key script
|
|
166
|
-
* <pk> OP_CHECKSIGVERIFY (if withVerify is true)
|
|
167
|
-
* <pk> OP_CHECKSIG (if withVerify is false)
|
|
168
|
-
* @param pk - The public key buffer.
|
|
169
|
-
* @param withVerify - A boolean indicating whether to include the OP_CHECKSIGVERIFY opcode.
|
|
170
|
-
* @returns The compiled script buffer.
|
|
171
|
-
*/
|
|
172
|
-
buildSingleKeyScript(pk, withVerify) {
|
|
173
|
-
if (pk.length != NO_COORD_PK_BYTE_LENGTH) {
|
|
174
|
-
throw new Error("Invalid key length");
|
|
175
|
-
}
|
|
176
|
-
return script.compile([
|
|
177
|
-
pk,
|
|
178
|
-
withVerify ? opcodes.OP_CHECKSIGVERIFY : opcodes.OP_CHECKSIG
|
|
179
|
-
]);
|
|
180
|
-
}
|
|
181
|
-
/**
|
|
182
|
-
* Builds a multi-key script in the form:
|
|
183
|
-
* <pk1> OP_CHEKCSIG <pk2> OP_CHECKSIGADD <pk3> OP_CHECKSIGADD ... <pkN> OP_CHECKSIGADD <threshold> OP_NUMEQUAL
|
|
184
|
-
* <withVerify -> OP_NUMEQUALVERIFY>
|
|
185
|
-
* It validates whether provided keys are unique and the threshold is not greater than number of keys
|
|
186
|
-
* If there is only one key provided it will return single key sig script
|
|
187
|
-
* @param pks - An array of public keys.
|
|
188
|
-
* @param threshold - The required number of valid signers.
|
|
189
|
-
* @param withVerify - A boolean indicating whether to include the OP_VERIFY opcode.
|
|
190
|
-
* @returns The compiled multi-key script as a Buffer.
|
|
191
|
-
* @throws {Error} If no keys are provided, if the required number of valid signers is greater than the number of provided keys, or if duplicate keys are provided.
|
|
192
|
-
*/
|
|
193
|
-
buildMultiKeyScript(pks, threshold, withVerify) {
|
|
194
|
-
if (!pks || pks.length === 0) {
|
|
195
|
-
throw new Error("No keys provided");
|
|
196
|
-
}
|
|
197
|
-
if (pks.some((pk) => pk.length != NO_COORD_PK_BYTE_LENGTH)) {
|
|
198
|
-
throw new Error("Invalid key length");
|
|
199
|
-
}
|
|
200
|
-
if (threshold > pks.length) {
|
|
201
|
-
throw new Error(
|
|
202
|
-
"Required number of valid signers is greater than number of provided keys"
|
|
203
|
-
);
|
|
204
|
-
}
|
|
205
|
-
if (pks.length === 1) {
|
|
206
|
-
return this.buildSingleKeyScript(pks[0], withVerify);
|
|
207
|
-
}
|
|
208
|
-
const sortedPks = [...pks].sort(Buffer.compare);
|
|
209
|
-
for (let i = 0; i < sortedPks.length - 1; ++i) {
|
|
210
|
-
if (sortedPks[i].equals(sortedPks[i + 1])) {
|
|
211
|
-
throw new Error("Duplicate keys provided");
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
const scriptElements = [sortedPks[0], opcodes.OP_CHECKSIG];
|
|
215
|
-
for (let i = 1; i < sortedPks.length; i++) {
|
|
216
|
-
scriptElements.push(sortedPks[i]);
|
|
217
|
-
scriptElements.push(opcodes.OP_CHECKSIGADD);
|
|
218
|
-
}
|
|
219
|
-
scriptElements.push(script.number.encode(threshold));
|
|
220
|
-
if (withVerify) {
|
|
221
|
-
scriptElements.push(opcodes.OP_NUMEQUALVERIFY);
|
|
222
|
-
} else {
|
|
223
|
-
scriptElements.push(opcodes.OP_NUMEQUAL);
|
|
224
|
-
}
|
|
225
|
-
return script.compile(scriptElements);
|
|
226
|
-
}
|
|
227
|
-
};
|
|
228
|
-
|
|
229
1
|
// src/error/index.ts
|
|
230
2
|
var StakingError = class _StakingError extends Error {
|
|
231
3
|
constructor(code, message) {
|
|
@@ -244,19 +16,14 @@ var StakingError = class _StakingError extends Error {
|
|
|
244
16
|
}
|
|
245
17
|
};
|
|
246
18
|
|
|
247
|
-
// src/
|
|
248
|
-
import
|
|
249
|
-
|
|
250
|
-
// src/constants/dustSat.ts
|
|
251
|
-
var BTC_DUST_SAT = 546;
|
|
19
|
+
// src/utils/btc.ts
|
|
20
|
+
import * as ecc from "@bitcoin-js/tiny-secp256k1-asmjs";
|
|
21
|
+
import { address, initEccLib, networks } from "bitcoinjs-lib";
|
|
252
22
|
|
|
253
|
-
// src/constants/
|
|
254
|
-
var
|
|
255
|
-
var internalPubkey = Buffer.from(key, "hex").subarray(1, 33);
|
|
23
|
+
// src/constants/keys.ts
|
|
24
|
+
var NO_COORD_PK_BYTE_LENGTH = 32;
|
|
256
25
|
|
|
257
26
|
// src/utils/btc.ts
|
|
258
|
-
import * as ecc from "@bitcoin-js/tiny-secp256k1-asmjs";
|
|
259
|
-
import { initEccLib, address, networks } from "bitcoinjs-lib";
|
|
260
27
|
var initBTCCurve = () => {
|
|
261
28
|
initEccLib(ecc);
|
|
262
29
|
};
|
|
@@ -330,124 +97,12 @@ var transactionIdToHash = (txId) => {
|
|
|
330
97
|
return Buffer.from(txId, "hex").reverse();
|
|
331
98
|
};
|
|
332
99
|
|
|
333
|
-
// src/utils/
|
|
334
|
-
import {
|
|
335
|
-
|
|
336
|
-
// src/constants/fee.ts
|
|
337
|
-
var DEFAULT_INPUT_SIZE = 180;
|
|
338
|
-
var P2WPKH_INPUT_SIZE = 68;
|
|
339
|
-
var P2TR_INPUT_SIZE = 58;
|
|
340
|
-
var TX_BUFFER_SIZE_OVERHEAD = 11;
|
|
341
|
-
var LOW_RATE_ESTIMATION_ACCURACY_BUFFER = 30;
|
|
342
|
-
var MAX_NON_LEGACY_OUTPUT_SIZE = 43;
|
|
343
|
-
var WITHDRAW_TX_BUFFER_SIZE = 17;
|
|
344
|
-
var WALLET_RELAY_FEE_RATE_THRESHOLD = 2;
|
|
345
|
-
var OP_RETURN_OUTPUT_VALUE_SIZE = 8;
|
|
346
|
-
var OP_RETURN_VALUE_SERIALIZE_SIZE = 1;
|
|
100
|
+
// src/utils/staking/index.ts
|
|
101
|
+
import { address as address2, payments } from "bitcoinjs-lib";
|
|
347
102
|
|
|
348
|
-
// src/
|
|
349
|
-
|
|
350
|
-
var
|
|
351
|
-
const decompiled = bitcoinScript.decompile(script4);
|
|
352
|
-
return !!decompiled && decompiled[0] === opcodes2.OP_RETURN;
|
|
353
|
-
};
|
|
354
|
-
var getInputSizeByScript = (script4) => {
|
|
355
|
-
try {
|
|
356
|
-
const { address: p2wpkhAddress } = payments.p2wpkh({
|
|
357
|
-
output: script4
|
|
358
|
-
});
|
|
359
|
-
if (p2wpkhAddress) {
|
|
360
|
-
return P2WPKH_INPUT_SIZE;
|
|
361
|
-
}
|
|
362
|
-
} catch (error) {
|
|
363
|
-
}
|
|
364
|
-
try {
|
|
365
|
-
const { address: p2trAddress } = payments.p2tr({
|
|
366
|
-
output: script4
|
|
367
|
-
});
|
|
368
|
-
if (p2trAddress) {
|
|
369
|
-
return P2TR_INPUT_SIZE;
|
|
370
|
-
}
|
|
371
|
-
} catch (error) {
|
|
372
|
-
}
|
|
373
|
-
return DEFAULT_INPUT_SIZE;
|
|
374
|
-
};
|
|
375
|
-
var getEstimatedChangeOutputSize = () => {
|
|
376
|
-
return MAX_NON_LEGACY_OUTPUT_SIZE;
|
|
377
|
-
};
|
|
378
|
-
var inputValueSum = (inputUTXOs) => {
|
|
379
|
-
return inputUTXOs.reduce((acc, utxo) => acc + utxo.value, 0);
|
|
380
|
-
};
|
|
381
|
-
|
|
382
|
-
// src/utils/fee/index.ts
|
|
383
|
-
var getStakingTxInputUTXOsAndFees = (availableUTXOs, stakingAmount, feeRate, outputs) => {
|
|
384
|
-
if (availableUTXOs.length === 0) {
|
|
385
|
-
throw new Error("Insufficient funds");
|
|
386
|
-
}
|
|
387
|
-
const validUTXOs = availableUTXOs.filter((utxo) => {
|
|
388
|
-
const script4 = Buffer.from(utxo.scriptPubKey, "hex");
|
|
389
|
-
return !!bitcoinScript2.decompile(script4);
|
|
390
|
-
});
|
|
391
|
-
if (validUTXOs.length === 0) {
|
|
392
|
-
throw new Error("Insufficient funds: no valid UTXOs available for staking");
|
|
393
|
-
}
|
|
394
|
-
const sortedUTXOs = validUTXOs.sort((a, b) => b.value - a.value);
|
|
395
|
-
const selectedUTXOs = [];
|
|
396
|
-
let accumulatedValue = 0;
|
|
397
|
-
let estimatedFee = 0;
|
|
398
|
-
for (const utxo of sortedUTXOs) {
|
|
399
|
-
selectedUTXOs.push(utxo);
|
|
400
|
-
accumulatedValue += utxo.value;
|
|
401
|
-
const estimatedSize = getEstimatedSize(selectedUTXOs, outputs);
|
|
402
|
-
estimatedFee = estimatedSize * feeRate + rateBasedTxBufferFee(feeRate);
|
|
403
|
-
if (accumulatedValue - (stakingAmount + estimatedFee) > BTC_DUST_SAT) {
|
|
404
|
-
estimatedFee += getEstimatedChangeOutputSize() * feeRate;
|
|
405
|
-
}
|
|
406
|
-
if (accumulatedValue >= stakingAmount + estimatedFee) {
|
|
407
|
-
break;
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
if (accumulatedValue < stakingAmount + estimatedFee) {
|
|
411
|
-
throw new Error(
|
|
412
|
-
"Insufficient funds: unable to gather enough UTXOs to cover the staking amount and fees"
|
|
413
|
-
);
|
|
414
|
-
}
|
|
415
|
-
return {
|
|
416
|
-
selectedUTXOs,
|
|
417
|
-
fee: estimatedFee
|
|
418
|
-
};
|
|
419
|
-
};
|
|
420
|
-
var getWithdrawTxFee = (feeRate) => {
|
|
421
|
-
const inputSize = P2TR_INPUT_SIZE;
|
|
422
|
-
const outputSize = getEstimatedChangeOutputSize();
|
|
423
|
-
return feeRate * (inputSize + outputSize + TX_BUFFER_SIZE_OVERHEAD + WITHDRAW_TX_BUFFER_SIZE) + rateBasedTxBufferFee(feeRate);
|
|
424
|
-
};
|
|
425
|
-
var getEstimatedSize = (inputUtxos, outputs) => {
|
|
426
|
-
const inputSize = inputUtxos.reduce((acc, u) => {
|
|
427
|
-
const script4 = Buffer.from(u.scriptPubKey, "hex");
|
|
428
|
-
const decompiledScript = bitcoinScript2.decompile(script4);
|
|
429
|
-
if (!decompiledScript) {
|
|
430
|
-
return acc;
|
|
431
|
-
}
|
|
432
|
-
return acc + getInputSizeByScript(script4);
|
|
433
|
-
}, 0);
|
|
434
|
-
const outputSize = outputs.reduce((acc, output) => {
|
|
435
|
-
if (isOP_RETURN(output.scriptPubKey)) {
|
|
436
|
-
return acc + output.scriptPubKey.length + OP_RETURN_OUTPUT_VALUE_SIZE + OP_RETURN_VALUE_SERIALIZE_SIZE;
|
|
437
|
-
}
|
|
438
|
-
return acc + MAX_NON_LEGACY_OUTPUT_SIZE;
|
|
439
|
-
}, 0);
|
|
440
|
-
return inputSize + outputSize + TX_BUFFER_SIZE_OVERHEAD;
|
|
441
|
-
};
|
|
442
|
-
var rateBasedTxBufferFee = (feeRate) => {
|
|
443
|
-
return feeRate <= WALLET_RELAY_FEE_RATE_THRESHOLD ? LOW_RATE_ESTIMATION_ACCURACY_BUFFER : 0;
|
|
444
|
-
};
|
|
445
|
-
|
|
446
|
-
// src/utils/staking/index.ts
|
|
447
|
-
import { address as address2, payments as payments2 } from "bitcoinjs-lib";
|
|
448
|
-
|
|
449
|
-
// src/constants/unbonding.ts
|
|
450
|
-
var MIN_UNBONDING_OUTPUT_VALUE = 1e3;
|
|
103
|
+
// src/constants/internalPubkey.ts
|
|
104
|
+
var key = "0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0";
|
|
105
|
+
var internalPubkey = Buffer.from(key, "hex").subarray(1, 33);
|
|
451
106
|
|
|
452
107
|
// src/utils/staking/index.ts
|
|
453
108
|
var buildStakingTransactionOutputs = (scripts, network, amount) => {
|
|
@@ -473,7 +128,7 @@ var deriveStakingOutputInfo = (scripts, network) => {
|
|
|
473
128
|
},
|
|
474
129
|
[{ output: scripts.unbondingScript }, { output: scripts.timelockScript }]
|
|
475
130
|
];
|
|
476
|
-
const stakingOutput =
|
|
131
|
+
const stakingOutput = payments.p2tr({
|
|
477
132
|
internalPubkey,
|
|
478
133
|
scriptTree,
|
|
479
134
|
network
|
|
@@ -496,7 +151,7 @@ var deriveUnbondingOutputInfo = (scripts, network) => {
|
|
|
496
151
|
},
|
|
497
152
|
{ output: scripts.unbondingTimelockScript }
|
|
498
153
|
];
|
|
499
|
-
const unbondingOutput =
|
|
154
|
+
const unbondingOutput = payments.p2tr({
|
|
500
155
|
internalPubkey,
|
|
501
156
|
scriptTree: outputScriptTree,
|
|
502
157
|
network
|
|
@@ -513,7 +168,7 @@ var deriveUnbondingOutputInfo = (scripts, network) => {
|
|
|
513
168
|
};
|
|
514
169
|
};
|
|
515
170
|
var deriveSlashingOutput = (scripts, network) => {
|
|
516
|
-
const slashingOutput =
|
|
171
|
+
const slashingOutput = payments.p2tr({
|
|
517
172
|
internalPubkey,
|
|
518
173
|
scriptTree: { output: scripts.unbondingTimelockScript },
|
|
519
174
|
network
|
|
@@ -532,7 +187,11 @@ var deriveSlashingOutput = (scripts, network) => {
|
|
|
532
187
|
};
|
|
533
188
|
var findMatchingTxOutputIndex = (tx, outputAddress, network) => {
|
|
534
189
|
const index = tx.outs.findIndex((output) => {
|
|
535
|
-
|
|
190
|
+
try {
|
|
191
|
+
return address2.fromOutputScript(output.script, network) === outputAddress;
|
|
192
|
+
} catch (error) {
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
536
195
|
});
|
|
537
196
|
if (index === -1) {
|
|
538
197
|
throw new StakingError(
|
|
@@ -542,135 +201,9 @@ var findMatchingTxOutputIndex = (tx, outputAddress, network) => {
|
|
|
542
201
|
}
|
|
543
202
|
return index;
|
|
544
203
|
};
|
|
545
|
-
var validateStakingTxInputData = (stakingAmountSat, timelock, params, inputUTXOs, feeRate) => {
|
|
546
|
-
if (stakingAmountSat < params.minStakingAmountSat || stakingAmountSat > params.maxStakingAmountSat) {
|
|
547
|
-
throw new StakingError(
|
|
548
|
-
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
549
|
-
"Invalid staking amount"
|
|
550
|
-
);
|
|
551
|
-
}
|
|
552
|
-
if (timelock < params.minStakingTimeBlocks || timelock > params.maxStakingTimeBlocks) {
|
|
553
|
-
throw new StakingError(
|
|
554
|
-
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
555
|
-
"Invalid timelock"
|
|
556
|
-
);
|
|
557
|
-
}
|
|
558
|
-
if (inputUTXOs.length == 0) {
|
|
559
|
-
throw new StakingError(
|
|
560
|
-
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
561
|
-
"No input UTXOs provided"
|
|
562
|
-
);
|
|
563
|
-
}
|
|
564
|
-
if (feeRate <= 0) {
|
|
565
|
-
throw new StakingError(
|
|
566
|
-
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
567
|
-
"Invalid fee rate"
|
|
568
|
-
);
|
|
569
|
-
}
|
|
570
|
-
};
|
|
571
|
-
var validateParams = (params) => {
|
|
572
|
-
if (params.covenantNoCoordPks.length == 0) {
|
|
573
|
-
throw new StakingError(
|
|
574
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
575
|
-
"Could not find any covenant public keys"
|
|
576
|
-
);
|
|
577
|
-
}
|
|
578
|
-
if (params.covenantNoCoordPks.length < params.covenantQuorum) {
|
|
579
|
-
throw new StakingError(
|
|
580
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
581
|
-
"Covenant public keys must be greater than or equal to the quorum"
|
|
582
|
-
);
|
|
583
|
-
}
|
|
584
|
-
params.covenantNoCoordPks.forEach((pk) => {
|
|
585
|
-
if (!isValidNoCoordPublicKey(pk)) {
|
|
586
|
-
throw new StakingError(
|
|
587
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
588
|
-
"Covenant public key should contains no coordinate"
|
|
589
|
-
);
|
|
590
|
-
}
|
|
591
|
-
});
|
|
592
|
-
if (params.unbondingTime <= 0) {
|
|
593
|
-
throw new StakingError(
|
|
594
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
595
|
-
"Unbonding time must be greater than 0"
|
|
596
|
-
);
|
|
597
|
-
}
|
|
598
|
-
if (params.unbondingFeeSat <= 0) {
|
|
599
|
-
throw new StakingError(
|
|
600
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
601
|
-
"Unbonding fee must be greater than 0"
|
|
602
|
-
);
|
|
603
|
-
}
|
|
604
|
-
if (params.maxStakingAmountSat < params.minStakingAmountSat) {
|
|
605
|
-
throw new StakingError(
|
|
606
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
607
|
-
"Max staking amount must be greater or equal to min staking amount"
|
|
608
|
-
);
|
|
609
|
-
}
|
|
610
|
-
if (params.minStakingAmountSat < params.unbondingFeeSat + MIN_UNBONDING_OUTPUT_VALUE) {
|
|
611
|
-
throw new StakingError(
|
|
612
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
613
|
-
`Min staking amount must be greater than unbonding fee plus ${MIN_UNBONDING_OUTPUT_VALUE}`
|
|
614
|
-
);
|
|
615
|
-
}
|
|
616
|
-
if (params.maxStakingTimeBlocks < params.minStakingTimeBlocks) {
|
|
617
|
-
throw new StakingError(
|
|
618
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
619
|
-
"Max staking time must be greater or equal to min staking time"
|
|
620
|
-
);
|
|
621
|
-
}
|
|
622
|
-
if (params.minStakingTimeBlocks <= 0) {
|
|
623
|
-
throw new StakingError(
|
|
624
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
625
|
-
"Min staking time must be greater than 0"
|
|
626
|
-
);
|
|
627
|
-
}
|
|
628
|
-
if (params.covenantQuorum <= 0) {
|
|
629
|
-
throw new StakingError(
|
|
630
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
631
|
-
"Covenant quorum must be greater than 0"
|
|
632
|
-
);
|
|
633
|
-
}
|
|
634
|
-
if (params.slashing) {
|
|
635
|
-
if (params.slashing.slashingRate <= 0) {
|
|
636
|
-
throw new StakingError(
|
|
637
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
638
|
-
"Slashing rate must be greater than 0"
|
|
639
|
-
);
|
|
640
|
-
}
|
|
641
|
-
if (params.slashing.slashingRate > 1) {
|
|
642
|
-
throw new StakingError(
|
|
643
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
644
|
-
"Slashing rate must be less or equal to 1"
|
|
645
|
-
);
|
|
646
|
-
}
|
|
647
|
-
if (params.slashing.slashingPkScriptHex.length == 0) {
|
|
648
|
-
throw new StakingError(
|
|
649
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
650
|
-
"Slashing public key script is missing"
|
|
651
|
-
);
|
|
652
|
-
}
|
|
653
|
-
if (params.slashing.minSlashingTxFeeSat <= 0) {
|
|
654
|
-
throw new StakingError(
|
|
655
|
-
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
656
|
-
"Minimum slashing transaction fee must be greater than 0"
|
|
657
|
-
);
|
|
658
|
-
}
|
|
659
|
-
}
|
|
660
|
-
};
|
|
661
|
-
var validateStakingTimelock = (stakingTimelock, params) => {
|
|
662
|
-
if (stakingTimelock < params.minStakingTimeBlocks || stakingTimelock > params.maxStakingTimeBlocks) {
|
|
663
|
-
throw new StakingError(
|
|
664
|
-
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
665
|
-
"Staking transaction timelock is out of range"
|
|
666
|
-
);
|
|
667
|
-
}
|
|
668
|
-
};
|
|
669
204
|
var toBuffers = (inputs) => {
|
|
670
205
|
try {
|
|
671
|
-
return inputs.map(
|
|
672
|
-
(i) => Buffer.from(i, "hex")
|
|
673
|
-
);
|
|
206
|
+
return inputs.map((i) => Buffer.from(i, "hex"));
|
|
674
207
|
} catch (error) {
|
|
675
208
|
throw StakingError.fromUnknown(
|
|
676
209
|
error,
|
|
@@ -679,561 +212,1291 @@ var toBuffers = (inputs) => {
|
|
|
679
212
|
);
|
|
680
213
|
}
|
|
681
214
|
};
|
|
215
|
+
var clearTxSignatures = (tx) => {
|
|
216
|
+
tx.ins.forEach((input) => {
|
|
217
|
+
input.script = Buffer.alloc(0);
|
|
218
|
+
input.witness = [];
|
|
219
|
+
});
|
|
220
|
+
return tx;
|
|
221
|
+
};
|
|
222
|
+
var deriveMerkleProof = (merkle) => {
|
|
223
|
+
const proofHex = merkle.reduce((acc, m) => {
|
|
224
|
+
return acc + Buffer.from(m, "hex").reverse().toString("hex");
|
|
225
|
+
}, "");
|
|
226
|
+
return proofHex;
|
|
227
|
+
};
|
|
228
|
+
var extractFirstSchnorrSignatureFromTransaction = (singedTransaction) => {
|
|
229
|
+
for (const input of singedTransaction.ins) {
|
|
230
|
+
if (input.witness && input.witness.length > 0) {
|
|
231
|
+
const schnorrSignature = input.witness[0];
|
|
232
|
+
if (schnorrSignature.length === 64) {
|
|
233
|
+
return schnorrSignature;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return void 0;
|
|
238
|
+
};
|
|
682
239
|
|
|
683
|
-
// src/
|
|
684
|
-
|
|
685
|
-
var TRANSACTION_VERSION = 2;
|
|
240
|
+
// src/staking/psbt.ts
|
|
241
|
+
import { Psbt, payments as payments3 } from "bitcoinjs-lib";
|
|
686
242
|
|
|
687
243
|
// src/constants/transaction.ts
|
|
688
244
|
var REDEEM_VERSION = 192;
|
|
689
245
|
|
|
690
|
-
// src/
|
|
691
|
-
var
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
if (amount <= 0 || feeRate <= 0) {
|
|
695
|
-
throw new Error("Amount and fee rate must be bigger than 0");
|
|
696
|
-
}
|
|
697
|
-
if (!isValidBitcoinAddress(changeAddress, network)) {
|
|
698
|
-
throw new Error("Invalid change address");
|
|
699
|
-
}
|
|
700
|
-
const stakingOutputs = buildStakingTransactionOutputs(scripts, network, amount);
|
|
701
|
-
const { selectedUTXOs, fee } = getStakingTxInputUTXOsAndFees(
|
|
702
|
-
inputUTXOs,
|
|
703
|
-
amount,
|
|
704
|
-
feeRate,
|
|
705
|
-
stakingOutputs
|
|
246
|
+
// src/utils/utxo/findInputUTXO.ts
|
|
247
|
+
var findInputUTXO = (inputUTXOs, input) => {
|
|
248
|
+
const inputUTXO = inputUTXOs.find(
|
|
249
|
+
(u) => transactionIdToHash(u.txid).toString("hex") === input.hash.toString("hex") && u.vout === input.index
|
|
706
250
|
);
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
const input = selectedUTXOs[i];
|
|
711
|
-
tx.addInput(
|
|
712
|
-
transactionIdToHash(input.txid),
|
|
713
|
-
input.vout,
|
|
714
|
-
NON_RBF_SEQUENCE
|
|
251
|
+
if (!inputUTXO) {
|
|
252
|
+
throw new Error(
|
|
253
|
+
`Input UTXO not found for txid: ${Buffer.from(input.hash).reverse().toString("hex")} and vout: ${input.index}`
|
|
715
254
|
);
|
|
716
255
|
}
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
256
|
+
return inputUTXO;
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
// src/utils/utxo/getScriptType.ts
|
|
260
|
+
import { payments as payments2 } from "bitcoinjs-lib";
|
|
261
|
+
var BitcoinScriptType = /* @__PURE__ */ ((BitcoinScriptType2) => {
|
|
262
|
+
BitcoinScriptType2["P2PKH"] = "pubkeyhash";
|
|
263
|
+
BitcoinScriptType2["P2SH"] = "scripthash";
|
|
264
|
+
BitcoinScriptType2["P2WPKH"] = "witnesspubkeyhash";
|
|
265
|
+
BitcoinScriptType2["P2WSH"] = "witnessscripthash";
|
|
266
|
+
BitcoinScriptType2["P2TR"] = "taproot";
|
|
267
|
+
return BitcoinScriptType2;
|
|
268
|
+
})(BitcoinScriptType || {});
|
|
269
|
+
var getScriptType = (script4) => {
|
|
270
|
+
try {
|
|
271
|
+
payments2.p2pkh({ output: script4 });
|
|
272
|
+
return "pubkeyhash" /* P2PKH */;
|
|
273
|
+
} catch {
|
|
726
274
|
}
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
275
|
+
try {
|
|
276
|
+
payments2.p2sh({ output: script4 });
|
|
277
|
+
return "scripthash" /* P2SH */;
|
|
278
|
+
} catch {
|
|
279
|
+
}
|
|
280
|
+
try {
|
|
281
|
+
payments2.p2wpkh({ output: script4 });
|
|
282
|
+
return "witnesspubkeyhash" /* P2WPKH */;
|
|
283
|
+
} catch {
|
|
284
|
+
}
|
|
285
|
+
try {
|
|
286
|
+
payments2.p2wsh({ output: script4 });
|
|
287
|
+
return "witnessscripthash" /* P2WSH */;
|
|
288
|
+
} catch {
|
|
289
|
+
}
|
|
290
|
+
try {
|
|
291
|
+
payments2.p2tr({ output: script4 });
|
|
292
|
+
return "taproot" /* P2TR */;
|
|
293
|
+
} catch {
|
|
294
|
+
}
|
|
295
|
+
throw new Error("Unknown script type");
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
// src/utils/utxo/getPsbtInputFields.ts
|
|
299
|
+
var getPsbtInputFields = (utxo, publicKeyNoCoord) => {
|
|
300
|
+
const scriptPubKey = Buffer.from(utxo.scriptPubKey, "hex");
|
|
301
|
+
const type = getScriptType(scriptPubKey);
|
|
302
|
+
switch (type) {
|
|
303
|
+
case "pubkeyhash" /* P2PKH */: {
|
|
304
|
+
if (!utxo.rawTxHex) {
|
|
305
|
+
throw new Error("Missing rawTxHex for legacy P2PKH input");
|
|
306
|
+
}
|
|
307
|
+
return { nonWitnessUtxo: Buffer.from(utxo.rawTxHex, "hex") };
|
|
730
308
|
}
|
|
731
|
-
|
|
309
|
+
case "scripthash" /* P2SH */: {
|
|
310
|
+
if (!utxo.rawTxHex) {
|
|
311
|
+
throw new Error("Missing rawTxHex for P2SH input");
|
|
312
|
+
}
|
|
313
|
+
if (!utxo.redeemScript) {
|
|
314
|
+
throw new Error("Missing redeemScript for P2SH input");
|
|
315
|
+
}
|
|
316
|
+
return {
|
|
317
|
+
nonWitnessUtxo: Buffer.from(utxo.rawTxHex, "hex"),
|
|
318
|
+
redeemScript: Buffer.from(utxo.redeemScript, "hex")
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
case "witnesspubkeyhash" /* P2WPKH */: {
|
|
322
|
+
return {
|
|
323
|
+
witnessUtxo: {
|
|
324
|
+
script: scriptPubKey,
|
|
325
|
+
value: utxo.value
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
case "witnessscripthash" /* P2WSH */: {
|
|
330
|
+
if (!utxo.witnessScript) {
|
|
331
|
+
throw new Error("Missing witnessScript for P2WSH input");
|
|
332
|
+
}
|
|
333
|
+
return {
|
|
334
|
+
witnessUtxo: {
|
|
335
|
+
script: scriptPubKey,
|
|
336
|
+
value: utxo.value
|
|
337
|
+
},
|
|
338
|
+
witnessScript: Buffer.from(utxo.witnessScript, "hex")
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
case "taproot" /* P2TR */: {
|
|
342
|
+
return {
|
|
343
|
+
witnessUtxo: {
|
|
344
|
+
script: scriptPubKey,
|
|
345
|
+
value: utxo.value
|
|
346
|
+
},
|
|
347
|
+
// this is needed only if the wallet is in taproot mode
|
|
348
|
+
...publicKeyNoCoord && { tapInternalKey: publicKeyNoCoord }
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
default:
|
|
352
|
+
throw new Error(`Unsupported script type: ${type}`);
|
|
732
353
|
}
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
const scriptTree = [
|
|
740
|
-
{
|
|
741
|
-
output: scripts.slashingScript
|
|
742
|
-
},
|
|
743
|
-
{ output: scripts.unbondingTimelockScript }
|
|
744
|
-
];
|
|
745
|
-
return withdrawalTransaction(
|
|
746
|
-
{
|
|
747
|
-
timelockScript: scripts.unbondingTimelockScript
|
|
748
|
-
},
|
|
749
|
-
scriptTree,
|
|
750
|
-
unbondingTx,
|
|
751
|
-
withdrawalAddress,
|
|
752
|
-
network,
|
|
753
|
-
feeRate,
|
|
754
|
-
0
|
|
755
|
-
// unbonding always has a single output
|
|
756
|
-
);
|
|
757
|
-
}
|
|
758
|
-
function withdrawTimelockUnbondedTransaction(scripts, tx, withdrawalAddress, network, feeRate, outputIndex = 0) {
|
|
759
|
-
const scriptTree = [
|
|
760
|
-
{
|
|
761
|
-
output: scripts.slashingScript
|
|
762
|
-
},
|
|
763
|
-
[{ output: scripts.unbondingScript }, { output: scripts.timelockScript }]
|
|
764
|
-
];
|
|
765
|
-
return withdrawalTransaction(
|
|
766
|
-
scripts,
|
|
767
|
-
scriptTree,
|
|
768
|
-
tx,
|
|
769
|
-
withdrawalAddress,
|
|
770
|
-
network,
|
|
771
|
-
feeRate,
|
|
772
|
-
outputIndex
|
|
773
|
-
);
|
|
774
|
-
}
|
|
775
|
-
function withdrawSlashingTransaction(scripts, slashingTx, withdrawalAddress, network, feeRate, outputIndex) {
|
|
776
|
-
const scriptTree = { output: scripts.unbondingTimelockScript };
|
|
777
|
-
return withdrawalTransaction(
|
|
778
|
-
{
|
|
779
|
-
timelockScript: scripts.unbondingTimelockScript
|
|
780
|
-
},
|
|
781
|
-
scriptTree,
|
|
782
|
-
slashingTx,
|
|
783
|
-
withdrawalAddress,
|
|
784
|
-
network,
|
|
785
|
-
feeRate,
|
|
786
|
-
outputIndex
|
|
787
|
-
);
|
|
788
|
-
}
|
|
789
|
-
function withdrawalTransaction(scripts, scriptTree, tx, withdrawalAddress, network, feeRate, outputIndex = 0) {
|
|
790
|
-
if (feeRate <= 0) {
|
|
791
|
-
throw new Error("Withdrawal feeRate must be bigger than 0");
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
// src/staking/psbt.ts
|
|
357
|
+
var stakingPsbt = (stakingTx, network, inputUTXOs, publicKeyNoCoord) => {
|
|
358
|
+
if (publicKeyNoCoord && publicKeyNoCoord.length !== NO_COORD_PK_BYTE_LENGTH) {
|
|
359
|
+
throw new Error("Invalid public key");
|
|
792
360
|
}
|
|
793
|
-
|
|
794
|
-
|
|
361
|
+
const psbt = new Psbt({ network });
|
|
362
|
+
if (stakingTx.version !== void 0) psbt.setVersion(stakingTx.version);
|
|
363
|
+
if (stakingTx.locktime !== void 0) psbt.setLocktime(stakingTx.locktime);
|
|
364
|
+
stakingTx.ins.forEach((input) => {
|
|
365
|
+
const inputUTXO = findInputUTXO(inputUTXOs, input);
|
|
366
|
+
const psbtInputData = getPsbtInputFields(inputUTXO, publicKeyNoCoord);
|
|
367
|
+
psbt.addInput({
|
|
368
|
+
hash: input.hash,
|
|
369
|
+
index: input.index,
|
|
370
|
+
sequence: input.sequence,
|
|
371
|
+
...psbtInputData
|
|
372
|
+
});
|
|
373
|
+
});
|
|
374
|
+
stakingTx.outs.forEach((o) => {
|
|
375
|
+
psbt.addOutput({ script: o.script, value: o.value });
|
|
376
|
+
});
|
|
377
|
+
return psbt;
|
|
378
|
+
};
|
|
379
|
+
var stakingExpansionPsbt = (network, stakingTx, previousStakingTxInfo, inputUTXOs, previousScripts, publicKeyNoCoord) => {
|
|
380
|
+
const psbt = new Psbt({ network });
|
|
381
|
+
if (stakingTx.version !== void 0) psbt.setVersion(stakingTx.version);
|
|
382
|
+
if (stakingTx.locktime !== void 0) psbt.setLocktime(stakingTx.locktime);
|
|
383
|
+
if (publicKeyNoCoord && publicKeyNoCoord.length !== NO_COORD_PK_BYTE_LENGTH) {
|
|
384
|
+
throw new Error("Invalid public key");
|
|
795
385
|
}
|
|
796
|
-
const
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
throw new Error("Timelock script is not valid");
|
|
386
|
+
const previousStakingOutput = previousStakingTxInfo.stakingTx.outs[previousStakingTxInfo.outputIndex];
|
|
387
|
+
if (!previousStakingOutput) {
|
|
388
|
+
throw new Error("Previous staking output not found");
|
|
800
389
|
}
|
|
801
|
-
|
|
802
|
-
if (
|
|
803
|
-
|
|
804
|
-
timelock = script2.number.decode(timeBuffer);
|
|
805
|
-
} else {
|
|
806
|
-
const wrap = decompiled[timePosition] % 16;
|
|
807
|
-
timelock = wrap === 0 ? 16 : wrap;
|
|
390
|
+
;
|
|
391
|
+
if (getScriptType(previousStakingOutput.script) !== "taproot" /* P2TR */) {
|
|
392
|
+
throw new Error("Previous staking output script type is not P2TR");
|
|
808
393
|
}
|
|
809
|
-
|
|
810
|
-
|
|
394
|
+
if (stakingTx.ins.length !== 2) {
|
|
395
|
+
throw new Error(
|
|
396
|
+
"Staking expansion transaction must have exactly 2 inputs"
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
const txInputs = stakingTx.ins;
|
|
400
|
+
if (Buffer.from(txInputs[0].hash).reverse().toString("hex") !== previousStakingTxInfo.stakingTx.getId()) {
|
|
401
|
+
throw new Error("Previous staking input hash does not match");
|
|
402
|
+
} else if (txInputs[0].index !== previousStakingTxInfo.outputIndex) {
|
|
403
|
+
throw new Error("Previous staking input index does not match");
|
|
404
|
+
}
|
|
405
|
+
const inputScriptTree = [
|
|
406
|
+
{ output: previousScripts.slashingScript },
|
|
407
|
+
[{ output: previousScripts.unbondingScript }, { output: previousScripts.timelockScript }]
|
|
408
|
+
];
|
|
409
|
+
const inputRedeem = {
|
|
410
|
+
output: previousScripts.unbondingScript,
|
|
811
411
|
redeemVersion: REDEEM_VERSION
|
|
812
412
|
};
|
|
813
413
|
const p2tr = payments3.p2tr({
|
|
814
414
|
internalPubkey,
|
|
815
|
-
scriptTree,
|
|
816
|
-
redeem,
|
|
415
|
+
scriptTree: inputScriptTree,
|
|
416
|
+
redeem: inputRedeem,
|
|
817
417
|
network
|
|
818
418
|
});
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
419
|
+
if (!p2tr.witness || p2tr.witness.length === 0) {
|
|
420
|
+
throw new Error(
|
|
421
|
+
"Failed to create P2TR witness for expansion transaction input"
|
|
422
|
+
);
|
|
423
|
+
}
|
|
424
|
+
const inputTapLeafScript = {
|
|
425
|
+
leafVersion: inputRedeem.redeemVersion,
|
|
426
|
+
script: inputRedeem.output,
|
|
822
427
|
controlBlock: p2tr.witness[p2tr.witness.length - 1]
|
|
823
428
|
};
|
|
824
|
-
const psbt = new Psbt({ network });
|
|
825
|
-
psbt.setVersion(TRANSACTION_VERSION);
|
|
826
429
|
psbt.addInput({
|
|
827
|
-
hash:
|
|
828
|
-
index:
|
|
829
|
-
|
|
430
|
+
hash: txInputs[0].hash,
|
|
431
|
+
index: txInputs[0].index,
|
|
432
|
+
sequence: txInputs[0].sequence,
|
|
830
433
|
witnessUtxo: {
|
|
831
|
-
|
|
832
|
-
|
|
434
|
+
script: previousStakingOutput.script,
|
|
435
|
+
value: previousStakingOutput.value
|
|
833
436
|
},
|
|
834
|
-
|
|
835
|
-
|
|
437
|
+
tapInternalKey: internalPubkey,
|
|
438
|
+
tapLeafScript: [inputTapLeafScript]
|
|
836
439
|
});
|
|
837
|
-
const
|
|
838
|
-
const
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
if (outputValue < BTC_DUST_SAT) {
|
|
845
|
-
throw new Error("Output value is less than dust limit");
|
|
846
|
-
}
|
|
847
|
-
psbt.addOutput({
|
|
848
|
-
address: withdrawalAddress,
|
|
849
|
-
value: outputValue
|
|
440
|
+
const inputUTXO = findInputUTXO(inputUTXOs, txInputs[1]);
|
|
441
|
+
const psbtInputData = getPsbtInputFields(inputUTXO, publicKeyNoCoord);
|
|
442
|
+
psbt.addInput({
|
|
443
|
+
hash: txInputs[1].hash,
|
|
444
|
+
index: txInputs[1].index,
|
|
445
|
+
sequence: txInputs[1].sequence,
|
|
446
|
+
...psbtInputData
|
|
850
447
|
});
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
{
|
|
860
|
-
output: scripts.slashingScript
|
|
861
|
-
},
|
|
862
|
-
[{ output: scripts.unbondingScript }, { output: scripts.timelockScript }]
|
|
863
|
-
];
|
|
864
|
-
return slashingTransaction(
|
|
865
|
-
{
|
|
866
|
-
unbondingTimelockScript: scripts.unbondingTimelockScript,
|
|
867
|
-
slashingScript: scripts.slashingScript
|
|
868
|
-
},
|
|
869
|
-
slashingScriptTree,
|
|
870
|
-
stakingTransaction2,
|
|
871
|
-
slashingPkScriptHex,
|
|
872
|
-
slashingRate,
|
|
873
|
-
minimumFee,
|
|
874
|
-
network,
|
|
875
|
-
outputIndex
|
|
876
|
-
);
|
|
877
|
-
}
|
|
878
|
-
function slashEarlyUnbondedTransaction(scripts, unbondingTx, slashingPkScriptHex, slashingRate, minimumSlashingFee, network) {
|
|
879
|
-
const unbondingScriptTree = [
|
|
880
|
-
{
|
|
881
|
-
output: scripts.slashingScript
|
|
882
|
-
},
|
|
883
|
-
{
|
|
884
|
-
output: scripts.unbondingTimelockScript
|
|
885
|
-
}
|
|
886
|
-
];
|
|
887
|
-
return slashingTransaction(
|
|
888
|
-
{
|
|
889
|
-
unbondingTimelockScript: scripts.unbondingTimelockScript,
|
|
890
|
-
slashingScript: scripts.slashingScript
|
|
891
|
-
},
|
|
892
|
-
unbondingScriptTree,
|
|
893
|
-
unbondingTx,
|
|
894
|
-
slashingPkScriptHex,
|
|
895
|
-
slashingRate,
|
|
896
|
-
minimumSlashingFee,
|
|
897
|
-
network,
|
|
898
|
-
0
|
|
899
|
-
// unbonding always has a single output
|
|
900
|
-
);
|
|
901
|
-
}
|
|
902
|
-
function slashingTransaction(scripts, scriptTree, transaction, slashingPkScriptHex, slashingRate, minimumFee, network, outputIndex = 0) {
|
|
903
|
-
if (slashingRate <= 0 || slashingRate >= 1) {
|
|
904
|
-
throw new Error("Slashing rate must be between 0 and 1");
|
|
448
|
+
stakingTx.outs.forEach((o) => {
|
|
449
|
+
psbt.addOutput({ script: o.script, value: o.value });
|
|
450
|
+
});
|
|
451
|
+
return psbt;
|
|
452
|
+
};
|
|
453
|
+
var unbondingPsbt = (scripts, unbondingTx, stakingTx, network) => {
|
|
454
|
+
if (unbondingTx.outs.length !== 1) {
|
|
455
|
+
throw new Error("Unbonding transaction must have exactly one output");
|
|
905
456
|
}
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
throw new Error("Minimum fee must be a positve integer");
|
|
457
|
+
if (unbondingTx.ins.length !== 1) {
|
|
458
|
+
throw new Error("Unbonding transaction must have exactly one input");
|
|
909
459
|
}
|
|
910
|
-
|
|
911
|
-
|
|
460
|
+
validateUnbondingOutput(scripts, unbondingTx, network);
|
|
461
|
+
const psbt = new Psbt({ network });
|
|
462
|
+
if (unbondingTx.version !== void 0) {
|
|
463
|
+
psbt.setVersion(unbondingTx.version);
|
|
912
464
|
}
|
|
913
|
-
if (
|
|
914
|
-
|
|
465
|
+
if (unbondingTx.locktime !== void 0) {
|
|
466
|
+
psbt.setLocktime(unbondingTx.locktime);
|
|
915
467
|
}
|
|
916
|
-
const
|
|
917
|
-
|
|
468
|
+
const input = unbondingTx.ins[0];
|
|
469
|
+
const outputIndex = input.index;
|
|
470
|
+
const inputScriptTree = [
|
|
471
|
+
{ output: scripts.slashingScript },
|
|
472
|
+
[{ output: scripts.unbondingScript }, { output: scripts.timelockScript }]
|
|
473
|
+
];
|
|
474
|
+
const inputRedeem = {
|
|
475
|
+
output: scripts.unbondingScript,
|
|
918
476
|
redeemVersion: REDEEM_VERSION
|
|
919
477
|
};
|
|
920
478
|
const p2tr = payments3.p2tr({
|
|
921
479
|
internalPubkey,
|
|
922
|
-
scriptTree,
|
|
923
|
-
redeem,
|
|
480
|
+
scriptTree: inputScriptTree,
|
|
481
|
+
redeem: inputRedeem,
|
|
924
482
|
network
|
|
925
483
|
});
|
|
926
|
-
const
|
|
927
|
-
leafVersion:
|
|
928
|
-
script:
|
|
484
|
+
const inputTapLeafScript = {
|
|
485
|
+
leafVersion: inputRedeem.redeemVersion,
|
|
486
|
+
script: inputRedeem.output,
|
|
929
487
|
controlBlock: p2tr.witness[p2tr.witness.length - 1]
|
|
930
488
|
};
|
|
931
|
-
const stakingAmount = transaction.outs[outputIndex].value;
|
|
932
|
-
const slashingAmount = Math.round(stakingAmount * slashingRate);
|
|
933
|
-
const slashingOutput = Buffer.from(slashingPkScriptHex, "hex");
|
|
934
|
-
if (opcodes3.OP_RETURN != slashingOutput[0]) {
|
|
935
|
-
if (slashingAmount <= BTC_DUST_SAT) {
|
|
936
|
-
throw new Error("Slashing amount is less than dust limit");
|
|
937
|
-
}
|
|
938
|
-
}
|
|
939
|
-
const userFunds = stakingAmount - slashingAmount - minimumFee;
|
|
940
|
-
if (userFunds <= BTC_DUST_SAT) {
|
|
941
|
-
throw new Error("User funds are less than dust limit");
|
|
942
|
-
}
|
|
943
|
-
const psbt = new Psbt({ network });
|
|
944
|
-
psbt.setVersion(TRANSACTION_VERSION);
|
|
945
489
|
psbt.addInput({
|
|
946
|
-
hash:
|
|
947
|
-
index:
|
|
490
|
+
hash: input.hash,
|
|
491
|
+
index: input.index,
|
|
492
|
+
sequence: input.sequence,
|
|
948
493
|
tapInternalKey: internalPubkey,
|
|
949
494
|
witnessUtxo: {
|
|
950
|
-
value:
|
|
951
|
-
script:
|
|
495
|
+
value: stakingTx.outs[outputIndex].value,
|
|
496
|
+
script: stakingTx.outs[outputIndex].script
|
|
952
497
|
},
|
|
953
|
-
tapLeafScript: [
|
|
954
|
-
// not RBF-able
|
|
955
|
-
sequence: NON_RBF_SEQUENCE
|
|
956
|
-
});
|
|
957
|
-
psbt.addOutput({
|
|
958
|
-
script: slashingOutput,
|
|
959
|
-
value: slashingAmount
|
|
960
|
-
});
|
|
961
|
-
const changeOutput = payments3.p2tr({
|
|
962
|
-
internalPubkey,
|
|
963
|
-
scriptTree: { output: scripts.unbondingTimelockScript },
|
|
964
|
-
network
|
|
498
|
+
tapLeafScript: [inputTapLeafScript]
|
|
965
499
|
});
|
|
966
500
|
psbt.addOutput({
|
|
967
|
-
|
|
968
|
-
value:
|
|
501
|
+
script: unbondingTx.outs[0].script,
|
|
502
|
+
value: unbondingTx.outs[0].value
|
|
969
503
|
});
|
|
970
|
-
psbt
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
function unbondingTransaction(scripts, stakingTx, unbondingFee, network, outputIndex = 0) {
|
|
974
|
-
if (unbondingFee <= 0) {
|
|
975
|
-
throw new Error("Unbonding fee must be bigger than 0");
|
|
976
|
-
}
|
|
977
|
-
if (outputIndex < 0) {
|
|
978
|
-
throw new Error("Output index must be bigger or equal to 0");
|
|
979
|
-
}
|
|
980
|
-
const tx = new Transaction2();
|
|
981
|
-
tx.version = TRANSACTION_VERSION;
|
|
982
|
-
tx.addInput(
|
|
983
|
-
stakingTx.getHash(),
|
|
984
|
-
outputIndex,
|
|
985
|
-
NON_RBF_SEQUENCE
|
|
986
|
-
// not RBF-able
|
|
987
|
-
);
|
|
504
|
+
return psbt;
|
|
505
|
+
};
|
|
506
|
+
var validateUnbondingOutput = (scripts, unbondingTx, network) => {
|
|
988
507
|
const unbondingOutputInfo = deriveUnbondingOutputInfo(scripts, network);
|
|
989
|
-
|
|
990
|
-
if (outputValue < BTC_DUST_SAT) {
|
|
991
|
-
throw new Error("Output value is less than dust limit for unbonding transaction");
|
|
992
|
-
}
|
|
993
|
-
if (!unbondingOutputInfo.outputAddress) {
|
|
994
|
-
throw new Error("Unbonding output address is not defined");
|
|
995
|
-
}
|
|
996
|
-
tx.addOutput(
|
|
997
|
-
unbondingOutputInfo.scriptPubKey,
|
|
998
|
-
outputValue
|
|
999
|
-
);
|
|
1000
|
-
tx.locktime = 0;
|
|
1001
|
-
return {
|
|
1002
|
-
transaction: tx,
|
|
1003
|
-
fee: unbondingFee
|
|
1004
|
-
};
|
|
1005
|
-
}
|
|
1006
|
-
var createCovenantWitness = (originalWitness, paramsCovenants, covenantSigs, covenantQuorum) => {
|
|
1007
|
-
if (covenantSigs.length < covenantQuorum) {
|
|
508
|
+
if (unbondingOutputInfo.scriptPubKey.toString("hex") !== unbondingTx.outs[0].script.toString("hex")) {
|
|
1008
509
|
throw new Error(
|
|
1009
|
-
|
|
510
|
+
"Unbonding output script does not match the expected script while building psbt"
|
|
1010
511
|
);
|
|
1011
512
|
}
|
|
1012
|
-
for (const sig of covenantSigs) {
|
|
1013
|
-
const btcPkHexBuf = Buffer.from(sig.btcPkHex, "hex");
|
|
1014
|
-
if (!paramsCovenants.some((covenant) => covenant.equals(btcPkHexBuf))) {
|
|
1015
|
-
throw new Error(
|
|
1016
|
-
`Covenant signature public key ${sig.btcPkHex} not found in params covenants`
|
|
1017
|
-
);
|
|
1018
|
-
}
|
|
1019
|
-
}
|
|
1020
|
-
const covenantSigsBuffers = covenantSigs.slice(0, covenantQuorum).map((sig) => ({
|
|
1021
|
-
btcPkHex: Buffer.from(sig.btcPkHex, "hex"),
|
|
1022
|
-
sigHex: Buffer.from(sig.sigHex, "hex")
|
|
1023
|
-
}));
|
|
1024
|
-
const paramsCovenantsSorted = [...paramsCovenants].sort(Buffer.compare).reverse();
|
|
1025
|
-
const composedCovenantSigs = paramsCovenantsSorted.map((covenant) => {
|
|
1026
|
-
const covenantSig = covenantSigsBuffers.find(
|
|
1027
|
-
(sig) => sig.btcPkHex.compare(covenant) === 0
|
|
1028
|
-
);
|
|
1029
|
-
return covenantSig?.sigHex || Buffer.alloc(0);
|
|
1030
|
-
});
|
|
1031
|
-
return [...composedCovenantSigs, ...originalWitness];
|
|
1032
513
|
};
|
|
1033
514
|
|
|
1034
|
-
// src/staking/
|
|
1035
|
-
import {
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
515
|
+
// src/staking/stakingScript.ts
|
|
516
|
+
import { opcodes, script } from "bitcoinjs-lib";
|
|
517
|
+
var MAGIC_BYTES_LEN = 4;
|
|
518
|
+
var StakingScriptData = class {
|
|
519
|
+
constructor(stakerKey, finalityProviderKeys, covenantKeys, covenantThreshold, stakingTimelock, unbondingTimelock) {
|
|
520
|
+
if (!stakerKey || !finalityProviderKeys || !covenantKeys || !covenantThreshold || !stakingTimelock || !unbondingTimelock) {
|
|
521
|
+
throw new Error("Missing required input values");
|
|
522
|
+
}
|
|
523
|
+
this.stakerKey = stakerKey;
|
|
524
|
+
this.finalityProviderKeys = finalityProviderKeys;
|
|
525
|
+
this.covenantKeys = covenantKeys;
|
|
526
|
+
this.covenantThreshold = covenantThreshold;
|
|
527
|
+
this.stakingTimeLock = stakingTimelock;
|
|
528
|
+
this.unbondingTimeLock = unbondingTimelock;
|
|
529
|
+
if (!this.validate()) {
|
|
530
|
+
throw new Error("Invalid script data provided");
|
|
531
|
+
}
|
|
1046
532
|
}
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
}
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
533
|
+
/**
|
|
534
|
+
* Validates the staking script.
|
|
535
|
+
* @returns {boolean} Returns true if the staking script is valid, otherwise false.
|
|
536
|
+
*/
|
|
537
|
+
validate() {
|
|
538
|
+
if (this.stakerKey.length != NO_COORD_PK_BYTE_LENGTH) {
|
|
539
|
+
return false;
|
|
540
|
+
}
|
|
541
|
+
if (this.finalityProviderKeys.some(
|
|
542
|
+
(finalityProviderKey) => finalityProviderKey.length != NO_COORD_PK_BYTE_LENGTH
|
|
543
|
+
)) {
|
|
544
|
+
return false;
|
|
545
|
+
}
|
|
546
|
+
if (this.covenantKeys.some((covenantKey) => covenantKey.length != NO_COORD_PK_BYTE_LENGTH)) {
|
|
547
|
+
return false;
|
|
548
|
+
}
|
|
549
|
+
const allPks = [
|
|
550
|
+
this.stakerKey,
|
|
551
|
+
...this.finalityProviderKeys,
|
|
552
|
+
...this.covenantKeys
|
|
553
|
+
];
|
|
554
|
+
const allPksSet = new Set(allPks);
|
|
555
|
+
if (allPks.length !== allPksSet.size) {
|
|
556
|
+
return false;
|
|
557
|
+
}
|
|
558
|
+
if (this.covenantThreshold <= 0 || this.covenantThreshold > this.covenantKeys.length) {
|
|
559
|
+
return false;
|
|
560
|
+
}
|
|
561
|
+
if (this.stakingTimeLock <= 0 || this.stakingTimeLock > 65535) {
|
|
562
|
+
return false;
|
|
563
|
+
}
|
|
564
|
+
if (this.unbondingTimeLock <= 0 || this.unbondingTimeLock > 65535) {
|
|
565
|
+
return false;
|
|
566
|
+
}
|
|
567
|
+
return true;
|
|
1065
568
|
}
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
569
|
+
// The staking script allows for multiple finality provider public keys
|
|
570
|
+
// to support (re)stake to multiple finality providers
|
|
571
|
+
// Covenant members are going to have multiple keys
|
|
572
|
+
/**
|
|
573
|
+
* Builds a timelock script.
|
|
574
|
+
* @param timelock - The timelock value to encode in the script.
|
|
575
|
+
* @returns {Buffer} containing the compiled timelock script.
|
|
576
|
+
*/
|
|
577
|
+
buildTimelockScript(timelock) {
|
|
578
|
+
return script.compile([
|
|
579
|
+
this.stakerKey,
|
|
580
|
+
opcodes.OP_CHECKSIGVERIFY,
|
|
581
|
+
script.number.encode(timelock),
|
|
582
|
+
opcodes.OP_CHECKSEQUENCEVERIFY
|
|
583
|
+
]);
|
|
1070
584
|
}
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
585
|
+
/**
|
|
586
|
+
* Builds the staking timelock script.
|
|
587
|
+
* Only holder of private key for given pubKey can spend after relative lock time
|
|
588
|
+
* Creates the timelock script in the form:
|
|
589
|
+
* <stakerPubKey>
|
|
590
|
+
* OP_CHECKSIGVERIFY
|
|
591
|
+
* <stakingTimeBlocks>
|
|
592
|
+
* OP_CHECKSEQUENCEVERIFY
|
|
593
|
+
* @returns {Buffer} The staking timelock script.
|
|
594
|
+
*/
|
|
595
|
+
buildStakingTimelockScript() {
|
|
596
|
+
return this.buildTimelockScript(this.stakingTimeLock);
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* Builds the unbonding timelock script.
|
|
600
|
+
* Creates the unbonding timelock script in the form:
|
|
601
|
+
* <stakerPubKey>
|
|
602
|
+
* OP_CHECKSIGVERIFY
|
|
603
|
+
* <unbondingTimeBlocks>
|
|
604
|
+
* OP_CHECKSEQUENCEVERIFY
|
|
605
|
+
* @returns {Buffer} The unbonding timelock script.
|
|
606
|
+
*/
|
|
607
|
+
buildUnbondingTimelockScript() {
|
|
608
|
+
return this.buildTimelockScript(this.unbondingTimeLock);
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Builds the unbonding script in the form:
|
|
612
|
+
* buildSingleKeyScript(stakerPk, true) ||
|
|
613
|
+
* buildMultiKeyScript(covenantPks, covenantThreshold, false)
|
|
614
|
+
* || means combining the scripts
|
|
615
|
+
* @returns {Buffer} The unbonding script.
|
|
616
|
+
*/
|
|
617
|
+
buildUnbondingScript() {
|
|
618
|
+
return Buffer.concat([
|
|
619
|
+
this.buildSingleKeyScript(this.stakerKey, true),
|
|
620
|
+
this.buildMultiKeyScript(
|
|
621
|
+
this.covenantKeys,
|
|
622
|
+
this.covenantThreshold,
|
|
623
|
+
false
|
|
624
|
+
)
|
|
625
|
+
]);
|
|
1075
626
|
}
|
|
627
|
+
/**
|
|
628
|
+
* Builds the slashing script for staking in the form:
|
|
629
|
+
* buildSingleKeyScript(stakerPk, true) ||
|
|
630
|
+
* buildMultiKeyScript(finalityProviderPKs, 1, true) ||
|
|
631
|
+
* buildMultiKeyScript(covenantPks, covenantThreshold, false)
|
|
632
|
+
* || means combining the scripts
|
|
633
|
+
* The slashing script is a combination of single-key and multi-key scripts.
|
|
634
|
+
* The single-key script is used for staker key verification.
|
|
635
|
+
* The multi-key script is used for finality provider key verification and covenant key verification.
|
|
636
|
+
* @returns {Buffer} The slashing script as a Buffer.
|
|
637
|
+
*/
|
|
638
|
+
buildSlashingScript() {
|
|
639
|
+
return Buffer.concat([
|
|
640
|
+
this.buildSingleKeyScript(this.stakerKey, true),
|
|
641
|
+
this.buildMultiKeyScript(
|
|
642
|
+
this.finalityProviderKeys,
|
|
643
|
+
// The threshold is always 1 as we only need one
|
|
644
|
+
// finalityProvider signature to perform slashing
|
|
645
|
+
// (only one finalityProvider performs an offence)
|
|
646
|
+
1,
|
|
647
|
+
// OP_VERIFY/OP_CHECKSIGVERIFY is added at the end
|
|
648
|
+
true
|
|
649
|
+
),
|
|
650
|
+
this.buildMultiKeyScript(
|
|
651
|
+
this.covenantKeys,
|
|
652
|
+
this.covenantThreshold,
|
|
653
|
+
// No need to add verify since covenants are at the end of the script
|
|
654
|
+
false
|
|
655
|
+
)
|
|
656
|
+
]);
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* Builds the staking scripts.
|
|
660
|
+
* @returns {StakingScripts} The staking scripts.
|
|
661
|
+
*/
|
|
662
|
+
buildScripts() {
|
|
663
|
+
return {
|
|
664
|
+
timelockScript: this.buildStakingTimelockScript(),
|
|
665
|
+
unbondingScript: this.buildUnbondingScript(),
|
|
666
|
+
slashingScript: this.buildSlashingScript(),
|
|
667
|
+
unbondingTimelockScript: this.buildUnbondingTimelockScript()
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
// buildSingleKeyScript and buildMultiKeyScript allow us to reuse functionality
|
|
671
|
+
// for creating Bitcoin scripts for the unbonding script and the slashing script
|
|
672
|
+
/**
|
|
673
|
+
* Builds a single key script in the form:
|
|
674
|
+
* buildSingleKeyScript creates a single key script
|
|
675
|
+
* <pk> OP_CHECKSIGVERIFY (if withVerify is true)
|
|
676
|
+
* <pk> OP_CHECKSIG (if withVerify is false)
|
|
677
|
+
* @param pk - The public key buffer.
|
|
678
|
+
* @param withVerify - A boolean indicating whether to include the OP_CHECKSIGVERIFY opcode.
|
|
679
|
+
* @returns The compiled script buffer.
|
|
680
|
+
*/
|
|
681
|
+
buildSingleKeyScript(pk, withVerify) {
|
|
682
|
+
if (pk.length != NO_COORD_PK_BYTE_LENGTH) {
|
|
683
|
+
throw new Error("Invalid key length");
|
|
684
|
+
}
|
|
685
|
+
return script.compile([
|
|
686
|
+
pk,
|
|
687
|
+
withVerify ? opcodes.OP_CHECKSIGVERIFY : opcodes.OP_CHECKSIG
|
|
688
|
+
]);
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Builds a multi-key script in the form:
|
|
692
|
+
* <pk1> OP_CHEKCSIG <pk2> OP_CHECKSIGADD <pk3> OP_CHECKSIGADD ... <pkN> OP_CHECKSIGADD <threshold> OP_NUMEQUAL
|
|
693
|
+
* <withVerify -> OP_NUMEQUALVERIFY>
|
|
694
|
+
* It validates whether provided keys are unique and the threshold is not greater than number of keys
|
|
695
|
+
* If there is only one key provided it will return single key sig script
|
|
696
|
+
* @param pks - An array of public keys.
|
|
697
|
+
* @param threshold - The required number of valid signers.
|
|
698
|
+
* @param withVerify - A boolean indicating whether to include the OP_VERIFY opcode.
|
|
699
|
+
* @returns The compiled multi-key script as a Buffer.
|
|
700
|
+
* @throws {Error} If no keys are provided, if the required number of valid signers is greater than the number of provided keys, or if duplicate keys are provided.
|
|
701
|
+
*/
|
|
702
|
+
buildMultiKeyScript(pks, threshold, withVerify) {
|
|
703
|
+
if (!pks || pks.length === 0) {
|
|
704
|
+
throw new Error("No keys provided");
|
|
705
|
+
}
|
|
706
|
+
if (pks.some((pk) => pk.length != NO_COORD_PK_BYTE_LENGTH)) {
|
|
707
|
+
throw new Error("Invalid key length");
|
|
708
|
+
}
|
|
709
|
+
if (threshold > pks.length) {
|
|
710
|
+
throw new Error(
|
|
711
|
+
"Required number of valid signers is greater than number of provided keys"
|
|
712
|
+
);
|
|
713
|
+
}
|
|
714
|
+
if (pks.length === 1) {
|
|
715
|
+
return this.buildSingleKeyScript(pks[0], withVerify);
|
|
716
|
+
}
|
|
717
|
+
const sortedPks = [...pks].sort(Buffer.compare);
|
|
718
|
+
for (let i = 0; i < sortedPks.length - 1; ++i) {
|
|
719
|
+
if (sortedPks[i].equals(sortedPks[i + 1])) {
|
|
720
|
+
throw new Error("Duplicate keys provided");
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
const scriptElements = [sortedPks[0], opcodes.OP_CHECKSIG];
|
|
724
|
+
for (let i = 1; i < sortedPks.length; i++) {
|
|
725
|
+
scriptElements.push(sortedPks[i]);
|
|
726
|
+
scriptElements.push(opcodes.OP_CHECKSIGADD);
|
|
727
|
+
}
|
|
728
|
+
scriptElements.push(script.number.encode(threshold));
|
|
729
|
+
if (withVerify) {
|
|
730
|
+
scriptElements.push(opcodes.OP_NUMEQUALVERIFY);
|
|
731
|
+
} else {
|
|
732
|
+
scriptElements.push(opcodes.OP_NUMEQUAL);
|
|
733
|
+
}
|
|
734
|
+
return script.compile(scriptElements);
|
|
735
|
+
}
|
|
736
|
+
};
|
|
737
|
+
|
|
738
|
+
// src/staking/transactions.ts
|
|
739
|
+
import {
|
|
740
|
+
Psbt as Psbt2,
|
|
741
|
+
Transaction as Transaction3,
|
|
742
|
+
payments as payments5,
|
|
743
|
+
script as script2,
|
|
744
|
+
address as address3,
|
|
745
|
+
opcodes as opcodes3
|
|
746
|
+
} from "bitcoinjs-lib";
|
|
747
|
+
|
|
748
|
+
// src/constants/dustSat.ts
|
|
749
|
+
var BTC_DUST_SAT = 546;
|
|
750
|
+
|
|
751
|
+
// src/utils/fee/index.ts
|
|
752
|
+
import { script as bitcoinScript2 } from "bitcoinjs-lib";
|
|
753
|
+
|
|
754
|
+
// src/constants/fee.ts
|
|
755
|
+
var DEFAULT_INPUT_SIZE = 180;
|
|
756
|
+
var P2WPKH_INPUT_SIZE = 68;
|
|
757
|
+
var P2TR_INPUT_SIZE = 58;
|
|
758
|
+
var P2TR_STAKING_EXPANSION_INPUT_SIZE = 268;
|
|
759
|
+
var TX_BUFFER_SIZE_OVERHEAD = 11;
|
|
760
|
+
var LOW_RATE_ESTIMATION_ACCURACY_BUFFER = 30;
|
|
761
|
+
var MAX_NON_LEGACY_OUTPUT_SIZE = 43;
|
|
762
|
+
var WITHDRAW_TX_BUFFER_SIZE = 17;
|
|
763
|
+
var WALLET_RELAY_FEE_RATE_THRESHOLD = 2;
|
|
764
|
+
var OP_RETURN_OUTPUT_VALUE_SIZE = 8;
|
|
765
|
+
var OP_RETURN_VALUE_SERIALIZE_SIZE = 1;
|
|
766
|
+
|
|
767
|
+
// src/utils/fee/utils.ts
|
|
768
|
+
import { script as bitcoinScript, opcodes as opcodes2, payments as payments4 } from "bitcoinjs-lib";
|
|
769
|
+
var isOP_RETURN = (script4) => {
|
|
770
|
+
const decompiled = bitcoinScript.decompile(script4);
|
|
771
|
+
return !!decompiled && decompiled[0] === opcodes2.OP_RETURN;
|
|
772
|
+
};
|
|
773
|
+
var getInputSizeByScript = (script4) => {
|
|
1076
774
|
try {
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
775
|
+
const { address: p2wpkhAddress } = payments4.p2wpkh({
|
|
776
|
+
output: script4
|
|
777
|
+
});
|
|
778
|
+
if (p2wpkhAddress) {
|
|
779
|
+
return P2WPKH_INPUT_SIZE;
|
|
780
|
+
}
|
|
781
|
+
} catch (error) {
|
|
1080
782
|
}
|
|
1081
783
|
try {
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
784
|
+
const { address: p2trAddress } = payments4.p2tr({
|
|
785
|
+
output: script4
|
|
786
|
+
});
|
|
787
|
+
if (p2trAddress) {
|
|
788
|
+
return P2TR_INPUT_SIZE;
|
|
789
|
+
}
|
|
790
|
+
} catch (error) {
|
|
1085
791
|
}
|
|
1086
|
-
|
|
792
|
+
return DEFAULT_INPUT_SIZE;
|
|
793
|
+
};
|
|
794
|
+
var getEstimatedChangeOutputSize = () => {
|
|
795
|
+
return MAX_NON_LEGACY_OUTPUT_SIZE;
|
|
796
|
+
};
|
|
797
|
+
var inputValueSum = (inputUTXOs) => {
|
|
798
|
+
return inputUTXOs.reduce((acc, utxo) => acc + utxo.value, 0);
|
|
1087
799
|
};
|
|
1088
800
|
|
|
1089
|
-
// src/utils/
|
|
1090
|
-
var
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
801
|
+
// src/utils/fee/index.ts
|
|
802
|
+
var getStakingTxInputUTXOsAndFees = (availableUTXOs, stakingAmount, feeRate, outputs) => {
|
|
803
|
+
if (availableUTXOs.length === 0) {
|
|
804
|
+
throw new Error("Insufficient funds");
|
|
805
|
+
}
|
|
806
|
+
const validUTXOs = availableUTXOs.filter((utxo) => {
|
|
807
|
+
const script4 = Buffer.from(utxo.scriptPubKey, "hex");
|
|
808
|
+
return !!bitcoinScript2.decompile(script4);
|
|
809
|
+
});
|
|
810
|
+
if (validUTXOs.length === 0) {
|
|
811
|
+
throw new Error("Insufficient funds: no valid UTXOs available for staking");
|
|
812
|
+
}
|
|
813
|
+
const sortedUTXOs = validUTXOs.sort((a, b) => b.value - a.value);
|
|
814
|
+
const selectedUTXOs = [];
|
|
815
|
+
let accumulatedValue = 0;
|
|
816
|
+
let estimatedFee = 0;
|
|
817
|
+
for (const utxo of sortedUTXOs) {
|
|
818
|
+
selectedUTXOs.push(utxo);
|
|
819
|
+
accumulatedValue += utxo.value;
|
|
820
|
+
const estimatedSize = getEstimatedSize(selectedUTXOs, outputs);
|
|
821
|
+
estimatedFee = estimatedSize * feeRate + rateBasedTxBufferFee(feeRate);
|
|
822
|
+
if (accumulatedValue - (stakingAmount + estimatedFee) > BTC_DUST_SAT) {
|
|
823
|
+
estimatedFee += getEstimatedChangeOutputSize() * feeRate;
|
|
1099
824
|
}
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
825
|
+
if (accumulatedValue >= stakingAmount + estimatedFee) {
|
|
826
|
+
break;
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
if (accumulatedValue < stakingAmount + estimatedFee) {
|
|
830
|
+
throw new Error(
|
|
831
|
+
"Insufficient funds: unable to gather enough UTXOs to cover the staking amount and fees"
|
|
832
|
+
);
|
|
833
|
+
}
|
|
834
|
+
return {
|
|
835
|
+
selectedUTXOs,
|
|
836
|
+
fee: estimatedFee
|
|
837
|
+
};
|
|
838
|
+
};
|
|
839
|
+
var getStakingExpansionTxFundingUTXOAndFees = (availableUTXOs, feeRate, outputs) => {
|
|
840
|
+
if (availableUTXOs.length === 0) {
|
|
841
|
+
throw new Error("Insufficient funds");
|
|
842
|
+
}
|
|
843
|
+
const validUTXOs = availableUTXOs.filter((utxo) => {
|
|
844
|
+
const script4 = Buffer.from(utxo.scriptPubKey, "hex");
|
|
845
|
+
const decompiledScript = bitcoinScript2.decompile(script4);
|
|
846
|
+
return decompiledScript && decompiledScript.length > 0;
|
|
847
|
+
});
|
|
848
|
+
if (validUTXOs.length === 0) {
|
|
849
|
+
throw new Error("Insufficient funds: no valid UTXOs available for staking");
|
|
850
|
+
}
|
|
851
|
+
const sortedUTXOs = validUTXOs.sort((a, b) => a.value - b.value);
|
|
852
|
+
for (const utxo of sortedUTXOs) {
|
|
853
|
+
const estimatedSize = getEstimatedSize(
|
|
854
|
+
[utxo],
|
|
855
|
+
outputs
|
|
856
|
+
) + P2TR_STAKING_EXPANSION_INPUT_SIZE;
|
|
857
|
+
let estimatedFee = estimatedSize * feeRate + rateBasedTxBufferFee(feeRate);
|
|
858
|
+
if (utxo.value >= estimatedFee) {
|
|
859
|
+
if (utxo.value - estimatedFee > BTC_DUST_SAT) {
|
|
860
|
+
estimatedFee += getEstimatedChangeOutputSize() * feeRate;
|
|
1103
861
|
}
|
|
1104
|
-
if (
|
|
1105
|
-
|
|
862
|
+
if (utxo.value >= estimatedFee) {
|
|
863
|
+
return {
|
|
864
|
+
selectedUTXO: utxo,
|
|
865
|
+
fee: estimatedFee
|
|
866
|
+
};
|
|
1106
867
|
}
|
|
1107
|
-
return {
|
|
1108
|
-
nonWitnessUtxo: Buffer.from(utxo.rawTxHex, "hex"),
|
|
1109
|
-
redeemScript: Buffer.from(utxo.redeemScript, "hex")
|
|
1110
|
-
};
|
|
1111
868
|
}
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
869
|
+
}
|
|
870
|
+
throw new Error(
|
|
871
|
+
"Insufficient funds: unable to find a UTXO to cover the fees for the staking expansion transaction."
|
|
872
|
+
);
|
|
873
|
+
};
|
|
874
|
+
var getWithdrawTxFee = (feeRate) => {
|
|
875
|
+
const inputSize = P2TR_INPUT_SIZE;
|
|
876
|
+
const outputSize = getEstimatedChangeOutputSize();
|
|
877
|
+
return feeRate * (inputSize + outputSize + TX_BUFFER_SIZE_OVERHEAD + WITHDRAW_TX_BUFFER_SIZE) + rateBasedTxBufferFee(feeRate);
|
|
878
|
+
};
|
|
879
|
+
var getEstimatedSize = (inputUtxos, outputs) => {
|
|
880
|
+
const inputSize = inputUtxos.reduce((acc, u) => {
|
|
881
|
+
const script4 = Buffer.from(u.scriptPubKey, "hex");
|
|
882
|
+
const decompiledScript = bitcoinScript2.decompile(script4);
|
|
883
|
+
if (!decompiledScript) {
|
|
884
|
+
return acc;
|
|
1119
885
|
}
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
return
|
|
1125
|
-
witnessUtxo: {
|
|
1126
|
-
script: scriptPubKey,
|
|
1127
|
-
value: utxo.value
|
|
1128
|
-
},
|
|
1129
|
-
witnessScript: Buffer.from(utxo.witnessScript, "hex")
|
|
1130
|
-
};
|
|
886
|
+
return acc + getInputSizeByScript(script4);
|
|
887
|
+
}, 0);
|
|
888
|
+
const outputSize = outputs.reduce((acc, output) => {
|
|
889
|
+
if (isOP_RETURN(output.scriptPubKey)) {
|
|
890
|
+
return acc + output.scriptPubKey.length + OP_RETURN_OUTPUT_VALUE_SIZE + OP_RETURN_VALUE_SERIALIZE_SIZE;
|
|
1131
891
|
}
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
892
|
+
return acc + MAX_NON_LEGACY_OUTPUT_SIZE;
|
|
893
|
+
}, 0);
|
|
894
|
+
return inputSize + outputSize + TX_BUFFER_SIZE_OVERHEAD;
|
|
895
|
+
};
|
|
896
|
+
var rateBasedTxBufferFee = (feeRate) => {
|
|
897
|
+
return feeRate <= WALLET_RELAY_FEE_RATE_THRESHOLD ? LOW_RATE_ESTIMATION_ACCURACY_BUFFER : 0;
|
|
898
|
+
};
|
|
899
|
+
|
|
900
|
+
// src/constants/psbt.ts
|
|
901
|
+
var NON_RBF_SEQUENCE = 4294967295;
|
|
902
|
+
var TRANSACTION_VERSION = 2;
|
|
903
|
+
|
|
904
|
+
// src/staking/transactions.ts
|
|
905
|
+
var BTC_LOCKTIME_HEIGHT_TIME_CUTOFF = 5e8;
|
|
906
|
+
var BTC_SLASHING_FRACTION_DIGITS = 4;
|
|
907
|
+
function stakingTransaction(scripts, amount, changeAddress, inputUTXOs, network, feeRate, lockHeight) {
|
|
908
|
+
if (amount <= 0 || feeRate <= 0) {
|
|
909
|
+
throw new Error("Amount and fee rate must be bigger than 0");
|
|
910
|
+
}
|
|
911
|
+
if (!isValidBitcoinAddress(changeAddress, network)) {
|
|
912
|
+
throw new Error("Invalid change address");
|
|
913
|
+
}
|
|
914
|
+
const stakingOutputs = buildStakingTransactionOutputs(scripts, network, amount);
|
|
915
|
+
const { selectedUTXOs, fee } = getStakingTxInputUTXOsAndFees(
|
|
916
|
+
inputUTXOs,
|
|
917
|
+
amount,
|
|
918
|
+
feeRate,
|
|
919
|
+
stakingOutputs
|
|
920
|
+
);
|
|
921
|
+
const tx = new Transaction3();
|
|
922
|
+
tx.version = TRANSACTION_VERSION;
|
|
923
|
+
for (let i = 0; i < selectedUTXOs.length; ++i) {
|
|
924
|
+
const input = selectedUTXOs[i];
|
|
925
|
+
tx.addInput(
|
|
926
|
+
transactionIdToHash(input.txid),
|
|
927
|
+
input.vout,
|
|
928
|
+
NON_RBF_SEQUENCE
|
|
929
|
+
);
|
|
930
|
+
}
|
|
931
|
+
stakingOutputs.forEach((o) => {
|
|
932
|
+
tx.addOutput(o.scriptPubKey, o.value);
|
|
933
|
+
});
|
|
934
|
+
const inputsSum = inputValueSum(selectedUTXOs);
|
|
935
|
+
if (inputsSum - (amount + fee) > BTC_DUST_SAT) {
|
|
936
|
+
tx.addOutput(
|
|
937
|
+
address3.toOutputScript(changeAddress, network),
|
|
938
|
+
inputsSum - (amount + fee)
|
|
939
|
+
);
|
|
940
|
+
}
|
|
941
|
+
if (lockHeight) {
|
|
942
|
+
if (lockHeight >= BTC_LOCKTIME_HEIGHT_TIME_CUTOFF) {
|
|
943
|
+
throw new Error("Invalid lock height");
|
|
1141
944
|
}
|
|
1142
|
-
|
|
1143
|
-
throw new Error(`Unsupported script type: ${type}`);
|
|
945
|
+
tx.locktime = lockHeight;
|
|
1144
946
|
}
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
947
|
+
return {
|
|
948
|
+
transaction: tx,
|
|
949
|
+
fee
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
function stakingExpansionTransaction(network, scripts, amount, changeAddress, feeRate, inputUTXOs, previousStakingTxInfo) {
|
|
953
|
+
if (amount <= 0 || feeRate <= 0) {
|
|
954
|
+
throw new Error("Amount and fee rate must be bigger than 0");
|
|
955
|
+
} else if (!isValidBitcoinAddress(changeAddress, network)) {
|
|
956
|
+
throw new Error("Invalid BTC change address");
|
|
1151
957
|
}
|
|
1152
|
-
const
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
}
|
|
1167
|
-
|
|
1168
|
-
|
|
958
|
+
const previousStakingOutputInfo = deriveStakingOutputInfo(
|
|
959
|
+
previousStakingTxInfo.scripts,
|
|
960
|
+
network
|
|
961
|
+
);
|
|
962
|
+
const previousStakingOutputIndex = findMatchingTxOutputIndex(
|
|
963
|
+
previousStakingTxInfo.stakingTx,
|
|
964
|
+
previousStakingOutputInfo.outputAddress,
|
|
965
|
+
network
|
|
966
|
+
);
|
|
967
|
+
const previousStakingAmount = previousStakingTxInfo.stakingTx.outs[previousStakingOutputIndex].value;
|
|
968
|
+
if (amount !== previousStakingAmount) {
|
|
969
|
+
throw new Error(
|
|
970
|
+
"Expansion staking transaction amount must be equal to the previous staking amount. Increase of the staking amount is not supported yet."
|
|
971
|
+
);
|
|
972
|
+
}
|
|
973
|
+
const stakingOutputs = buildStakingTransactionOutputs(
|
|
974
|
+
scripts,
|
|
975
|
+
network,
|
|
976
|
+
amount
|
|
977
|
+
);
|
|
978
|
+
const { selectedUTXO, fee } = getStakingExpansionTxFundingUTXOAndFees(
|
|
979
|
+
inputUTXOs,
|
|
980
|
+
feeRate,
|
|
981
|
+
stakingOutputs
|
|
982
|
+
);
|
|
983
|
+
const tx = new Transaction3();
|
|
984
|
+
tx.version = TRANSACTION_VERSION;
|
|
985
|
+
tx.addInput(
|
|
986
|
+
previousStakingTxInfo.stakingTx.getHash(),
|
|
987
|
+
previousStakingOutputIndex,
|
|
988
|
+
NON_RBF_SEQUENCE
|
|
989
|
+
);
|
|
990
|
+
tx.addInput(
|
|
991
|
+
transactionIdToHash(selectedUTXO.txid),
|
|
992
|
+
selectedUTXO.vout,
|
|
993
|
+
NON_RBF_SEQUENCE
|
|
994
|
+
);
|
|
995
|
+
stakingOutputs.forEach((o) => {
|
|
996
|
+
tx.addOutput(o.scriptPubKey, o.value);
|
|
1169
997
|
});
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
998
|
+
if (selectedUTXO.value - fee > BTC_DUST_SAT) {
|
|
999
|
+
tx.addOutput(
|
|
1000
|
+
address3.toOutputScript(changeAddress, network),
|
|
1001
|
+
selectedUTXO.value - fee
|
|
1002
|
+
);
|
|
1175
1003
|
}
|
|
1176
|
-
|
|
1177
|
-
|
|
1004
|
+
return {
|
|
1005
|
+
transaction: tx,
|
|
1006
|
+
fee,
|
|
1007
|
+
fundingUTXO: selectedUTXO
|
|
1008
|
+
};
|
|
1009
|
+
}
|
|
1010
|
+
function withdrawEarlyUnbondedTransaction(scripts, unbondingTx, withdrawalAddress, network, feeRate) {
|
|
1011
|
+
const scriptTree = [
|
|
1012
|
+
{
|
|
1013
|
+
output: scripts.slashingScript
|
|
1014
|
+
},
|
|
1015
|
+
{ output: scripts.unbondingTimelockScript }
|
|
1016
|
+
];
|
|
1017
|
+
return withdrawalTransaction(
|
|
1018
|
+
{
|
|
1019
|
+
timelockScript: scripts.unbondingTimelockScript
|
|
1020
|
+
},
|
|
1021
|
+
scriptTree,
|
|
1022
|
+
unbondingTx,
|
|
1023
|
+
withdrawalAddress,
|
|
1024
|
+
network,
|
|
1025
|
+
feeRate,
|
|
1026
|
+
0
|
|
1027
|
+
// unbonding always has a single output
|
|
1028
|
+
);
|
|
1029
|
+
}
|
|
1030
|
+
function withdrawTimelockUnbondedTransaction(scripts, tx, withdrawalAddress, network, feeRate, outputIndex = 0) {
|
|
1031
|
+
const scriptTree = [
|
|
1032
|
+
{
|
|
1033
|
+
output: scripts.slashingScript
|
|
1034
|
+
},
|
|
1035
|
+
[{ output: scripts.unbondingScript }, { output: scripts.timelockScript }]
|
|
1036
|
+
];
|
|
1037
|
+
return withdrawalTransaction(
|
|
1038
|
+
scripts,
|
|
1039
|
+
scriptTree,
|
|
1040
|
+
tx,
|
|
1041
|
+
withdrawalAddress,
|
|
1042
|
+
network,
|
|
1043
|
+
feeRate,
|
|
1044
|
+
outputIndex
|
|
1045
|
+
);
|
|
1046
|
+
}
|
|
1047
|
+
function withdrawSlashingTransaction(scripts, slashingTx, withdrawalAddress, network, feeRate, outputIndex) {
|
|
1048
|
+
const scriptTree = { output: scripts.unbondingTimelockScript };
|
|
1049
|
+
return withdrawalTransaction(
|
|
1050
|
+
{
|
|
1051
|
+
timelockScript: scripts.unbondingTimelockScript
|
|
1052
|
+
},
|
|
1053
|
+
scriptTree,
|
|
1054
|
+
slashingTx,
|
|
1055
|
+
withdrawalAddress,
|
|
1056
|
+
network,
|
|
1057
|
+
feeRate,
|
|
1058
|
+
outputIndex
|
|
1059
|
+
);
|
|
1060
|
+
}
|
|
1061
|
+
function withdrawalTransaction(scripts, scriptTree, tx, withdrawalAddress, network, feeRate, outputIndex = 0) {
|
|
1062
|
+
if (feeRate <= 0) {
|
|
1063
|
+
throw new Error("Withdrawal feeRate must be bigger than 0");
|
|
1178
1064
|
}
|
|
1179
|
-
|
|
1065
|
+
if (outputIndex < 0) {
|
|
1066
|
+
throw new Error("Output index must be bigger or equal to 0");
|
|
1067
|
+
}
|
|
1068
|
+
const timePosition = 2;
|
|
1069
|
+
const decompiled = script2.decompile(scripts.timelockScript);
|
|
1070
|
+
if (!decompiled) {
|
|
1071
|
+
throw new Error("Timelock script is not valid");
|
|
1072
|
+
}
|
|
1073
|
+
let timelock = 0;
|
|
1074
|
+
if (typeof decompiled[timePosition] !== "number") {
|
|
1075
|
+
const timeBuffer = decompiled[timePosition];
|
|
1076
|
+
timelock = script2.number.decode(timeBuffer);
|
|
1077
|
+
} else {
|
|
1078
|
+
const wrap = decompiled[timePosition] % 16;
|
|
1079
|
+
timelock = wrap === 0 ? 16 : wrap;
|
|
1080
|
+
}
|
|
1081
|
+
const redeem = {
|
|
1082
|
+
output: scripts.timelockScript,
|
|
1083
|
+
redeemVersion: REDEEM_VERSION
|
|
1084
|
+
};
|
|
1085
|
+
const p2tr = payments5.p2tr({
|
|
1086
|
+
internalPubkey,
|
|
1087
|
+
scriptTree,
|
|
1088
|
+
redeem,
|
|
1089
|
+
network
|
|
1090
|
+
});
|
|
1091
|
+
const tapLeafScript = {
|
|
1092
|
+
leafVersion: redeem.redeemVersion,
|
|
1093
|
+
script: redeem.output,
|
|
1094
|
+
controlBlock: p2tr.witness[p2tr.witness.length - 1]
|
|
1095
|
+
};
|
|
1180
1096
|
const psbt = new Psbt2({ network });
|
|
1181
|
-
|
|
1182
|
-
|
|
1097
|
+
psbt.setVersion(TRANSACTION_VERSION);
|
|
1098
|
+
psbt.addInput({
|
|
1099
|
+
hash: tx.getHash(),
|
|
1100
|
+
index: outputIndex,
|
|
1101
|
+
tapInternalKey: internalPubkey,
|
|
1102
|
+
witnessUtxo: {
|
|
1103
|
+
value: tx.outs[outputIndex].value,
|
|
1104
|
+
script: tx.outs[outputIndex].script
|
|
1105
|
+
},
|
|
1106
|
+
tapLeafScript: [tapLeafScript],
|
|
1107
|
+
sequence: timelock
|
|
1108
|
+
});
|
|
1109
|
+
const estimatedFee = getWithdrawTxFee(feeRate);
|
|
1110
|
+
const outputValue = tx.outs[outputIndex].value - estimatedFee;
|
|
1111
|
+
if (outputValue < 0) {
|
|
1112
|
+
throw new Error(
|
|
1113
|
+
"Not enough funds to cover the fee for withdrawal transaction"
|
|
1114
|
+
);
|
|
1183
1115
|
}
|
|
1184
|
-
if (
|
|
1185
|
-
|
|
1116
|
+
if (outputValue < BTC_DUST_SAT) {
|
|
1117
|
+
throw new Error("Output value is less than dust limit");
|
|
1186
1118
|
}
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1119
|
+
psbt.addOutput({
|
|
1120
|
+
address: withdrawalAddress,
|
|
1121
|
+
value: outputValue
|
|
1122
|
+
});
|
|
1123
|
+
psbt.setLocktime(0);
|
|
1124
|
+
return {
|
|
1125
|
+
psbt,
|
|
1126
|
+
fee: estimatedFee
|
|
1127
|
+
};
|
|
1128
|
+
}
|
|
1129
|
+
function slashTimelockUnbondedTransaction(scripts, stakingTransaction2, slashingPkScriptHex, slashingRate, minimumFee, network, outputIndex = 0) {
|
|
1130
|
+
const slashingScriptTree = [
|
|
1131
|
+
{
|
|
1132
|
+
output: scripts.slashingScript
|
|
1133
|
+
},
|
|
1191
1134
|
[{ output: scripts.unbondingScript }, { output: scripts.timelockScript }]
|
|
1192
1135
|
];
|
|
1193
|
-
|
|
1194
|
-
|
|
1136
|
+
return slashingTransaction(
|
|
1137
|
+
{
|
|
1138
|
+
unbondingTimelockScript: scripts.unbondingTimelockScript,
|
|
1139
|
+
slashingScript: scripts.slashingScript
|
|
1140
|
+
},
|
|
1141
|
+
slashingScriptTree,
|
|
1142
|
+
stakingTransaction2,
|
|
1143
|
+
slashingPkScriptHex,
|
|
1144
|
+
slashingRate,
|
|
1145
|
+
minimumFee,
|
|
1146
|
+
network,
|
|
1147
|
+
outputIndex
|
|
1148
|
+
);
|
|
1149
|
+
}
|
|
1150
|
+
function slashEarlyUnbondedTransaction(scripts, unbondingTx, slashingPkScriptHex, slashingRate, minimumSlashingFee, network) {
|
|
1151
|
+
const unbondingScriptTree = [
|
|
1152
|
+
{
|
|
1153
|
+
output: scripts.slashingScript
|
|
1154
|
+
},
|
|
1155
|
+
{
|
|
1156
|
+
output: scripts.unbondingTimelockScript
|
|
1157
|
+
}
|
|
1158
|
+
];
|
|
1159
|
+
return slashingTransaction(
|
|
1160
|
+
{
|
|
1161
|
+
unbondingTimelockScript: scripts.unbondingTimelockScript,
|
|
1162
|
+
slashingScript: scripts.slashingScript
|
|
1163
|
+
},
|
|
1164
|
+
unbondingScriptTree,
|
|
1165
|
+
unbondingTx,
|
|
1166
|
+
slashingPkScriptHex,
|
|
1167
|
+
slashingRate,
|
|
1168
|
+
minimumSlashingFee,
|
|
1169
|
+
network,
|
|
1170
|
+
0
|
|
1171
|
+
// unbonding always has a single output
|
|
1172
|
+
);
|
|
1173
|
+
}
|
|
1174
|
+
function slashingTransaction(scripts, scriptTree, transaction, slashingPkScriptHex, slashingRate, minimumFee, network, outputIndex = 0) {
|
|
1175
|
+
if (slashingRate <= 0 || slashingRate >= 1) {
|
|
1176
|
+
throw new Error("Slashing rate must be between 0 and 1");
|
|
1177
|
+
}
|
|
1178
|
+
slashingRate = parseFloat(slashingRate.toFixed(BTC_SLASHING_FRACTION_DIGITS));
|
|
1179
|
+
if (minimumFee <= 0 || !Number.isInteger(minimumFee)) {
|
|
1180
|
+
throw new Error("Minimum fee must be a positve integer");
|
|
1181
|
+
}
|
|
1182
|
+
if (outputIndex < 0 || !Number.isInteger(outputIndex)) {
|
|
1183
|
+
throw new Error("Output index must be an integer bigger or equal to 0");
|
|
1184
|
+
}
|
|
1185
|
+
if (!transaction.outs[outputIndex]) {
|
|
1186
|
+
throw new Error("Output index is out of range");
|
|
1187
|
+
}
|
|
1188
|
+
const redeem = {
|
|
1189
|
+
output: scripts.slashingScript,
|
|
1195
1190
|
redeemVersion: REDEEM_VERSION
|
|
1196
1191
|
};
|
|
1197
1192
|
const p2tr = payments5.p2tr({
|
|
1198
1193
|
internalPubkey,
|
|
1199
|
-
scriptTree
|
|
1200
|
-
redeem
|
|
1194
|
+
scriptTree,
|
|
1195
|
+
redeem,
|
|
1201
1196
|
network
|
|
1202
1197
|
});
|
|
1203
|
-
const
|
|
1204
|
-
leafVersion:
|
|
1205
|
-
script:
|
|
1198
|
+
const tapLeafScript = {
|
|
1199
|
+
leafVersion: redeem.redeemVersion,
|
|
1200
|
+
script: redeem.output,
|
|
1206
1201
|
controlBlock: p2tr.witness[p2tr.witness.length - 1]
|
|
1207
1202
|
};
|
|
1203
|
+
const stakingAmount = transaction.outs[outputIndex].value;
|
|
1204
|
+
const slashingAmount = Math.round(stakingAmount * slashingRate);
|
|
1205
|
+
const slashingOutput = Buffer.from(slashingPkScriptHex, "hex");
|
|
1206
|
+
if (opcodes3.OP_RETURN != slashingOutput[0]) {
|
|
1207
|
+
if (slashingAmount <= BTC_DUST_SAT) {
|
|
1208
|
+
throw new Error("Slashing amount is less than dust limit");
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
const userFunds = stakingAmount - slashingAmount - minimumFee;
|
|
1212
|
+
if (userFunds <= BTC_DUST_SAT) {
|
|
1213
|
+
throw new Error("User funds are less than dust limit");
|
|
1214
|
+
}
|
|
1215
|
+
const psbt = new Psbt2({ network });
|
|
1216
|
+
psbt.setVersion(TRANSACTION_VERSION);
|
|
1208
1217
|
psbt.addInput({
|
|
1209
|
-
hash:
|
|
1210
|
-
index:
|
|
1211
|
-
sequence: input.sequence,
|
|
1218
|
+
hash: transaction.getHash(),
|
|
1219
|
+
index: outputIndex,
|
|
1212
1220
|
tapInternalKey: internalPubkey,
|
|
1213
1221
|
witnessUtxo: {
|
|
1214
|
-
value:
|
|
1215
|
-
script:
|
|
1222
|
+
value: stakingAmount,
|
|
1223
|
+
script: transaction.outs[outputIndex].script
|
|
1216
1224
|
},
|
|
1217
|
-
tapLeafScript: [
|
|
1225
|
+
tapLeafScript: [tapLeafScript],
|
|
1226
|
+
// not RBF-able
|
|
1227
|
+
sequence: NON_RBF_SEQUENCE
|
|
1218
1228
|
});
|
|
1219
1229
|
psbt.addOutput({
|
|
1220
|
-
script:
|
|
1221
|
-
value:
|
|
1230
|
+
script: slashingOutput,
|
|
1231
|
+
value: slashingAmount
|
|
1222
1232
|
});
|
|
1223
|
-
|
|
1233
|
+
const changeOutput = payments5.p2tr({
|
|
1234
|
+
internalPubkey,
|
|
1235
|
+
scriptTree: { output: scripts.unbondingTimelockScript },
|
|
1236
|
+
network
|
|
1237
|
+
});
|
|
1238
|
+
psbt.addOutput({
|
|
1239
|
+
address: changeOutput.address,
|
|
1240
|
+
value: userFunds
|
|
1241
|
+
});
|
|
1242
|
+
psbt.setLocktime(0);
|
|
1243
|
+
return { psbt };
|
|
1244
|
+
}
|
|
1245
|
+
function unbondingTransaction(scripts, stakingTx, unbondingFee, network, outputIndex = 0) {
|
|
1246
|
+
if (unbondingFee <= 0) {
|
|
1247
|
+
throw new Error("Unbonding fee must be bigger than 0");
|
|
1248
|
+
}
|
|
1249
|
+
if (outputIndex < 0) {
|
|
1250
|
+
throw new Error("Output index must be bigger or equal to 0");
|
|
1251
|
+
}
|
|
1252
|
+
const tx = new Transaction3();
|
|
1253
|
+
tx.version = TRANSACTION_VERSION;
|
|
1254
|
+
tx.addInput(
|
|
1255
|
+
stakingTx.getHash(),
|
|
1256
|
+
outputIndex,
|
|
1257
|
+
NON_RBF_SEQUENCE
|
|
1258
|
+
// not RBF-able
|
|
1259
|
+
);
|
|
1260
|
+
const unbondingOutputInfo = deriveUnbondingOutputInfo(scripts, network);
|
|
1261
|
+
const outputValue = stakingTx.outs[outputIndex].value - unbondingFee;
|
|
1262
|
+
if (outputValue < BTC_DUST_SAT) {
|
|
1263
|
+
throw new Error("Output value is less than dust limit for unbonding transaction");
|
|
1264
|
+
}
|
|
1265
|
+
if (!unbondingOutputInfo.outputAddress) {
|
|
1266
|
+
throw new Error("Unbonding output address is not defined");
|
|
1267
|
+
}
|
|
1268
|
+
tx.addOutput(
|
|
1269
|
+
unbondingOutputInfo.scriptPubKey,
|
|
1270
|
+
outputValue
|
|
1271
|
+
);
|
|
1272
|
+
tx.locktime = 0;
|
|
1273
|
+
return {
|
|
1274
|
+
transaction: tx,
|
|
1275
|
+
fee: unbondingFee
|
|
1276
|
+
};
|
|
1277
|
+
}
|
|
1278
|
+
var createCovenantWitness = (originalWitness, paramsCovenants, covenantSigs, covenantQuorum) => {
|
|
1279
|
+
if (covenantSigs.length < covenantQuorum) {
|
|
1280
|
+
throw new Error(
|
|
1281
|
+
`Not enough covenant signatures. Required: ${covenantQuorum}, got: ${covenantSigs.length}`
|
|
1282
|
+
);
|
|
1283
|
+
}
|
|
1284
|
+
const filteredCovenantSigs = covenantSigs.filter((sig) => {
|
|
1285
|
+
const btcPkHexBuf = Buffer.from(sig.btcPkHex, "hex");
|
|
1286
|
+
return paramsCovenants.some((covenant) => covenant.equals(btcPkHexBuf));
|
|
1287
|
+
});
|
|
1288
|
+
if (filteredCovenantSigs.length < covenantQuorum) {
|
|
1289
|
+
throw new Error(
|
|
1290
|
+
`Not enough valid covenant signatures. Required: ${covenantQuorum}, got: ${filteredCovenantSigs.length}`
|
|
1291
|
+
);
|
|
1292
|
+
}
|
|
1293
|
+
const covenantSigsBuffers = covenantSigs.slice(0, covenantQuorum).map((sig) => ({
|
|
1294
|
+
btcPkHex: Buffer.from(sig.btcPkHex, "hex"),
|
|
1295
|
+
sigHex: Buffer.from(sig.sigHex, "hex")
|
|
1296
|
+
}));
|
|
1297
|
+
const paramsCovenantsSorted = [...paramsCovenants].sort(Buffer.compare).reverse();
|
|
1298
|
+
const composedCovenantSigs = paramsCovenantsSorted.map((covenant) => {
|
|
1299
|
+
const covenantSig = covenantSigsBuffers.find(
|
|
1300
|
+
(sig) => sig.btcPkHex.compare(covenant) === 0
|
|
1301
|
+
);
|
|
1302
|
+
return covenantSig?.sigHex || Buffer.alloc(0);
|
|
1303
|
+
});
|
|
1304
|
+
return [...composedCovenantSigs, ...originalWitness];
|
|
1305
|
+
};
|
|
1306
|
+
|
|
1307
|
+
// src/constants/unbonding.ts
|
|
1308
|
+
var MIN_UNBONDING_OUTPUT_VALUE = 1e3;
|
|
1309
|
+
|
|
1310
|
+
// src/utils/babylon.ts
|
|
1311
|
+
import { fromBech32 } from "@cosmjs/encoding";
|
|
1312
|
+
var isValidBabylonAddress = (address4) => {
|
|
1313
|
+
try {
|
|
1314
|
+
const { prefix } = fromBech32(address4);
|
|
1315
|
+
return prefix === "bbn";
|
|
1316
|
+
} catch (error) {
|
|
1317
|
+
return false;
|
|
1318
|
+
}
|
|
1319
|
+
};
|
|
1320
|
+
|
|
1321
|
+
// src/utils/staking/validation.ts
|
|
1322
|
+
var validateStakingExpansionInputs = ({
|
|
1323
|
+
babylonBtcTipHeight,
|
|
1324
|
+
inputUTXOs,
|
|
1325
|
+
stakingInput,
|
|
1326
|
+
previousStakingInput,
|
|
1327
|
+
babylonAddress
|
|
1328
|
+
}) => {
|
|
1329
|
+
if (babylonBtcTipHeight === 0) {
|
|
1330
|
+
throw new StakingError(
|
|
1331
|
+
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
1332
|
+
"Babylon BTC tip height cannot be 0"
|
|
1333
|
+
);
|
|
1334
|
+
}
|
|
1335
|
+
if (!inputUTXOs || inputUTXOs.length === 0) {
|
|
1336
|
+
throw new StakingError(
|
|
1337
|
+
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
1338
|
+
"No input UTXOs provided"
|
|
1339
|
+
);
|
|
1340
|
+
}
|
|
1341
|
+
if (babylonAddress && !isValidBabylonAddress(babylonAddress)) {
|
|
1342
|
+
throw new StakingError(
|
|
1343
|
+
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
1344
|
+
"Invalid Babylon address"
|
|
1345
|
+
);
|
|
1346
|
+
}
|
|
1347
|
+
if (stakingInput.stakingAmountSat !== previousStakingInput.stakingAmountSat) {
|
|
1348
|
+
throw new StakingError(
|
|
1349
|
+
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
1350
|
+
"Staking expansion amount must equal the previous staking amount"
|
|
1351
|
+
);
|
|
1352
|
+
}
|
|
1353
|
+
const currentFPs = stakingInput.finalityProviderPksNoCoordHex;
|
|
1354
|
+
const previousFPs = previousStakingInput.finalityProviderPksNoCoordHex;
|
|
1355
|
+
const missingPreviousFPs = previousFPs.filter((prevFp) => !currentFPs.includes(prevFp));
|
|
1356
|
+
if (missingPreviousFPs.length > 0) {
|
|
1357
|
+
throw new StakingError(
|
|
1358
|
+
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
1359
|
+
`Invalid staking expansion: all finality providers from the previous
|
|
1360
|
+
staking must be included. Missing: ${missingPreviousFPs.join(", ")}`
|
|
1361
|
+
);
|
|
1362
|
+
}
|
|
1363
|
+
};
|
|
1364
|
+
var validateStakingTxInputData = (stakingAmountSat, timelock, params, inputUTXOs, feeRate) => {
|
|
1365
|
+
if (stakingAmountSat < params.minStakingAmountSat || stakingAmountSat > params.maxStakingAmountSat) {
|
|
1366
|
+
throw new StakingError(
|
|
1367
|
+
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
1368
|
+
"Invalid staking amount"
|
|
1369
|
+
);
|
|
1370
|
+
}
|
|
1371
|
+
if (timelock < params.minStakingTimeBlocks || timelock > params.maxStakingTimeBlocks) {
|
|
1372
|
+
throw new StakingError("INVALID_INPUT" /* INVALID_INPUT */, "Invalid timelock");
|
|
1373
|
+
}
|
|
1374
|
+
if (inputUTXOs.length == 0) {
|
|
1375
|
+
throw new StakingError(
|
|
1376
|
+
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
1377
|
+
"No input UTXOs provided"
|
|
1378
|
+
);
|
|
1379
|
+
}
|
|
1380
|
+
if (feeRate <= 0) {
|
|
1381
|
+
throw new StakingError("INVALID_INPUT" /* INVALID_INPUT */, "Invalid fee rate");
|
|
1382
|
+
}
|
|
1383
|
+
};
|
|
1384
|
+
var validateParams = (params) => {
|
|
1385
|
+
if (params.covenantNoCoordPks.length == 0) {
|
|
1386
|
+
throw new StakingError(
|
|
1387
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1388
|
+
"Could not find any covenant public keys"
|
|
1389
|
+
);
|
|
1390
|
+
}
|
|
1391
|
+
if (params.covenantNoCoordPks.length < params.covenantQuorum) {
|
|
1392
|
+
throw new StakingError(
|
|
1393
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1394
|
+
"Covenant public keys must be greater than or equal to the quorum"
|
|
1395
|
+
);
|
|
1396
|
+
}
|
|
1397
|
+
params.covenantNoCoordPks.forEach((pk) => {
|
|
1398
|
+
if (!isValidNoCoordPublicKey(pk)) {
|
|
1399
|
+
throw new StakingError(
|
|
1400
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1401
|
+
"Covenant public key should contains no coordinate"
|
|
1402
|
+
);
|
|
1403
|
+
}
|
|
1404
|
+
});
|
|
1405
|
+
if (params.unbondingTime <= 0) {
|
|
1406
|
+
throw new StakingError(
|
|
1407
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1408
|
+
"Unbonding time must be greater than 0"
|
|
1409
|
+
);
|
|
1410
|
+
}
|
|
1411
|
+
if (params.unbondingFeeSat <= 0) {
|
|
1412
|
+
throw new StakingError(
|
|
1413
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1414
|
+
"Unbonding fee must be greater than 0"
|
|
1415
|
+
);
|
|
1416
|
+
}
|
|
1417
|
+
if (params.maxStakingAmountSat < params.minStakingAmountSat) {
|
|
1418
|
+
throw new StakingError(
|
|
1419
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1420
|
+
"Max staking amount must be greater or equal to min staking amount"
|
|
1421
|
+
);
|
|
1422
|
+
}
|
|
1423
|
+
if (params.minStakingAmountSat < params.unbondingFeeSat + MIN_UNBONDING_OUTPUT_VALUE) {
|
|
1424
|
+
throw new StakingError(
|
|
1425
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1426
|
+
`Min staking amount must be greater than unbonding fee plus ${MIN_UNBONDING_OUTPUT_VALUE}`
|
|
1427
|
+
);
|
|
1428
|
+
}
|
|
1429
|
+
if (params.maxStakingTimeBlocks < params.minStakingTimeBlocks) {
|
|
1430
|
+
throw new StakingError(
|
|
1431
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1432
|
+
"Max staking time must be greater or equal to min staking time"
|
|
1433
|
+
);
|
|
1434
|
+
}
|
|
1435
|
+
if (params.minStakingTimeBlocks <= 0) {
|
|
1436
|
+
throw new StakingError(
|
|
1437
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1438
|
+
"Min staking time must be greater than 0"
|
|
1439
|
+
);
|
|
1440
|
+
}
|
|
1441
|
+
if (params.covenantQuorum <= 0) {
|
|
1442
|
+
throw new StakingError(
|
|
1443
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1444
|
+
"Covenant quorum must be greater than 0"
|
|
1445
|
+
);
|
|
1446
|
+
}
|
|
1447
|
+
if (params.slashing) {
|
|
1448
|
+
if (params.slashing.slashingRate <= 0) {
|
|
1449
|
+
throw new StakingError(
|
|
1450
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1451
|
+
"Slashing rate must be greater than 0"
|
|
1452
|
+
);
|
|
1453
|
+
}
|
|
1454
|
+
if (params.slashing.slashingRate > 1) {
|
|
1455
|
+
throw new StakingError(
|
|
1456
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1457
|
+
"Slashing rate must be less or equal to 1"
|
|
1458
|
+
);
|
|
1459
|
+
}
|
|
1460
|
+
if (params.slashing.slashingPkScriptHex.length == 0) {
|
|
1461
|
+
throw new StakingError(
|
|
1462
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1463
|
+
"Slashing public key script is missing"
|
|
1464
|
+
);
|
|
1465
|
+
}
|
|
1466
|
+
if (params.slashing.minSlashingTxFeeSat <= 0) {
|
|
1467
|
+
throw new StakingError(
|
|
1468
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
1469
|
+
"Minimum slashing transaction fee must be greater than 0"
|
|
1470
|
+
);
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1224
1473
|
};
|
|
1225
|
-
var
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
"
|
|
1474
|
+
var validateStakingTimelock = (stakingTimelock, params) => {
|
|
1475
|
+
if (stakingTimelock < params.minStakingTimeBlocks || stakingTimelock > params.maxStakingTimeBlocks) {
|
|
1476
|
+
throw new StakingError(
|
|
1477
|
+
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
1478
|
+
"Staking transaction timelock is out of range"
|
|
1479
|
+
);
|
|
1480
|
+
}
|
|
1481
|
+
};
|
|
1482
|
+
var validateStakingExpansionCovenantQuorum = (paramsForPreviousStakingTx, paramsForCurrentStakingTx) => {
|
|
1483
|
+
const previousCovenantMembers = paramsForPreviousStakingTx.covenantNoCoordPks;
|
|
1484
|
+
const currentCovenantMembers = paramsForCurrentStakingTx.covenantNoCoordPks;
|
|
1485
|
+
const requiredQuorum = paramsForPreviousStakingTx.covenantQuorum;
|
|
1486
|
+
const activePreviousMembers = previousCovenantMembers.filter(
|
|
1487
|
+
(prevMember) => currentCovenantMembers.includes(prevMember)
|
|
1488
|
+
).length;
|
|
1489
|
+
if (activePreviousMembers < requiredQuorum) {
|
|
1490
|
+
throw new StakingError(
|
|
1491
|
+
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
1492
|
+
`Staking expansion failed: insufficient covenant quorum. Required: ${requiredQuorum}, Available: ${activePreviousMembers}. Too many covenant members have rotated out.`
|
|
1230
1493
|
);
|
|
1231
1494
|
}
|
|
1232
1495
|
};
|
|
1233
1496
|
|
|
1234
1497
|
// src/staking/index.ts
|
|
1235
|
-
var Staking = class {
|
|
1236
|
-
constructor(network, stakerInfo, params,
|
|
1498
|
+
var Staking = class _Staking {
|
|
1499
|
+
constructor(network, stakerInfo, params, finalityProviderPksNoCoordHex, stakingTimelock) {
|
|
1237
1500
|
if (!isValidBitcoinAddress(stakerInfo.address, network)) {
|
|
1238
1501
|
throw new StakingError(
|
|
1239
1502
|
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
@@ -1246,10 +1509,10 @@ var Staking = class {
|
|
|
1246
1509
|
"Invalid staker public key"
|
|
1247
1510
|
);
|
|
1248
1511
|
}
|
|
1249
|
-
if (!isValidNoCoordPublicKey
|
|
1512
|
+
if (finalityProviderPksNoCoordHex.length === 0 || !finalityProviderPksNoCoordHex.every(isValidNoCoordPublicKey)) {
|
|
1250
1513
|
throw new StakingError(
|
|
1251
1514
|
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
1252
|
-
"Invalid finality
|
|
1515
|
+
"Invalid finality providers public keys"
|
|
1253
1516
|
);
|
|
1254
1517
|
}
|
|
1255
1518
|
validateParams(params);
|
|
@@ -1257,14 +1520,14 @@ var Staking = class {
|
|
|
1257
1520
|
this.network = network;
|
|
1258
1521
|
this.stakerInfo = stakerInfo;
|
|
1259
1522
|
this.params = params;
|
|
1260
|
-
this.
|
|
1523
|
+
this.finalityProviderPksNoCoordHex = finalityProviderPksNoCoordHex;
|
|
1261
1524
|
this.stakingTimelock = stakingTimelock;
|
|
1262
1525
|
}
|
|
1263
1526
|
/**
|
|
1264
1527
|
* buildScripts builds the staking scripts for the staking transaction.
|
|
1265
1528
|
* Note: different staking types may have different scripts.
|
|
1266
1529
|
* e.g the observable staking script has a data embed script.
|
|
1267
|
-
*
|
|
1530
|
+
*
|
|
1268
1531
|
* @returns {StakingScripts} - The staking scripts.
|
|
1269
1532
|
*/
|
|
1270
1533
|
buildScripts() {
|
|
@@ -1273,7 +1536,7 @@ var Staking = class {
|
|
|
1273
1536
|
try {
|
|
1274
1537
|
stakingScriptData = new StakingScriptData(
|
|
1275
1538
|
Buffer.from(this.stakerInfo.publicKeyNoCoordHex, "hex"),
|
|
1276
|
-
|
|
1539
|
+
this.finalityProviderPksNoCoordHex.map((pk) => Buffer.from(pk, "hex")),
|
|
1277
1540
|
toBuffers(covenantNoCoordPks),
|
|
1278
1541
|
covenantQuorum,
|
|
1279
1542
|
this.stakingTimelock,
|
|
@@ -1300,9 +1563,9 @@ var Staking = class {
|
|
|
1300
1563
|
}
|
|
1301
1564
|
/**
|
|
1302
1565
|
* Create a staking transaction for staking.
|
|
1303
|
-
*
|
|
1566
|
+
*
|
|
1304
1567
|
* @param {number} stakingAmountSat - The amount to stake in satoshis.
|
|
1305
|
-
* @param {UTXO[]} inputUTXOs - The UTXOs to use as inputs for the staking
|
|
1568
|
+
* @param {UTXO[]} inputUTXOs - The UTXOs to use as inputs for the staking
|
|
1306
1569
|
* transaction.
|
|
1307
1570
|
* @param {number} feeRate - The fee rate for the transaction in satoshis per byte.
|
|
1308
1571
|
* @returns {TransactionResult} - An object containing the unsigned
|
|
@@ -1340,10 +1603,85 @@ var Staking = class {
|
|
|
1340
1603
|
}
|
|
1341
1604
|
}
|
|
1342
1605
|
/**
|
|
1343
|
-
*
|
|
1606
|
+
* Creates a staking expansion transaction that extends an existing BTC stake
|
|
1607
|
+
* to new finality providers or renews the timelock.
|
|
1344
1608
|
*
|
|
1609
|
+
* This method implements RFC 037 BTC Stake Expansion,
|
|
1610
|
+
* allowing existing active BTC staking transactions
|
|
1611
|
+
* to extend their delegation to new finality providers without going through
|
|
1612
|
+
* the full unbonding process.
|
|
1613
|
+
*
|
|
1614
|
+
* The expansion transaction:
|
|
1615
|
+
* 1. Spends the previous staking transaction output as the first input
|
|
1616
|
+
* 2. Uses funding UTXO as additional input to cover transaction fees or
|
|
1617
|
+
* to increase the staking amount
|
|
1618
|
+
* 3. Creates a new staking output with expanded finality provider coverage or
|
|
1619
|
+
* renews the timelock
|
|
1620
|
+
* 4. Has an output returning the remaining funds as change (if any) to the
|
|
1621
|
+
* staker BTC address
|
|
1622
|
+
*
|
|
1623
|
+
* @param {number} stakingAmountSat - The total staking amount in satoshis
|
|
1624
|
+
* (The amount had to be equal to the previous staking amount for now, this
|
|
1625
|
+
* lib does not yet support increasing the staking amount at this stage)
|
|
1626
|
+
* @param {UTXO[]} inputUTXOs - Available UTXOs to use for funding the
|
|
1627
|
+
* expansion transaction fees. Only one will be selected for the expansion
|
|
1628
|
+
* @param {number} feeRate - Fee rate in satoshis per byte for the
|
|
1629
|
+
* expansion transaction
|
|
1630
|
+
* @param {StakingParams} paramsForPreviousStakingTx - Staking parameters
|
|
1631
|
+
* used in the previous staking transaction
|
|
1632
|
+
* @param {Object} previousStakingTxInfo - Necessary information to spend the
|
|
1633
|
+
* previous staking transaction.
|
|
1634
|
+
* @returns {TransactionResult & { fundingUTXO: UTXO }} - An object containing
|
|
1635
|
+
* the unsigned expansion transaction and calculated fee, and the funding UTXO
|
|
1636
|
+
* @throws {StakingError} - If the transaction cannot be built or validation
|
|
1637
|
+
* fails
|
|
1638
|
+
*/
|
|
1639
|
+
createStakingExpansionTransaction(stakingAmountSat, inputUTXOs, feeRate, paramsForPreviousStakingTx, previousStakingTxInfo) {
|
|
1640
|
+
validateStakingTxInputData(
|
|
1641
|
+
stakingAmountSat,
|
|
1642
|
+
this.stakingTimelock,
|
|
1643
|
+
this.params,
|
|
1644
|
+
inputUTXOs,
|
|
1645
|
+
feeRate
|
|
1646
|
+
);
|
|
1647
|
+
validateStakingExpansionCovenantQuorum(
|
|
1648
|
+
paramsForPreviousStakingTx,
|
|
1649
|
+
this.params
|
|
1650
|
+
);
|
|
1651
|
+
const previousStaking = new _Staking(
|
|
1652
|
+
this.network,
|
|
1653
|
+
this.stakerInfo,
|
|
1654
|
+
paramsForPreviousStakingTx,
|
|
1655
|
+
previousStakingTxInfo.stakingInput.finalityProviderPksNoCoordHex,
|
|
1656
|
+
previousStakingTxInfo.stakingInput.stakingTimelock
|
|
1657
|
+
);
|
|
1658
|
+
const {
|
|
1659
|
+
transaction: stakingExpansionTx,
|
|
1660
|
+
fee: stakingExpansionTxFee,
|
|
1661
|
+
fundingUTXO
|
|
1662
|
+
} = stakingExpansionTransaction(
|
|
1663
|
+
this.network,
|
|
1664
|
+
this.buildScripts(),
|
|
1665
|
+
stakingAmountSat,
|
|
1666
|
+
this.stakerInfo.address,
|
|
1667
|
+
feeRate,
|
|
1668
|
+
inputUTXOs,
|
|
1669
|
+
{
|
|
1670
|
+
stakingTx: previousStakingTxInfo.stakingTx,
|
|
1671
|
+
scripts: previousStaking.buildScripts()
|
|
1672
|
+
}
|
|
1673
|
+
);
|
|
1674
|
+
return {
|
|
1675
|
+
transaction: stakingExpansionTx,
|
|
1676
|
+
fee: stakingExpansionTxFee,
|
|
1677
|
+
fundingUTXO
|
|
1678
|
+
};
|
|
1679
|
+
}
|
|
1680
|
+
/**
|
|
1681
|
+
* Create a staking psbt based on the existing staking transaction.
|
|
1682
|
+
*
|
|
1345
1683
|
* @param {Transaction} stakingTx - The staking transaction.
|
|
1346
|
-
* @param {UTXO[]} inputUTXOs - The UTXOs to use as inputs for the staking
|
|
1684
|
+
* @param {UTXO[]} inputUTXOs - The UTXOs to use as inputs for the staking
|
|
1347
1685
|
* transaction. The UTXOs that were used to create the staking transaction should
|
|
1348
1686
|
* be included in this array.
|
|
1349
1687
|
* @returns {Psbt} - The psbt.
|
|
@@ -1360,15 +1698,54 @@ var Staking = class {
|
|
|
1360
1698
|
stakingTx,
|
|
1361
1699
|
this.network,
|
|
1362
1700
|
inputUTXOs,
|
|
1363
|
-
isTaproot(
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1701
|
+
isTaproot(this.stakerInfo.address, this.network) ? Buffer.from(this.stakerInfo.publicKeyNoCoordHex, "hex") : void 0
|
|
1702
|
+
);
|
|
1703
|
+
}
|
|
1704
|
+
/**
|
|
1705
|
+
* Convert a staking expansion transaction to a PSBT.
|
|
1706
|
+
*
|
|
1707
|
+
* @param {Transaction} stakingExpansionTx - The staking expansion
|
|
1708
|
+
* transaction to convert
|
|
1709
|
+
* @param {UTXO[]} inputUTXOs - Available UTXOs for the
|
|
1710
|
+
* funding input (second input)
|
|
1711
|
+
* @param {StakingParams} paramsForPreviousStakingTx - Staking parameters
|
|
1712
|
+
* used for the previous staking transaction
|
|
1713
|
+
* @param {Object} previousStakingTxInfo - Information about the previous
|
|
1714
|
+
* staking transaction
|
|
1715
|
+
* @returns {Psbt} The PSBT for the staking expansion transaction
|
|
1716
|
+
* @throws {Error} If the previous staking output cannot be found or
|
|
1717
|
+
* validation fails
|
|
1718
|
+
*/
|
|
1719
|
+
toStakingExpansionPsbt(stakingExpansionTx, inputUTXOs, paramsForPreviousStakingTx, previousStakingTxInfo) {
|
|
1720
|
+
const previousStaking = new _Staking(
|
|
1721
|
+
this.network,
|
|
1722
|
+
this.stakerInfo,
|
|
1723
|
+
paramsForPreviousStakingTx,
|
|
1724
|
+
previousStakingTxInfo.stakingInput.finalityProviderPksNoCoordHex,
|
|
1725
|
+
previousStakingTxInfo.stakingInput.stakingTimelock
|
|
1726
|
+
);
|
|
1727
|
+
const previousScripts = previousStaking.buildScripts();
|
|
1728
|
+
const { outputAddress } = deriveStakingOutputInfo(previousScripts, this.network);
|
|
1729
|
+
const previousStakingOutputIndex = findMatchingTxOutputIndex(
|
|
1730
|
+
previousStakingTxInfo.stakingTx,
|
|
1731
|
+
outputAddress,
|
|
1732
|
+
this.network
|
|
1733
|
+
);
|
|
1734
|
+
return stakingExpansionPsbt(
|
|
1735
|
+
this.network,
|
|
1736
|
+
stakingExpansionTx,
|
|
1737
|
+
{
|
|
1738
|
+
stakingTx: previousStakingTxInfo.stakingTx,
|
|
1739
|
+
outputIndex: previousStakingOutputIndex
|
|
1740
|
+
},
|
|
1741
|
+
inputUTXOs,
|
|
1742
|
+
previousScripts,
|
|
1743
|
+
isTaproot(this.stakerInfo.address, this.network) ? Buffer.from(this.stakerInfo.publicKeyNoCoordHex, "hex") : void 0
|
|
1367
1744
|
);
|
|
1368
1745
|
}
|
|
1369
1746
|
/**
|
|
1370
1747
|
* Create an unbonding transaction for staking.
|
|
1371
|
-
*
|
|
1748
|
+
*
|
|
1372
1749
|
* @param {Transaction} stakingTx - The staking transaction to unbond.
|
|
1373
1750
|
* @returns {TransactionResult} - An object containing the unsigned
|
|
1374
1751
|
* transaction, and fee
|
|
@@ -1405,10 +1782,10 @@ var Staking = class {
|
|
|
1405
1782
|
/**
|
|
1406
1783
|
* Create an unbonding psbt based on the existing unbonding transaction and
|
|
1407
1784
|
* staking transaction.
|
|
1408
|
-
*
|
|
1785
|
+
*
|
|
1409
1786
|
* @param {Transaction} unbondingTx - The unbonding transaction.
|
|
1410
1787
|
* @param {Transaction} stakingTx - The staking transaction.
|
|
1411
|
-
*
|
|
1788
|
+
*
|
|
1412
1789
|
* @returns {Psbt} - The psbt.
|
|
1413
1790
|
*/
|
|
1414
1791
|
toUnbondingPsbt(unbondingTx, stakingTx) {
|
|
@@ -1423,7 +1800,7 @@ var Staking = class {
|
|
|
1423
1800
|
* Creates a withdrawal transaction that spends from an unbonding or slashing
|
|
1424
1801
|
* transaction. The timelock on the input transaction must have expired before
|
|
1425
1802
|
* this withdrawal can be valid.
|
|
1426
|
-
*
|
|
1803
|
+
*
|
|
1427
1804
|
* @param {Transaction} earlyUnbondedTx - The unbonding or slashing
|
|
1428
1805
|
* transaction to withdraw from
|
|
1429
1806
|
* @param {number} feeRate - Fee rate in satoshis per byte for the withdrawal
|
|
@@ -1451,9 +1828,9 @@ var Staking = class {
|
|
|
1451
1828
|
}
|
|
1452
1829
|
}
|
|
1453
1830
|
/**
|
|
1454
|
-
* Create a withdrawal psbt that spends a naturally expired staking
|
|
1831
|
+
* Create a withdrawal psbt that spends a naturally expired staking
|
|
1455
1832
|
* transaction.
|
|
1456
|
-
*
|
|
1833
|
+
*
|
|
1457
1834
|
* @param {Transaction} stakingTx - The staking transaction to withdraw from.
|
|
1458
1835
|
* @param {number} feeRate - The fee rate for the transaction in satoshis per byte.
|
|
1459
1836
|
* @returns {PsbtResult} - An object containing the unsigned psbt and fee
|
|
@@ -1486,7 +1863,7 @@ var Staking = class {
|
|
|
1486
1863
|
}
|
|
1487
1864
|
/**
|
|
1488
1865
|
* Create a slashing psbt spending from the staking output.
|
|
1489
|
-
*
|
|
1866
|
+
*
|
|
1490
1867
|
* @param {Transaction} stakingTx - The staking transaction to slash.
|
|
1491
1868
|
* @returns {PsbtResult} - An object containing the unsigned psbt and fee
|
|
1492
1869
|
* @throws {StakingError} - If the delegation is invalid or the transaction cannot be built
|
|
@@ -1499,6 +1876,12 @@ var Staking = class {
|
|
|
1499
1876
|
);
|
|
1500
1877
|
}
|
|
1501
1878
|
const scripts = this.buildScripts();
|
|
1879
|
+
const { outputAddress } = deriveStakingOutputInfo(scripts, this.network);
|
|
1880
|
+
const stakingOutputIndex = findMatchingTxOutputIndex(
|
|
1881
|
+
stakingTx,
|
|
1882
|
+
outputAddress,
|
|
1883
|
+
this.network
|
|
1884
|
+
);
|
|
1502
1885
|
try {
|
|
1503
1886
|
const { psbt } = slashTimelockUnbondedTransaction(
|
|
1504
1887
|
scripts,
|
|
@@ -1506,7 +1889,8 @@ var Staking = class {
|
|
|
1506
1889
|
this.params.slashing.slashingPkScriptHex,
|
|
1507
1890
|
this.params.slashing.slashingRate,
|
|
1508
1891
|
this.params.slashing.minSlashingTxFeeSat,
|
|
1509
|
-
this.network
|
|
1892
|
+
this.network,
|
|
1893
|
+
stakingOutputIndex
|
|
1510
1894
|
);
|
|
1511
1895
|
return {
|
|
1512
1896
|
psbt,
|
|
@@ -1522,7 +1906,7 @@ var Staking = class {
|
|
|
1522
1906
|
}
|
|
1523
1907
|
/**
|
|
1524
1908
|
* Create a slashing psbt for an unbonding output.
|
|
1525
|
-
*
|
|
1909
|
+
*
|
|
1526
1910
|
* @param {Transaction} unbondingTx - The unbonding transaction to slash.
|
|
1527
1911
|
* @returns {PsbtResult} - An object containing the unsigned psbt and fee
|
|
1528
1912
|
* @throws {StakingError} - If the delegation is invalid or the transaction cannot be built
|
|
@@ -1559,7 +1943,7 @@ var Staking = class {
|
|
|
1559
1943
|
/**
|
|
1560
1944
|
* Create a withdraw slashing psbt that spends a slashing transaction from the
|
|
1561
1945
|
* staking output.
|
|
1562
|
-
*
|
|
1946
|
+
*
|
|
1563
1947
|
* @param {Transaction} slashingTx - The slashing transaction.
|
|
1564
1948
|
* @param {number} feeRate - The fee rate for the transaction in satoshis per byte.
|
|
1565
1949
|
* @returns {PsbtResult} - An object containing the unsigned psbt and fee
|
|
@@ -1586,260 +1970,30 @@ var Staking = class {
|
|
|
1586
1970
|
throw StakingError.fromUnknown(
|
|
1587
1971
|
error,
|
|
1588
1972
|
"BUILD_TRANSACTION_FAILURE" /* BUILD_TRANSACTION_FAILURE */,
|
|
1589
|
-
"Cannot build withdraw slashing transaction"
|
|
1590
|
-
);
|
|
1591
|
-
}
|
|
1592
|
-
}
|
|
1593
|
-
};
|
|
1594
|
-
|
|
1595
|
-
// src/staking/observable/observableStakingScript.ts
|
|
1596
|
-
import { opcodes as opcodes4, script as script3 } from "bitcoinjs-lib";
|
|
1597
|
-
var ObservableStakingScriptData = class extends StakingScriptData {
|
|
1598
|
-
constructor(stakerKey, finalityProviderKeys, covenantKeys, covenantThreshold, stakingTimelock, unbondingTimelock, magicBytes) {
|
|
1599
|
-
super(
|
|
1600
|
-
stakerKey,
|
|
1601
|
-
finalityProviderKeys,
|
|
1602
|
-
covenantKeys,
|
|
1603
|
-
covenantThreshold,
|
|
1604
|
-
stakingTimelock,
|
|
1605
|
-
unbondingTimelock
|
|
1606
|
-
);
|
|
1607
|
-
if (!magicBytes) {
|
|
1608
|
-
throw new Error("Missing required input values");
|
|
1609
|
-
}
|
|
1610
|
-
if (magicBytes.length != MAGIC_BYTES_LEN) {
|
|
1611
|
-
throw new Error("Invalid script data provided");
|
|
1612
|
-
}
|
|
1613
|
-
this.magicBytes = magicBytes;
|
|
1614
|
-
}
|
|
1615
|
-
/**
|
|
1616
|
-
* Builds a data embed script for staking in the form:
|
|
1617
|
-
* OP_RETURN || <serializedStakingData>
|
|
1618
|
-
* where serializedStakingData is the concatenation of:
|
|
1619
|
-
* MagicBytes || Version || StakerPublicKey || FinalityProviderPublicKey || StakingTimeLock
|
|
1620
|
-
* Note: Only a single finality provider key is supported for now in phase 1
|
|
1621
|
-
* @throws {Error} If the number of finality provider keys is not equal to 1.
|
|
1622
|
-
* @returns {Buffer} The compiled data embed script.
|
|
1623
|
-
*/
|
|
1624
|
-
buildDataEmbedScript() {
|
|
1625
|
-
if (this.finalityProviderKeys.length != 1) {
|
|
1626
|
-
throw new Error("Only a single finality provider key is supported");
|
|
1627
|
-
}
|
|
1628
|
-
const version = Buffer.alloc(1);
|
|
1629
|
-
version.writeUInt8(0);
|
|
1630
|
-
const stakingTimeLock = Buffer.alloc(2);
|
|
1631
|
-
stakingTimeLock.writeUInt16BE(this.stakingTimeLock);
|
|
1632
|
-
const serializedStakingData = Buffer.concat([
|
|
1633
|
-
this.magicBytes,
|
|
1634
|
-
version,
|
|
1635
|
-
this.stakerKey,
|
|
1636
|
-
this.finalityProviderKeys[0],
|
|
1637
|
-
stakingTimeLock
|
|
1638
|
-
]);
|
|
1639
|
-
return script3.compile([opcodes4.OP_RETURN, serializedStakingData]);
|
|
1640
|
-
}
|
|
1641
|
-
/**
|
|
1642
|
-
* Builds the staking scripts.
|
|
1643
|
-
* @returns {ObservableStakingScripts} The staking scripts that can be used to stake.
|
|
1644
|
-
* contains the timelockScript, unbondingScript, slashingScript,
|
|
1645
|
-
* unbondingTimelockScript, and dataEmbedScript.
|
|
1646
|
-
* @throws {Error} If script data is invalid.
|
|
1647
|
-
*/
|
|
1648
|
-
buildScripts() {
|
|
1649
|
-
const scripts = super.buildScripts();
|
|
1650
|
-
return {
|
|
1651
|
-
...scripts,
|
|
1652
|
-
dataEmbedScript: this.buildDataEmbedScript()
|
|
1653
|
-
};
|
|
1654
|
-
}
|
|
1655
|
-
};
|
|
1656
|
-
|
|
1657
|
-
// src/staking/observable/index.ts
|
|
1658
|
-
var ObservableStaking = class extends Staking {
|
|
1659
|
-
constructor(network, stakerInfo, params, finalityProviderPkNoCoordHex, stakingTimelock) {
|
|
1660
|
-
super(
|
|
1661
|
-
network,
|
|
1662
|
-
stakerInfo,
|
|
1663
|
-
params,
|
|
1664
|
-
finalityProviderPkNoCoordHex,
|
|
1665
|
-
stakingTimelock
|
|
1666
|
-
);
|
|
1667
|
-
if (!params.tag) {
|
|
1668
|
-
throw new StakingError(
|
|
1669
|
-
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
1670
|
-
"Observable staking parameters must include tag"
|
|
1671
|
-
);
|
|
1672
|
-
}
|
|
1673
|
-
if (!params.btcActivationHeight) {
|
|
1674
|
-
throw new StakingError(
|
|
1675
|
-
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
1676
|
-
"Observable staking parameters must include a positive activation height"
|
|
1677
|
-
);
|
|
1678
|
-
}
|
|
1679
|
-
this.params = params;
|
|
1680
|
-
}
|
|
1681
|
-
/**
|
|
1682
|
-
* Build the staking scripts for observable staking.
|
|
1683
|
-
* This method overwrites the base method to include the OP_RETURN tag based
|
|
1684
|
-
* on the tag provided in the parameters.
|
|
1685
|
-
*
|
|
1686
|
-
* @returns {ObservableStakingScripts} - The staking scripts for observable staking.
|
|
1687
|
-
* @throws {StakingError} - If the scripts cannot be built.
|
|
1688
|
-
*/
|
|
1689
|
-
buildScripts() {
|
|
1690
|
-
const { covenantQuorum, covenantNoCoordPks, unbondingTime, tag } = this.params;
|
|
1691
|
-
let stakingScriptData;
|
|
1692
|
-
try {
|
|
1693
|
-
stakingScriptData = new ObservableStakingScriptData(
|
|
1694
|
-
Buffer.from(this.stakerInfo.publicKeyNoCoordHex, "hex"),
|
|
1695
|
-
[Buffer.from(this.finalityProviderPkNoCoordHex, "hex")],
|
|
1696
|
-
toBuffers(covenantNoCoordPks),
|
|
1697
|
-
covenantQuorum,
|
|
1698
|
-
this.stakingTimelock,
|
|
1699
|
-
unbondingTime,
|
|
1700
|
-
Buffer.from(tag, "hex")
|
|
1701
|
-
);
|
|
1702
|
-
} catch (error) {
|
|
1703
|
-
throw StakingError.fromUnknown(
|
|
1704
|
-
error,
|
|
1705
|
-
"SCRIPT_FAILURE" /* SCRIPT_FAILURE */,
|
|
1706
|
-
"Cannot build staking script data"
|
|
1707
|
-
);
|
|
1708
|
-
}
|
|
1709
|
-
let scripts;
|
|
1710
|
-
try {
|
|
1711
|
-
scripts = stakingScriptData.buildScripts();
|
|
1712
|
-
} catch (error) {
|
|
1713
|
-
throw StakingError.fromUnknown(
|
|
1714
|
-
error,
|
|
1715
|
-
"SCRIPT_FAILURE" /* SCRIPT_FAILURE */,
|
|
1716
|
-
"Cannot build staking scripts"
|
|
1717
|
-
);
|
|
1718
|
-
}
|
|
1719
|
-
return scripts;
|
|
1720
|
-
}
|
|
1721
|
-
/**
|
|
1722
|
-
* Create a staking transaction for observable staking.
|
|
1723
|
-
* This overwrites the method from the Staking class with the addtion
|
|
1724
|
-
* of the
|
|
1725
|
-
* 1. OP_RETURN tag in the staking scripts
|
|
1726
|
-
* 2. lockHeight parameter
|
|
1727
|
-
*
|
|
1728
|
-
* @param {number} stakingAmountSat - The amount to stake in satoshis.
|
|
1729
|
-
* @param {UTXO[]} inputUTXOs - The UTXOs to use as inputs for the staking
|
|
1730
|
-
* transaction.
|
|
1731
|
-
* @param {number} feeRate - The fee rate for the transaction in satoshis per byte.
|
|
1732
|
-
* @returns {TransactionResult} - An object containing the unsigned transaction,
|
|
1733
|
-
* and fee
|
|
1734
|
-
*/
|
|
1735
|
-
createStakingTransaction(stakingAmountSat, inputUTXOs, feeRate) {
|
|
1736
|
-
validateStakingTxInputData(
|
|
1737
|
-
stakingAmountSat,
|
|
1738
|
-
this.stakingTimelock,
|
|
1739
|
-
this.params,
|
|
1740
|
-
inputUTXOs,
|
|
1741
|
-
feeRate
|
|
1742
|
-
);
|
|
1743
|
-
const scripts = this.buildScripts();
|
|
1744
|
-
try {
|
|
1745
|
-
const { transaction, fee } = stakingTransaction(
|
|
1746
|
-
scripts,
|
|
1747
|
-
stakingAmountSat,
|
|
1748
|
-
this.stakerInfo.address,
|
|
1749
|
-
inputUTXOs,
|
|
1750
|
-
this.network,
|
|
1751
|
-
feeRate,
|
|
1752
|
-
// `lockHeight` is exclusive of the provided value.
|
|
1753
|
-
// For example, if a Bitcoin height of X is provided,
|
|
1754
|
-
// the transaction will be included starting from height X+1.
|
|
1755
|
-
// https://learnmeabitcoin.com/technical/transaction/locktime/
|
|
1756
|
-
this.params.btcActivationHeight - 1
|
|
1757
|
-
);
|
|
1758
|
-
return {
|
|
1759
|
-
transaction,
|
|
1760
|
-
fee
|
|
1761
|
-
};
|
|
1762
|
-
} catch (error) {
|
|
1763
|
-
throw StakingError.fromUnknown(
|
|
1764
|
-
error,
|
|
1765
|
-
"BUILD_TRANSACTION_FAILURE" /* BUILD_TRANSACTION_FAILURE */,
|
|
1766
|
-
"Cannot build unsigned staking transaction"
|
|
1973
|
+
"Cannot build withdraw slashing transaction"
|
|
1767
1974
|
);
|
|
1768
1975
|
}
|
|
1769
1976
|
}
|
|
1770
|
-
/**
|
|
1771
|
-
* Create a staking psbt for observable staking.
|
|
1772
|
-
*
|
|
1773
|
-
* @param {Transaction} stakingTx - The staking transaction.
|
|
1774
|
-
* @param {UTXO[]} inputUTXOs - The UTXOs to use as inputs for the staking
|
|
1775
|
-
* transaction.
|
|
1776
|
-
* @returns {Psbt} - The psbt.
|
|
1777
|
-
*/
|
|
1778
|
-
toStakingPsbt(stakingTx, inputUTXOs) {
|
|
1779
|
-
return stakingPsbt(
|
|
1780
|
-
stakingTx,
|
|
1781
|
-
this.network,
|
|
1782
|
-
inputUTXOs,
|
|
1783
|
-
isTaproot(
|
|
1784
|
-
this.stakerInfo.address,
|
|
1785
|
-
this.network
|
|
1786
|
-
) ? Buffer.from(this.stakerInfo.publicKeyNoCoordHex, "hex") : void 0
|
|
1787
|
-
);
|
|
1788
|
-
}
|
|
1789
|
-
};
|
|
1790
|
-
|
|
1791
|
-
// src/utils/babylon.ts
|
|
1792
|
-
import { fromBech32 } from "@cosmjs/encoding";
|
|
1793
|
-
var isValidBabylonAddress = (address4) => {
|
|
1794
|
-
try {
|
|
1795
|
-
const { prefix } = fromBech32(address4);
|
|
1796
|
-
return prefix === "bbn";
|
|
1797
|
-
} catch (error) {
|
|
1798
|
-
return false;
|
|
1799
|
-
}
|
|
1800
|
-
};
|
|
1801
|
-
|
|
1802
|
-
// src/utils/staking/param.ts
|
|
1803
|
-
var getBabylonParamByBtcHeight = (height, babylonParamsVersions) => {
|
|
1804
|
-
const sortedParams = [...babylonParamsVersions].sort(
|
|
1805
|
-
(a, b) => b.btcActivationHeight - a.btcActivationHeight
|
|
1806
|
-
);
|
|
1807
|
-
const params = sortedParams.find(
|
|
1808
|
-
(p) => height >= p.btcActivationHeight
|
|
1809
|
-
);
|
|
1810
|
-
if (!params)
|
|
1811
|
-
throw new Error(`Babylon params not found for height ${height}`);
|
|
1812
|
-
return params;
|
|
1813
|
-
};
|
|
1814
|
-
var getBabylonParamByVersion = (version, babylonParams) => {
|
|
1815
|
-
const params = babylonParams.find((p) => p.version === version);
|
|
1816
|
-
if (!params)
|
|
1817
|
-
throw new Error(`Babylon params not found for version ${version}`);
|
|
1818
|
-
return params;
|
|
1819
1977
|
};
|
|
1820
1978
|
|
|
1821
1979
|
// src/staking/manager.ts
|
|
1822
|
-
import {
|
|
1823
|
-
import {
|
|
1824
|
-
btccheckpoint,
|
|
1825
|
-
btcstaking,
|
|
1826
|
-
btcstakingtx
|
|
1827
|
-
} from "@babylonlabs-io/babylon-proto-ts";
|
|
1980
|
+
import { btccheckpoint, btcstaking, btcstakingtx } from "@babylonlabs-io/babylon-proto-ts";
|
|
1828
1981
|
import {
|
|
1829
1982
|
BIP322Sig,
|
|
1830
1983
|
BTCSigType
|
|
1831
1984
|
} from "@babylonlabs-io/babylon-proto-ts/dist/generated/babylon/btcstaking/v1/pop";
|
|
1985
|
+
import { Psbt as Psbt3, Transaction as Transaction4 } from "bitcoinjs-lib";
|
|
1832
1986
|
|
|
1833
1987
|
// src/constants/registry.ts
|
|
1834
1988
|
var BABYLON_REGISTRY_TYPE_URLS = {
|
|
1835
|
-
MsgCreateBTCDelegation: "/babylon.btcstaking.v1.MsgCreateBTCDelegation"
|
|
1989
|
+
MsgCreateBTCDelegation: "/babylon.btcstaking.v1.MsgCreateBTCDelegation",
|
|
1990
|
+
MsgBtcStakeExpand: "/babylon.btcstaking.v1.MsgBtcStakeExpand"
|
|
1836
1991
|
};
|
|
1837
1992
|
|
|
1838
1993
|
// src/utils/index.ts
|
|
1839
1994
|
var reverseBuffer = (buffer) => {
|
|
1840
1995
|
const clonedBuffer = new Uint8Array(buffer);
|
|
1841
|
-
if (clonedBuffer.length < 1)
|
|
1842
|
-
return clonedBuffer;
|
|
1996
|
+
if (clonedBuffer.length < 1) return clonedBuffer;
|
|
1843
1997
|
for (let i = 0, j = clonedBuffer.length - 1; i < clonedBuffer.length / 2; i++, j--) {
|
|
1844
1998
|
let tmp = clonedBuffer[i];
|
|
1845
1999
|
clonedBuffer[i] = clonedBuffer[j];
|
|
@@ -1848,28 +2002,56 @@ var reverseBuffer = (buffer) => {
|
|
|
1848
2002
|
return clonedBuffer;
|
|
1849
2003
|
};
|
|
1850
2004
|
|
|
2005
|
+
// src/utils/pop.ts
|
|
2006
|
+
import { sha256 } from "bitcoinjs-lib/src/crypto";
|
|
2007
|
+
|
|
2008
|
+
// src/constants/staking.ts
|
|
2009
|
+
var STAKING_MODULE_ADDRESS = "bbn13837feaxn8t0zvwcjwhw7lhpgdcx4s36eqteah";
|
|
2010
|
+
|
|
2011
|
+
// src/utils/pop.ts
|
|
2012
|
+
function createStakerPopContext(chainId, popContextVersion = 0) {
|
|
2013
|
+
const contextString = `btcstaking/${popContextVersion}/staker_pop/${chainId}/${STAKING_MODULE_ADDRESS}`;
|
|
2014
|
+
return sha256(Buffer.from(contextString, "utf8")).toString("hex");
|
|
2015
|
+
}
|
|
2016
|
+
function buildPopMessage(bech32Address, currentHeight, chainId, upgradeConfig) {
|
|
2017
|
+
if (chainId !== void 0 && upgradeConfig?.upgradeHeight !== void 0 && upgradeConfig.version !== void 0 && currentHeight !== void 0 && currentHeight >= upgradeConfig.upgradeHeight) {
|
|
2018
|
+
const contextHash = createStakerPopContext(chainId, upgradeConfig.version);
|
|
2019
|
+
return contextHash + bech32Address;
|
|
2020
|
+
}
|
|
2021
|
+
return bech32Address;
|
|
2022
|
+
}
|
|
2023
|
+
|
|
2024
|
+
// src/utils/staking/param.ts
|
|
2025
|
+
var getBabylonParamByBtcHeight = (height, babylonParamsVersions) => {
|
|
2026
|
+
const sortedParams = [...babylonParamsVersions].sort(
|
|
2027
|
+
(a, b) => b.btcActivationHeight - a.btcActivationHeight
|
|
2028
|
+
);
|
|
2029
|
+
const params = sortedParams.find(
|
|
2030
|
+
(p) => height >= p.btcActivationHeight
|
|
2031
|
+
);
|
|
2032
|
+
if (!params) throw new Error(`Babylon params not found for height ${height}`);
|
|
2033
|
+
return params;
|
|
2034
|
+
};
|
|
2035
|
+
var getBabylonParamByVersion = (version, babylonParams) => {
|
|
2036
|
+
const params = babylonParams.find((p) => p.version === version);
|
|
2037
|
+
if (!params) throw new Error(`Babylon params not found for version ${version}`);
|
|
2038
|
+
return params;
|
|
2039
|
+
};
|
|
2040
|
+
|
|
1851
2041
|
// src/staking/manager.ts
|
|
1852
|
-
var SigningStep = /* @__PURE__ */ ((SigningStep2) => {
|
|
1853
|
-
SigningStep2["STAKING_SLASHING"] = "staking-slashing";
|
|
1854
|
-
SigningStep2["UNBONDING_SLASHING"] = "unbonding-slashing";
|
|
1855
|
-
SigningStep2["PROOF_OF_POSSESSION"] = "proof-of-possession";
|
|
1856
|
-
SigningStep2["CREATE_BTC_DELEGATION_MSG"] = "create-btc-delegation-msg";
|
|
1857
|
-
SigningStep2["STAKING"] = "staking";
|
|
1858
|
-
SigningStep2["UNBONDING"] = "unbonding";
|
|
1859
|
-
SigningStep2["WITHDRAW_STAKING_EXPIRED"] = "withdraw-staking-expired";
|
|
1860
|
-
SigningStep2["WITHDRAW_EARLY_UNBONDED"] = "withdraw-early-unbonded";
|
|
1861
|
-
SigningStep2["WITHDRAW_SLASHING"] = "withdraw-slashing";
|
|
1862
|
-
return SigningStep2;
|
|
1863
|
-
})(SigningStep || {});
|
|
1864
2042
|
var BabylonBtcStakingManager = class {
|
|
1865
|
-
constructor(network, stakingParams, btcProvider, babylonProvider) {
|
|
2043
|
+
constructor(network, stakingParams, btcProvider, babylonProvider, ee, upgradeConfig) {
|
|
1866
2044
|
this.network = network;
|
|
2045
|
+
this.stakingParams = stakingParams;
|
|
1867
2046
|
this.btcProvider = btcProvider;
|
|
1868
2047
|
this.babylonProvider = babylonProvider;
|
|
2048
|
+
this.ee = ee;
|
|
2049
|
+
this.network = network;
|
|
1869
2050
|
if (stakingParams.length === 0) {
|
|
1870
2051
|
throw new Error("No staking parameters provided");
|
|
1871
2052
|
}
|
|
1872
2053
|
this.stakingParams = stakingParams;
|
|
2054
|
+
this.upgradeConfig = upgradeConfig;
|
|
1873
2055
|
}
|
|
1874
2056
|
/**
|
|
1875
2057
|
* Creates a signed Pre-Staking Registration transaction that is ready to be
|
|
@@ -1884,7 +2066,7 @@ var BabylonBtcStakingManager = class {
|
|
|
1884
2066
|
* fee rate is above 1. If the fee rate is too low, the transaction will not
|
|
1885
2067
|
* be included in a block.
|
|
1886
2068
|
* @param babylonAddress - The Babylon bech32 encoded address of the staker.
|
|
1887
|
-
* @returns The signed babylon pre-staking registration transaction in base64
|
|
2069
|
+
* @returns The signed babylon pre-staking registration transaction in base64
|
|
1888
2070
|
* format.
|
|
1889
2071
|
*/
|
|
1890
2072
|
async preStakeRegistrationBabylonTransaction(stakerBtcInfo, stakingInput, babylonBtcTipHeight, inputUTXOs, feeRate, babylonAddress) {
|
|
@@ -1897,23 +2079,17 @@ var BabylonBtcStakingManager = class {
|
|
|
1897
2079
|
if (!isValidBabylonAddress(babylonAddress)) {
|
|
1898
2080
|
throw new Error("Invalid Babylon address");
|
|
1899
2081
|
}
|
|
1900
|
-
const params = getBabylonParamByBtcHeight(
|
|
1901
|
-
babylonBtcTipHeight,
|
|
1902
|
-
this.stakingParams
|
|
1903
|
-
);
|
|
2082
|
+
const params = getBabylonParamByBtcHeight(babylonBtcTipHeight, this.stakingParams);
|
|
1904
2083
|
const staking = new Staking(
|
|
1905
2084
|
this.network,
|
|
1906
2085
|
stakerBtcInfo,
|
|
1907
2086
|
params,
|
|
1908
|
-
stakingInput.
|
|
2087
|
+
stakingInput.finalityProviderPksNoCoordHex,
|
|
1909
2088
|
stakingInput.stakingTimelock
|
|
1910
2089
|
);
|
|
1911
|
-
const { transaction } = staking.createStakingTransaction(
|
|
1912
|
-
stakingInput.stakingAmountSat,
|
|
1913
|
-
inputUTXOs,
|
|
1914
|
-
feeRate
|
|
1915
|
-
);
|
|
2090
|
+
const { transaction } = staking.createStakingTransaction(stakingInput.stakingAmountSat, inputUTXOs, feeRate);
|
|
1916
2091
|
const msg = await this.createBtcDelegationMsg(
|
|
2092
|
+
"delegation:create",
|
|
1917
2093
|
staking,
|
|
1918
2094
|
stakingInput,
|
|
1919
2095
|
transaction,
|
|
@@ -1921,23 +2097,127 @@ var BabylonBtcStakingManager = class {
|
|
|
1921
2097
|
stakerBtcInfo,
|
|
1922
2098
|
params
|
|
1923
2099
|
);
|
|
2100
|
+
this.ee?.emit("delegation:create", {
|
|
2101
|
+
type: "create-btc-delegation-msg"
|
|
2102
|
+
});
|
|
1924
2103
|
return {
|
|
1925
|
-
signedBabylonTx: await this.babylonProvider.signTransaction(
|
|
1926
|
-
"create-btc-delegation-msg" /* CREATE_BTC_DELEGATION_MSG */,
|
|
1927
|
-
msg
|
|
1928
|
-
),
|
|
2104
|
+
signedBabylonTx: await this.babylonProvider.signTransaction(msg),
|
|
1929
2105
|
stakingTx: transaction
|
|
1930
2106
|
};
|
|
1931
2107
|
}
|
|
1932
2108
|
/**
|
|
1933
|
-
*
|
|
1934
|
-
*
|
|
1935
|
-
|
|
2109
|
+
* Create a signed staking expansion transaction that is ready to be sent to
|
|
2110
|
+
* the Babylon chain.
|
|
2111
|
+
*/
|
|
2112
|
+
async stakingExpansionRegistrationBabylonTransaction(stakerBtcInfo, stakingInput, babylonBtcTipHeight, inputUTXOs, feeRate, babylonAddress, previousStakingTxInfo) {
|
|
2113
|
+
validateStakingExpansionInputs({
|
|
2114
|
+
babylonBtcTipHeight,
|
|
2115
|
+
inputUTXOs,
|
|
2116
|
+
stakingInput,
|
|
2117
|
+
previousStakingInput: previousStakingTxInfo.stakingInput,
|
|
2118
|
+
babylonAddress
|
|
2119
|
+
});
|
|
2120
|
+
const params = getBabylonParamByBtcHeight(babylonBtcTipHeight, this.stakingParams);
|
|
2121
|
+
const paramsForPreviousStakingTx = getBabylonParamByVersion(previousStakingTxInfo.paramVersion, this.stakingParams);
|
|
2122
|
+
const stakingInstance = new Staking(
|
|
2123
|
+
this.network,
|
|
2124
|
+
stakerBtcInfo,
|
|
2125
|
+
params,
|
|
2126
|
+
stakingInput.finalityProviderPksNoCoordHex,
|
|
2127
|
+
stakingInput.stakingTimelock
|
|
2128
|
+
);
|
|
2129
|
+
const { transaction: stakingExpansionTx, fundingUTXO } = stakingInstance.createStakingExpansionTransaction(
|
|
2130
|
+
stakingInput.stakingAmountSat,
|
|
2131
|
+
inputUTXOs,
|
|
2132
|
+
feeRate,
|
|
2133
|
+
paramsForPreviousStakingTx,
|
|
2134
|
+
previousStakingTxInfo
|
|
2135
|
+
);
|
|
2136
|
+
let fundingTx;
|
|
2137
|
+
try {
|
|
2138
|
+
fundingTx = await this.btcProvider.getTransactionHex(fundingUTXO.txid);
|
|
2139
|
+
} catch (error) {
|
|
2140
|
+
throw StakingError.fromUnknown(
|
|
2141
|
+
error,
|
|
2142
|
+
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
2143
|
+
"Failed to retrieve funding transaction hex"
|
|
2144
|
+
);
|
|
2145
|
+
}
|
|
2146
|
+
const msg = await this.createBtcDelegationMsg(
|
|
2147
|
+
"delegation:expand",
|
|
2148
|
+
stakingInstance,
|
|
2149
|
+
stakingInput,
|
|
2150
|
+
stakingExpansionTx,
|
|
2151
|
+
babylonAddress,
|
|
2152
|
+
stakerBtcInfo,
|
|
2153
|
+
params,
|
|
2154
|
+
{
|
|
2155
|
+
delegationExpansionInfo: {
|
|
2156
|
+
previousStakingTx: previousStakingTxInfo.stakingTx,
|
|
2157
|
+
fundingTx: Transaction4.fromHex(fundingTx)
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
);
|
|
2161
|
+
this.ee?.emit("delegation:expand", {
|
|
2162
|
+
type: "create-btc-delegation-msg"
|
|
2163
|
+
});
|
|
2164
|
+
return {
|
|
2165
|
+
signedBabylonTx: await this.babylonProvider.signTransaction(msg),
|
|
2166
|
+
stakingTx: stakingExpansionTx
|
|
2167
|
+
};
|
|
2168
|
+
}
|
|
2169
|
+
/**
|
|
2170
|
+
* Estimates the transaction fee for a BTC staking expansion transaction.
|
|
2171
|
+
*
|
|
2172
|
+
* @param {StakerInfo} stakerBtcInfo - The staker's Bitcoin information
|
|
2173
|
+
* including address and public key
|
|
2174
|
+
* @param {number} babylonBtcTipHeight - The current Babylon BTC tip height
|
|
2175
|
+
* used to determine staking parameters
|
|
2176
|
+
* @param {StakingInputs} stakingInput - The new staking input parameters for
|
|
2177
|
+
* the expansion
|
|
2178
|
+
* @param {UTXO[]} inputUTXOs - Available UTXOs that can be used for funding
|
|
2179
|
+
* the expansion transaction
|
|
2180
|
+
* @param {number} feeRate - Fee rate in satoshis per byte for the expansion
|
|
2181
|
+
* transaction
|
|
2182
|
+
* @param {Object} previousStakingTxInfo - Information about the previous
|
|
2183
|
+
* staking transaction being expanded
|
|
2184
|
+
* @returns {number} - The estimated transaction fee in satoshis
|
|
2185
|
+
* @throws {Error} - If validation fails or the fee cannot be calculated
|
|
2186
|
+
*/
|
|
2187
|
+
estimateBtcStakingExpansionFee(stakerBtcInfo, babylonBtcTipHeight, stakingInput, inputUTXOs, feeRate, previousStakingTxInfo) {
|
|
2188
|
+
validateStakingExpansionInputs({
|
|
2189
|
+
babylonBtcTipHeight,
|
|
2190
|
+
inputUTXOs,
|
|
2191
|
+
stakingInput,
|
|
2192
|
+
previousStakingInput: previousStakingTxInfo.stakingInput
|
|
2193
|
+
});
|
|
2194
|
+
const params = getBabylonParamByBtcHeight(babylonBtcTipHeight, this.stakingParams);
|
|
2195
|
+
const paramsForPreviousStakingTx = getBabylonParamByVersion(previousStakingTxInfo.paramVersion, this.stakingParams);
|
|
2196
|
+
const stakingInstance = new Staking(
|
|
2197
|
+
this.network,
|
|
2198
|
+
stakerBtcInfo,
|
|
2199
|
+
params,
|
|
2200
|
+
stakingInput.finalityProviderPksNoCoordHex,
|
|
2201
|
+
stakingInput.stakingTimelock
|
|
2202
|
+
);
|
|
2203
|
+
const { fee } = stakingInstance.createStakingExpansionTransaction(
|
|
2204
|
+
stakingInput.stakingAmountSat,
|
|
2205
|
+
inputUTXOs,
|
|
2206
|
+
feeRate,
|
|
2207
|
+
paramsForPreviousStakingTx,
|
|
2208
|
+
previousStakingTxInfo
|
|
2209
|
+
);
|
|
2210
|
+
return fee;
|
|
2211
|
+
}
|
|
2212
|
+
/**
|
|
2213
|
+
* Creates a signed post-staking registration transaction that is ready to be
|
|
2214
|
+
* sent to the Babylon chain. This is used when a staking transaction is
|
|
2215
|
+
* already created and included in a BTC block and we want to register it on
|
|
1936
2216
|
* the Babylon chain.
|
|
1937
2217
|
* @param stakerBtcInfo - The staker BTC info which includes the BTC address
|
|
1938
2218
|
* and the no-coord public key in hex format.
|
|
1939
2219
|
* @param stakingTx - The staking transaction.
|
|
1940
|
-
* @param stakingTxHeight - The BTC height in which the staking transaction
|
|
2220
|
+
* @param stakingTxHeight - The BTC height in which the staking transaction
|
|
1941
2221
|
* is included.
|
|
1942
2222
|
* @param stakingInput - The staking inputs.
|
|
1943
2223
|
* @param inclusionProof - Merkle Proof of Inclusion: Verifies transaction
|
|
@@ -1954,30 +2234,29 @@ var BabylonBtcStakingManager = class {
|
|
|
1954
2234
|
this.network,
|
|
1955
2235
|
stakerBtcInfo,
|
|
1956
2236
|
params,
|
|
1957
|
-
stakingInput.
|
|
2237
|
+
stakingInput.finalityProviderPksNoCoordHex,
|
|
1958
2238
|
stakingInput.stakingTimelock
|
|
1959
2239
|
);
|
|
1960
2240
|
const scripts = stakingInstance.buildScripts();
|
|
1961
2241
|
const stakingOutputInfo = deriveStakingOutputInfo(scripts, this.network);
|
|
1962
|
-
findMatchingTxOutputIndex(
|
|
1963
|
-
stakingTx,
|
|
1964
|
-
stakingOutputInfo.outputAddress,
|
|
1965
|
-
this.network
|
|
1966
|
-
);
|
|
2242
|
+
findMatchingTxOutputIndex(stakingTx, stakingOutputInfo.outputAddress, this.network);
|
|
1967
2243
|
const delegationMsg = await this.createBtcDelegationMsg(
|
|
2244
|
+
"delegation:register",
|
|
1968
2245
|
stakingInstance,
|
|
1969
2246
|
stakingInput,
|
|
1970
2247
|
stakingTx,
|
|
1971
2248
|
babylonAddress,
|
|
1972
2249
|
stakerBtcInfo,
|
|
1973
2250
|
params,
|
|
1974
|
-
|
|
2251
|
+
{
|
|
2252
|
+
inclusionProof: this.getInclusionProof(inclusionProof)
|
|
2253
|
+
}
|
|
1975
2254
|
);
|
|
2255
|
+
this.ee?.emit("delegation:register", {
|
|
2256
|
+
type: "create-btc-delegation-msg"
|
|
2257
|
+
});
|
|
1976
2258
|
return {
|
|
1977
|
-
signedBabylonTx: await this.babylonProvider.signTransaction(
|
|
1978
|
-
"create-btc-delegation-msg" /* CREATE_BTC_DELEGATION_MSG */,
|
|
1979
|
-
delegationMsg
|
|
1980
|
-
)
|
|
2259
|
+
signedBabylonTx: await this.babylonProvider.signTransaction(delegationMsg)
|
|
1981
2260
|
};
|
|
1982
2261
|
}
|
|
1983
2262
|
/**
|
|
@@ -1998,26 +2277,19 @@ var BabylonBtcStakingManager = class {
|
|
|
1998
2277
|
if (babylonBtcTipHeight === 0) {
|
|
1999
2278
|
throw new Error("Babylon BTC tip height cannot be 0");
|
|
2000
2279
|
}
|
|
2001
|
-
const params = getBabylonParamByBtcHeight(
|
|
2002
|
-
babylonBtcTipHeight,
|
|
2003
|
-
this.stakingParams
|
|
2004
|
-
);
|
|
2280
|
+
const params = getBabylonParamByBtcHeight(babylonBtcTipHeight, this.stakingParams);
|
|
2005
2281
|
const staking = new Staking(
|
|
2006
2282
|
this.network,
|
|
2007
2283
|
stakerBtcInfo,
|
|
2008
2284
|
params,
|
|
2009
|
-
stakingInput.
|
|
2285
|
+
stakingInput.finalityProviderPksNoCoordHex,
|
|
2010
2286
|
stakingInput.stakingTimelock
|
|
2011
2287
|
);
|
|
2012
|
-
const { fee: stakingFee } = staking.createStakingTransaction(
|
|
2013
|
-
stakingInput.stakingAmountSat,
|
|
2014
|
-
inputUTXOs,
|
|
2015
|
-
feeRate
|
|
2016
|
-
);
|
|
2288
|
+
const { fee: stakingFee } = staking.createStakingTransaction(stakingInput.stakingAmountSat, inputUTXOs, feeRate);
|
|
2017
2289
|
return stakingFee;
|
|
2018
2290
|
}
|
|
2019
2291
|
/**
|
|
2020
|
-
* Creates a signed staking transaction that is ready to be sent to the BTC
|
|
2292
|
+
* Creates a signed staking transaction that is ready to be sent to the BTC
|
|
2021
2293
|
* network.
|
|
2022
2294
|
* @param stakerBtcInfo - The staker BTC info which includes the BTC address
|
|
2023
2295
|
* and the no-coord public key in hex format.
|
|
@@ -2038,18 +2310,129 @@ var BabylonBtcStakingManager = class {
|
|
|
2038
2310
|
this.network,
|
|
2039
2311
|
stakerBtcInfo,
|
|
2040
2312
|
params,
|
|
2041
|
-
stakingInput.
|
|
2313
|
+
stakingInput.finalityProviderPksNoCoordHex,
|
|
2042
2314
|
stakingInput.stakingTimelock
|
|
2043
2315
|
);
|
|
2044
|
-
const stakingPsbt2 = staking.toStakingPsbt(
|
|
2045
|
-
|
|
2046
|
-
|
|
2316
|
+
const stakingPsbt2 = staking.toStakingPsbt(unsignedStakingTx, inputUTXOs);
|
|
2317
|
+
const contracts = [
|
|
2318
|
+
{
|
|
2319
|
+
id: "babylon:staking" /* STAKING */,
|
|
2320
|
+
params: {
|
|
2321
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2322
|
+
finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
|
|
2323
|
+
covenantPks: params.covenantNoCoordPks,
|
|
2324
|
+
covenantThreshold: params.covenantQuorum,
|
|
2325
|
+
minUnbondingTime: params.unbondingTime,
|
|
2326
|
+
stakingDuration: stakingInput.stakingTimelock
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
];
|
|
2330
|
+
this.ee?.emit("delegation:stake", {
|
|
2331
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2332
|
+
finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
|
|
2333
|
+
covenantPks: params.covenantNoCoordPks,
|
|
2334
|
+
covenantThreshold: params.covenantQuorum,
|
|
2335
|
+
unbondingTimeBlocks: params.unbondingTime,
|
|
2336
|
+
stakingDuration: stakingInput.stakingTimelock,
|
|
2337
|
+
type: "staking"
|
|
2338
|
+
});
|
|
2339
|
+
const signedStakingPsbtHex = await this.btcProvider.signPsbt(stakingPsbt2.toHex(), {
|
|
2340
|
+
contracts,
|
|
2341
|
+
action: {
|
|
2342
|
+
name: "sign-btc-staking-transaction" /* SIGN_BTC_STAKING_TRANSACTION */
|
|
2343
|
+
}
|
|
2344
|
+
});
|
|
2345
|
+
return Psbt3.fromHex(signedStakingPsbtHex).extractTransaction();
|
|
2346
|
+
}
|
|
2347
|
+
/**
|
|
2348
|
+
* Creates a signed staking expansion transaction that is ready to be sent to
|
|
2349
|
+
* the BTC network.
|
|
2350
|
+
*
|
|
2351
|
+
* @param {StakerInfo} stakerBtcInfo - The staker's BTC information including
|
|
2352
|
+
* address and public key
|
|
2353
|
+
* @param {StakingInputs} stakingInput - The staking inputs for the expansion
|
|
2354
|
+
* @param {Transaction} unsignedStakingExpansionTx - The unsigned staking
|
|
2355
|
+
* expansion transaction
|
|
2356
|
+
* @param {UTXO[]} inputUTXOs - Available UTXOs for the funding input
|
|
2357
|
+
* @param {number} stakingParamsVersion - The version of staking parameters
|
|
2358
|
+
* that was used when registering the staking expansion delegation.
|
|
2359
|
+
* @param {Object} previousStakingTxInfo - Information about the previous
|
|
2360
|
+
* staking transaction
|
|
2361
|
+
* @param {Array} covenantStakingExpansionSignatures - Covenant committee
|
|
2362
|
+
* signatures for the expansion
|
|
2363
|
+
* @returns {Promise<Transaction>} The fully signed staking expansion
|
|
2364
|
+
* transaction
|
|
2365
|
+
* @throws {Error} If signing fails, validation fails, or required data is
|
|
2366
|
+
* missing
|
|
2367
|
+
*/
|
|
2368
|
+
async createSignedBtcStakingExpansionTransaction(stakerBtcInfo, stakingInput, unsignedStakingExpansionTx, inputUTXOs, stakingParamsVersion, previousStakingTxInfo, covenantStakingExpansionSignatures) {
|
|
2369
|
+
validateStakingExpansionInputs({
|
|
2370
|
+
inputUTXOs,
|
|
2371
|
+
stakingInput,
|
|
2372
|
+
previousStakingInput: previousStakingTxInfo.stakingInput
|
|
2373
|
+
});
|
|
2374
|
+
const params = getBabylonParamByVersion(stakingParamsVersion, this.stakingParams);
|
|
2375
|
+
if (inputUTXOs.length === 0) {
|
|
2376
|
+
throw new Error("No input UTXOs provided");
|
|
2377
|
+
}
|
|
2378
|
+
const staking = new Staking(
|
|
2379
|
+
this.network,
|
|
2380
|
+
stakerBtcInfo,
|
|
2381
|
+
params,
|
|
2382
|
+
stakingInput.finalityProviderPksNoCoordHex,
|
|
2383
|
+
stakingInput.stakingTimelock
|
|
2047
2384
|
);
|
|
2048
|
-
const
|
|
2049
|
-
|
|
2050
|
-
|
|
2385
|
+
const previousParams = getBabylonParamByVersion(previousStakingTxInfo.paramVersion, this.stakingParams);
|
|
2386
|
+
const stakingExpansionPsbt2 = staking.toStakingExpansionPsbt(
|
|
2387
|
+
unsignedStakingExpansionTx,
|
|
2388
|
+
inputUTXOs,
|
|
2389
|
+
previousParams,
|
|
2390
|
+
previousStakingTxInfo
|
|
2391
|
+
);
|
|
2392
|
+
const contracts = [
|
|
2393
|
+
{
|
|
2394
|
+
id: "babylon:staking" /* STAKING */,
|
|
2395
|
+
params: {
|
|
2396
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2397
|
+
finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
|
|
2398
|
+
covenantPks: params.covenantNoCoordPks,
|
|
2399
|
+
covenantThreshold: params.covenantQuorum,
|
|
2400
|
+
minUnbondingTime: params.unbondingTime,
|
|
2401
|
+
stakingDuration: stakingInput.stakingTimelock
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
];
|
|
2405
|
+
this.ee?.emit("delegation:stake", {
|
|
2406
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2407
|
+
finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
|
|
2408
|
+
covenantPks: params.covenantNoCoordPks,
|
|
2409
|
+
covenantThreshold: params.covenantQuorum,
|
|
2410
|
+
unbondingTimeBlocks: params.unbondingTime,
|
|
2411
|
+
stakingDuration: stakingInput.stakingTimelock,
|
|
2412
|
+
type: "staking"
|
|
2413
|
+
});
|
|
2414
|
+
const signedStakingPsbtHex = await this.btcProvider.signPsbt(stakingExpansionPsbt2.toHex(), {
|
|
2415
|
+
contracts,
|
|
2416
|
+
action: {
|
|
2417
|
+
name: "sign-btc-staking-transaction" /* SIGN_BTC_STAKING_TRANSACTION */
|
|
2418
|
+
}
|
|
2419
|
+
});
|
|
2420
|
+
const signedStakingExpansionTx = Psbt3.fromHex(signedStakingPsbtHex).extractTransaction();
|
|
2421
|
+
if (signedStakingExpansionTx.getId() !== unsignedStakingExpansionTx.getId()) {
|
|
2422
|
+
throw new Error("Staking expansion transaction hash does not match the computed hash");
|
|
2423
|
+
}
|
|
2424
|
+
const covenantBuffers = previousParams.covenantNoCoordPks.map((covenant) => Buffer.from(covenant, "hex"));
|
|
2425
|
+
const witness = createCovenantWitness(
|
|
2426
|
+
// The first input of the staking expansion transaction is the previous
|
|
2427
|
+
// staking output. We will attach the covenant signatures to this input
|
|
2428
|
+
// to unbond the previousstaking output.
|
|
2429
|
+
signedStakingExpansionTx.ins[0].witness,
|
|
2430
|
+
covenantBuffers,
|
|
2431
|
+
covenantStakingExpansionSignatures,
|
|
2432
|
+
previousParams.covenantQuorum
|
|
2051
2433
|
);
|
|
2052
|
-
|
|
2434
|
+
signedStakingExpansionTx.ins[0].witness = witness;
|
|
2435
|
+
return signedStakingExpansionTx;
|
|
2053
2436
|
}
|
|
2054
2437
|
/**
|
|
2055
2438
|
* Creates a partial signed unbonding transaction that is only signed by the
|
|
@@ -2066,36 +2449,64 @@ var BabylonBtcStakingManager = class {
|
|
|
2066
2449
|
* @returns The partial signed unbonding transaction and its fee.
|
|
2067
2450
|
*/
|
|
2068
2451
|
async createPartialSignedBtcUnbondingTransaction(stakerBtcInfo, stakingInput, stakingParamsVersion, stakingTx) {
|
|
2069
|
-
const params = getBabylonParamByVersion(
|
|
2070
|
-
stakingParamsVersion,
|
|
2071
|
-
this.stakingParams
|
|
2072
|
-
);
|
|
2452
|
+
const params = getBabylonParamByVersion(stakingParamsVersion, this.stakingParams);
|
|
2073
2453
|
const staking = new Staking(
|
|
2074
2454
|
this.network,
|
|
2075
2455
|
stakerBtcInfo,
|
|
2076
2456
|
params,
|
|
2077
|
-
stakingInput.
|
|
2457
|
+
stakingInput.finalityProviderPksNoCoordHex,
|
|
2078
2458
|
stakingInput.stakingTimelock
|
|
2079
2459
|
);
|
|
2080
|
-
const {
|
|
2081
|
-
transaction: unbondingTx,
|
|
2082
|
-
fee
|
|
2083
|
-
} = staking.createUnbondingTransaction(stakingTx);
|
|
2460
|
+
const { transaction: unbondingTx, fee } = staking.createUnbondingTransaction(stakingTx);
|
|
2084
2461
|
const psbt = staking.toUnbondingPsbt(unbondingTx, stakingTx);
|
|
2085
|
-
const
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2462
|
+
const contracts = [
|
|
2463
|
+
{
|
|
2464
|
+
id: "babylon:staking" /* STAKING */,
|
|
2465
|
+
params: {
|
|
2466
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2467
|
+
finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
|
|
2468
|
+
covenantPks: params.covenantNoCoordPks,
|
|
2469
|
+
covenantThreshold: params.covenantQuorum,
|
|
2470
|
+
minUnbondingTime: params.unbondingTime,
|
|
2471
|
+
stakingDuration: stakingInput.stakingTimelock
|
|
2472
|
+
}
|
|
2473
|
+
},
|
|
2474
|
+
{
|
|
2475
|
+
id: "babylon:unbonding" /* UNBONDING */,
|
|
2476
|
+
params: {
|
|
2477
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2478
|
+
finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
|
|
2479
|
+
covenantPks: params.covenantNoCoordPks,
|
|
2480
|
+
covenantThreshold: params.covenantQuorum,
|
|
2481
|
+
unbondingTimeBlocks: params.unbondingTime,
|
|
2482
|
+
unbondingFeeSat: params.unbondingFeeSat
|
|
2483
|
+
}
|
|
2484
|
+
}
|
|
2485
|
+
];
|
|
2486
|
+
this.ee?.emit("delegation:unbond", {
|
|
2487
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2488
|
+
finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
|
|
2489
|
+
covenantPks: params.covenantNoCoordPks,
|
|
2490
|
+
covenantThreshold: params.covenantQuorum,
|
|
2491
|
+
stakingDuration: stakingInput.stakingTimelock,
|
|
2492
|
+
unbondingTimeBlocks: params.unbondingTime,
|
|
2493
|
+
unbondingFeeSat: params.unbondingFeeSat,
|
|
2494
|
+
type: "unbonding"
|
|
2495
|
+
});
|
|
2496
|
+
const signedUnbondingPsbtHex = await this.btcProvider.signPsbt(psbt.toHex(), {
|
|
2497
|
+
contracts,
|
|
2498
|
+
action: {
|
|
2499
|
+
name: "sign-btc-unbonding-transaction" /* SIGN_BTC_UNBONDING_TRANSACTION */
|
|
2500
|
+
}
|
|
2501
|
+
});
|
|
2502
|
+
const signedUnbondingTx = Psbt3.fromHex(signedUnbondingPsbtHex).extractTransaction();
|
|
2092
2503
|
return {
|
|
2093
2504
|
transaction: signedUnbondingTx,
|
|
2094
2505
|
fee
|
|
2095
2506
|
};
|
|
2096
2507
|
}
|
|
2097
2508
|
/**
|
|
2098
|
-
* Creates a signed unbonding transaction that is ready to be sent to the BTC
|
|
2509
|
+
* Creates a signed unbonding transaction that is ready to be sent to the BTC
|
|
2099
2510
|
* network.
|
|
2100
2511
|
* @param stakerBtcInfo - The staker BTC info which includes the BTC address
|
|
2101
2512
|
* and the no-coord public key in hex format.
|
|
@@ -2109,27 +2520,17 @@ var BabylonBtcStakingManager = class {
|
|
|
2109
2520
|
* @returns The signed unbonding transaction and its fee.
|
|
2110
2521
|
*/
|
|
2111
2522
|
async createSignedBtcUnbondingTransaction(stakerBtcInfo, stakingInput, stakingParamsVersion, stakingTx, unsignedUnbondingTx, covenantUnbondingSignatures) {
|
|
2112
|
-
const params = getBabylonParamByVersion(
|
|
2113
|
-
|
|
2114
|
-
this.stakingParams
|
|
2115
|
-
);
|
|
2116
|
-
const {
|
|
2117
|
-
transaction: signedUnbondingTx,
|
|
2118
|
-
fee
|
|
2119
|
-
} = await this.createPartialSignedBtcUnbondingTransaction(
|
|
2523
|
+
const params = getBabylonParamByVersion(stakingParamsVersion, this.stakingParams);
|
|
2524
|
+
const { transaction: signedUnbondingTx, fee } = await this.createPartialSignedBtcUnbondingTransaction(
|
|
2120
2525
|
stakerBtcInfo,
|
|
2121
2526
|
stakingInput,
|
|
2122
2527
|
stakingParamsVersion,
|
|
2123
2528
|
stakingTx
|
|
2124
2529
|
);
|
|
2125
2530
|
if (signedUnbondingTx.getId() !== unsignedUnbondingTx.getId()) {
|
|
2126
|
-
throw new Error(
|
|
2127
|
-
"Unbonding transaction hash does not match the computed hash"
|
|
2128
|
-
);
|
|
2531
|
+
throw new Error("Unbonding transaction hash does not match the computed hash");
|
|
2129
2532
|
}
|
|
2130
|
-
const covenantBuffers = params.covenantNoCoordPks.map(
|
|
2131
|
-
(covenant) => Buffer.from(covenant, "hex")
|
|
2132
|
-
);
|
|
2533
|
+
const covenantBuffers = params.covenantNoCoordPks.map((covenant) => Buffer.from(covenant, "hex"));
|
|
2133
2534
|
const witness = createCovenantWitness(
|
|
2134
2535
|
// Since unbonding transactions always have a single input and output,
|
|
2135
2536
|
// we expect exactly one signature in TaprootScriptSpendSig when the
|
|
@@ -2146,7 +2547,7 @@ var BabylonBtcStakingManager = class {
|
|
|
2146
2547
|
};
|
|
2147
2548
|
}
|
|
2148
2549
|
/**
|
|
2149
|
-
* Creates a signed withdrawal transaction on the unbodning output expiry path
|
|
2550
|
+
* Creates a signed withdrawal transaction on the unbodning output expiry path
|
|
2150
2551
|
* that is ready to be sent to the BTC network.
|
|
2151
2552
|
* @param stakingInput - The staking inputs.
|
|
2152
2553
|
* @param stakingParamsVersion - The params version that was used to create the
|
|
@@ -2158,32 +2559,42 @@ var BabylonBtcStakingManager = class {
|
|
|
2158
2559
|
* @returns The signed withdrawal transaction and its fee.
|
|
2159
2560
|
*/
|
|
2160
2561
|
async createSignedBtcWithdrawEarlyUnbondedTransaction(stakerBtcInfo, stakingInput, stakingParamsVersion, earlyUnbondingTx, feeRate) {
|
|
2161
|
-
const params = getBabylonParamByVersion(
|
|
2162
|
-
stakingParamsVersion,
|
|
2163
|
-
this.stakingParams
|
|
2164
|
-
);
|
|
2562
|
+
const params = getBabylonParamByVersion(stakingParamsVersion, this.stakingParams);
|
|
2165
2563
|
const staking = new Staking(
|
|
2166
2564
|
this.network,
|
|
2167
2565
|
stakerBtcInfo,
|
|
2168
2566
|
params,
|
|
2169
|
-
stakingInput.
|
|
2567
|
+
stakingInput.finalityProviderPksNoCoordHex,
|
|
2170
2568
|
stakingInput.stakingTimelock
|
|
2171
2569
|
);
|
|
2172
|
-
const { psbt: unbondingPsbt2, fee } = staking.createWithdrawEarlyUnbondedTransaction(
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2570
|
+
const { psbt: unbondingPsbt2, fee } = staking.createWithdrawEarlyUnbondedTransaction(earlyUnbondingTx, feeRate);
|
|
2571
|
+
const contracts = [
|
|
2572
|
+
{
|
|
2573
|
+
id: "babylon:withdraw" /* WITHDRAW */,
|
|
2574
|
+
params: {
|
|
2575
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2576
|
+
timelockBlocks: params.unbondingTime
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
];
|
|
2580
|
+
this.ee?.emit("delegation:withdraw", {
|
|
2581
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2582
|
+
timelockBlocks: params.unbondingTime,
|
|
2583
|
+
type: "early-unbonded"
|
|
2584
|
+
});
|
|
2585
|
+
const signedWithdrawalPsbtHex = await this.btcProvider.signPsbt(unbondingPsbt2.toHex(), {
|
|
2586
|
+
contracts,
|
|
2587
|
+
action: {
|
|
2588
|
+
name: "sign-btc-withdraw-transaction" /* SIGN_BTC_WITHDRAW_TRANSACTION */
|
|
2589
|
+
}
|
|
2590
|
+
});
|
|
2180
2591
|
return {
|
|
2181
2592
|
transaction: Psbt3.fromHex(signedWithdrawalPsbtHex).extractTransaction(),
|
|
2182
2593
|
fee
|
|
2183
2594
|
};
|
|
2184
2595
|
}
|
|
2185
2596
|
/**
|
|
2186
|
-
* Creates a signed withdrawal transaction on the staking output expiry path
|
|
2597
|
+
* Creates a signed withdrawal transaction on the staking output expiry path
|
|
2187
2598
|
* that is ready to be sent to the BTC network.
|
|
2188
2599
|
* @param stakerBtcInfo - The staker BTC info which includes the BTC address
|
|
2189
2600
|
* and the no-coord public key in hex format.
|
|
@@ -2197,32 +2608,42 @@ var BabylonBtcStakingManager = class {
|
|
|
2197
2608
|
* @returns The signed withdrawal transaction and its fee.
|
|
2198
2609
|
*/
|
|
2199
2610
|
async createSignedBtcWithdrawStakingExpiredTransaction(stakerBtcInfo, stakingInput, stakingParamsVersion, stakingTx, feeRate) {
|
|
2200
|
-
const params = getBabylonParamByVersion(
|
|
2201
|
-
stakingParamsVersion,
|
|
2202
|
-
this.stakingParams
|
|
2203
|
-
);
|
|
2611
|
+
const params = getBabylonParamByVersion(stakingParamsVersion, this.stakingParams);
|
|
2204
2612
|
const staking = new Staking(
|
|
2205
2613
|
this.network,
|
|
2206
2614
|
stakerBtcInfo,
|
|
2207
2615
|
params,
|
|
2208
|
-
stakingInput.
|
|
2616
|
+
stakingInput.finalityProviderPksNoCoordHex,
|
|
2209
2617
|
stakingInput.stakingTimelock
|
|
2210
2618
|
);
|
|
2211
|
-
const { psbt, fee } = staking.createWithdrawStakingExpiredPsbt(
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2619
|
+
const { psbt, fee } = staking.createWithdrawStakingExpiredPsbt(stakingTx, feeRate);
|
|
2620
|
+
const contracts = [
|
|
2621
|
+
{
|
|
2622
|
+
id: "babylon:withdraw" /* WITHDRAW */,
|
|
2623
|
+
params: {
|
|
2624
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2625
|
+
timelockBlocks: stakingInput.stakingTimelock
|
|
2626
|
+
}
|
|
2627
|
+
}
|
|
2628
|
+
];
|
|
2629
|
+
this.ee?.emit("delegation:withdraw", {
|
|
2630
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2631
|
+
timelockBlocks: stakingInput.stakingTimelock,
|
|
2632
|
+
type: "staking-expired"
|
|
2633
|
+
});
|
|
2634
|
+
const signedWithdrawalPsbtHex = await this.btcProvider.signPsbt(psbt.toHex(), {
|
|
2635
|
+
contracts,
|
|
2636
|
+
action: {
|
|
2637
|
+
name: "sign-btc-withdraw-transaction" /* SIGN_BTC_WITHDRAW_TRANSACTION */
|
|
2638
|
+
}
|
|
2639
|
+
});
|
|
2219
2640
|
return {
|
|
2220
2641
|
transaction: Psbt3.fromHex(signedWithdrawalPsbtHex).extractTransaction(),
|
|
2221
2642
|
fee
|
|
2222
2643
|
};
|
|
2223
2644
|
}
|
|
2224
2645
|
/**
|
|
2225
|
-
* Creates a signed withdrawal transaction for the expired slashing output that
|
|
2646
|
+
* Creates a signed withdrawal transaction for the expired slashing output that
|
|
2226
2647
|
* is ready to be sent to the BTC network.
|
|
2227
2648
|
* @param stakerBtcInfo - The staker BTC info which includes the BTC address
|
|
2228
2649
|
* and the no-coord public key in hex format.
|
|
@@ -2236,44 +2657,70 @@ var BabylonBtcStakingManager = class {
|
|
|
2236
2657
|
* @returns The signed withdrawal transaction and its fee.
|
|
2237
2658
|
*/
|
|
2238
2659
|
async createSignedBtcWithdrawSlashingTransaction(stakerBtcInfo, stakingInput, stakingParamsVersion, slashingTx, feeRate) {
|
|
2239
|
-
const params = getBabylonParamByVersion(
|
|
2240
|
-
stakingParamsVersion,
|
|
2241
|
-
this.stakingParams
|
|
2242
|
-
);
|
|
2660
|
+
const params = getBabylonParamByVersion(stakingParamsVersion, this.stakingParams);
|
|
2243
2661
|
const staking = new Staking(
|
|
2244
2662
|
this.network,
|
|
2245
2663
|
stakerBtcInfo,
|
|
2246
2664
|
params,
|
|
2247
|
-
stakingInput.
|
|
2665
|
+
stakingInput.finalityProviderPksNoCoordHex,
|
|
2248
2666
|
stakingInput.stakingTimelock
|
|
2249
2667
|
);
|
|
2250
|
-
const { psbt, fee } = staking.createWithdrawSlashingPsbt(
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2668
|
+
const { psbt, fee } = staking.createWithdrawSlashingPsbt(slashingTx, feeRate);
|
|
2669
|
+
const contracts = [
|
|
2670
|
+
{
|
|
2671
|
+
id: "babylon:withdraw" /* WITHDRAW */,
|
|
2672
|
+
params: {
|
|
2673
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2674
|
+
timelockBlocks: params.unbondingTime
|
|
2675
|
+
}
|
|
2676
|
+
}
|
|
2677
|
+
];
|
|
2678
|
+
this.ee?.emit("delegation:withdraw", {
|
|
2679
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2680
|
+
timelockBlocks: params.unbondingTime,
|
|
2681
|
+
type: "slashing"
|
|
2682
|
+
});
|
|
2683
|
+
const signedWithrawSlashingPsbtHex = await this.btcProvider.signPsbt(psbt.toHex(), {
|
|
2684
|
+
contracts,
|
|
2685
|
+
action: {
|
|
2686
|
+
name: "sign-btc-withdraw-transaction" /* SIGN_BTC_WITHDRAW_TRANSACTION */
|
|
2687
|
+
}
|
|
2688
|
+
});
|
|
2258
2689
|
return {
|
|
2259
|
-
transaction: Psbt3.fromHex(
|
|
2690
|
+
transaction: Psbt3.fromHex(signedWithrawSlashingPsbtHex).extractTransaction(),
|
|
2260
2691
|
fee
|
|
2261
2692
|
};
|
|
2262
2693
|
}
|
|
2263
2694
|
/**
|
|
2264
2695
|
* Creates a proof of possession for the staker based on ECDSA signature.
|
|
2265
|
-
* @param bech32Address - The staker's bech32 address
|
|
2266
|
-
* @param stakerBtcAddress - The staker's BTC address.
|
|
2696
|
+
* @param bech32Address - The staker's bech32 address.
|
|
2267
2697
|
* @returns The proof of possession.
|
|
2268
2698
|
*/
|
|
2269
|
-
async createProofOfPossession(bech32Address, stakerBtcAddress) {
|
|
2699
|
+
async createProofOfPossession(channel, bech32Address, stakerBtcAddress) {
|
|
2270
2700
|
let sigType = BTCSigType.ECDSA;
|
|
2271
2701
|
if (isTaproot(stakerBtcAddress, this.network) || isNativeSegwit(stakerBtcAddress, this.network)) {
|
|
2272
2702
|
sigType = BTCSigType.BIP322;
|
|
2273
2703
|
}
|
|
2274
|
-
const
|
|
2275
|
-
|
|
2704
|
+
const [chainId, babyTipHeight] = await Promise.all([
|
|
2705
|
+
this.babylonProvider.getChainId?.(),
|
|
2706
|
+
this.babylonProvider.getCurrentHeight?.()
|
|
2707
|
+
]);
|
|
2708
|
+
const upgradeConfig = this.upgradeConfig?.pop;
|
|
2709
|
+
const messageToSign = buildPopMessage(
|
|
2276
2710
|
bech32Address,
|
|
2711
|
+
babyTipHeight,
|
|
2712
|
+
chainId,
|
|
2713
|
+
upgradeConfig && {
|
|
2714
|
+
upgradeHeight: upgradeConfig.upgradeHeight,
|
|
2715
|
+
version: upgradeConfig.version
|
|
2716
|
+
}
|
|
2717
|
+
);
|
|
2718
|
+
this.ee?.emit(channel, {
|
|
2719
|
+
messageToSign,
|
|
2720
|
+
type: "proof-of-possession"
|
|
2721
|
+
});
|
|
2722
|
+
const signedBabylonAddress = await this.btcProvider.signMessage(
|
|
2723
|
+
messageToSign,
|
|
2277
2724
|
sigType === BTCSigType.BIP322 ? "bip322-simple" : "ecdsa"
|
|
2278
2725
|
);
|
|
2279
2726
|
let btcSig;
|
|
@@ -2292,11 +2739,11 @@ var BabylonBtcStakingManager = class {
|
|
|
2292
2739
|
};
|
|
2293
2740
|
}
|
|
2294
2741
|
/**
|
|
2295
|
-
* Creates the unbonding, slashing, and unbonding slashing transactions and
|
|
2742
|
+
* Creates the unbonding, slashing, and unbonding slashing transactions and
|
|
2296
2743
|
* PSBTs.
|
|
2297
2744
|
* @param stakingInstance - The staking instance.
|
|
2298
2745
|
* @param stakingTx - The staking transaction.
|
|
2299
|
-
* @returns The unbonding, slashing, and unbonding slashing transactions and
|
|
2746
|
+
* @returns The unbonding, slashing, and unbonding slashing transactions and
|
|
2300
2747
|
* PSBTs.
|
|
2301
2748
|
*/
|
|
2302
2749
|
async createDelegationTransactionsAndPsbts(stakingInstance, stakingTx) {
|
|
@@ -2311,84 +2758,164 @@ var BabylonBtcStakingManager = class {
|
|
|
2311
2758
|
}
|
|
2312
2759
|
/**
|
|
2313
2760
|
* Creates a protobuf message for the BTC delegation.
|
|
2761
|
+
* @param channel - The event channel to emit the message on.
|
|
2314
2762
|
* @param stakingInstance - The staking instance.
|
|
2315
2763
|
* @param stakingInput - The staking inputs.
|
|
2316
2764
|
* @param stakingTx - The staking transaction.
|
|
2317
2765
|
* @param bech32Address - The staker's babylon chain bech32 address
|
|
2318
|
-
* @param stakerBtcInfo - The staker's BTC information such as address and
|
|
2766
|
+
* @param stakerBtcInfo - The staker's BTC information such as address and
|
|
2319
2767
|
* public key
|
|
2320
2768
|
* @param params - The staking parameters.
|
|
2321
|
-
* @param
|
|
2769
|
+
* @param options - The options for the BTC delegation.
|
|
2770
|
+
* @param options.inclusionProof - The inclusion proof of the staking
|
|
2771
|
+
* transaction.
|
|
2772
|
+
* @param options.delegationExpansionInfo - The information for the BTC
|
|
2773
|
+
* delegation expansion.
|
|
2322
2774
|
* @returns The protobuf message.
|
|
2323
2775
|
*/
|
|
2324
|
-
async createBtcDelegationMsg(stakingInstance, stakingInput, stakingTx, bech32Address, stakerBtcInfo, params,
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2776
|
+
async createBtcDelegationMsg(channel, stakingInstance, stakingInput, stakingTx, bech32Address, stakerBtcInfo, params, options) {
|
|
2777
|
+
if (!params.slashing) {
|
|
2778
|
+
throw new StakingError(
|
|
2779
|
+
"INVALID_PARAMS" /* INVALID_PARAMS */,
|
|
2780
|
+
"Slashing parameters are required for creating delegation message"
|
|
2781
|
+
);
|
|
2782
|
+
}
|
|
2783
|
+
const { unbondingTx, slashingPsbt, unbondingSlashingPsbt } = await this.createDelegationTransactionsAndPsbts(
|
|
2330
2784
|
stakingInstance,
|
|
2331
2785
|
stakingTx
|
|
2332
2786
|
);
|
|
2333
|
-
const
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2787
|
+
const slashingContracts = [
|
|
2788
|
+
{
|
|
2789
|
+
id: "babylon:staking" /* STAKING */,
|
|
2790
|
+
params: {
|
|
2791
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2792
|
+
finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
|
|
2793
|
+
covenantPks: params.covenantNoCoordPks,
|
|
2794
|
+
covenantThreshold: params.covenantQuorum,
|
|
2795
|
+
minUnbondingTime: params.unbondingTime,
|
|
2796
|
+
stakingDuration: stakingInput.stakingTimelock
|
|
2797
|
+
}
|
|
2798
|
+
},
|
|
2799
|
+
{
|
|
2800
|
+
id: "babylon:slashing" /* SLASHING */,
|
|
2801
|
+
params: {
|
|
2802
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2803
|
+
unbondingTimeBlocks: params.unbondingTime,
|
|
2804
|
+
slashingFeeSat: params.slashing.minSlashingTxFeeSat
|
|
2805
|
+
}
|
|
2806
|
+
},
|
|
2807
|
+
{
|
|
2808
|
+
id: "babylon:slashing-burn" /* SLASHING_BURN */,
|
|
2809
|
+
params: {
|
|
2810
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2811
|
+
slashingPkScriptHex: params.slashing.slashingPkScriptHex
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
];
|
|
2815
|
+
this.ee?.emit(channel, {
|
|
2816
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2817
|
+
finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
|
|
2818
|
+
covenantPks: params.covenantNoCoordPks,
|
|
2819
|
+
covenantThreshold: params.covenantQuorum,
|
|
2820
|
+
unbondingTimeBlocks: params.unbondingTime,
|
|
2821
|
+
stakingDuration: stakingInput.stakingTimelock,
|
|
2822
|
+
slashingFeeSat: params.slashing.minSlashingTxFeeSat,
|
|
2823
|
+
slashingPkScriptHex: params.slashing.slashingPkScriptHex,
|
|
2824
|
+
type: "staking-slashing"
|
|
2825
|
+
});
|
|
2826
|
+
const signedSlashingPsbtHex = await this.btcProvider.signPsbt(slashingPsbt.toHex(), {
|
|
2827
|
+
contracts: slashingContracts,
|
|
2828
|
+
action: {
|
|
2829
|
+
name: "sign-btc-slashing-transaction" /* SIGN_BTC_SLASHING_TRANSACTION */
|
|
2830
|
+
}
|
|
2831
|
+
});
|
|
2832
|
+
const signedSlashingTx = Psbt3.fromHex(signedSlashingPsbtHex).extractTransaction();
|
|
2833
|
+
const slashingSig = extractFirstSchnorrSignatureFromTransaction(signedSlashingTx);
|
|
2343
2834
|
if (!slashingSig) {
|
|
2344
2835
|
throw new Error("No signature found in the staking output slashing PSBT");
|
|
2345
2836
|
}
|
|
2346
|
-
const
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2837
|
+
const unbondingSlashingContracts = [
|
|
2838
|
+
{
|
|
2839
|
+
id: "babylon:unbonding" /* UNBONDING */,
|
|
2840
|
+
params: {
|
|
2841
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2842
|
+
finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
|
|
2843
|
+
covenantPks: params.covenantNoCoordPks,
|
|
2844
|
+
covenantThreshold: params.covenantQuorum,
|
|
2845
|
+
unbondingTimeBlocks: params.unbondingTime,
|
|
2846
|
+
unbondingFeeSat: params.unbondingFeeSat
|
|
2847
|
+
}
|
|
2848
|
+
},
|
|
2849
|
+
{
|
|
2850
|
+
id: "babylon:slashing" /* SLASHING */,
|
|
2851
|
+
params: {
|
|
2852
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2853
|
+
unbondingTimeBlocks: params.unbondingTime,
|
|
2854
|
+
slashingFeeSat: params.slashing.minSlashingTxFeeSat
|
|
2855
|
+
}
|
|
2856
|
+
},
|
|
2857
|
+
{
|
|
2858
|
+
id: "babylon:slashing-burn" /* SLASHING_BURN */,
|
|
2859
|
+
params: {
|
|
2860
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2861
|
+
slashingPkScriptHex: params.slashing.slashingPkScriptHex
|
|
2862
|
+
}
|
|
2863
|
+
}
|
|
2864
|
+
];
|
|
2865
|
+
this.ee?.emit(channel, {
|
|
2866
|
+
stakerPk: stakerBtcInfo.publicKeyNoCoordHex,
|
|
2867
|
+
finalityProviders: stakingInput.finalityProviderPksNoCoordHex,
|
|
2868
|
+
covenantPks: params.covenantNoCoordPks,
|
|
2869
|
+
covenantThreshold: params.covenantQuorum,
|
|
2870
|
+
unbondingTimeBlocks: params.unbondingTime,
|
|
2871
|
+
unbondingFeeSat: params.unbondingFeeSat,
|
|
2872
|
+
slashingFeeSat: params.slashing.minSlashingTxFeeSat,
|
|
2873
|
+
slashingPkScriptHex: params.slashing.slashingPkScriptHex,
|
|
2874
|
+
type: "unbonding-slashing"
|
|
2875
|
+
});
|
|
2876
|
+
const signedUnbondingSlashingPsbtHex = await this.btcProvider.signPsbt(unbondingSlashingPsbt.toHex(), {
|
|
2877
|
+
contracts: unbondingSlashingContracts,
|
|
2878
|
+
action: {
|
|
2879
|
+
name: "sign-btc-unbonding-slashing-transaction" /* SIGN_BTC_UNBONDING_SLASHING_TRANSACTION */
|
|
2880
|
+
}
|
|
2881
|
+
});
|
|
2882
|
+
const signedUnbondingSlashingTx = Psbt3.fromHex(signedUnbondingSlashingPsbtHex).extractTransaction();
|
|
2883
|
+
const unbondingSignatures = extractFirstSchnorrSignatureFromTransaction(signedUnbondingSlashingTx);
|
|
2356
2884
|
if (!unbondingSignatures) {
|
|
2357
2885
|
throw new Error("No signature found in the unbonding output slashing PSBT");
|
|
2358
2886
|
}
|
|
2359
|
-
const proofOfPossession = await this.createProofOfPossession(
|
|
2360
|
-
|
|
2361
|
-
stakerBtcInfo.address
|
|
2362
|
-
);
|
|
2363
|
-
const msg = btcstakingtx.MsgCreateBTCDelegation.fromPartial({
|
|
2887
|
+
const proofOfPossession = await this.createProofOfPossession(channel, bech32Address, stakerBtcInfo.address);
|
|
2888
|
+
const commonMsg = {
|
|
2364
2889
|
stakerAddr: bech32Address,
|
|
2365
2890
|
pop: proofOfPossession,
|
|
2366
|
-
btcPk: Uint8Array.from(
|
|
2367
|
-
|
|
2368
|
-
),
|
|
2369
|
-
fpBtcPkList: [
|
|
2370
|
-
Uint8Array.from(
|
|
2371
|
-
Buffer.from(stakingInput.finalityProviderPkNoCoordHex, "hex")
|
|
2372
|
-
)
|
|
2373
|
-
],
|
|
2891
|
+
btcPk: Uint8Array.from(Buffer.from(stakerBtcInfo.publicKeyNoCoordHex, "hex")),
|
|
2892
|
+
fpBtcPkList: stakingInput.finalityProviderPksNoCoordHex.map((pk) => Uint8Array.from(Buffer.from(pk, "hex"))),
|
|
2374
2893
|
stakingTime: stakingInput.stakingTimelock,
|
|
2375
2894
|
stakingValue: stakingInput.stakingAmountSat,
|
|
2376
2895
|
stakingTx: Uint8Array.from(stakingTx.toBuffer()),
|
|
2377
|
-
slashingTx: Uint8Array.from(
|
|
2378
|
-
Buffer.from(clearTxSignatures(signedSlashingTx).toHex(), "hex")
|
|
2379
|
-
),
|
|
2896
|
+
slashingTx: Uint8Array.from(Buffer.from(clearTxSignatures(signedSlashingTx).toHex(), "hex")),
|
|
2380
2897
|
delegatorSlashingSig: Uint8Array.from(slashingSig),
|
|
2381
2898
|
unbondingTime: params.unbondingTime,
|
|
2382
2899
|
unbondingTx: Uint8Array.from(unbondingTx.toBuffer()),
|
|
2383
2900
|
unbondingValue: stakingInput.stakingAmountSat - params.unbondingFeeSat,
|
|
2384
|
-
unbondingSlashingTx: Uint8Array.from(
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2901
|
+
unbondingSlashingTx: Uint8Array.from(Buffer.from(clearTxSignatures(signedUnbondingSlashingTx).toHex(), "hex")),
|
|
2902
|
+
delegatorUnbondingSlashingSig: Uint8Array.from(unbondingSignatures)
|
|
2903
|
+
};
|
|
2904
|
+
if (options?.delegationExpansionInfo) {
|
|
2905
|
+
const fundingTx = Uint8Array.from(options.delegationExpansionInfo.fundingTx.toBuffer());
|
|
2906
|
+
const msg2 = btcstakingtx.MsgBtcStakeExpand.fromPartial({
|
|
2907
|
+
...commonMsg,
|
|
2908
|
+
previousStakingTxHash: options.delegationExpansionInfo.previousStakingTx.getId(),
|
|
2909
|
+
fundingTx
|
|
2910
|
+
});
|
|
2911
|
+
return {
|
|
2912
|
+
typeUrl: BABYLON_REGISTRY_TYPE_URLS.MsgBtcStakeExpand,
|
|
2913
|
+
value: msg2
|
|
2914
|
+
};
|
|
2915
|
+
}
|
|
2916
|
+
const msg = btcstakingtx.MsgCreateBTCDelegation.fromPartial({
|
|
2917
|
+
...commonMsg,
|
|
2918
|
+
stakingTxInclusionProof: options?.inclusionProof
|
|
2392
2919
|
});
|
|
2393
2920
|
return {
|
|
2394
2921
|
typeUrl: BABYLON_REGISTRY_TYPE_URLS.MsgCreateBTCDelegation,
|
|
@@ -2402,11 +2929,7 @@ var BabylonBtcStakingManager = class {
|
|
|
2402
2929
|
* @returns The inclusion proof.
|
|
2403
2930
|
*/
|
|
2404
2931
|
getInclusionProof(inclusionProof) {
|
|
2405
|
-
const {
|
|
2406
|
-
pos,
|
|
2407
|
-
merkle,
|
|
2408
|
-
blockHashHex
|
|
2409
|
-
} = inclusionProof;
|
|
2932
|
+
const { pos, merkle, blockHashHex } = inclusionProof;
|
|
2410
2933
|
const proofHex = deriveMerkleProof(merkle);
|
|
2411
2934
|
const hash = reverseBuffer(Uint8Array.from(Buffer.from(blockHashHex, "hex")));
|
|
2412
2935
|
const inclusionProofKey = btccheckpoint.TransactionKey.fromPartial({
|
|
@@ -2419,54 +2942,235 @@ var BabylonBtcStakingManager = class {
|
|
|
2419
2942
|
});
|
|
2420
2943
|
}
|
|
2421
2944
|
};
|
|
2422
|
-
var extractFirstSchnorrSignatureFromTransaction = (singedTransaction) => {
|
|
2423
|
-
for (const input of singedTransaction.ins) {
|
|
2424
|
-
if (input.witness && input.witness.length > 0) {
|
|
2425
|
-
const schnorrSignature = input.witness[0];
|
|
2426
|
-
if (schnorrSignature.length === 64) {
|
|
2427
|
-
return schnorrSignature;
|
|
2428
|
-
}
|
|
2429
|
-
}
|
|
2430
|
-
}
|
|
2431
|
-
return void 0;
|
|
2432
|
-
};
|
|
2433
|
-
var clearTxSignatures = (tx) => {
|
|
2434
|
-
tx.ins.forEach((input) => {
|
|
2435
|
-
input.script = Buffer.alloc(0);
|
|
2436
|
-
input.witness = [];
|
|
2437
|
-
});
|
|
2438
|
-
return tx;
|
|
2439
|
-
};
|
|
2440
|
-
var deriveMerkleProof = (merkle) => {
|
|
2441
|
-
const proofHex = merkle.reduce((acc, m) => {
|
|
2442
|
-
return acc + Buffer.from(m, "hex").reverse().toString("hex");
|
|
2443
|
-
}, "");
|
|
2444
|
-
return proofHex;
|
|
2445
|
-
};
|
|
2446
2945
|
var getUnbondingTxStakerSignature = (unbondingTx) => {
|
|
2447
2946
|
try {
|
|
2448
2947
|
return unbondingTx.ins[0].witness[0].toString("hex");
|
|
2449
2948
|
} catch (error) {
|
|
2450
|
-
throw StakingError.fromUnknown(
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2949
|
+
throw StakingError.fromUnknown(error, "INVALID_INPUT" /* INVALID_INPUT */, "Failed to get staker signature");
|
|
2950
|
+
}
|
|
2951
|
+
};
|
|
2952
|
+
|
|
2953
|
+
// src/staking/observable/observableStakingScript.ts
|
|
2954
|
+
import { opcodes as opcodes4, script as script3 } from "bitcoinjs-lib";
|
|
2955
|
+
var ObservableStakingScriptData = class extends StakingScriptData {
|
|
2956
|
+
constructor(stakerKey, finalityProviderKeys, covenantKeys, covenantThreshold, stakingTimelock, unbondingTimelock, magicBytes) {
|
|
2957
|
+
super(
|
|
2958
|
+
stakerKey,
|
|
2959
|
+
finalityProviderKeys,
|
|
2960
|
+
covenantKeys,
|
|
2961
|
+
covenantThreshold,
|
|
2962
|
+
stakingTimelock,
|
|
2963
|
+
unbondingTimelock
|
|
2964
|
+
);
|
|
2965
|
+
if (!magicBytes) {
|
|
2966
|
+
throw new Error("Missing required input values");
|
|
2967
|
+
}
|
|
2968
|
+
if (magicBytes.length != MAGIC_BYTES_LEN) {
|
|
2969
|
+
throw new Error("Invalid script data provided");
|
|
2970
|
+
}
|
|
2971
|
+
this.magicBytes = magicBytes;
|
|
2972
|
+
}
|
|
2973
|
+
/**
|
|
2974
|
+
* Builds a data embed script for staking in the form:
|
|
2975
|
+
* OP_RETURN || <serializedStakingData>
|
|
2976
|
+
* where serializedStakingData is the concatenation of:
|
|
2977
|
+
* MagicBytes || Version || StakerPublicKey || FinalityProviderPublicKey || StakingTimeLock
|
|
2978
|
+
* Note: Only a single finality provider key is supported for now in phase 1
|
|
2979
|
+
* @throws {Error} If the number of finality provider keys is not equal to 1.
|
|
2980
|
+
* @returns {Buffer} The compiled data embed script.
|
|
2981
|
+
*/
|
|
2982
|
+
buildDataEmbedScript() {
|
|
2983
|
+
if (this.finalityProviderKeys.length != 1) {
|
|
2984
|
+
throw new Error("Only a single finality provider key is supported");
|
|
2985
|
+
}
|
|
2986
|
+
const version = Buffer.alloc(1);
|
|
2987
|
+
version.writeUInt8(0);
|
|
2988
|
+
const stakingTimeLock = Buffer.alloc(2);
|
|
2989
|
+
stakingTimeLock.writeUInt16BE(this.stakingTimeLock);
|
|
2990
|
+
const serializedStakingData = Buffer.concat([
|
|
2991
|
+
this.magicBytes,
|
|
2992
|
+
version,
|
|
2993
|
+
this.stakerKey,
|
|
2994
|
+
this.finalityProviderKeys[0],
|
|
2995
|
+
stakingTimeLock
|
|
2996
|
+
]);
|
|
2997
|
+
return script3.compile([opcodes4.OP_RETURN, serializedStakingData]);
|
|
2998
|
+
}
|
|
2999
|
+
/**
|
|
3000
|
+
* Builds the staking scripts.
|
|
3001
|
+
* @returns {ObservableStakingScripts} The staking scripts that can be used to stake.
|
|
3002
|
+
* contains the timelockScript, unbondingScript, slashingScript,
|
|
3003
|
+
* unbondingTimelockScript, and dataEmbedScript.
|
|
3004
|
+
* @throws {Error} If script data is invalid.
|
|
3005
|
+
*/
|
|
3006
|
+
buildScripts() {
|
|
3007
|
+
const scripts = super.buildScripts();
|
|
3008
|
+
return {
|
|
3009
|
+
...scripts,
|
|
3010
|
+
dataEmbedScript: this.buildDataEmbedScript()
|
|
3011
|
+
};
|
|
3012
|
+
}
|
|
3013
|
+
};
|
|
3014
|
+
|
|
3015
|
+
// src/staking/observable/index.ts
|
|
3016
|
+
var ObservableStaking = class extends Staking {
|
|
3017
|
+
constructor(network, stakerInfo, params, finalityProviderPksNoCoordHex, stakingTimelock) {
|
|
3018
|
+
super(
|
|
3019
|
+
network,
|
|
3020
|
+
stakerInfo,
|
|
3021
|
+
params,
|
|
3022
|
+
finalityProviderPksNoCoordHex,
|
|
3023
|
+
stakingTimelock
|
|
3024
|
+
);
|
|
3025
|
+
if (!params.tag) {
|
|
3026
|
+
throw new StakingError(
|
|
3027
|
+
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
3028
|
+
"Observable staking parameters must include tag"
|
|
3029
|
+
);
|
|
3030
|
+
}
|
|
3031
|
+
if (!params.btcActivationHeight) {
|
|
3032
|
+
throw new StakingError(
|
|
3033
|
+
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
3034
|
+
"Observable staking parameters must include a positive activation height"
|
|
3035
|
+
);
|
|
3036
|
+
}
|
|
3037
|
+
if (finalityProviderPksNoCoordHex.length !== 1) {
|
|
3038
|
+
throw new StakingError(
|
|
3039
|
+
"INVALID_INPUT" /* INVALID_INPUT */,
|
|
3040
|
+
"Observable staking requires exactly one finality provider public key"
|
|
3041
|
+
);
|
|
3042
|
+
}
|
|
3043
|
+
this.params = params;
|
|
3044
|
+
}
|
|
3045
|
+
/**
|
|
3046
|
+
* Build the staking scripts for observable staking.
|
|
3047
|
+
* This method overwrites the base method to include the OP_RETURN tag based
|
|
3048
|
+
* on the tag provided in the parameters.
|
|
3049
|
+
*
|
|
3050
|
+
* @returns {ObservableStakingScripts} - The staking scripts for observable staking.
|
|
3051
|
+
* @throws {StakingError} - If the scripts cannot be built.
|
|
3052
|
+
*/
|
|
3053
|
+
buildScripts() {
|
|
3054
|
+
const { covenantQuorum, covenantNoCoordPks, unbondingTime, tag } = this.params;
|
|
3055
|
+
let stakingScriptData;
|
|
3056
|
+
try {
|
|
3057
|
+
stakingScriptData = new ObservableStakingScriptData(
|
|
3058
|
+
Buffer.from(this.stakerInfo.publicKeyNoCoordHex, "hex"),
|
|
3059
|
+
this.finalityProviderPksNoCoordHex.map((pk) => Buffer.from(pk, "hex")),
|
|
3060
|
+
toBuffers(covenantNoCoordPks),
|
|
3061
|
+
covenantQuorum,
|
|
3062
|
+
this.stakingTimelock,
|
|
3063
|
+
unbondingTime,
|
|
3064
|
+
Buffer.from(tag, "hex")
|
|
3065
|
+
);
|
|
3066
|
+
} catch (error) {
|
|
3067
|
+
throw StakingError.fromUnknown(
|
|
3068
|
+
error,
|
|
3069
|
+
"SCRIPT_FAILURE" /* SCRIPT_FAILURE */,
|
|
3070
|
+
"Cannot build staking script data"
|
|
3071
|
+
);
|
|
3072
|
+
}
|
|
3073
|
+
let scripts;
|
|
3074
|
+
try {
|
|
3075
|
+
scripts = stakingScriptData.buildScripts();
|
|
3076
|
+
} catch (error) {
|
|
3077
|
+
throw StakingError.fromUnknown(
|
|
3078
|
+
error,
|
|
3079
|
+
"SCRIPT_FAILURE" /* SCRIPT_FAILURE */,
|
|
3080
|
+
"Cannot build staking scripts"
|
|
3081
|
+
);
|
|
3082
|
+
}
|
|
3083
|
+
return scripts;
|
|
3084
|
+
}
|
|
3085
|
+
/**
|
|
3086
|
+
* Create a staking transaction for observable staking.
|
|
3087
|
+
* This overwrites the method from the Staking class with the addtion
|
|
3088
|
+
* of the
|
|
3089
|
+
* 1. OP_RETURN tag in the staking scripts
|
|
3090
|
+
* 2. lockHeight parameter
|
|
3091
|
+
*
|
|
3092
|
+
* @param {number} stakingAmountSat - The amount to stake in satoshis.
|
|
3093
|
+
* @param {UTXO[]} inputUTXOs - The UTXOs to use as inputs for the staking
|
|
3094
|
+
* transaction.
|
|
3095
|
+
* @param {number} feeRate - The fee rate for the transaction in satoshis per byte.
|
|
3096
|
+
* @returns {TransactionResult} - An object containing the unsigned transaction,
|
|
3097
|
+
* and fee
|
|
3098
|
+
*/
|
|
3099
|
+
createStakingTransaction(stakingAmountSat, inputUTXOs, feeRate) {
|
|
3100
|
+
validateStakingTxInputData(
|
|
3101
|
+
stakingAmountSat,
|
|
3102
|
+
this.stakingTimelock,
|
|
3103
|
+
this.params,
|
|
3104
|
+
inputUTXOs,
|
|
3105
|
+
feeRate
|
|
3106
|
+
);
|
|
3107
|
+
const scripts = this.buildScripts();
|
|
3108
|
+
try {
|
|
3109
|
+
const { transaction, fee } = stakingTransaction(
|
|
3110
|
+
scripts,
|
|
3111
|
+
stakingAmountSat,
|
|
3112
|
+
this.stakerInfo.address,
|
|
3113
|
+
inputUTXOs,
|
|
3114
|
+
this.network,
|
|
3115
|
+
feeRate,
|
|
3116
|
+
// `lockHeight` is exclusive of the provided value.
|
|
3117
|
+
// For example, if a Bitcoin height of X is provided,
|
|
3118
|
+
// the transaction will be included starting from height X+1.
|
|
3119
|
+
// https://learnmeabitcoin.com/technical/transaction/locktime/
|
|
3120
|
+
this.params.btcActivationHeight - 1
|
|
3121
|
+
);
|
|
3122
|
+
return {
|
|
3123
|
+
transaction,
|
|
3124
|
+
fee
|
|
3125
|
+
};
|
|
3126
|
+
} catch (error) {
|
|
3127
|
+
throw StakingError.fromUnknown(
|
|
3128
|
+
error,
|
|
3129
|
+
"BUILD_TRANSACTION_FAILURE" /* BUILD_TRANSACTION_FAILURE */,
|
|
3130
|
+
"Cannot build unsigned staking transaction"
|
|
3131
|
+
);
|
|
3132
|
+
}
|
|
3133
|
+
}
|
|
3134
|
+
/**
|
|
3135
|
+
* Create a staking psbt for observable staking.
|
|
3136
|
+
*
|
|
3137
|
+
* @param {Transaction} stakingTx - The staking transaction.
|
|
3138
|
+
* @param {UTXO[]} inputUTXOs - The UTXOs to use as inputs for the staking
|
|
3139
|
+
* transaction.
|
|
3140
|
+
* @returns {Psbt} - The psbt.
|
|
3141
|
+
*/
|
|
3142
|
+
toStakingPsbt(stakingTx, inputUTXOs) {
|
|
3143
|
+
return stakingPsbt(
|
|
3144
|
+
stakingTx,
|
|
3145
|
+
this.network,
|
|
3146
|
+
inputUTXOs,
|
|
3147
|
+
isTaproot(
|
|
3148
|
+
this.stakerInfo.address,
|
|
3149
|
+
this.network
|
|
3150
|
+
) ? Buffer.from(this.stakerInfo.publicKeyNoCoordHex, "hex") : void 0
|
|
2454
3151
|
);
|
|
2455
3152
|
}
|
|
2456
3153
|
};
|
|
3154
|
+
|
|
3155
|
+
// src/types/params.ts
|
|
3156
|
+
function hasSlashing(params) {
|
|
3157
|
+
return params.slashing !== void 0;
|
|
3158
|
+
}
|
|
2457
3159
|
export {
|
|
2458
3160
|
BabylonBtcStakingManager,
|
|
2459
3161
|
BitcoinScriptType,
|
|
2460
3162
|
ObservableStaking,
|
|
2461
3163
|
ObservableStakingScriptData,
|
|
2462
|
-
SigningStep,
|
|
2463
3164
|
Staking,
|
|
2464
3165
|
StakingScriptData,
|
|
2465
3166
|
buildStakingTransactionOutputs,
|
|
3167
|
+
clearTxSignatures,
|
|
2466
3168
|
createCovenantWitness,
|
|
3169
|
+
deriveMerkleProof,
|
|
2467
3170
|
deriveSlashingOutput,
|
|
2468
3171
|
deriveStakingOutputInfo,
|
|
2469
3172
|
deriveUnbondingOutputInfo,
|
|
3173
|
+
extractFirstSchnorrSignatureFromTransaction,
|
|
2470
3174
|
findInputUTXO,
|
|
2471
3175
|
findMatchingTxOutputIndex,
|
|
2472
3176
|
getBabylonParamByBtcHeight,
|
|
@@ -2475,6 +3179,7 @@ export {
|
|
|
2475
3179
|
getPublicKeyNoCoord,
|
|
2476
3180
|
getScriptType,
|
|
2477
3181
|
getUnbondingTxStakerSignature,
|
|
3182
|
+
hasSlashing,
|
|
2478
3183
|
initBTCCurve,
|
|
2479
3184
|
isNativeSegwit,
|
|
2480
3185
|
isTaproot,
|
|
@@ -2483,14 +3188,13 @@ export {
|
|
|
2483
3188
|
isValidNoCoordPublicKey,
|
|
2484
3189
|
slashEarlyUnbondedTransaction,
|
|
2485
3190
|
slashTimelockUnbondedTransaction,
|
|
3191
|
+
stakingExpansionTransaction,
|
|
2486
3192
|
stakingTransaction,
|
|
2487
3193
|
toBuffers,
|
|
2488
3194
|
transactionIdToHash,
|
|
2489
3195
|
unbondingTransaction,
|
|
2490
|
-
validateParams,
|
|
2491
|
-
validateStakingTimelock,
|
|
2492
|
-
validateStakingTxInputData,
|
|
2493
3196
|
withdrawEarlyUnbondedTransaction,
|
|
2494
3197
|
withdrawSlashingTransaction,
|
|
2495
3198
|
withdrawTimelockUnbondedTransaction
|
|
2496
3199
|
};
|
|
3200
|
+
//# sourceMappingURL=index.js.map
|