This repository has been archived by the owner on Apr 22, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 328
/
filters.js
494 lines (418 loc) · 12.9 KB
/
filters.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
const async = require('async')
const inherits = require('util').inherits
const ethUtil = require('ethereumjs-util')
const Subprovider = require('./subprovider.js')
const Stoplight = require('../util/stoplight.js')
module.exports = FilterSubprovider
// handles the following RPC methods:
// eth_newBlockFilter
// eth_newPendingTransactionFilter
// eth_newFilter
// eth_getFilterChanges
// eth_uninstallFilter
// eth_getFilterLogs
inherits(FilterSubprovider, Subprovider)
function FilterSubprovider(opts) {
opts = opts || {}
const self = this
self.filterIndex = 0
self.filters = {}
self.filterDestroyHandlers = {}
self.asyncBlockHandlers = {}
self.asyncPendingBlockHandlers = {}
self._ready = new Stoplight()
self._ready.go()
self.pendingBlockTimeout = opts.pendingBlockTimeout || 4000
self.checkForPendingBlocksActive = false
// we dont have engine immeditately
setTimeout(function(){
// asyncBlockHandlers require locking provider until updates are completed
self.engine.on('block', function(block){
// pause processing
self._ready.stop()
// update filters
var updaters = valuesFor(self.asyncBlockHandlers)
.map(function(fn){ return fn.bind(null, block) })
async.parallel(updaters, function(err){
if (err) console.error(err)
// unpause processing
self._ready.go()
})
})
})
}
FilterSubprovider.prototype.handleRequest = function(payload, next, end){
const self = this
switch(payload.method){
case 'eth_newBlockFilter':
self.newBlockFilter(end)
return
case 'eth_newPendingTransactionFilter':
self.newPendingTransactionFilter(end)
self.checkForPendingBlocks()
return
case 'eth_newFilter':
self.newLogFilter(payload.params[0], end)
return
case 'eth_getFilterChanges':
self._ready.await(function(){
self.getFilterChanges(payload.params[0], end)
})
return
case 'eth_getFilterLogs':
self._ready.await(function(){
self.getFilterLogs(payload.params[0], end)
})
return
case 'eth_uninstallFilter':
self._ready.await(function(){
self.uninstallFilter(payload.params[0], end)
})
return
default:
next()
return
}
}
FilterSubprovider.prototype.newBlockFilter = function(cb) {
const self = this
self._getBlockNumber(function(err, blockNumber){
if (err) return cb(err)
var filter = new BlockFilter({
blockNumber: blockNumber,
})
var newBlockHandler = filter.update.bind(filter)
self.engine.on('block', newBlockHandler)
var destroyHandler = function(){
self.engine.removeListener('block', newBlockHandler)
}
self.filterIndex++
var hexFilterIndex = intToHex(self.filterIndex)
self.filters[hexFilterIndex] = filter
self.filterDestroyHandlers[hexFilterIndex] = destroyHandler
cb(null, hexFilterIndex)
})
}
FilterSubprovider.prototype.newLogFilter = function(opts, cb) {
const self = this
self._getBlockNumber(function(err, blockNumber){
if (err) return cb(err)
var filter = new LogFilter(opts)
var newLogHandler = filter.update.bind(filter)
var blockHandler = function(block, cb){
self._logsForBlock(block, function(err, logs){
if (err) return cb(err)
logs.forEach(newLogHandler)
cb()
})
}
self.filterIndex++
var hexFilterIndex = intToHex(self.filterIndex)
self.asyncBlockHandlers[hexFilterIndex] = blockHandler
self.filters[hexFilterIndex] = filter
cb(null, hexFilterIndex)
})
}
FilterSubprovider.prototype.newPendingTransactionFilter = function(cb) {
const self = this
var filter = new PendingTransactionFilter()
var newTxHandler = filter.update.bind(filter)
var blockHandler = function(block, cb){
self._txHashesForBlock(block, function(err, txs){
if (err) return cb(err)
txs.forEach(newTxHandler)
cb()
})
}
self.filterIndex++
var hexFilterIndex = intToHex(self.filterIndex)
self.asyncPendingBlockHandlers[hexFilterIndex] = blockHandler
self.filters[hexFilterIndex] = filter
cb(null, hexFilterIndex)
}
FilterSubprovider.prototype.getFilterChanges = function(filterId, cb) {
const self = this
var filter = self.filters[filterId]
if (!filter) console.warn('FilterSubprovider - no filter with that id:', filterId)
if (!filter) return cb(null, [])
var results = filter.getChanges()
filter.clearChanges()
cb(null, results)
}
FilterSubprovider.prototype.getFilterLogs = function(filterId, cb) {
const self = this
var filter = self.filters[filterId]
if (!filter) console.warn('FilterSubprovider - no filter with that id:', filterId)
if (!filter) return cb(null, [])
if (filter.type === 'log') {
self.emitPayload({
method: 'eth_getLogs',
params: [{
fromBlock: filter.fromBlock,
toBlock: filter.toBlock,
address: filter.address,
topics: filter.topics,
}],
}, function(err, res){
if (err) return cb(err)
cb(null, res.result)
})
} else {
var results = filter.getAllResults()
cb(null, results)
}
}
FilterSubprovider.prototype.uninstallFilter = function(filterId, cb) {
const self = this
var filter = self.filters[filterId]
if (!filter) {
cb(null, false)
return
}
var destroyHandler = self.filterDestroyHandlers[filterId]
delete self.filters[filterId]
delete self.asyncBlockHandlers[filterId]
delete self.asyncPendingBlockHandlers[filterId]
delete self.filterDestroyHandlers[filterId]
if (destroyHandler) destroyHandler()
cb(null, true)
}
// private
// check for pending blocks
FilterSubprovider.prototype.checkForPendingBlocks = function(){
const self = this
if (self.checkForPendingBlocksActive) return
var activePendingTxFilters = !!Object.keys(self.asyncPendingBlockHandlers).length
if (activePendingTxFilters) {
self.checkForPendingBlocksActive = true
self.emitPayload({
method: 'eth_getBlockByNumber',
params: ['pending', true],
}, function(err, res){
if (err) {
self.checkForPendingBlocksActive = false
console.error(err)
return
}
self.onNewPendingBlock(res.result, function(err){
if (err) console.error(err)
self.checkForPendingBlocksActive = false
setTimeout(self.checkForPendingBlocks.bind(self), self.pendingBlockTimeout)
})
})
}
}
FilterSubprovider.prototype.onNewPendingBlock = function(block, cb){
const self = this
// update filters
var updaters = valuesFor(self.asyncPendingBlockHandlers)
.map(function(fn){ return fn.bind(null, block) })
async.parallel(updaters, cb)
}
FilterSubprovider.prototype._getBlockNumber = function(cb) {
const self = this
var blockNumber = bufferToNumberHex(self.engine.currentBlock.number)
cb(null, blockNumber)
}
FilterSubprovider.prototype._logsForBlock = function(block, cb) {
const self = this
var blockNumber = bufferToNumberHex(block.number)
self.emitPayload({
method: 'eth_getLogs',
params: [{
fromBlock: blockNumber,
toBlock: blockNumber,
}],
}, function(err, response){
if (err) return cb(err)
if (response.error) return cb(response.error)
cb(null, response.result)
})
}
FilterSubprovider.prototype._txHashesForBlock = function(block, cb) {
const self = this
var txs = block.transactions
// short circuit if empty
if (txs.length === 0) return cb(null, [])
// txs are already hashes
if ('string' === typeof txs[0]) {
cb(null, txs)
// txs are obj, need to map to hashes
} else {
var results = txs.map((tx) => tx.hash)
cb(null, results)
}
}
//
// BlockFilter
//
function BlockFilter(opts) {
// console.log('BlockFilter - new')
const self = this
self.type = 'block'
self.engine = opts.engine
self.blockNumber = opts.blockNumber
self.updates = []
}
BlockFilter.prototype.update = function(block){
// console.log('BlockFilter - update')
const self = this
var blockHash = bufferToHex(block.hash)
self.updates.push(blockHash)
}
BlockFilter.prototype.getChanges = function(){
const self = this
var results = self.updates
// console.log('BlockFilter - getChanges:', results.length)
return results
}
BlockFilter.prototype.clearChanges = function(){
// console.log('BlockFilter - clearChanges')
const self = this
self.updates = []
}
//
// LogFilter
//
function LogFilter(opts) {
// console.log('LogFilter - new')
const self = this
self.type = 'log'
self.fromBlock = opts.fromBlock || 'latest'
self.toBlock = opts.toBlock || 'latest'
self.address = opts.address ? normalizeHex(opts.address) : opts.address
self.topics = opts.topics || []
self.updates = []
self.allResults = []
}
LogFilter.prototype.validateLog = function(log){
// console.log('LogFilter - validateLog:', log)
const self = this
// check if block number in bounds:
// console.log('LogFilter - validateLog - blockNumber', self.fromBlock, self.toBlock)
if (blockTagIsNumber(self.fromBlock) && hexToInt(self.fromBlock) >= hexToInt(log.blockNumber)) return false
if (blockTagIsNumber(self.toBlock) && hexToInt(self.toBlock) <= hexToInt(log.blockNumber)) return false
// address is correct:
// console.log('LogFilter - validateLog - address', self.address)
if (self.address && self.address !== log.address) return false
// topics match:
// topics are position-dependant
// topics can be nested to represent `or` [[a || b], c]
// topics can be null, representing a wild card for that position
// console.log('LogFilter - validateLog - topics', log.topics)
// console.log('LogFilter - validateLog - against topics', self.topics)
var topicsMatch = self.topics.reduce(function(previousMatched, topicPattern, index){
// abort in progress
if (!previousMatched) return false
// wild card
if (!topicPattern) return true
// pattern is longer than actual topics
var logTopic = log.topics[index]
if (!logTopic) return false
// check each possible matching topic
var subtopicsToMatch = Array.isArray(topicPattern) ? topicPattern : [topicPattern]
var topicDoesMatch = subtopicsToMatch.filter(function(subTopic){
return logTopic === subTopic
}).length > 0
return topicDoesMatch
}, true)
// console.log('LogFilter - validateLog - '+(topicsMatch ? 'approved!' : 'denied!')+' ==============')
return topicsMatch
}
LogFilter.prototype.update = function(log){
// console.log('LogFilter - update')
const self = this
// validate filter match
var validated = self.validateLog(log)
if (!validated) return
// add to results
self.updates.push(log)
self.allResults.push(log)
}
LogFilter.prototype.getChanges = function(){
// console.log('LogFilter - getChanges')
const self = this
var results = self.updates
return results
}
LogFilter.prototype.getAllResults = function(){
// console.log('LogFilter - getAllResults')
const self = this
var results = self.allResults
return results
}
LogFilter.prototype.clearChanges = function(){
// console.log('LogFilter - clearChanges')
const self = this
self.updates = []
}
//
// PendingTxFilter
//
function PendingTransactionFilter(){
// console.log('PendingTransactionFilter - new')
const self = this
self.type = 'pendingTx'
self.updates = []
self.allResults = []
}
PendingTransactionFilter.prototype.validateUnique = function(tx){
const self = this
return self.allResults.indexOf(tx) === -1
}
PendingTransactionFilter.prototype.update = function(tx){
// console.log('PendingTransactionFilter - update')
const self = this
// validate filter match
var validated = self.validateUnique(tx)
if (!validated) return
// add to results
self.updates.push(tx)
self.allResults.push(tx)
}
PendingTransactionFilter.prototype.getChanges = function(){
// console.log('PendingTransactionFilter - getChanges')
const self = this
var results = self.updates
return results
}
PendingTransactionFilter.prototype.getAllResults = function(){
// console.log('PendingTransactionFilter - getAllResults')
const self = this
var results = self.allResults
return results
}
PendingTransactionFilter.prototype.clearChanges = function(){
// console.log('PendingTransactionFilter - clearChanges')
const self = this
self.updates = []
}
// util
function normalizeHex(hexString) {
return hexString.slice(0, 2) === '0x' ? hexString : '0x'+hexString
}
function intToHex(value) {
return ethUtil.intToHex(value)
}
function hexToInt(hexString) {
return Number(hexString)
}
function bufferToHex(buffer) {
return '0x'+buffer.toString('hex')
}
function bufferToNumberHex(buffer) {
return stripLeadingZero(buffer.toString('hex'))
}
function stripLeadingZero(hexNum) {
let stripped = ethUtil.stripHexPrefix(hexNum)
while (stripped[0] === '0') {
stripped = stripped.substr(1)
}
return `0x${stripped}`
}
function blockTagIsNumber(blockTag){
return blockTag && ['earliest', 'latest', 'pending'].indexOf(blockTag) === -1
}
function valuesFor(obj){
return Object.keys(obj).map(function(key){ return obj[key] })
}