forked from willyko/relayer
-
Notifications
You must be signed in to change notification settings - Fork 7
/
getter.js
67 lines (50 loc) · 1.78 KB
/
getter.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
"use strict"
class Getter {
constructor(client) {
this.client = client;
}
async downloadBlocks(blocks){
var self = this;
return new Promise(function(resolve, reject){
var blockDict = {}; //temp storage for the received blocks
var receivedBlocks = 0; //how many blocks have been successfully received
var expectedBlocks = blocks.length;
console.log("Getter: Downloading " + blocks.length + " blocks starting from block " + blocks[0]);
var handler = function(err, block){
if (err) {
resolve(null);
}
else {
if(block == null){
console.error("Getter: Received empty block!");
} else {
blockDict[block.number] = block;
}
receivedBlocks++;
if(receivedBlocks >= expectedBlocks){
console.log("Getter: Received all blocks...");
resolve(blockDict);
}
}
}
self.requestBlocks(blocks, handler);
}).catch(function(error) {
console.log("Getter: error caught downloading blocks: " + error);
});
}
//requests blocks from given array of block numbers
async requestBlocks(blocks, handler){
var batch = [];
for(let i=0; i<blocks.length; i++) {
batch.push({
method: 'eth_getHeaderByNumber',
params: ["0x" + blocks[i].toString(16)]
});
}
this.client.cmd(batch, handler);
}
async getAll(blocks) {
return this.downloadBlocks(blocks);
}
}
module.exports = Getter;