-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbit.js
326 lines (302 loc) · 9.22 KB
/
bit.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
const zmq = require('zeromq')
const RpcClient = require('wormholed-rpc')
const TNA = require('tna')
const pLimit = require('p-limit')
const pQueue = require('p-queue')
const Config = require('./config.js')
const queue = new pQueue({concurrency: Config.rpc.limit})
const mingo = require('mingo')
const jq = require('bigjq')
const bcode = require('bcode')
const Filter = require('./bitdb.json')
var Db
var Info
var rpc
var filter
var processor
const init = function(db, info) {
return new Promise(function(resolve) {
Db = db
Info = info
if (Filter.filter && Filter.filter.q && Filter.filter.q.find) {
let query = bcode.encode(Filter.filter.q.find)
filter = new mingo.Query(query)
} else {
filter = null
}
if (Filter.filter && Filter.filter.r && Filter.filter.r.f) {
processor = Filter.filter.r.f
}
rpc = new RpcClient(Config.rpc)
resolve()
})
}
const request = {
block: function(block_index) {
return new Promise(function(resolve) {
rpc.getBlockHash(block_index, function(err, res) {
if (err) {
console.log('Err = ', err)
throw new Error(err)
} else {
rpc.getBlock(res.result, function(err, block) {
resolve(block)
})
}
})
})
},
whcBlock: function(block_index) {
return new Promise(async function(resolve) {
const block = await request.block(block_index)
rpc.whc_listBlockTransactions(block_index, function(err, whcBlockTxs) {
if (err) {
console.log('Err = ', err)
throw new Error(err)
} else {
block.result.tx = whcBlockTxs.result
resolve(block)
}
})
})
},
/**
* Return the current blockchain height
*/
height: function() {
return new Promise(function(resolve) {
rpc.getBlockCount(function(err, res) {
if (err) {
console.log('Err = ', err)
throw new Error(err)
} else {
resolve(res.result)
}
})
})
},
tx: async function(hash) {
let content = await TNA.fromHash(hash, Config.rpc)
return content
},
whcTx: function(hash) {
return new Promise(async function(resolve, reject) {
rpc.whc_gettransaction(hash, function(err, res) {
if (err) {
if (err.code == -5 && err.message == 'Not a Wormhole Protocol transaction') {
reject(err)
}
else {
console.log('Err = ', err)
throw new Error(err)
}
} else {
res.result.tx = {
h: res.result.txid
}
resolve(res.result)
}
})
})
},
mempool: function() {
return new Promise(function(resolve) {
rpc.getRawMemPool(async function(err, ret) {
if (err) {
console.log('Err', err)
} else {
let tasks = []
const limit = pLimit(Config.rpc.limit)
let txs = ret.result
console.log('txs = ', txs.length)
for(let i=0; i<txs.length; i++) {
tasks.push(limit(async function() {
let content = await request.whcTx(txs[i]).catch(function(e) {
console.log('Error = ', e)
})
return content
}))
}
let btxs = await Promise.all(tasks)
resolve(btxs)
}
})
})
},
whcMempool: function() {
return new Promise(function(resolve) {
rpc.getRawMemPool(async function(err, ret) {
if (err) {
console.log('Err', err)
} else {
let tasks = []
const limit = pLimit(Config.rpc.limit)
let txs = ret.result
console.log('txs = ', txs.length)
for(let i=0; i<txs.length; i++) {
tasks.push(limit(async function() {
try {
let content = await request.whcTx(txs[i])
return content
} catch (e) {
if (e.code == -5 && e.message == 'Not a Wormhole Protocol transaction') {
return null
} else {
throw e
}
}
}))
}
let btxs = await Promise.all(tasks)
btxs = btxs.filter(btx => btx != null)
resolve(btxs)
}
})
})
}
}
const crawl = async function(block_index) {
let block_content = await request.whcBlock(block_index)
let block_hash = block_content.result.hash
let block_time = block_content.result.time
if (block_content && block_content.result) {
let txs = block_content.result.tx
console.log('crawling txs = ', txs.length)
let tasks = []
const limit = pLimit(Config.rpc.limit)
for(let i=0; i<txs.length; i++) {
tasks.push(limit(async function() {
let t = await request.whcTx(txs[i]).catch(function(e) {
console.log('Error = ', e)
})
t.blk = {
i: block_index,
h: block_hash,
t: block_time
}
return t
}))
}
let btxs = await Promise.all(tasks)
if (filter) {
btxs = btxs.filter(function(row) {
return filter.test(row)
})
if (processor) {
btxs = bcode.decode(btxs)
btxs = await jq.run(processor, btxs)
}
console.log('Filtered Xputs = ', btxs.length)
}
console.log('Block ' + block_index + ' : ' + txs.length + 'txs | ' + btxs.length + ' filtered txs')
return btxs
} else {
return []
}
}
const outsock = zmq.socket('pub')
const listen = function() {
let sock = zmq.socket('sub')
sock.connect('tcp://' + Config.zmq.incoming.host + ':' + Config.zmq.incoming.port)
sock.subscribe('hashtx')
sock.subscribe('hashblock')
console.log('Subscriber connected to port ' + Config.zmq.incoming.port)
outsock.bindSync('tcp://' + Config.zmq.outgoing.host + ':' + Config.zmq.outgoing.port)
console.log('Started publishing to ' + Config.zmq.outgoing.host + ':' + Config.zmq.outgoing.port)
// Listen to ZMQ
sock.on('message', async function(topic, message) {
if (topic.toString() === 'hashtx') {
let hash = message.toString('hex')
console.log('New mempool hash from ZMQ = ', hash)
await sync('mempool', hash)
} else if (topic.toString() === 'hashblock') {
let hash = message.toString('hex')
console.log('New block hash from ZMQ = ', hash)
await sync('block')
}
})
// Don't trust ZMQ. Try synchronizing every 1 minute in case ZMQ didn't fire
setInterval(async function() {
await sync('block')
}, 60000)
}
const sync = async function(type, hash) {
if (type === 'block') {
try {
const lastSynchronized = await Info.checkpoint()
const currentHeight = await request.height()
console.log('Last Synchronized = ', lastSynchronized)
console.log('Current Height = ', currentHeight)
for(let index=lastSynchronized+1; index<=currentHeight; index++) {
console.log('RPC BEGIN ' + index, new Date().toString())
console.time('RPC END ' + index)
let content = await crawl(index)
console.timeEnd('RPC END ' + index)
console.log(new Date().toString())
console.log('DB BEGIN ' + index, new Date().toString())
console.time('DB Insert ' + index)
await Db.block.insert(content, index)
await Info.updateTip(index)
console.timeEnd('DB Insert ' + index)
console.log('------------------------------------------')
console.log('\n')
// zmq broadcast
let b = { i: index, txs: content }
console.log('Zmq block = ', JSON.stringify(b, null, 2))
outsock.send(['block', JSON.stringify(b)])
}
// clear mempool and synchronize
if (lastSynchronized < currentHeight) {
console.log('Clear mempool and repopulate')
let items = await request.whcMempool()
await Db.mempool.sync(items)
}
if (lastSynchronized === currentHeight) {
console.log('no update')
return null
} else {
console.log('[finished]')
return currentHeight
}
} catch (e) {
console.log('Error', e)
console.log('Shutting down Bitdb...', new Date().toString())
await Db.exit()
process.exit()
}
} else if (type === 'mempool') {
queue.add(async function() {
let content
try {
content = await request.whcTx(hash)
await Db.mempool.insert(content)
console.log('# Q inserted [size: ' + queue.size + ']', hash)
console.log(content)
outsock.send(['mempool', JSON.stringify(content)])
} catch (e) {
// duplicates are ok because they will be ignored
if (e.code == 11000) {
console.log('Duplicate mempool item: ', content)
} else if (e.code == -5 && e.message == 'Not a Wormhole Protocol transaction') {
console.log('Non wormhole tx from mempool')
}
else {
console.log('## ERR ', e, content)
process.exit()
}
}
})
return hash
}
}
const run = async function() {
// initial block sync
await sync('block')
// initial mempool sync
console.log('Clear mempool and repopulate')
let items = await request.whcMempool()
await Db.mempool.sync(items)
}
module.exports = {
init: init, crawl: crawl, listen: listen, sync: sync, run: run
}