forked from MetaMask/web3-provider-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
274 lines (231 loc) · 7.19 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
const EventEmitter = require('events').EventEmitter
const inherits = require('util').inherits
const ethUtil = require('ethereumjs-util')
const EthBlockTracker = require('eth-block-tracker')
const map = require('async/map')
const eachSeries = require('async/eachSeries')
const Stoplight = require('./util/stoplight.js')
const cacheUtils = require('./util/rpc-cache-utils.js')
const createPayload = require('./util/create-payload.js')
const noop = function(){}
module.exports = Web3ProviderEngine
inherits(Web3ProviderEngine, EventEmitter)
function Web3ProviderEngine(opts) {
const self = this
EventEmitter.call(self)
self.setMaxListeners(30)
// parse options
opts = opts || {}
// block polling
const directProvider = { sendAsync: self._handleAsync.bind(self) }
const blockTrackerProvider = opts.blockTrackerProvider || directProvider
self._blockTracker = opts.blockTracker || new EthBlockTracker({
provider: blockTrackerProvider,
pollingInterval: opts.pollingInterval || 4000,
setSkipCacheFlag: true,
})
// set initialization blocker
self._ready = new Stoplight()
// local state
self.currentBlock = null
self._providers = []
}
// public
Web3ProviderEngine.prototype.start = function(cb = noop){
const self = this
// trigger start
self._ready.go()
// on new block, request block body and emit as events
self._blockTracker.on('latest', (blockNumber) => {
// get block body
self._getBlockByNumberWithRetry(blockNumber, (err, block) => {
if (err) {
this.emit('error', err)
return
}
if (!block) {
console.log(block)
this.emit('error', new Error("Could not find block"))
return
}
const bufferBlock = toBufferBlock(block)
// set current + emit "block" event
self._setCurrentBlock(bufferBlock)
// emit other events
self.emit('rawBlock', block)
self.emit('latest', block)
})
})
// forward other events
self._blockTracker.on('sync', self.emit.bind(self, 'sync'))
self._blockTracker.on('error', self.emit.bind(self, 'error'))
// update state
self._running = true
// signal that we started
self.emit('start')
}
Web3ProviderEngine.prototype.stop = function(){
const self = this
// stop block polling by removing event listeners
self._blockTracker.removeAllListeners()
// update state
self._running = false
// signal that we stopped
self.emit('stop')
}
Web3ProviderEngine.prototype.isRunning = function(){
const self = this
return self._running
}
Web3ProviderEngine.prototype.addProvider = function(source, index){
const self = this
if (typeof index === 'number') {
self._providers.splice(index, 0, source)
} else {
self._providers.push(source)
}
source.setEngine(this)
}
Web3ProviderEngine.prototype.removeProvider = function(source){
const self = this
const index = self._providers.indexOf(source)
if (index < 0) throw new Error('Provider not found.')
self._providers.splice(index, 1)
}
Web3ProviderEngine.prototype.send = function(payload){
throw new Error('Web3ProviderEngine does not support synchronous requests.')
}
Web3ProviderEngine.prototype.sendAsync = function(payload, cb){
const self = this
self._ready.await(function(){
if (Array.isArray(payload)) {
// handle batch
map(payload, self._handleAsync.bind(self), cb)
} else {
// handle single
self._handleAsync(payload, cb)
}
})
}
// private
Web3ProviderEngine.prototype._getBlockByNumberWithRetry = function(blockNumber, cb) {
const self = this
let retriesRemaining = 5
attemptRequest()
return
function attemptRequest () {
self._getBlockByNumber(blockNumber, afterRequest)
}
function afterRequest (err, block) {
// anomalous error occurred
if (err) return cb(err)
// block not ready yet
if (!block) {
if (retriesRemaining > 0) {
// wait 1s then try again
retriesRemaining--
setTimeout(function () {
attemptRequest()
}, 1000)
return
} else {
// give up, return a null block
cb(null, null)
return
}
}
// otherwise return result
cb(null, block)
return
}
}
Web3ProviderEngine.prototype._getBlockByNumber = function(blockNumber, cb) {
const req = createPayload({ method: 'eth_getBlockByNumber', params: [blockNumber, false], skipCache: true })
this._handleAsync(req, (err, res) => {
if (err) return cb(err)
return cb(null, res.result)
})
}
Web3ProviderEngine.prototype._handleAsync = function(payload, finished) {
var self = this
var currentProvider = -1
var result = null
var error = null
var stack = []
next()
function next(after) {
currentProvider += 1
stack.unshift(after)
// Bubbled down as far as we could go, and the request wasn't
// handled. Return an error.
if (currentProvider >= self._providers.length) {
end(new Error('Request for method "' + payload.method + '" not handled by any subprovider. Please check your subprovider configuration to ensure this method is handled.'))
} else {
try {
var provider = self._providers[currentProvider]
provider.handleRequest(payload, next, end)
} catch (e) {
end(e)
}
}
}
function end(_error, _result) {
error = _error
result = _result
eachSeries(stack, function(fn, callback) {
if (fn) {
fn(error, result, callback)
} else {
callback()
}
}, function() {
var resultObj = {
id: payload.id,
jsonrpc: payload.jsonrpc,
result: result
}
if (error != null) {
resultObj.error = {
message: error.stack || error.message || error,
code: -32000
}
// respond with both error formats
finished(error, resultObj)
} else {
finished(null, resultObj)
}
})
}
}
//
// from remote-data
//
Web3ProviderEngine.prototype._setCurrentBlock = function(block){
const self = this
self.currentBlock = block
self.emit('block', block)
}
// util
function toBufferBlock (jsonBlock) {
return {
number: ethUtil.toBuffer(jsonBlock.number),
hash: ethUtil.toBuffer(jsonBlock.hash),
parentHash: ethUtil.toBuffer(jsonBlock.parentHash),
nonce: ethUtil.toBuffer(jsonBlock.nonce),
mixHash: ethUtil.toBuffer(jsonBlock.mixHash),
sha3Uncles: ethUtil.toBuffer(jsonBlock.sha3Uncles),
logsBloom: ethUtil.toBuffer(jsonBlock.logsBloom),
transactionsRoot: ethUtil.toBuffer(jsonBlock.transactionsRoot),
stateRoot: ethUtil.toBuffer(jsonBlock.stateRoot),
receiptsRoot: ethUtil.toBuffer(jsonBlock.receiptRoot || jsonBlock.receiptsRoot),
miner: ethUtil.toBuffer(jsonBlock.miner),
difficulty: ethUtil.toBuffer(jsonBlock.difficulty),
totalDifficulty: ethUtil.toBuffer(jsonBlock.totalDifficulty),
size: ethUtil.toBuffer(jsonBlock.size),
extraData: ethUtil.toBuffer(jsonBlock.extraData),
gasLimit: ethUtil.toBuffer(jsonBlock.gasLimit),
gasUsed: ethUtil.toBuffer(jsonBlock.gasUsed),
timestamp: ethUtil.toBuffer(jsonBlock.timestamp),
transactions: jsonBlock.transactions,
}
}