forked from MetaMask/web3-provider-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
261 lines (212 loc) · 6.98 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
const EventEmitter = require('events').EventEmitter
const inherits = require('util').inherits
const Stoplight = require('./util/stoplight.js')
const cacheUtils = require('./util/rpc-cache-utils.js')
const createPayload = require('./util/create-payload.js')
const ethUtil = require('ethereumjs-util')
const async = require('async')
module.exports = Web3ProviderEngine
inherits(Web3ProviderEngine, EventEmitter)
function Web3ProviderEngine(opts) {
const self = this
EventEmitter.call(self)
self.setMaxListeners(30)
// set initialization blocker
self._ready = new Stoplight()
// unblock initialization after first block
self.once('block', function(){
self._ready.go()
})
// parse options
opts = opts || {}
self._pollingShouldUnref = opts.pollingShouldUnref !== false
self._pollingInterval = opts.pollingInterval || 4000
// local state
self.currentBlock = null
self._providers = []
}
// public
Web3ProviderEngine.prototype.start = function(){
const self = this
// start block polling
self._startPolling()
}
Web3ProviderEngine.prototype.stop = function(){
const self = this
// stop block polling
self._stopPolling()
}
Web3ProviderEngine.prototype.addProvider = function(source){
const self = this
self._providers.push(source)
source.setEngine(this)
}
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
async.map(payload, self._handleAsync.bind(self), cb)
} else {
// handle single
self._handleAsync(payload, cb)
}
})
}
// private
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
async.eachSeries(stack, function(fn, callback) {
if (fn) {
fn(error, result, callback)
} else {
callback()
}
}, function() {
// console.log('COMPLETED:', payload)
// console.log('RESULT: ', result)
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 {
self._inspectResponseForNewBlock(payload, resultObj, finished)
}
})
}
}
//
// from remote-data
//
Web3ProviderEngine.prototype._startPolling = function(){
const self = this
self._fetchLatestBlock()
self._pollIntervalId = setInterval(function() {
self._fetchLatestBlock()
}, self._pollingInterval)
// Tell node that block polling shouldn't keep the process open.
// https://nodejs.org/api/timers.html#timers_timeout_unref
if (self._pollIntervalId.unref && self._pollingShouldUnref) {
self._pollIntervalId.unref()
}
}
Web3ProviderEngine.prototype._stopPolling = function(){
const self = this
clearInterval(self._pollIntervalId)
}
Web3ProviderEngine.prototype._fetchLatestBlock = function(cb) {
if (!cb) cb = function(err) { if (err) return console.error(err) }
const self = this
self._fetchBlock('latest', function(err, block) {
if (err) {
self.emit('error', err)
return cb(err)
}
if (!self.currentBlock || 0 !== self.currentBlock.hash.compare(block.hash)) {
self._setCurrentBlock(block)
}
cb(null, block)
})
}
Web3ProviderEngine.prototype._setCurrentBlock = function(block){
const self = this
self.currentBlock = block
self.emit('block', block)
}
Web3ProviderEngine.prototype._fetchBlock = function(number, cb){
const self = this
// skip: cache, readiness, block number rewrite
self._handleAsync(createPayload({
method: 'eth_getBlockByNumber',
params: [number, false],
}), function(err, resultObj){
if (err) return cb(err)
if (resultObj.error) return cb(resultObj.error)
var data = resultObj.result;
// json -> buffers
var block = {
number: ethUtil.toBuffer(data.number),
hash: ethUtil.toBuffer(data.hash),
parentHash: ethUtil.toBuffer(data.parentHash),
nonce: ethUtil.toBuffer(data.nonce),
sha3Uncles: ethUtil.toBuffer(data.sha3Uncles),
logsBloom: ethUtil.toBuffer(data.logsBloom),
transactionsRoot: ethUtil.toBuffer(data.transactionsRoot),
stateRoot: ethUtil.toBuffer(data.stateRoot),
receiptRoot: ethUtil.toBuffer(data.receiptRoot),
miner: ethUtil.toBuffer(data.miner),
difficulty: ethUtil.toBuffer(data.difficulty),
totalDifficulty: ethUtil.toBuffer(data.totalDifficulty),
size: ethUtil.toBuffer(data.size),
extraData: ethUtil.toBuffer(data.extraData),
gasLimit: ethUtil.toBuffer(data.gasLimit),
gasUsed: ethUtil.toBuffer(data.gasUsed),
timestamp: ethUtil.toBuffer(data.timestamp),
transactions: data.transactions,
}
cb(null, block)
})
}
Web3ProviderEngine.prototype._inspectResponseForNewBlock = function(payload, resultObj, cb) {
// these methods return responses with a block reference
if (payload.method != 'eth_getTransactionByHash'
&& payload.method != 'eth_getTransactionReceipt') {
return cb(null, resultObj)
}
if (resultObj.result == null || resultObj.result.blockNumber == null) {
return cb(null, resultObj)
}
var blockNumber = ethUtil.toBuffer(resultObj.result.blockNumber)
// If we found a new block number on the result,
// fetch the block details before returning the original response.
// We do this b/c a user might be polling for a tx by hash,
// and when getting a response may assume that we are on the new block and
// try to query data from that block but would otherwise get old data due to
// our blockTag-rewriting mechanism
if (0 !== this.currentBlock.number.compare(blockNumber)) {
this._fetchLatestBlock(function(err, block) {
cb(null, resultObj)
})
} else {
cb(null, resultObj)
}
}
// util
function SourceNotFoundError(payload){
return new Error('Source for RPC method "'+payload.method+'" not found.')
}