This repository has been archived by the owner on Apr 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
/
index.ts
1199 lines (1071 loc) · 29.8 KB
/
index.ts
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
import * as async from 'async'
import { BN, rlp } from 'ethereumjs-util'
import Common from 'ethereumjs-common'
import { callbackify } from './callbackify'
import DBManager from './dbManager'
import {
bodyKey,
bufBE8,
hashToNumberKey,
headBlockKey,
headHeaderKey,
headerKey,
numberToHashKey,
tdKey,
} from './util'
const Block = require('ethereumjs-block')
const Ethash = require('ethashjs')
const Stoplight = require('flow-stoplight')
const level = require('level-mem')
const semaphore = require('semaphore')
export type Block = any
export interface BlockchainInterface {
/**
* Adds a block to the blockchain.
*
* @param block - The block to be added to the blockchain.
* @param cb - The callback. It is given two parameters `err` and the saved `block`
* @param isGenesis - True if block is the genesis block.
*/
putBlock(block: Block, cb: any, isGenesis?: boolean): void
/**
* Deletes a block from the blockchain. All child blocks in the chain are deleted and any
* encountered heads are set to the parent block.
*
* @param blockHash - The hash of the block to be deleted
* @param cb - A callback.
*/
delBlock(blockHash: Buffer, cb: any): void
/**
* Returns a block by its hash or number.
*/
getBlock(blockTag: Buffer | number | BN, cb: (err: Error | null, block?: Block) => void): void
/**
* Iterates through blocks starting at the specified iterator head and calls the onBlock function
* on each block.
*
* @param name - Name of the state root head
* @param onBlock - Function called on each block with params (block, reorg, cb)
* @param cb - A callback function
*/
iterator(name: string, onBlock: any, cb: any): void
/**
* This method is only here for backwards compatibility. It can be removed once
* [this PR](https://github.com/ethereumjs/ethereumjs-block/pull/72/files) gets merged, released,
* and ethereumjs-block is updated here.
*
* The method should just call `cb` with `null` as first argument.
*/
getDetails(_: string, cb: any): void
}
/**
* This are the options that the Blockchain constructor can receive.
*/
export interface BlockchainOptions {
/**
* The chain id or name. Default: `"mainnet"`.
*/
chain?: string | number
/**
* Hardfork for the blocks. If `undefined` or `null` is passed, it gets computed based on block
* numbers.
*/
hardfork?: string | null
/**
* An alternative way to specify the chain and hardfork is by passing a Common instance.
*/
common?: Common
/**
* Database to store blocks and metadata. Should be a
* [levelup](https://github.com/rvagg/node-levelup) instance.
*/
db?: any
/**
* This the flag indicates if blocks and Proof-of-Work should be validated.
* This option can't be used in conjunction with `validatePow` nor `validateBlocks`.
*
* @deprecated
*/
validate?: boolean
/**
* This flags indicates if Proof-of-work should be validated. If `validate` is provided, this
* option takes its value. If neither `validate` nor this option are provided, it defaults to
* `true`.
*/
validatePow?: boolean
/**
* This flags indicates if blocks should be validated. See Block#validate for details. If
* `validate` is provided, this option takes its value. If neither `validate` nor this option are
* provided, it defaults to `true`.
*/
validateBlocks?: boolean
}
/**
* This class stores and interacts with blocks.
*/
export default class Blockchain implements BlockchainInterface {
/**
* @hidden
*/
_common: Common
/**
* @hidden
*/
_genesis: any
/**
* @hidden
*/
_headBlock: any
/**
* @hidden
*/
_headHeader: any
/**
* @hidden
*/
_heads: any
/**
* @hidden
*/
_initDone: boolean
/**
* @hidden
*/
_initLock: any
/**
* @hidden
*/
_putSemaphore: any
/**
* @hidden
*/
_staleHeadBlock: any
/**
* @hidden
*/
_staleHeads: any
db: any
dbManager: DBManager
ethash: any
/**
* This field is always `true`. It's here only for backwards compatibility.
*
* @deprecated
*/
public readonly validate: boolean = true
private readonly _validatePow: boolean
private readonly _validateBlocks: boolean
/**
* Creates new Blockchain object
*
* @param opts - An object with the options that this constructor takes. See [[BlockchainOptions]].
*/
constructor(opts: BlockchainOptions = {}) {
if (opts.common) {
if (opts.chain) {
throw new Error('Instantiation with both opts.common and opts.chain parameter not allowed!')
}
this._common = opts.common
} else {
const chain = opts.chain ? opts.chain : 'mainnet'
const hardfork = opts.hardfork ? opts.hardfork : null
this._common = new Common(chain, hardfork)
}
if (opts.validate !== undefined) {
if (opts.validatePow !== undefined || opts.validateBlocks !== undefined) {
throw new Error(
"opts.validate can't be used at the same time than opts.validatePow nor opts.validateBlocks",
)
}
}
// defaults
if (opts.validate !== undefined) {
this._validatePow = opts.validate
this._validateBlocks = opts.validate
} else {
this._validatePow = opts.validatePow !== undefined ? opts.validatePow : true
this._validateBlocks = opts.validateBlocks !== undefined ? opts.validateBlocks : true
}
this.db = opts.db ? opts.db : level()
this.dbManager = new DBManager(this.db, this._common)
this.ethash = this._validatePow ? new Ethash(this.db) : null
this._heads = {}
this._genesis = null
this._headHeader = null
this._headBlock = null
this._initDone = false
this._putSemaphore = semaphore(1)
this._initLock = new Stoplight()
this._init((err?: any) => {
if (err) {
throw err
}
this._initLock.go()
})
}
/**
* Returns an object with metadata about the Blockchain. It's defined for backwards compatibility.
*/
get meta() {
return {
rawHead: this._headHeader,
heads: this._heads,
genesis: this._genesis,
}
}
/**
* Fetches the meta info about the blockchain from the db. Meta info contains
* hashes of the headerchain head, blockchain head, genesis block and iterator
* heads.
*
* @hidden
*/
_init(cb: any): void {
const self = this
async.waterfall(
[(cb: any) => self._numberToHash(new BN(0), cb), callbackify(getHeads.bind(this))],
err => {
if (err) {
// if genesis block doesn't exist, create one
return self._setCanonicalGenesisBlock((err?: any) => {
if (err) {
return cb(err)
}
self._heads = {}
self._headHeader = self._genesis
self._headBlock = self._genesis
cb()
})
}
cb()
},
)
async function getHeads(genesisHash: any) {
self._genesis = genesisHash
// load verified iterator heads
try {
const heads = await self.dbManager.getHeads()
Object.keys(heads).forEach(key => {
heads[key] = Buffer.from(heads[key])
})
self._heads = heads
} catch (e) {
self._heads = {}
}
// load headerchain head
let hash
try {
hash = await self.dbManager.getHeadHeader()
self._headHeader = hash
} catch (e) {
self._headHeader = genesisHash
}
// load blockchain head
try {
hash = await self.dbManager.getHeadBlock()
self._headBlock = hash
} catch (e) {
self._headBlock = genesisHash
}
}
}
/**
* Sets the default genesis block
*
* @hidden
*/
_setCanonicalGenesisBlock(cb: any): void {
const genesisBlock = new Block(null, { common: this._common })
genesisBlock.setGenesisParams()
this._putBlockOrHeader(genesisBlock, cb, true)
}
/**
* Puts the genesis block in the database
*
* @param genesis - The genesis block to be added
* @param cb - The callback. It is given two parameters `err` and the saved `block`
*/
putGenesis(genesis: any, cb: any): void {
this.putBlock(genesis, cb, true)
}
/**
* Returns the specified iterator head.
*
* @param name - Optional name of the state root head (default: 'vm')
* @param cb - The callback. It is given two parameters `err` and the returned `block`
*/
getHead(name: any, cb?: any): void {
// handle optional args
if (typeof name === 'function') {
cb = name
name = 'vm'
}
// ensure init completed
this._initLock.await(() => {
// if the head is not found return the headHeader
const hash = this._heads[name] || this._headBlock
if (!hash) {
return cb(new Error('No head found.'))
}
this.getBlock(hash, cb)
})
}
/**
* Returns the latest header in the canonical chain.
*
* @param cb - The callback. It is given two parameters `err` and the returned `header`
*/
getLatestHeader(cb: any): void {
// ensure init completed
this._initLock.await(() => {
this.getBlock(this._headHeader, (err?: any, block?: any) => {
if (err) {
return cb(err)
}
cb(null, block.header)
})
})
}
/**
* Returns the latest full block in the canonical chain.
*
* @param cb - The callback. It is given two parameters `err` and the returned `block`
*/
getLatestBlock(cb: any) {
// ensure init completed
this._initLock.await(() => {
this.getBlock(this._headBlock, cb)
})
}
/**
* Adds many blocks to the blockchain.
*
* @param blocks - The blocks to be added to the blockchain
* @param cb - The callback. It is given two parameters `err` and the last of the saved `blocks`
*/
putBlocks(blocks: Array<any>, cb: any) {
async.eachSeries(
blocks,
(block, done) => {
this.putBlock(block, done)
},
cb,
)
}
/**
* Adds a block to the blockchain.
*
* @param block - The block to be added to the blockchain
* @param cb - The callback. It is given two parameters `err` and the saved `block`
*/
putBlock(block: object, cb: any, isGenesis?: boolean) {
// make sure init has completed
this._initLock.await(() => {
// perform put with mutex dance
this._lockUnlock((done: any) => {
this._putBlockOrHeader(block, done, isGenesis)
}, cb)
})
}
/**
* Adds many headers to the blockchain.
*
* @param headers - The headers to be added to the blockchain
* @param cb - The callback. It is given two parameters `err` and the last of the saved `headers`
*/
putHeaders(headers: Array<any>, cb: any) {
async.eachSeries(
headers,
(header, done) => {
this.putHeader(header, done)
},
cb,
)
}
/**
* Adds a header to the blockchain.
*
* @param header - The header to be added to the blockchain
* @param cb - The callback. It is given two parameters `err` and the saved `header`
*/
putHeader(header: object, cb: any) {
// make sure init has completed
this._initLock.await(() => {
// perform put with mutex dance
this._lockUnlock((done: any) => {
this._putBlockOrHeader(header, done)
}, cb)
})
}
/**
* @hidden
*/
_putBlockOrHeader(item: any, cb: any, isGenesis?: boolean) {
const self = this
const isHeader = item instanceof Block.Header
let block = isHeader ? new Block([item.raw, [], []], { common: item._common }) : item
const header = block.header
const hash = block.hash()
const number = new BN(header.number)
const td = new BN(header.difficulty)
const currentTd: any = { header: null, block: null }
const dbOps: any[] = []
if (block.constructor !== Block) {
block = new Block(block, { common: self._common })
}
if (block._common.chainId() !== self._common.chainId()) {
return cb(new Error('Chain mismatch while trying to put block or header'))
}
async.series(
[
verify,
verifyPOW,
getCurrentTd,
getBlockTd,
rebuildInfo,
cb => self._batchDbOps(dbOps.concat(self._saveHeadOps()), cb),
],
cb,
)
function verify(next: any) {
if (!self._validateBlocks) {
return next()
}
if (!isGenesis && block.isGenesis()) {
return next(new Error('already have genesis set'))
}
block.validate(self, next)
}
function verifyPOW(next: any) {
if (!self._validatePow) {
return next()
}
self.ethash.verifyPOW(block, (valid: boolean) => {
next(valid ? null : new Error('invalid POW'))
})
}
function getCurrentTd(next: any) {
if (isGenesis) {
currentTd.header = new BN(0)
currentTd.block = new BN(0)
return next()
}
async.parallel(
[
cb =>
self._getTd(self._headHeader, (err?: any, td?: any) => {
currentTd.header = td
cb(err)
}),
cb =>
self._getTd(self._headBlock, (err?: any, td?: any) => {
currentTd.block = td
cb(err)
}),
],
next,
)
}
function getBlockTd(next: any) {
// calculate the total difficulty of the new block
if (isGenesis) {
return next()
}
self._getTd(header.parentHash, number.subn(1), (err?: any, parentTd?: any) => {
if (err) {
return next(err)
}
td.iadd(parentTd)
next()
})
}
function rebuildInfo(next: any) {
// save block and total difficulty to the database
let key = tdKey(number, hash)
let value = rlp.encode(td)
dbOps.push({
type: 'put',
key: key,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: value,
})
self.dbManager._cache.td.set(key, value)
// save header
key = headerKey(number, hash)
value = rlp.encode(header.raw)
dbOps.push({
type: 'put',
key: key,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: value,
})
self.dbManager._cache.header.set(key, value)
// store body if it exists
if (isGenesis || block.transactions.length || block.uncleHeaders.length) {
const body = block.serialize(false).slice(1)
key = bodyKey(number, hash)
value = rlp.encode(body)
dbOps.push({
type: 'put',
key: key,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: value,
})
self.dbManager._cache.body.set(key, value)
}
// if total difficulty is higher than current, add it to canonical chain
if (block.isGenesis() || td.gt(currentTd.header)) {
self._headHeader = hash
if (!isHeader) {
self._headBlock = hash
}
if (block.isGenesis()) {
self._genesis = hash
}
// delete higher number assignments and overwrite stale canonical chain
async.parallel(
[
cb => self._deleteStaleAssignments(number.addn(1), hash, dbOps, cb),
cb => self._rebuildCanonical(header, dbOps, cb),
],
next,
)
} else {
if (td.gt(currentTd.block) && !isHeader) {
self._headBlock = hash
}
// save hash to number lookup info even if rebuild not needed
key = hashToNumberKey(hash)
value = bufBE8(number)
dbOps.push({
type: 'put',
key: key,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: value,
})
self.dbManager._cache.hashToNumber.set(key, value)
next()
}
}
}
/**
* Gets a block by its hash.
*
* @param blockTag - The block's hash or number
* @param cb - The callback. It is given two parameters `err` and the found `block` (an instance of https://github.com/ethereumjs/ethereumjs-block) if any.
*/
getBlock(blockTag: Buffer | number | BN, cb: any) {
// ensure init completed
this._initLock.await(() => {
this._getBlock(blockTag, cb)
})
}
/**
* @hidden
*/
_getBlock(blockTag: Buffer | number | BN, cb: any) {
callbackify(this.dbManager.getBlock.bind(this.dbManager))(blockTag, cb)
}
/**
* Looks up many blocks relative to blockId
*
* @param blockId - The block's hash or number
* @param maxBlocks - Max number of blocks to return
* @param skip - Number of blocks to skip
* @param reverse - Fetch blocks in reverse
* @param cb - The callback. It is given two parameters `err` and the found `blocks` if any.
*/
getBlocks(blockId: Buffer | number, maxBlocks: number, skip: number, reverse: boolean, cb: any) {
const self = this
const blocks: any[] = []
let i = -1
function nextBlock(blockId: any) {
self.getBlock(blockId, function(err?: any, block?: any) {
i++
if (err) {
if (err.notFound) {
return cb(null, blocks)
} else {
return cb(err)
}
}
const nextBlockNumber = new BN(block.header.number).addn(reverse ? -1 : 1)
if (i !== 0 && skip && i % (skip + 1) !== 0) {
return nextBlock(nextBlockNumber)
}
blocks.push(block)
if (blocks.length === maxBlocks) {
return cb(null, blocks)
}
nextBlock(nextBlockNumber)
})
}
nextBlock(blockId)
}
/**
* This method used to return block details by its hash. It's only here for backwards compatibility.
*
* @deprecated
*/
getDetails(_: string, cb: any) {
cb(null, {})
}
/**
* Given an ordered array, returns to the callback an array of hashes that are not in the blockchain yet.
*
* @param hashes - Ordered array of hashes
* @param cb - The callback. It is given two parameters `err` and hashes found.
*/
selectNeededHashes(hashes: Array<any>, cb: any) {
const self = this
let max: number, mid: number, min: number
max = hashes.length - 1
mid = min = 0
async.whilst(
function test() {
return max >= min
},
function iterate(cb2) {
self._hashToNumber(hashes[mid], (err?: any, number?: any) => {
if (!err && number) {
min = mid + 1
} else {
max = mid - 1
}
mid = Math.floor((min + max) / 2)
cb2()
})
},
function onDone(err) {
if (err) return cb(err)
cb(null, hashes.slice(min))
},
)
}
/**
* @hidden
*/
_saveHeadOps() {
return [
{
type: 'put',
key: 'heads',
keyEncoding: 'binary',
valueEncoding: 'json',
value: this._heads,
},
{
type: 'put',
key: headHeaderKey,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: this._headHeader,
},
{
type: 'put',
key: headBlockKey,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: this._headBlock,
},
]
}
/**
* @hidden
*/
_saveHeads(cb: any) {
this._batchDbOps(this._saveHeadOps(), cb)
}
/**
* Delete canonical number assignments for specified number and above
*
* @hidden
*/
_deleteStaleAssignments(number: BN, headHash: Buffer, ops: any, cb: any) {
const key = numberToHashKey(number)
this._numberToHash(number, (err?: any, hash?: Buffer) => {
if (err) {
return cb()
}
ops.push({
type: 'del',
key: key,
keyEncoding: 'binary',
})
this.dbManager._cache.numberToHash.del(key)
// reset stale iterator heads to current canonical head
Object.keys(this._heads).forEach(name => {
if (this._heads[name].equals(hash)) {
this._heads[name] = headHash
}
})
// reset stale headBlock to current canonical
if (this._headBlock.equals(hash)) {
this._headBlock = headHash
}
this._deleteStaleAssignments(number.addn(1), headHash, ops, cb)
})
}
/**
* Overwrites stale canonical number assignments.
*
* @hidden
*/
_rebuildCanonical(header: any, ops: any, cb: any) {
const self = this
const hash = header.hash()
const number = new BN(header.number)
function saveLookups(hash: Buffer, number: BN) {
let key = numberToHashKey(number)
let value
ops.push({
type: 'put',
key: key,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: hash,
})
self.dbManager._cache.numberToHash.set(key, hash)
key = hashToNumberKey(hash)
value = bufBE8(number)
ops.push({
type: 'put',
key: key,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: value,
})
self.dbManager._cache.hashToNumber.set(key, value)
}
// handle genesis block
if (number.cmpn(0) === 0) {
saveLookups(hash, number)
return cb()
}
self._numberToHash(number, (err?: any, staleHash?: Buffer | null) => {
if (err) {
staleHash = null
}
if (!staleHash || !hash.equals(staleHash)) {
saveLookups(hash, number)
// flag stale head for reset
Object.keys(self._heads).forEach(function(name) {
if (staleHash && self._heads[name].equals(staleHash)) {
self._staleHeads = self._staleHeads || []
self._staleHeads.push(name)
}
})
// flag stale headBlock for reset
if (staleHash && self._headBlock.equals(staleHash)) {
self._staleHeadBlock = true
}
self._getHeader(header.parentHash, number.subn(1), (err?: any, header?: any) => {
if (err) {
delete self._staleHeads
return cb(err)
}
self._rebuildCanonical(header, ops, cb)
})
} else {
// set stale heads to last previously valid canonical block
;(self._staleHeads || []).forEach((name: string) => {
self._heads[name] = hash
})
delete self._staleHeads
// set stale headBlock to last previously valid canonical block
if (self._staleHeadBlock) {
self._headBlock = hash
delete self._staleHeadBlock
}
cb()
}
})
}
/**
* Deletes a block from the blockchain. All child blocks in the chain are deleted and any
* encountered heads are set to the parent block.
*
* @param blockHash - The hash of the block to be deleted
* @param cb - A callback.
*/
delBlock(blockHash: Buffer, cb: any) {
// make sure init has completed
this._initLock.await(() => {
// perform put with mutex dance
this._lockUnlock((done: boolean) => {
this._delBlock(blockHash, done)
}, cb)
})
}
/**
* @hidden
*/
_delBlock(blockHash: Buffer | typeof Block, cb: any) {
const self = this
const dbOps: any[] = []
let blockHeader = null
let blockNumber: any = null
let parentHash: any = null
let inCanonical: any = null
if (!Buffer.isBuffer(blockHash)) {
blockHash = blockHash.hash()
}
async.series(
[
getHeader,
checkCanonical,
buildDBops,
deleteStaleAssignments,
cb => self._batchDbOps(dbOps, cb),
],
cb,
)
function getHeader(cb2: any) {
self._getHeader(blockHash, (err?: any, header?: any) => {
if (err) return cb2(err)
blockHeader = header
blockNumber = new BN(blockHeader.number)
parentHash = blockHeader.parentHash
cb2()
})
}
// check if block is in the canonical chain
function checkCanonical(cb2: any) {
self._numberToHash(blockNumber, (err?: any, hash?: any) => {
inCanonical = !err && hash.equals(blockHash)
cb2()
})
}
// delete the block, and if block is in the canonical chain, delete all
// children as well
function buildDBops(cb2: any) {
self._delChild(blockHash, blockNumber, inCanonical ? parentHash : null, dbOps, cb2)
}
// delete all number to hash mappings for deleted block number and above
function deleteStaleAssignments(cb2: any) {
if (inCanonical) {
self._deleteStaleAssignments(blockNumber, parentHash, dbOps, cb2)
} else {
cb2()
}
}
}
/**
* @hidden
*/
_delChild(hash: Buffer, number: BN, headHash: Buffer, ops: any, cb: any) {
const self = this
// delete header, body, hash to number mapping and td
ops.push({
type: 'del',
key: headerKey(number, hash),
keyEncoding: 'binary',
})
self.dbManager._cache.header.del(headerKey(number, hash))
ops.push({
type: 'del',
key: bodyKey(number, hash),
keyEncoding: 'binary',
})
self.dbManager._cache.body.del(bodyKey(number, hash))
ops.push({
type: 'del',
key: hashToNumberKey(hash),
keyEncoding: 'binary',
})
self.dbManager._cache.hashToNumber.del(hashToNumberKey(hash))
ops.push({
type: 'del',
key: tdKey(number, hash),
keyEncoding: 'binary',
})
self.dbManager._cache.td.del(tdKey(number, hash))
if (!headHash) {
return cb()
}
if (hash.equals(self._headHeader)) {
self._headHeader = headHash