@dashevo/dash-spv 6.0.2 → 6.1.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/test/reorg.js ADDED
@@ -0,0 +1,359 @@
1
+ const { expect } = require('chai');
2
+ const { BlockHeader } = require('@dashevo/dashcore-lib');
3
+
4
+ const SpvChain = require('../lib/spvchain');
5
+ const pow = require('../lib/pow');
6
+ const utils = require('../lib/utils');
7
+
8
+ const REGTEST_BITS = 0x207fffff;
9
+
10
+ // Mines a regtest header on `prev`; `salt` makes sibling headers differ
11
+ const mine = (prev, salt = 0) => {
12
+ const merkleRoot = Buffer.alloc(32);
13
+ merkleRoot.writeUInt32LE(salt);
14
+ let nonce = 0;
15
+ let header;
16
+ do {
17
+ header = new BlockHeader({
18
+ version: 2,
19
+ prevHash: Buffer.from(prev.hash, 'hex').reverse(),
20
+ merkleRoot,
21
+ time: prev.time + 1,
22
+ bits: REGTEST_BITS,
23
+ nonce,
24
+ });
25
+ nonce += 1;
26
+ } while (!utils.validProofOfWork(header));
27
+ return header;
28
+ };
29
+
30
+ const mineChain = (from, length, salt = 0) => {
31
+ const headers = [];
32
+ let prev = from;
33
+ for (let i = 0; i < length; i += 1) {
34
+ prev = mine(prev, salt);
35
+ headers.push(prev);
36
+ }
37
+ return headers;
38
+ };
39
+
40
+ describe('SpvChain reorgs', () => {
41
+ let chain;
42
+ let main;
43
+ let connected;
44
+
45
+ before(async () => {
46
+ await SpvChain.wasmX11Ready();
47
+ });
48
+
49
+ beforeEach(() => {
50
+ chain = new SpvChain('regtest');
51
+ chain.initialize();
52
+ main = mineChain(chain.genesis, 5);
53
+ chain.addHeaders(main);
54
+
55
+ connected = [];
56
+ chain.on(SpvChain.EVENTS.CONNECTED, (headers, firstHeight) => {
57
+ connected.push({ hashes: headers.map((h) => h.hash), firstHeight });
58
+ });
59
+ });
60
+
61
+ it('should switch to a fork from below the tip once it has more work', () => {
62
+ const fork = mineChain(main[3], 2, 1); // heights 5 and 6, on height 4
63
+
64
+ chain.addHeaders([fork[0]]);
65
+ expect(chain.getTipHash()).to.equal(main[4].hash);
66
+
67
+ chain.addHeaders([fork[1]]);
68
+
69
+ expect(chain.getTipHash()).to.equal(fork[1].hash);
70
+ expect(chain.getTipHeight()).to.equal(6);
71
+ expect(chain.hashesByHeight.get(5)).to.equal(fork[0].hash);
72
+ expect(chain.heightByHash.has(main[4].hash)).to.equal(false);
73
+ expect(chain.getOrphanChunks()).to.have.lengthOf(0);
74
+ expect(() => chain.validate()).to.not.throw();
75
+ expect(connected).to.deep.equal([{ hashes: fork.map((h) => h.hash), firstHeight: 5 }]);
76
+ });
77
+
78
+ it('should keep following the new chain after a reorg', () => {
79
+ const fork = mineChain(main[3], 2, 1);
80
+ chain.addHeaders(fork);
81
+
82
+ const next = mine(fork[1]);
83
+ chain.addHeaders([next]);
84
+
85
+ expect(chain.getTipHash()).to.equal(next.hash);
86
+ expect(chain.getTipHeight()).to.equal(7);
87
+ });
88
+
89
+ it('should switch back when the old chain outgrows the fork', () => {
90
+ const fork = mineChain(main[3], 2, 1);
91
+ chain.addHeaders(fork);
92
+
93
+ const oldChainExtension = mineChain(main[4], 2); // heights 6 and 7 on the first chain
94
+ chain.addHeaders(oldChainExtension);
95
+
96
+ expect(chain.getTipHash()).to.equal(oldChainExtension[1].hash);
97
+ expect(chain.hashesByHeight.get(5)).to.equal(main[4].hash);
98
+ expect(connected[connected.length - 1]).to.deep.equal({
99
+ hashes: [main[4], ...oldChainExtension].map((h) => h.hash),
100
+ firstHeight: 5,
101
+ });
102
+ });
103
+
104
+ it('should report headers connected to the tip with their height', () => {
105
+ const next = mineChain(main[4], 2);
106
+ chain.addHeaders(next);
107
+
108
+ expect(connected).to.deep.equal([{ hashes: next.map((h) => h.hash), firstHeight: 6 }]);
109
+ });
110
+
111
+ it('should reject a fork from below the confirmed headers', () => {
112
+ chain = new SpvChain('regtest', 3);
113
+ chain.initialize();
114
+ chain.addHeaders(main);
115
+
116
+ expect(() => chain.addHeaders(mineChain(main[0], 6, 1))).to.throw();
117
+ expect(chain.getTipHash()).to.equal(main[4].hash);
118
+ });
119
+ });
120
+
121
+ describe('SpvChain memory', () => {
122
+ let chain;
123
+ let headers;
124
+
125
+ before(async () => {
126
+ await SpvChain.wasmX11Ready();
127
+ chain = new SpvChain('regtest');
128
+ chain.initialize();
129
+ headers = mineChain(chain.genesis, pow.MAX_HISTORY + 1000);
130
+ chain.addHeaders(headers);
131
+ });
132
+
133
+ it('should keep only the confirmed headers validation reads', () => {
134
+ expect(chain.getLongestChain()).to.have.lengthOf(100);
135
+ expect(chain.prunedHeaders).to.have.lengthOf(pow.MAX_HISTORY);
136
+ expect(chain.hashesByHeight.size).to.equal(pow.MAX_HISTORY + 100);
137
+ expect(chain.heightByHash.size).to.equal(pow.MAX_HISTORY + 100);
138
+ expect(() => chain.validate()).to.not.throw();
139
+ });
140
+
141
+ it('should still know the tip height', () => {
142
+ expect(chain.getTipHeight()).to.equal(headers.length);
143
+ expect(chain.hashesByHeight.get(headers.length)).to.equal(headers[headers.length - 1].hash);
144
+ });
145
+
146
+ it('should find kept headers by hash, confirmed or not', () => {
147
+ const confirmed = headers[headers.length - 200];
148
+ const unconfirmed = headers[headers.length - 50];
149
+
150
+ expect(chain.getHeader(confirmed.hash).hash).to.equal(confirmed.hash);
151
+ expect(chain.getHeader(unconfirmed.hash).hash).to.equal(unconfirmed.hash);
152
+ expect(chain.getHeader(headers[0].hash)).to.equal(undefined);
153
+ });
154
+
155
+ it('should keep validating new headers', () => {
156
+ const next = mineChain(headers[headers.length - 1], 3);
157
+ chain.addHeaders(next);
158
+
159
+ expect(chain.getTipHash()).to.equal(next[2].hash);
160
+ expect(chain.prunedHeaders).to.have.lengthOf(pow.MAX_HISTORY);
161
+ });
162
+ });
163
+
164
+ describe('SpvChain forks', () => {
165
+ let chain;
166
+ let main;
167
+
168
+ before(async () => {
169
+ await SpvChain.wasmX11Ready();
170
+ });
171
+
172
+ beforeEach(() => {
173
+ chain = new SpvChain('regtest', 3);
174
+ chain.initialize();
175
+ main = mineChain(chain.genesis, 5);
176
+ chain.addHeaders(main);
177
+ });
178
+
179
+ it('should keep the main chain first while a fork has less work', () => {
180
+ const fork = mine(main[3], 1);
181
+ chain.addHeaders([fork]);
182
+
183
+ expect(chain.getAllBranches()).to.have.lengthOf(2);
184
+ expect(chain.getLongestChain()[2].hash).to.equal(main[4].hash);
185
+ expect(chain.getTipHash()).to.equal(main[4].hash);
186
+ });
187
+
188
+ it('should ignore fork headers it already has', () => {
189
+ const fork = mineChain(main[3], 2, 1);
190
+ chain.addHeaders(fork);
191
+
192
+ const branches = chain.getAllBranches().map((branch) => branch.map((h) => h.hash));
193
+
194
+ chain.addHeaders([main[3], ...fork]);
195
+
196
+ expect(chain.getAllBranches().map((branch) => branch.map((h) => h.hash)))
197
+ .to.deep.equal(branches);
198
+ expect(chain.getTipHash()).to.equal(fork[1].hash);
199
+ });
200
+
201
+ it('should start a fork off a fork header', () => {
202
+ // Same work as the main chain's heights 4 and 5, so no reorg
203
+ const fork = mineChain(main[2], 2, 1);
204
+ chain.addHeaders(fork);
205
+ const forkOfFork = mineChain(fork[0], 2, 2);
206
+
207
+ chain.addHeaders(forkOfFork);
208
+
209
+ // Heights 4' 5'' 6'' have more work than 4 and 5
210
+ expect(chain.getTipHash()).to.equal(forkOfFork[1].hash);
211
+ expect(chain.hashesByHeight.get(4)).to.equal(fork[0].hash);
212
+ expect(chain.getTipHeight()).to.equal(6);
213
+ expect(() => chain.validate()).to.not.throw();
214
+ // The two replaced headers and the rest of the first fork remain, the
215
+ // latter now rooted at its header that joined the main chain
216
+ expect(chain.getAllBranches().slice(1).map((branch) => branch.map((h) => h.hash)))
217
+ .to.have.deep.members([[main[3].hash, main[4].hash], [fork[1].hash]]);
218
+ });
219
+
220
+ it('should keep a fork whose start joined the main chain while it can still win', () => {
221
+ // As above: main chain A1..A3 B4 C5 C6, with B5 left on the side
222
+ const fork = mineChain(main[2], 2, 1);
223
+ chain.addHeaders(fork);
224
+ const forkOfFork = mineChain(fork[0], 2, 2);
225
+ chain.addHeaders(forkOfFork);
226
+
227
+ // C7 confirms height 4 (B4); B5 still forks off it, at unconfirmed height 5
228
+ chain.addHeaders([mine(forkOfFork[1], 3)]);
229
+
230
+ const winner = mineChain(fork[1], 3, 4); // B6 B7 B8
231
+ chain.addHeaders(winner);
232
+
233
+ expect(chain.getTipHash()).to.equal(winner[2].hash);
234
+ expect(chain.hashesByHeight.get(5)).to.equal(fork[1].hash);
235
+ expect(() => chain.validate()).to.not.throw();
236
+ });
237
+
238
+ it('should drop an invalid orphan chunk without rejecting the headers that connected it', () => {
239
+ chain = new SpvChain('regtest', 100);
240
+ chain.initialize();
241
+ chain.addHeaders(main.slice(0, 3));
242
+ // A child of height 5 that is older than the median time before it
243
+ let invalid;
244
+ let nonce = 0;
245
+ do {
246
+ invalid = new BlockHeader({
247
+ version: 2,
248
+ prevHash: Buffer.from(main[4].hash, 'hex').reverse(),
249
+ merkleRoot: Buffer.alloc(32),
250
+ time: chain.genesis.time,
251
+ bits: REGTEST_BITS,
252
+ nonce,
253
+ });
254
+ nonce += 1;
255
+ } while (!utils.validProofOfWork(invalid));
256
+ chain.addHeaders([invalid]);
257
+ expect(chain.getOrphanChunks()).to.have.lengthOf(1);
258
+
259
+ chain.addHeaders(main.slice(3));
260
+
261
+ expect(chain.getTipHash()).to.equal(main[4].hash);
262
+ expect(chain.getOrphanChunks()).to.have.lengthOf(0);
263
+ expect(chain.hasHeader(invalid.hash)).to.equal(false);
264
+ });
265
+
266
+ it('should connect headers that arrived before the fork header they continue', () => {
267
+ chain = new SpvChain('regtest', 100);
268
+ chain.initialize();
269
+ chain.addHeaders(main);
270
+ const forkAt5 = mine(main[3], 1);
271
+ const [forkAt6, forkAt7] = mineChain(forkAt5, 2, 1);
272
+
273
+ chain.addHeaders([forkAt6, forkAt7]);
274
+ expect(chain.getOrphanChunks()).to.have.lengthOf(1);
275
+
276
+ chain.addHeaders([forkAt5]);
277
+
278
+ expect(chain.getOrphanChunks()).to.have.lengthOf(0);
279
+ expect(chain.getTipHash()).to.equal(forkAt7.hash);
280
+ expect(() => chain.validate()).to.not.throw();
281
+ });
282
+
283
+ it('should keep at most 10 forks, dropping the oldest', () => {
284
+ chain = new SpvChain('regtest', 100);
285
+ chain.initialize();
286
+ chain.addHeaders(main);
287
+ const forks = [];
288
+ for (let salt = 1; salt <= 11; salt += 1) {
289
+ forks.push(mine(main[3], salt));
290
+ chain.addHeaders([forks[forks.length - 1]]);
291
+ }
292
+
293
+ expect(chain.getAllBranches()).to.have.lengthOf(11);
294
+ expect(chain.hasHeader(forks[0].hash)).to.equal(false);
295
+ expect(chain.hasHeader(forks[10].hash)).to.equal(true);
296
+ });
297
+
298
+ it('should still keep at most 10 forks after a reorg', () => {
299
+ chain = new SpvChain('regtest', 100);
300
+ chain.initialize();
301
+ chain.addHeaders(main);
302
+ for (let salt = 1; salt <= 10; salt += 1) {
303
+ chain.addHeaders([mine(main[3], salt)]);
304
+ }
305
+
306
+ const winner = mineChain(main[3], 2, 11);
307
+ chain.addHeaders(winner);
308
+
309
+ expect(chain.getTipHash()).to.equal(winner[1].hash);
310
+ expect(chain.getAllBranches()).to.have.lengthOf(11);
311
+ });
312
+
313
+ it('should reorg to a fork much longer than the unconfirmed headers when it has more work', () => {
314
+ // As after a wallet slept through many blocks while its tip was replaced
315
+ const fork = mineChain(main[3], 20, 1);
316
+
317
+ chain.addHeaders(fork);
318
+
319
+ expect(chain.getTipHash()).to.equal(fork[19].hash);
320
+ expect(chain.getTipHeight()).to.equal(24);
321
+ expect(() => chain.validate()).to.not.throw();
322
+ });
323
+
324
+ it('should not keep a fork longer than twice the unconfirmed headers without more work', () => {
325
+ // Every regtest header has the same work, so make the fork's count for less
326
+ const { getChainWork } = pow;
327
+ const fork = mineChain(main[2], 7, 1);
328
+ const forkHashes = new Set(fork.map((h) => h.hash));
329
+ pow.getChainWork = (headers) => (headers.some((h) => forkHashes.has(h.hash))
330
+ ? 0n : getChainWork(headers));
331
+ try {
332
+ expect(() => chain.addHeaders(fork)).to.throw('longer than 6 headers without more work');
333
+ } finally {
334
+ pow.getChainWork = getChainWork;
335
+ }
336
+ expect(chain.getAllBranches()).to.have.lengthOf(1);
337
+ expect(chain.getTipHash()).to.equal(main[4].hash);
338
+ });
339
+
340
+ it('should not keep a fork whose first header is invalid', () => {
341
+ const { hash, ...fields } = mine(main[3], 1).toObject();
342
+ const invalid = new BlockHeader({ ...fields, bits: 0x1d00ffff });
343
+
344
+ expect(() => chain.addHeaders([invalid])).to.throw();
345
+ expect(chain.getAllBranches()).to.have.lengthOf(1);
346
+ });
347
+
348
+ it('should drop a fork once it could only replace confirmed headers', () => {
349
+ chain.addHeaders([mine(main[3], 1)]); // forks off height 4
350
+
351
+ // Heights 5 to 7 unconfirmed: the fork could still replace them
352
+ chain.addHeaders(mineChain(main[4], 2));
353
+ expect(chain.getAllBranches()).to.have.lengthOf(2);
354
+
355
+ // Height 5 confirmed
356
+ chain.addHeaders([mine(chain.getTipHeader())]);
357
+ expect(chain.getAllBranches()).to.have.lengthOf(1);
358
+ });
359
+ });