forked from ethereumjs/ethereumjs-blockchain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1056 lines (939 loc) · 26 KB
/
index.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
'use strict'
const async = require('async')
const Stoplight = require('flow-stoplight')
const semaphore = require('semaphore')
const levelup = require('levelup')
const memdown = require('memdown')
const Block = require('ethereumjs-block')
const ethUtil = require('ethereumjs-util')
const Ethash = require('ethashjs')
const Buffer = require('safe-buffer').Buffer
const LRU = require('lru-cache')
const BN = ethUtil.BN
const rlp = ethUtil.rlp
// geth compatible db keys
const headHeaderKey = 'LastHeader' // current canonical head for light sync
const headBlockKey = 'LastBlock' // current canonical head for full sync
const headerPrefix = new Buffer('h') // headerPrefix + number + hash -> header
const tdSuffix = new Buffer('t') // headerPrefix + number + hash + tdSuffix -> td
const numSuffix = new Buffer('n') // headerPrefix + number + numSuffix -> hash
const blockHashPrefix = new Buffer('H') // blockHashPrefix + hash -> number
const bodyPrefix = new Buffer('b') // bodyPrefix + number + hash -> block body
// utility functions
const bufBE8 = n => n.toBuffer('be', 8) // convert BN to big endian Buffer
const tdKey = (n, hash) => Buffer.concat([headerPrefix, bufBE8(n), hash, tdSuffix])
const headerKey = (n, hash) => Buffer.concat([headerPrefix, bufBE8(n), hash])
const bodyKey = (n, hash) => Buffer.concat([bodyPrefix, bufBE8(n), hash])
const numberToHashKey = n => Buffer.concat([headerPrefix, bufBE8(n), numSuffix])
const hashToNumberKey = hash => Buffer.concat([blockHashPrefix, hash])
module.exports = Blockchain
function Blockchain (opts) {
opts = opts || {}
const self = this
// backwards compatibilty with older constructor interfaces
if (opts.constructor.name === 'LevelUP') {
opts = { db: opts }
}
self.db = opts.db || opts.blockDb
// defaults
self.db = self.db ? self.db : levelup('', { db: memdown })
self.validate = (opts.validate === undefined ? true : opts.validate)
self.ethash = self.validate ? new Ethash(self.db) : null
self._heads = {}
self._genesis = null
self._headHeader = null
self._headBlock = null
self._cache = {
td: new Cache({ max: 1024 }),
header: new Cache({ max: 512 }),
body: new Cache({ max: 256 }),
numberToHash: new Cache({ max: 2048 }),
hashToNumber: new Cache({ max: 2048 })
}
self._initDone = false
self._putSemaphore = semaphore(1)
self._initLock = new Stoplight()
self._init(function (err) {
if (err) throw err
self._initLock.go()
})
}
/**
* Define meta getter for backwards compatibilty
*/
Blockchain.prototype = {
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.
* @method _init
*/
Blockchain.prototype._init = function (cb) {
const self = this
async.waterfall([
(cb) => self._numberToHash(new BN(0), cb),
getHeads
], (err) => {
if (err) {
// if genesis block doesn't exist, create one
return self._setCanonicalGenesisBlock((err) => {
if (err) return cb(err)
self._heads = {}
self._headHeader = self._genesis
self._headBlock = self._genesis
cb()
})
}
cb()
})
function getHeads (genesisHash, cb) {
self._genesis = genesisHash
async.series([
// load verified iterator heads
(cb) => self.db.get('heads', {
keyEncoding: 'binary',
valueEncoding: 'json'
}, (err, heads) => {
if (err) heads = {}
Object.keys(heads).map(key => { heads[key] = Buffer.from(heads[key]) })
self._heads = heads
cb()
}),
// load headerchain head
(cb) => self.db.get(headHeaderKey, {
keyEncoding: 'binary',
valueEncoding: 'binary'
}, (err, hash) => {
self._headHeader = err ? genesisHash : hash
cb()
}),
// load blockchain head
(cb) => self.db.get(headBlockKey, {
keyEncoding: 'binary',
valueEncoding: 'binary'
}, (err, hash) => {
self._headBlock = err ? genesisHash : hash
cb()
})
], cb)
}
}
/**
* Sets the default genesis block
* @method _setCanonicalGenesisBlock
*/
Blockchain.prototype._setCanonicalGenesisBlock = function (cb) {
const self = this
var genesisBlock = new Block()
genesisBlock.setGenesisParams()
self._putBlock(genesisBlock, cb, true)
}
/**
* Puts the genesis block in the database
* @method putGenesis
*/
Blockchain.prototype.putGenesis = function (genesis, cb) {
const self = this
self.putBlock(genesis, cb, true)
}
/**
* Returns the specified iterator head.
* @method getHead
* @param name name of the head (default: 'vm')
* @param cb Function the callback
*/
Blockchain.prototype.getHead = function (name, cb) {
const self = this
// handle optional args
if (typeof name === 'function') {
cb = name
name = 'vm'
}
// ensure init completed
self._initLock.await(function runGetHead () {
// if the head is not found return the headHeader
var hash = self._heads[name] || self._headBlock
if (!hash) {
return cb(new Error('No head found.'))
}
self.getBlock(hash, cb)
})
}
/**
* Returns the latest header in the canonical chain.
* @method getLatestHeader
* @param cb Function the callback
*/
Blockchain.prototype.getLatestHeader = function (cb) {
const self = this
// ensure init completed
self._initLock.await(function runGetLatestHeader () {
self.getBlock(self._headHeader, (err, block) => {
if (err) return cb(err)
cb(null, block.header)
})
})
}
/**
* Returns the latest full block in the canonical chain.
* @method getLatestBlock
* @param cb Function the callback
*/
Blockchain.prototype.getLatestBlock = function (cb) {
const self = this
// ensure init completed
self._initLock.await(function runGetLatestBlock () {
self.getBlock(self._headBlock, cb)
})
}
/**
* Adds many blocks to the blockchain
* @method putBlocks
* @param {array} blocks - the blocks to be added to the blockchain
* @param {function} cb - a callback function
*/
Blockchain.prototype.putBlocks = function (blocks, cb) {
const self = this
async.eachSeries(blocks, function (block, done) {
self.putBlock(block, done)
}, cb)
}
/**
* Adds a block to the blockchain
* @method putBlock
* @param {object} block -the block to be added to the block chain
* @param {function} cb - a callback function
* @param {function} isGenesis - a flag for indicating if the block is the genesis block
*/
Blockchain.prototype.putBlock = function (block, cb, isGenesis) {
const self = this
// make sure init has completed
self._initLock.await(() => {
// perform put with mutex dance
lockUnlock(function (done) {
self._putBlock(block, done, isGenesis)
}, cb)
})
// lock, call fn, unlock
function lockUnlock (fn, cb) {
// take lock
self._putSemaphore.take(function () {
// call fn
fn(function () {
// leave lock
self._putSemaphore.leave()
// exit
cb.apply(null, arguments)
})
})
}
}
Blockchain.prototype._putBlock = function (block, cb, isGenesis) {
const self = this
var header = block.header
var hash = block.hash()
var number = new BN(header.number)
var td = new BN(header.difficulty)
var currentTd = null
var dbOps = []
if (block.constructor !== Block) {
block = new Block(block)
}
async.series([
verify,
verifyPOW,
getCurrentTd,
getBlockTd,
rebuildInfo,
(cb) => self._saveHeads(cb),
(cb) => self._batchDbOps(dbOps, cb)
], cb)
function verify (next) {
if (!self.validate) return next()
if (!isGenesis && block.isGenesis()) {
return next(new Error('already have genesis set'))
}
block.validate(self, next)
}
function verifyPOW (next) {
if (!self.validate) return next()
self.ethash.verifyPOW(block, function (valid) {
next(valid ? null : new Error('invalid POW'))
})
}
function getCurrentTd (next) {
if (isGenesis) {
currentTd = 0
return next()
}
self._getTd(self._headHeader, (err, td) => {
if (err) return next(err)
currentTd = td
next()
})
}
function getBlockTd (next) {
// calculate the total difficulty of the new block
if (isGenesis) {
return next()
}
self._getTd(header.parentHash, number.subn(1), (err, parentTd) => {
if (err) return next(err)
td.iadd(parentTd)
next()
})
}
function rebuildInfo (next) {
// save block and total difficulty to the database
var key = tdKey(number, hash)
dbOps.push({
type: 'put',
key: key,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: rlp.encode(td)
})
self._cache.td.set(key, td)
// save header
key = headerKey(number, hash)
dbOps.push({
type: 'put',
key: key,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: rlp.encode(header.raw)
})
self._cache.header.set(key, header)
// store body if not empty
if (block.transactions.length || block.uncleHeaders.length) {
var body = block.serialize(false).slice(1)
key = bodyKey(number, hash)
dbOps.push({
type: 'put',
key: key,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: rlp.encode(body)
})
self._cache.body.set(key, body)
}
// if total difficulty is higher than current, add it to canonical chain
// second if clause is to reduce selfish mining vulnerability
if (block.isGenesis() || td.cmp(currentTd) > 0 ||
(td.cmp(currentTd) === 0 && Math.random() < 0.5)) {
self._headHeader = hash
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 {
// save hash to number lookup info even if rebuild not needed
key = hashToNumberKey(hash)
dbOps.push({
type: 'put',
key: key,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: bufBE8(number)
})
self._cache.hashToNumber.set(key, number)
next()
}
}
}
/**
*Gets a block by its hash
* @method getBlock
* @param {Buffer|Number|BN} hash - the sha256 hash of the rlp encoding of the block
* @param {Function} cb - the callback function
*/
Blockchain.prototype.getBlock = function (blockTag, cb) {
const self = this
// ensure init completed
self._initLock.await(function runGetBlock () {
self._getBlock(blockTag, cb)
})
}
Blockchain.prototype._getBlock = function (blockTag, cb) {
const self = this
// determine BlockTag type
if (Number.isInteger(blockTag)) {
blockTag = new BN(blockTag)
}
async.waterfall([
(cb) => {
if (Buffer.isBuffer(blockTag)) {
self._hashToNumber(blockTag, (err, number) => {
if (err) return cb(err)
cb(null, blockTag, number)
})
} else if (BN.isBN(blockTag)) {
self._numberToHash(blockTag, (err, hash) => {
if (err) return cb(err)
cb(null, hash, blockTag)
})
} else {
cb(new Error('Unknown blockTag type'))
}
},
lookupByHashAndNumber
], cb)
function lookupByHashAndNumber (hash, number, cb) {
async.parallel({
header: (cb) => {
self._getHeader(hash, number, (err, header) => {
if (err) return cb(err)
cb(null, header.raw)
})
},
body: (cb) => {
self._getBody(hash, number, (err, body) => {
if (err) return cb(null, [[], []])
cb(null, body)
})
}
}, (err, parts) => {
if (err) return cb(err)
cb(null, new Block([parts.header].concat(parts.body)))
})
}
}
/**
* Looks up many blocks relative to blockId
* @method getBlocks
* @param {Buffer|Number} blockId - the block's hash or number
* @param {Number} skip - number of blocks to skip
* @param {Bool} reverse - fetch blocks in reverse
* @param {Function} cb - the callback function
*/
Blockchain.prototype.getBlocks = function (blockId, maxBlocks, skip, reverse, cb) {
const self = this
var blocks = []
var i = -1
function nextBlock (blockId) {
self.getBlock(blockId, function (err, block) {
i++
if (err) {
if (err.notFound) {
return cb(null, blocks)
} else {
return cb(err)
}
}
var 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)
}
/**
* Gets block details by its hash (This is DEPRECATED and returns an empty object)
* @method getDetails
* @param {String} hash - the sha256 hash of the rlp encoding of the block
* @param {Function} cb - the callback function
*/
Blockchain.prototype.getDetails = function (hash, cb) {
cb(null, {})
}
/**
* Given an ordered array, returns to the callback an array of hashes that are
* not in the blockchain yet
* @method selectNeededHashes
* @param {Array} hashes
* @param {function} cb the callback
*/
Blockchain.prototype.selectNeededHashes = function (hashes, cb) {
const self = this
var max, mid, min
max = hashes.length - 1
mid = min = 0
async.whilst(function test () {
return max >= min
},
function iterate (cb2) {
self._hashToNumber(hashes[mid], (err, number) => {
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))
})
}
Blockchain.prototype._saveHeads = function (cb) {
var dbOps = [{
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
}]
this._batchDbOps(dbOps, cb)
}
// delete canonical number assignments for specified number and above
Blockchain.prototype._deleteStaleAssignments = function (number, headHash, ops, cb) {
const self = this
var key = numberToHashKey(number)
self._numberToHash(number, (err, hash) => {
if (err) return cb()
ops.push({
type: 'del',
key: key,
keyEncoding: 'binary'
})
self._cache.numberToHash.del(key)
// reset stale iterator heads to current canonical head
Object.keys(self._heads).forEach(function (name) {
if (self._heads[name].equals(hash)) {
self._heads[name] = headHash
}
})
self._deleteStaleAssignments(number.addn(1), headHash, ops, cb)
})
}
// overwrite stale canonical number assignments
Blockchain.prototype._rebuildCanonical = function (header, ops, cb) {
const self = this
const hash = header.hash()
const number = new BN(header.number)
function saveLookups (hash, number) {
var key = numberToHashKey(number)
ops.push({
type: 'put',
key: key,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: hash
})
self._cache.numberToHash.set(key, hash)
key = hashToNumberKey(hash)
ops.push({
type: 'put',
key: key,
keyEncoding: 'binary',
valueEncoding: 'binary',
value: bufBE8(number)
})
self._cache.hashToNumber.set(key, number)
}
// handle genesis block
if (number.cmpn(0) === 0) {
saveLookups(hash, number)
return cb()
}
self._numberToHash(number, (err, staleHash) => {
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)
}
})
self._getHeader(header.parentHash, number.subn(1), (err, header) => {
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(function (name) {
self._heads[name] = hash
})
delete self._staleHeads
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
* @method delBlock
* @param {Buffer} blockHash -the hash of the block to be deleted
* @param {function} cb - a callback function
*/
Blockchain.prototype.delBlock = function (blockHash, cb) {
const self = this
// make sure init has completed
self._initLock.await(() => {
// perform put with mutex dance
lockUnlock(function (done) {
self._delBlock(blockHash, done)
}, cb)
})
// lock, call fn, unlock
function lockUnlock (fn, cb) {
// take lock
self._putSemaphore.take(function () {
// call fn
fn(function () {
// leave lock
self._putSemaphore.leave()
// exit
cb.apply(null, arguments)
})
})
}
}
Blockchain.prototype._delBlock = function (blockHash, cb) {
const self = this
var dbOps = []
var blockHeader = null
var blockNumber = null
var parentHash = null
var inCanonical = null
if (!Buffer.isBuffer(blockHash)) {
blockHash = blockHash.hash()
}
async.series([
getHeader,
checkCanonical,
buildDBops,
deleteStaleAssignments,
(cb) => self._batchDbOps(dbOps, cb)
], cb)
function getHeader (cb2) {
self._getHeader(blockHash, (err, header) => {
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) {
self._numberToHash(blockNumber, (err, hash) => {
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) {
self._delChild(blockHash, blockNumber, inCanonical ? parentHash : null, dbOps, cb2)
}
// delete all number to hash mappings for deleted block number and above
function deleteStaleAssignments (cb2) {
if (inCanonical) {
self._deleteStaleAssignments(blockNumber, parentHash, dbOps, cb2)
} else {
cb2()
}
}
}
Blockchain.prototype._delChild = function (hash, number, headHash, ops, cb) {
const self = this
// delete header, body, hash to number mapping and td
ops.push({
type: 'del',
key: headerKey(number, hash),
keyEncoding: 'binary'
})
self._cache.header.del(headerKey(number, hash))
ops.push({
type: 'del',
key: bodyKey(number, hash),
keyEncoding: 'binary'
})
self._cache.body.del(bodyKey(number, hash))
ops.push({
type: 'del',
key: hashToNumberKey(hash),
keyEncoding: 'binary'
})
self._cache.hashToNumber.del(hashToNumberKey(hash))
ops.push({
type: 'del',
key: tdKey(number, hash),
keyEncoding: 'binary'
})
self._cache.td.del(tdKey(number, hash))
if (!headHash) {
return cb()
}
if (hash.equals(self._headHeader)) {
self._headHeader = headHash
}
if (hash.equals(self._headBlock)) {
self._headBlock = headHash
}
self._getCanonicalHeader(number.addn(1), (err, childHeader) => {
if (err) return cb()
self._delChild(childHeader.hash(), new BN(childHeader.number), headHash, ops, cb)
})
}
/**
* Iterates through blocks starting at the specified iterator head and calls
* the onBlock function on each block. The current location of an iterator head
* can be retrieved using the `getHead()`` method
* @method iterator
* @param {String} name - the name of the iterator head
* @param {function} onBlock - function called on each block with params (block, reorg, cb)
* @param {function} cb - a callback function
*/
Blockchain.prototype.iterator = function (name, onBlock, cb) {
const self = this
// ensure init completed
self._initLock.await(function () {
self._iterator(name, onBlock, cb)
})
}
Blockchain.prototype._iterator = function (name, func, cb) {
const self = this
var blockHash = self._heads[name] || self._genesis
var blockNumber
var lastBlock
if (!blockHash) {
return cb()
}
self._hashToNumber(blockHash, (err, number) => {
if (err) return cb(err)
blockNumber = number.addn(1)
async.whilst(
() => blockNumber,
run,
() => self._saveHeads(cb)
)
})
function run (cb2) {
var block
async.series([
getBlock,
runFunc
], function (err) {
if (!err) {
blockNumber.iaddn(1)
} else {
blockNumber = false
}
cb2(err)
})
function getBlock (cb3) {
self.getBlock(blockNumber, function (err, b) {
block = b
if (block) {
self._heads[name] = block.hash()
}
cb3(err)
})
}
function runFunc (cb3) {
var reorg = lastBlock ? lastBlock.hash().equals(block.header.parentHash) : false
lastBlock = block
func(block, reorg, cb3)
}
}
}
/**
* Executes multiple db operations in a single batch call
* @method _batchDbOps
*/
Blockchain.prototype._batchDbOps = function (dbOps, cb) {
this.db.batch(dbOps, cb)
}
/**
* Performs a block hash to block number lookup
* @method _hashToNumber
*/
Blockchain.prototype._hashToNumber = function (hash, cb) {
const self = this
var key = hashToNumberKey(hash)
var number = self._cache.hashToNumber.get(key)
if (number) {
return cb(null, number)
}
self.db.get(key, {
keyEncoding: 'binary',
valueEncoding: 'binary'
}, (err, number) => {
if (err) return cb(err)
number = new BN(number)
self._cache.hashToNumber.set(key, number)
cb(null, number)
})
}
/**
* Performs a block number to block hash lookup
* @method _numberToHash
*/
Blockchain.prototype._numberToHash = function (number, cb) {
const self = this
if (number.ltn(0)) {
return cb(new levelup.errors.NotFoundError())
}
var key = numberToHashKey(number)
var hash = self._cache.numberToHash.get(key)
if (hash) {
return cb(null, hash)
}
self.db.get(key, {
keyEncoding: 'binary',
valueEncoding: 'binary'
}, (err, hash) => {
if (err) return cb(err)
self._cache.numberToHash.set(key, hash)
cb(null, hash)
})
}
/**
* Helper function to lookup a block by either hash only or a hash and number pair
* @method _lookupByHashNumber
*/
Blockchain.prototype._lookupByHashNumber = function (hash, number, cb, next) {
if (typeof number === 'function') {
cb = number
return this._hashToNumber(hash, (err, number) => {
if (err) return next(err)
next(null, hash, number, cb)
})
}
next(null, hash, number, cb)
}
/**
* Gets a header by hash and number. Header can exist outside the canonical chain
* @method _getHeader
*/
Blockchain.prototype._getHeader = function (hash, number, cb) {
const self = this
self._lookupByHashNumber(hash, number, cb, (err, hash, number, cb) => {
if (err) return cb(err)
var key = headerKey(number, hash)
var header = self._cache.header.get(key)
if (header) {
return cb(null, header)
}
self.db.get(headerKey(number, hash), {
keyEncoding: 'binary',
valueEncoding: 'binary'
}, (err, encodedHeader) => {
if (err) return cb(err)
header = new Block.Header(rlp.decode(encodedHeader))
self._cache.header.set(key, header)
cb(null, header)
})
})
}
/**
* Gets a header by number. Header must be in the canonical chain
* @method _getCanonicalHeader
*/
Blockchain.prototype._getCanonicalHeader = function (number, cb) {
const self = this
self._numberToHash(number, (err, hash) => {
if (err) return cb(err)
self._getHeader(hash, number, cb)
})
}
/**
* Gets a block body by hash and number
* @method _getBody
*/
Blockchain.prototype._getBody = function (hash, number, cb) {
const self = this
self._lookupByHashNumber(hash, number, cb, (err, hash, number, cb) => {
if (err) return cb(err)
var key = bodyKey(number, hash)
var body = self._cache.body.get(key)
if (body) {
return cb(null, body)
}
self.db.get(key, {
keyEncoding: 'binary',
valueEncoding: 'binary'
}, (err, encodedBody) => {
if (err) return cb(err)
body = rlp.decode(encodedBody)
self._cache.body.set(key, body)