-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsyncManager.js
53 lines (48 loc) · 1.67 KB
/
syncManager.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
const BN = require('vaporyjs-util').BN
const genesisHash = require('vapory-common').genesisHash.v.slice(2)
const async = require('async')
const ethUtil = require('vaporyjs-util')
var SyncManager = module.exports = function(blockchain) {
this.maxNumToDownload = 32 // the number of hashed to get per request TODO: vary on rating of peer
this.syncingPeers = {}
this.blockchain = blockchain
/**
* hash enum
* fetching, fetched, needed
*/
this.hashes = {}
}
SyncManager.prototype.sync = function(bctd, height, peer, cb) {
var td = new BN(peer.status.td)
var bestHash = peer.status.bestHash.toString('hex')
if (new BN(bctd).cmp(td) < 0) {
peer.doneSyncing = false //is the ordered hash list full?
peer.skipList = [peer.status.bestHash]
this.hashes[bestHash] = 'needed'
this.hashes[genesisHash] = 'have'
this.downloadChain(peer, ethUtil.bufferToInt(height) + 1, cb)
} else {
cb()
}
}
SyncManager.prototype.downloadChain = function(peer, startHeight, cb){
var self = this
console.log('downloading');
peer.sendBlockHashesFromNumber(startHeight, this.maxNumToDownload)
peer.once('blockHashes', function(hashes){
console.log('got blockHashes');
peer.fetchBlocks(hashes, function(blocks){
self.blockchain.putBlocks(blocks, function(){
console.log('added blocks');
console.log(self.blockchain.meta);
var lastHash = hashes[hashes.length - 1]
if(lastHash && lastHash.toString('hex') === peer.status.bestHash.toString('hex'))
return cb()
else{
console.log(startHeight);
self.downloadChain(peer, startHeight + self.maxNumToDownload, cb)
}
})
})
})
}