-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
86 lines (66 loc) · 2.36 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
'use strict'
const logger = require('simple-node-logger').createSimpleLogger()
const nconf = require('nconf')
const fs = require('fs')
const LAST_BLOCK_FILE = '.lastblock'
let pushers = null
nconf.argv().env('__')
nconf.defaults({conf: `${__dirname}/config.json`})
nconf.file(nconf.get('conf'))
const api = require('./lib/eosApi')(nconf.get('eosApi'), nconf.get('eosHistoryApi'), nconf.get('apiTimeout'))
const actions = require('./lib/actions')(nconf.get('accounts'))
const watchInterval = nconf.get('watchInterval')
let lastChainInfo = null
let nextSyncBlock = nconf.get('initialBlock')
let isSyncing = true
const mainLoop = async () => {
if (!pushers)
pushers = await require('./lib/pushers')(logger, nconf.get('zeromq'), nconf.get('mongodb'), nconf.get('amqp'))
const currentBlock = nextSyncBlock
logger.info(`Syncing block ${currentBlock}`)
try {
if (lastChainInfo == null || nextSyncBlock <= lastChainInfo.head_block_num) {
lastChainInfo = await api.getChainInfo()
}
if (lastChainInfo && lastChainInfo.head_block_num >= nextSyncBlock) {
const blockInfo = await api.getBlockInfo(nextSyncBlock)
const transactionsIds = actions.filteredTransactionsIds(blockInfo)
const transactions = transactionsIds && transactionsIds.length ?
await api.getBulkTransactions(transactionsIds) : null
if (transactions && transactions.length) {
pushTransactions(transactions)
}
await saveLastBlock()
nextSyncBlock++
}
} catch (err) {
const { message } = err
logger.error(`Sync failed on block ${currentBlock} >>> `,
message || err || 'Unknown Error')
}
isSyncing = !lastChainInfo || lastChainInfo.head_block_num > nextSyncBlock
isSyncing ? setImmediate(mainLoop)
: setTimeout(mainLoop, watchInterval)
}
const saveLastBlock = () => {
return new Promise((resolve, reject) => {
fs.writeFile(LAST_BLOCK_FILE, nextSyncBlock, (err) => {
if (err)
reject(err)
else
resolve(true)
});
})
}
const pushTransactions = transactions => {
return Promise.all(pushers.map(p => p(transactions)))
}
fs.readFile(LAST_BLOCK_FILE, (err,data) => {
if (err) {
logger.info(`Blocks were never synced, starting from ${nextSyncBlock}`)
} else {
nextSyncBlock = Number(data) + 1
logger.info(`Last synced block: ${nextSyncBlock} - resyncing...`)
}
mainLoop()
})