-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfarvault.test.js
389 lines (357 loc) · 13.3 KB
/
farvault.test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
//Take inspitation from this: https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/test/integration/csv.spec.ts
//
//Create a bip32 wallet
//Fund the wallet with a faucet including p2pkh, p2sh-p2wpkh, p2wpkh utxos
//Coinselect up to X Bitcoin from all the utxos and send to @safe
//Send to @timeLocked
//Scenario 1: try to send to @hot before the time permits so: fails
//Scenario 2: try to send to @rescued before the time permits to get it in @hot: succeeds
//Scenario 3: try to send to @hot after the time permits so: succeeds
//
//Things to check: fees
const MULTIFEE_SAMPLES = 100;
import { payments } from 'bitcoinjs-lib';
import { generateMnemonic } from 'bip39';
import {
fundRegtest,
BITCOIND_CATCH_UP_TIME,
REGTEST_SERVER_CATCH_UP_TIME,
ESPLORA_CATCH_UP_TIME
} from '../tools';
import {
createTransaction,
createMultiFeeTransactions
} from '../../src/transactions';
import { createRelativeTimeLockScript } from '../../src/scripts';
import { decodeTx } from '../../src/decodeTx';
import { SoftHDSigner } from '../../src/HDSigner/soft';
import { getDerivationPathAddress } from '../../src/bip44';
import { EsploraExplorer } from '../../src/explorer/esplora';
import { Discovery } from '../../src/discovery';
import { getNextDerivationPath } from '../../src/bip44/chain';
import {
VAULT_SKIP,
ESPLORA,
ESPLORA_LOCAL_REGTEST_URL
} from '../../src/constants';
import { coinselect } from '../../src/coinselect';
import { fixtures } from '../fixtures/farvault';
import { pickFeeEstimate } from '../../src/fees';
const TEST_TIME = 120000;
import bip68 from 'bip68';
import { readSetup, writeSetup } from '../../src/serialization';
describe('FarVault full pipe', () => {
const {
network,
mnemonic,
guardTxTargetTime,
unlockTxTargetTime,
lockTime,
lockNBlocks,
safeValue,
fundingDescriptors,
coldAddress
} = fixtures;
describe('Create a wallet', () => {
test(
'Create a blockchain, a wallet, fund it, coinselect X BTC, send to @timeLocked and try to claim from @hot before time',
async () => {
//Create an initial funded wallet.
//This is my hot wallet.
const {
HDSigner: hotHDSigner,
paths: walletPaths,
utxos: walletUtxos,
regtestUtils
} = await fundRegtest({
mnemonic,
fundingDescriptors,
network
});
//Give esplora some time to catch up
await new Promise(r => setTimeout(r, ESPLORA_CATCH_UP_TIME));
const blockstreamExplorer = new EsploraExplorer();
const localExplorer = new EsploraExplorer({
url: ESPLORA_LOCAL_REGTEST_URL
});
const discovery = new Discovery({
extPubGetter: hotHDSigner.getExtPub.bind(hotHDSigner),
explorer: localExplorer,
forceFetchChange: true
});
await discovery.fetch({ network });
const usedPaths = discovery.getUsedDerivationPaths({ network });
const fundedPaths = discovery.getFundedDerivationPaths({ network });
////Get the derivation paths and utxos of the wallet
await discovery.fetchUtxos({ network });
const utxos = discovery.getUtxos({ network });
expect(utxos).toEqual(expect.arrayContaining(walletUtxos));
//This used to fail but was fixed:
//https://github.com/bitcoinjs/regtest-client/pull/4
expect(walletUtxos.length - utxos.length === 0).toEqual(true);
expect(fundedPaths).toEqual(expect.arrayContaining(walletPaths));
expect(fundedPaths.length).toEqual(walletPaths.length);
//Create the safeAddress that will keep the funds safe.
//We must not save this mnemonic below.
const safeHDSigner = new SoftHDSigner({
mnemonic: generateMnemonic(256)
});
await safeHDSigner.init();
const safePath = getNextDerivationPath({
isChange: false,
usedPaths: [],
network
});
expect(safePath).toEqual("84'/1'/0'/0/0");
const safeAddress = await getDerivationPathAddress({
extPubGetter: safeHDSigner.getExtPub.bind(safeHDSigner),
path: safePath,
network
});
const rushedHDSigner = new SoftHDSigner({
mnemonic: generateMnemonic(256)
});
await rushedHDSigner.init();
const rushedPath = getNextDerivationPath({
isChange: false,
usedPaths: [],
network
});
expect(rushedPath).toEqual("84'/1'/0'/0/0");
const rushedPublicKey = await rushedHDSigner.getPublicKey(
rushedPath,
network
);
const maturedHDSigner = new SoftHDSigner({
mnemonic: generateMnemonic(256)
});
await maturedHDSigner.init();
const maturedPath = getNextDerivationPath({
isChange: false,
usedPaths: [],
network
});
expect(maturedPath).toEqual("84'/1'/0'/0/0");
const maturedPublicKey = await maturedHDSigner.getPublicKey(
maturedPath,
network
);
//Get the list of paths that may receive funds from the setup file
//Try not to re-use addresses that may be used as destinataries of
//other vaults.
const setup = readSetup() || { vaults: {} };
const prereservedPaths = Object.values(setup.vaults).map(
vault => vault.hotPath
);
const hotPath = getNextDerivationPath({
usedPaths,
prereservedPaths,
isChange: false,
skip: VAULT_SKIP,
network
});
prereservedPaths.push(hotPath);
//console.log({ usedPaths, prereservedPaths, nextPath: hotPath });
const hotPublicKey = await hotHDSigner.getPublicKey(hotPath, network);
const feeEstimates = await blockstreamExplorer.fetchFeeEstimates();
const guardTxFeeRate = pickFeeEstimate(feeEstimates, guardTxTargetTime);
//Get which utxos will be protected. utxos are selected based on
//the number of sats (safeValue) that the user selected
const {
utxos: fundsUtxos,
fee: safeFee,
targets: guardTargets
} = await coinselect({
utxos,
targets: [
{
address: safeAddress,
value: safeValue
}
],
changeAddress: async () => {
const path = getNextDerivationPath({
isChange: true,
usedPaths,
prereservedPaths,
network
});
prereservedPaths.push(path);
return await getDerivationPathAddress({
extPubGetter: hotHDSigner.getExtPub.bind(hotHDSigner),
path,
network
});
},
feeRate: guardTxFeeRate,
network
});
expect(fundsUtxos).not.toBeUndefined();
expect(guardTargets).not.toBeUndefined();
console.log(
'WARNING! Test it also with send all so that targets.length === 1'
);
const timer = Date.now();
//Create the transaction that will send the funds to safeAddress.
//We won't keep the keys of this safeAddress. We will save
//pre-computed txs that can unlock them based on a contract.
const guardTx = await createTransaction({
utxos: fundsUtxos,
targets: guardTargets,
getPublicKey: hotHDSigner.getPublicKey.bind(hotHDSigner),
createSigners: hotHDSigner.createSigners.bind(hotHDSigner),
network
});
const guardTxid = decodeTx(guardTx, network).txid;
console.log('WARNING! Should check the fees here somehow');
const bip68LockTime = bip68.encode({
//seconds must be a multiple of 512
//seconds: Math.round(lockTime / 512) * 512
blocks: lockNBlocks
});
const relativeTimeLockScript = createRelativeTimeLockScript({
maturedPublicKey,
rushedPublicKey,
bip68LockTime
});
//console.log({ relativeTimeLockScript });
const recoverTxs = await createMultiFeeTransactions({
utxos: [
{
path: safePath,
n: 0,
tx: guardTx
}
],
address: payments.p2wsh({
redeem: {
output: relativeTimeLockScript,
network
},
network
}).address,
getPublicKey: safeHDSigner.getPublicKey.bind(safeHDSigner),
createSigners: safeHDSigner.createSigners.bind(safeHDSigner),
feeRateSamplingParams: { samples: MULTIFEE_SAMPLES },
network
});
if (!Array.isArray(recoverTxs) || recoverTxs.length === 0) {
throw new Error('Could not create recover funds txs');
}
const hotAddress = await getDerivationPathAddress({
//unlock will use hotHDSigner. cancel will use rushedHDSigner
extPubGetter: hotHDSigner.getExtPub.bind(hotHDSigner),
//unlock will use hotHDSigner. cancel will use coldDerivationPath
path: hotPath,
network
});
setup.vaults[guardTxid] = {
hotPath,
hotAddress,
coldAddress,
guardTx,
guardTxid,
recoverTxs: {}
};
for (const recoverTx of recoverTxs) {
const unlockTxs = await createMultiFeeTransactions({
utxos: [
{
tx: recoverTx.tx,
n: 0,
path: maturedPath,
witnessScript: relativeTimeLockScript.toString('hex')
}
],
address: hotAddress,
getPublicKey: maturedHDSigner.getPublicKey.bind(maturedHDSigner),
createSigners: maturedHDSigner.createSigners.bind(maturedHDSigner),
feeRateSamplingParams: { samples: MULTIFEE_SAMPLES },
network
});
const cancelTxs = await createMultiFeeTransactions({
utxos: [
{
tx: recoverTx.tx,
n: 0,
path: rushedPath,
witnessScript: relativeTimeLockScript.toString('hex')
}
],
address: coldAddress,
getPublicKey: rushedHDSigner.getPublicKey.bind(rushedHDSigner),
createSigners: rushedHDSigner.createSigners.bind(rushedHDSigner),
feeRateSamplingParams: { samples: MULTIFEE_SAMPLES },
network
});
setup.vaults[guardTxid].recoverTxs[
decodeTx(recoverTx.tx, network).txid
] = {
txid: decodeTx(recoverTx.tx, network).txid,
tx: recoverTx.tx,
feeRate: recoverTx.feeRate,
fee: recoverTx.fee,
unlockTxs,
cancelTxs
};
}
console.log(
'Vault creation time: ' + Math.round((Date.now() - timer) / 1000)
);
writeSetup(setup);
//CREATE A FUNCTION IN FEES FOR THIS BLOCK
//
//
const unlockTxFeeRate = pickFeeEstimate(
feeEstimates,
unlockTxTargetTime
);
//TODO: encapsulate this into a function and test it.
//Note that we will het a setup object (not an array)
//Pick the best recoverTx as the one with the lowest feeRate that is
//larger than the unlockTxFeeRate.
//If none of the recoverTx has a feeRate larger than unlockTxFeeRate
//then pick the one with largest feeRate.
const recoverTx = recoverTxs.reduce((best, curr) =>
(curr.feeRate >= unlockTxFeeRate && curr.feeRate < best.feeRate) ||
(best.feeRate < unlockTxFeeRate && curr.feeRate > best.feeRate)
? curr
: best
);
//
//
//CREATE A FUNCTION IN FEES FOR THIS BLOCK
//Note that we're picking 5 below. Use the function to get the correct tx based on fee.
const recoverTxid = decodeTx(recoverTx.tx, network).txid;
await regtestUtils.broadcast(guardTx);
const unlockTx =
setup.vaults[guardTxid].recoverTxs[recoverTxid].unlockTxs[5].tx;
await regtestUtils.broadcast(
setup.vaults[guardTxid].recoverTxs[recoverTxid].tx
);
//Rejection reason should be non-BIP68-final
if (lockNBlocks > 1)
console.log(await regtestUtils.mine(lockNBlocks - 1));
await expect(regtestUtils.broadcast(unlockTx)).rejects.toThrow(
'non-BIP68-final'
);
await regtestUtils.mine(1);
await expect(regtestUtils.broadcast(unlockTx)).resolves.toEqual(null);
//console.log(await regtestUtils.mine(1));
await regtestUtils.fetch(recoverTxid);
await regtestUtils.fetch(decodeTx(unlockTx, network).txid);
//await regtestUtils.broadcast(guardTx);
//const cancelTx = setup.vaults.[guardTxid].recoverTxs[recoverTxid].cancelTxs[5].tx;
//await regtestUtils.broadcast(setup.vaults.[guardTxid].recoverTxs[recoverTxid].tx);
//await regtestUtils.broadcast(cancelTx);
//console.log(await regtestUtils.mine(6));
//console.log(await regtestUtils.fetch(recoverTxid));
//console.log(await regtestUtils.fetch(decodeTx(cancelTx, network).txid));
},
ESPLORA_CATCH_UP_TIME +
BITCOIND_CATCH_UP_TIME +
REGTEST_SERVER_CATCH_UP_TIME +
TEST_TIME
);
});
});