-
Notifications
You must be signed in to change notification settings - Fork 809
/
chain.js
2959 lines (2367 loc) · 68.5 KB
/
chain.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* chain.js - blockchain management for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const assert = require('bsert');
const path = require('path');
const AsyncEmitter = require('bevent');
const Logger = require('blgr');
const {Lock} = require('bmutex');
const LRU = require('blru');
const {BufferMap} = require('buffer-map');
const Network = require('../protocol/network');
const ChainDB = require('./chaindb');
const common = require('./common');
const consensus = require('../protocol/consensus');
const util = require('../utils/util');
const ChainEntry = require('./chainentry');
const CoinView = require('../coins/coinview');
const Script = require('../script/script');
const {VerifyError} = require('../protocol/errors');
const thresholdStates = common.thresholdStates;
/**
* Blockchain
* @alias module:blockchain.Chain
* @property {ChainDB} db
* @property {ChainEntry?} tip
* @property {Number} height
* @property {DeploymentState} state
*/
class Chain extends AsyncEmitter {
/**
* Create a blockchain.
* @constructor
* @param {Object} options
*/
constructor(options) {
super();
this.opened = false;
this.options = new ChainOptions(options);
this.network = this.options.network;
this.logger = this.options.logger.context('chain');
this.workers = this.options.workers;
this.db = new ChainDB(this.options);
this.locker = new Lock(true, BufferMap);
this.invalid = new LRU(100, null, BufferMap);
this.state = new DeploymentState();
this.tip = new ChainEntry();
this.height = -1;
this.synced = false;
this.orphanMap = new BufferMap();
this.orphanPrev = new BufferMap();
}
/**
* Open the chain, wait for the database to load.
* @returns {Promise}
*/
async open() {
assert(!this.opened, 'Chain is already open.');
this.opened = true;
this.logger.info('Chain is loading.');
if (this.options.checkpoints)
this.logger.info('Checkpoints are enabled.');
if (this.options.coinCache)
this.logger.info('Coin cache is enabled.');
if (this.options.bip91)
this.logger.warning('BIP91 enabled. Segsignal will be enforced.');
if (this.options.bip148)
this.logger.warning('BIP148 enabled. UASF will be enforced.');
await this.db.open();
const tip = await this.db.getTip();
assert(tip);
this.tip = tip;
this.height = tip.height;
this.logger.info('Chain Height: %d', tip.height);
this.logger.memory();
const state = await this.getDeploymentState();
this.setDeploymentState(state);
this.logger.memory();
this.emit('tip', tip);
this.maybeSync();
}
/**
* Close the chain, wait for the database to close.
* @returns {Promise}
*/
async close() {
assert(this.opened, 'Chain is not open.');
this.opened = false;
return this.db.close();
}
/**
* Perform all necessary contextual verification on a block.
* @private
* @param {Block} block
* @param {ChainEntry} prev
* @param {Number} flags
* @returns {Promise} - Returns {@link ContextResult}.
*/
async verifyContext(block, prev, flags) {
// Initial non-contextual verification.
const state = await this.verify(block, prev, flags);
// Skip everything if we're in SPV mode.
if (this.options.spv) {
const view = new CoinView();
return [view, state];
}
// Skip everything if we're using checkpoints.
if (this.isHistorical(prev)) {
const view = await this.updateInputs(block, prev);
return [view, state];
}
// BIP30 - Verify there are no duplicate txids.
// Note that BIP34 made it impossible to create
// duplicate txids.
if (!state.hasBIP34())
await this.verifyDuplicates(block, prev);
// Verify scripts, spend and add coins.
const view = await this.verifyInputs(block, prev, state);
return [view, state];
}
/**
* Perform all necessary contextual verification
* on a block, without POW check.
* @param {Block} block
* @returns {Promise}
*/
async verifyBlock(block) {
const unlock = await this.locker.lock();
try {
return await this._verifyBlock(block);
} finally {
unlock();
}
}
/**
* Perform all necessary contextual verification
* on a block, without POW check (no lock).
* @private
* @param {Block} block
* @returns {Promise}
*/
async _verifyBlock(block) {
const flags = common.flags.DEFAULT_FLAGS & ~common.flags.VERIFY_POW;
return this.verifyContext(block, this.tip, flags);
}
/**
* Test whether the hash is in the main chain.
* @param {Hash} hash
* @returns {Promise} - Returns Boolean.
*/
isMainHash(hash) {
return this.db.isMainHash(hash);
}
/**
* Test whether the entry is in the main chain.
* @param {ChainEntry} entry
* @returns {Promise} - Returns Boolean.
*/
isMainChain(entry) {
return this.db.isMainChain(entry);
}
/**
* Get ancestor by `height`.
* @param {ChainEntry} entry
* @param {Number} height
* @returns {Promise} - Returns ChainEntry.
*/
getAncestor(entry, height) {
return this.db.getAncestor(entry, height);
}
/**
* Get previous entry.
* @param {ChainEntry} entry
* @returns {Promise} - Returns ChainEntry.
*/
getPrevious(entry) {
return this.db.getPrevious(entry);
}
/**
* Get previous cached entry.
* @param {ChainEntry} entry
* @returns {ChainEntry|null}
*/
getPrevCache(entry) {
return this.db.getPrevCache(entry);
}
/**
* Get next entry.
* @param {ChainEntry} entry
* @returns {Promise} - Returns ChainEntry.
*/
getNext(entry) {
return this.db.getNext(entry);
}
/**
* Get next entry.
* @param {ChainEntry} entry
* @returns {Promise} - Returns ChainEntry.
*/
getNextEntry(entry) {
return this.db.getNextEntry(entry);
}
/**
* Calculate median time past.
* @param {ChainEntry} prev
* @param {Number?} time
* @returns {Promise} - Returns Number.
*/
async getMedianTime(prev, time) {
let timespan = consensus.MEDIAN_TIMESPAN;
const median = [];
// In case we ever want to check
// the MTP of the _current_ block
// (necessary for BIP148).
if (time != null) {
median.push(time);
timespan -= 1;
}
let entry = prev;
for (let i = 0; i < timespan && entry; i++) {
median.push(entry.time);
const cache = this.getPrevCache(entry);
if (cache)
entry = cache;
else
entry = await this.getPrevious(entry);
}
median.sort(cmp);
return median[median.length >>> 1];
}
/**
* Test whether the entry is potentially
* an ancestor of a checkpoint.
* @param {ChainEntry} prev
* @returns {Boolean}
*/
isHistorical(prev) {
if (this.options.checkpoints) {
if (prev.height + 1 <= this.network.lastCheckpoint)
return true;
}
return false;
}
/**
* Contextual verification for a block, including
* version deployments (IsSuperMajority), versionbits,
* coinbase height, finality checks.
* @private
* @param {Block} block
* @param {ChainEntry} prev
* @param {Number} flags
* @returns {Promise} - Returns {@link DeploymentState}.
*/
async verify(block, prev, flags) {
assert(typeof flags === 'number');
// Extra sanity check.
if (!block.prevBlock.equals(prev.hash))
throw new VerifyError(block, 'invalid', 'bad-prevblk', 0);
// Verify a checkpoint if there is one.
const hash = block.hash();
if (!this.verifyCheckpoint(prev, hash)) {
throw new VerifyError(block,
'checkpoint',
'checkpoint mismatch',
100);
}
// Skip everything when using checkpoints.
// We can do this safely because every
// block in between each checkpoint was
// validated outside in the header chain.
if (this.isHistorical(prev)) {
if (this.options.spv)
return this.state;
// Check merkle root.
if (flags & common.flags.VERIFY_BODY) {
assert(typeof block.createMerkleRoot === 'function');
const root = block.createMerkleRoot();
if (!root || !block.merkleRoot.equals(root)) {
throw new VerifyError(block,
'invalid',
'bad-txnmrklroot',
100,
true);
}
flags &= ~common.flags.VERIFY_BODY;
}
// Once segwit is active, we will still
// need to check for block mutability.
if (!block.hasWitness() && !block.getCommitmentHash())
return new DeploymentState();
}
// Non-contextual checks.
if (flags & common.flags.VERIFY_BODY) {
const [valid, reason, score] = block.checkBody();
if (!valid)
throw new VerifyError(block, 'invalid', reason, score, true);
}
// Ensure the POW is what we expect.
const bits = await this.getTarget(block.time, prev);
if (block.bits !== bits) {
throw new VerifyError(block,
'invalid',
'bad-diffbits',
100);
}
// Skip all blocks in spv mode once
// we've verified the network target.
if (this.options.spv)
return this.state;
// Ensure the timestamp is correct.
const mtp = await this.getMedianTime(prev);
if (block.time <= mtp) {
throw new VerifyError(block,
'invalid',
'time-too-old',
0);
}
// Check timestamp against adj-time+2hours.
// If this fails we may be able to accept
// the block later.
if (block.time > this.network.now() + 2 * 60 * 60) {
throw new VerifyError(block,
'invalid',
'time-too-new',
0,
true);
}
// Calculate height of current block.
const height = prev.height + 1;
// Only allow version 2 blocks (coinbase height)
// once the majority of blocks are using it.
if (block.version < 2 && height >= this.network.block.bip34height)
throw new VerifyError(block, 'obsolete', 'bad-version', 0);
// Only allow version 3 blocks (sig validation)
// once the majority of blocks are using it.
if (block.version < 3 && height >= this.network.block.bip66height)
throw new VerifyError(block, 'obsolete', 'bad-version', 0);
// Only allow version 4 blocks (checklocktimeverify)
// once the majority of blocks are using it.
if (block.version < 4 && height >= this.network.block.bip65height)
throw new VerifyError(block, 'obsolete', 'bad-version', 0);
// Get the new deployment state.
const state = await this.getDeployments(block.time, prev);
// Enforce BIP91/BIP148.
if (state.hasBIP91() || state.hasBIP148()) {
const {segwit} = this.network.deployments;
if (!consensus.hasBit(block.version, segwit.bit))
throw new VerifyError(block, 'invalid', 'bad-no-segwit', 0);
}
// Get timestamp for tx.isFinal().
const time = state.hasMTP() ? mtp : block.time;
// Transactions must be finalized with
// regards to nSequence and nLockTime.
for (const tx of block.txs) {
if (!tx.isFinal(height, time)) {
throw new VerifyError(block,
'invalid',
'bad-txns-nonfinal',
10);
}
}
// Make sure the height contained
// in the coinbase is correct.
if (state.hasBIP34()) {
if (block.getCoinbaseHeight() !== height) {
throw new VerifyError(block,
'invalid',
'bad-cb-height',
100);
}
}
// Check the commitment hash for segwit.
let commit = null;
if (state.hasWitness()) {
commit = block.getCommitmentHash();
if (commit) {
// These are totally malleable. Someone
// may have even accidentally sent us
// the non-witness version of the block.
// We don't want to consider this block
// "invalid" if either of these checks
// fail.
if (!block.getWitnessNonce()) {
throw new VerifyError(block,
'invalid',
'bad-witness-nonce-size',
100,
true);
}
if (!commit.equals(block.createCommitmentHash())) {
throw new VerifyError(block,
'invalid',
'bad-witness-merkle-match',
100,
true);
}
}
}
// Blocks that do not commit to
// witness data cannot contain it.
if (!commit) {
if (block.hasWitness()) {
throw new VerifyError(block,
'invalid',
'unexpected-witness',
100,
true);
}
}
// Check block weight (different from block size
// check in non-contextual verification).
if (block.getWeight() > consensus.MAX_BLOCK_WEIGHT) {
throw new VerifyError(block,
'invalid',
'bad-blk-weight',
100);
}
return state;
}
/**
* Check all deployments on a chain, ranging from p2sh to segwit.
* @param {Number} time
* @param {ChainEntry} prev
* @returns {Promise} - Returns {@link DeploymentState}.
*/
async getDeployments(time, prev) {
const deployments = this.network.deployments;
const height = prev.height + 1;
const state = new DeploymentState();
// For some reason bitcoind has p2sh in the
// mandatory flags by default, when in reality
// it wasn't activated until march 30th 2012.
// The first p2sh output and redeem script
// appeared on march 7th 2012, only it did
// not have a signature. See:
// 6a26d2ecb67f27d1fa5524763b49029d7106e91e3cc05743073461a719776192
// 9c08a4d78931342b37fd5f72900fb9983087e6f46c4a097d8a1f52c74e28eaf6
if (time >= consensus.BIP16_TIME)
state.flags |= Script.flags.VERIFY_P2SH;
// Coinbase heights are now enforced (bip34).
if (height >= this.network.block.bip34height)
state.bip34 = true;
// Signature validation is now enforced (bip66).
if (height >= this.network.block.bip66height)
state.flags |= Script.flags.VERIFY_DERSIG;
// CHECKLOCKTIMEVERIFY is now usable (bip65).
if (height >= this.network.block.bip65height)
state.flags |= Script.flags.VERIFY_CHECKLOCKTIMEVERIFY;
// CHECKSEQUENCEVERIFY and median time
// past locktimes are now usable (bip9 & bip113).
if (await this.isActive(prev, deployments.csv)) {
state.flags |= Script.flags.VERIFY_CHECKSEQUENCEVERIFY;
state.lockFlags |= common.lockFlags.VERIFY_SEQUENCE;
state.lockFlags |= common.lockFlags.MEDIAN_TIME_PAST;
}
// Check the state of the segwit deployment.
const witness = await this.getState(prev, deployments.segwit);
// Segregrated witness (bip141) is now usable
// along with SCRIPT_VERIFY_NULLDUMMY (bip147).
if (witness === thresholdStates.ACTIVE) {
state.flags |= Script.flags.VERIFY_WITNESS;
state.flags |= Script.flags.VERIFY_NULLDUMMY;
}
// Segsignal is now enforced (bip91).
if (this.options.bip91) {
if (witness === thresholdStates.STARTED) {
if (await this.isActive(prev, deployments.segsignal))
state.bip91 = true;
}
}
// UASF is now enforced (bip148) (mainnet-only).
if (this.options.bip148 && this.network === Network.main) {
if (witness !== thresholdStates.LOCKED_IN
&& witness !== thresholdStates.ACTIVE) {
// The BIP148 MTP check is nonsensical in
// that it includes the _current_ entry's
// timestamp. This requires some hackery,
// since bcoin only operates on the sane
// assumption that deployment checks should
// only ever examine the values of the
// previous block (necessary for mining).
const mtp = await this.getMedianTime(prev, time);
if (mtp >= 1501545600 && mtp <= 1510704000)
state.bip148 = true;
}
}
return state;
}
/**
* Set a new deployment state.
* @param {DeploymentState} state
*/
setDeploymentState(state) {
if (this.options.checkpoints && this.height < this.network.lastCheckpoint) {
this.state = state;
return;
}
if (!this.state.hasP2SH() && state.hasP2SH())
this.logger.warning('P2SH has been activated.');
if (!this.state.hasBIP34() && state.hasBIP34())
this.logger.warning('BIP34 has been activated.');
if (!this.state.hasBIP66() && state.hasBIP66())
this.logger.warning('BIP66 has been activated.');
if (!this.state.hasCLTV() && state.hasCLTV())
this.logger.warning('BIP65 has been activated.');
if (!this.state.hasCSV() && state.hasCSV())
this.logger.warning('CSV has been activated.');
if (!this.state.hasWitness() && state.hasWitness())
this.logger.warning('Segwit has been activated.');
if (!this.state.hasBIP91() && state.hasBIP91())
this.logger.warning('BIP91 has been activated.');
if (!this.state.hasBIP148() && state.hasBIP148())
this.logger.warning('BIP148 has been activated.');
this.state = state;
}
/**
* Determine whether to check block for duplicate txids in blockchain
* history (BIP30). If we're on a chain that has bip34 activated, we
* can skip this.
* @private
* @see https://github.com/bitcoin/bips/blob/master/bip-0030.mediawiki
* @param {Block} block
* @param {ChainEntry} prev
* @returns {Promise}
*/
async verifyDuplicates(block, prev) {
for (const tx of block.txs) {
if (!await this.hasCoins(tx))
continue;
const height = prev.height + 1;
const hash = this.network.bip30[height];
// Blocks 91842 and 91880 created duplicate
// txids by using the same exact output script
// and extraNonce.
if (!hash || !block.hash().equals(hash))
throw new VerifyError(block, 'invalid', 'bad-txns-BIP30', 100);
}
}
/**
* Spend and update inputs (checkpoints only).
* @private
* @param {Block} block
* @param {ChainEntry} prev
* @returns {Promise} - Returns {@link CoinView}.
*/
async updateInputs(block, prev) {
const view = new CoinView();
const height = prev.height + 1;
const cb = block.txs[0];
view.addTX(cb, height);
for (let i = 1; i < block.txs.length; i++) {
const tx = block.txs[i];
assert(await view.spendInputs(this.db, tx),
'BUG: Spent inputs in historical data!');
view.addTX(tx, height);
}
return view;
}
/**
* Check block transactions for all things pertaining
* to inputs. This function is important because it is
* what actually fills the coins into the block. This
* function will check the block reward, the sigops,
* the tx values, and execute and verify the scripts (it
* will attempt to do this on the worker pool). If
* `checkpoints` is enabled, it will skip verification
* for historical data.
* @private
* @see TX#verifyInputs
* @see TX#verify
* @param {Block} block
* @param {ChainEntry} prev
* @param {DeploymentState} state
* @returns {Promise} - Returns {@link CoinView}.
*/
async verifyInputs(block, prev, state) {
const view = new CoinView();
const height = prev.height + 1;
const interval = this.network.halvingInterval;
let sigops = 0;
let reward = 0;
// Check all transactions
for (let i = 0; i < block.txs.length; i++) {
const tx = block.txs[i];
// Ensure tx is not double spending an output.
if (i > 0) {
if (!await view.spendInputs(this.db, tx)) {
throw new VerifyError(block,
'invalid',
'bad-txns-inputs-missingorspent',
100);
}
}
// Verify sequence locks.
if (i > 0 && tx.version >= 2) {
const valid = await this.verifyLocks(prev, tx, view, state.lockFlags);
if (!valid) {
throw new VerifyError(block,
'invalid',
'bad-txns-nonfinal',
100);
}
}
// Count sigops (legacy + scripthash? + witness?)
sigops += tx.getSigopsCost(view, state.flags);
if (sigops > consensus.MAX_BLOCK_SIGOPS_COST) {
throw new VerifyError(block,
'invalid',
'bad-blk-sigops',
100);
}
// Contextual sanity checks.
if (i > 0) {
const [fee, reason, score] = tx.checkInputs(view, height);
if (fee === -1) {
throw new VerifyError(block,
'invalid',
reason,
score);
}
reward += fee;
if (reward > consensus.MAX_MONEY) {
throw new VerifyError(block,
'invalid',
'bad-cb-amount',
100);
}
}
// Add new coins.
view.addTX(tx, height);
}
// Make sure the miner isn't trying to conjure more coins.
reward += consensus.getReward(height, interval);
if (block.getClaimed() > reward) {
throw new VerifyError(block,
'invalid',
'bad-cb-amount',
100);
}
// Push onto verification queue.
const jobs = [];
for (let i = 1; i < block.txs.length; i++) {
const tx = block.txs[i];
jobs.push(tx.verifyAsync(view, state.flags, this.workers));
}
// Verify all txs in parallel.
const results = await Promise.all(jobs);
for (const result of results) {
if (!result) {
throw new VerifyError(block,
'invalid',
'mandatory-script-verify-flag-failed',
100);
}
}
return view;
}
/**
* Find the block at which a fork ocurred.
* @private
* @param {ChainEntry} fork - The current chain.
* @param {ChainEntry} longer - The competing chain.
* @returns {Promise}
*/
async findFork(fork, longer) {
while (!fork.hash.equals(longer.hash)) {
while (longer.height > fork.height) {
longer = await this.getPrevious(longer);
if (!longer)
throw new Error('No previous entry for new tip.');
}
if (fork.hash.equals(longer.hash))
return fork;
fork = await this.getPrevious(fork);
if (!fork)
throw new Error('No previous entry for old tip.');
}
return fork;
}
/**
* Reorganize the blockchain (connect and disconnect inputs).
* Called when a competing chain with a higher chainwork
* is received.
* @private
* @param {ChainEntry} competitor - The competing chain's tip.
* @returns {Promise}
*/
async reorganize(competitor) {
const tip = this.tip;
const fork = await this.findFork(tip, competitor);
assert(fork, 'No free space or data corruption.');
// Blocks to disconnect.
const disconnect = [];
let entry = tip;
while (!entry.hash.equals(fork.hash)) {
disconnect.push(entry);
entry = await this.getPrevious(entry);
assert(entry);
}
// Blocks to connect.
const connect = [];
entry = competitor;
while (!entry.hash.equals(fork.hash)) {
connect.push(entry);
entry = await this.getPrevious(entry);
assert(entry);
}
// Disconnect blocks/txs.
for (let i = 0; i < disconnect.length; i++) {
const entry = disconnect[i];
await this.disconnect(entry);
}
// Connect blocks/txs.
// We don't want to connect the new tip here.
// That will be done outside in setBestChain.
for (let i = connect.length - 1; i >= 1; i--) {
const entry = connect[i];
await this.reconnect(entry);
}
this.logger.warning(
'Chain reorganization: old=%h(%d) new=%h(%d)',
tip.hash,
tip.height,
competitor.hash,
competitor.height
);
await this.emitAsync('reorganize', tip, competitor);
}
/**
* Reorganize the blockchain for SPV. This
* will reset the chain to the fork block.
* @private
* @param {ChainEntry} competitor - The competing chain's tip.
* @returns {Promise}
*/
async reorganizeSPV(competitor) {
const tip = this.tip;
const fork = await this.findFork(tip, competitor);
assert(fork, 'No free space or data corruption.');
// Buffer disconnected blocks.
const disconnect = [];
let entry = tip;
while (!entry.hash.equals(fork.hash)) {
disconnect.push(entry);
entry = await this.getPrevious(entry);
assert(entry);
}
// Reset the main chain back
// to the fork block, causing
// us to redownload the blocks
// on the new main chain.
await this._reset(fork.hash, true);
// Emit disconnection events now that
// the chain has successfully reset.
for (const entry of disconnect) {
const headers = entry.toHeaders();
const view = new CoinView();
await this.emitAsync('disconnect', entry, headers, view);
}
this.logger.warning(
'SPV reorganization: old=%h(%d) new=%h(%d)',
tip.hash,
tip.height,
competitor.hash,
competitor.height
);
this.logger.warning(
'Chain replay from height %d necessary.',
fork.height);
return this.emitAsync('reorganize', tip, competitor);
}
/**
* Disconnect an entry from the chain (updates the tip).
* @param {ChainEntry} entry
* @returns {Promise}
*/
async disconnect(entry) {
let block = await this.getBlock(entry.hash);
if (!block) {
if (!this.options.spv)
throw new Error('Block not found.');
block = entry.toHeaders();
}
const prev = await this.getPrevious(entry);
const view = await this.db.disconnect(entry, block);
assert(prev);
this.tip = prev;
this.height = prev.height;
this.emit('tip', prev);
return this.emitAsync('disconnect', entry, block, view);
}
/**
* Reconnect an entry to the chain (updates the tip).
* This will do contextual-verification on the block
* (necessary because we cannot validate the inputs
* in alternate chains when they come in).
* @param {ChainEntry} entry
* @param {Number} flags
* @returns {Promise}
*/
async reconnect(entry) {
const flags = common.flags.VERIFY_NONE;
let block = await this.getBlock(entry.hash);
if (!block) {
if (!this.options.spv)
throw new Error('Block not found.');
block = entry.toHeaders();