This repository has been archived by the owner on Jul 19, 2024. It is now read-only.
forked from bitcoinjs/indexd
-
Notifications
You must be signed in to change notification settings - Fork 6
/
resync.js
75 lines (60 loc) · 2.01 KB
/
resync.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
let debug = require('./debug')('indexd:resync')
let parallel = require('run-parallel')
let rpcUtil = require('./rpc')
// recursively calls connectBlock(id) until `bitcoind[id].next` is falsy
function connectBlock (rpc, indexd, id, height, callback) {
debug(`Connecting ${id} @ ${height}`)
indexd.connect(id, height, (err, nextblockhash) => {
if (err) return callback(err)
debug(`Connected ${id} @ ${height}`)
if (!nextblockhash) return callback()
// recurse until next is falsy
connectBlock(rpc, indexd, nextblockhash, height + 1, callback)
})
}
function disconnectBlock (indexd, id, callback) {
debug(`Disconnecting ${id}`)
indexd.disconnect(id, (err) => {
if (err) return callback(err)
debug(`Disconnected ${id}`)
callback()
})
}
module.exports = function resync (rpc, indexd, callback) {
debug('fetching bitcoind/indexd tips')
parallel({
bitcoind: (f) => rpcUtil.tip(rpc, f),
indexd: (f) => indexd.tip(f)
}, (err, tips) => {
if (err) return callback(err)
// Step 0, genesis?
if (!tips.indexd) {
debug('genesis')
return rpcUtil.blockIdAtHeight(rpc, 0, (err, genesisId) => {
if (err) return callback(err)
connectBlock(rpc, indexd, genesisId, 0, callback)
})
}
// Step 1, equal?
debug('...', tips)
if (tips.bitcoind === tips.indexd) return callback()
// else, Step 2, is indexd behind? [bitcoind has indexd tip]
rpcUtil.headerJSON(rpc, tips.indexd, (err, common) => {
// not in bitcoind chain? [forked]
if (
(err && err.message === 'Block not found') ||
(!err && common.confirmations === -1)
) {
debug('indexd is forked')
return disconnectBlock(indexd, tips.indexd, (err) => {
if (err) return callback(err)
resync(rpc, indexd, callback)
})
}
if (err) return callback(err)
// indexd is behind
debug('bitcoind is ahead')
connectBlock(rpc, indexd, common.nextblockhash, common.height + 1, callback)
})
})
}