-
Notifications
You must be signed in to change notification settings - Fork 52
/
discovery.js
43 lines (34 loc) · 979 Bytes
/
discovery.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
// https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#account-discovery
module.exports = function discovery (chain, gapLimit, queryCb, done) {
let gap = 0
let checked = 0
function cycle () {
const batch = [chain.get()]
checked++
while (batch.length < gapLimit) {
chain.next()
batch.push(chain.get())
checked++
}
queryCb(batch, function (err, queryResultSet) {
if (Array.isArray(queryResultSet)) return done(new TypeError('Expected query set, not Array'))
if (err) return done(err)
// iterate batch, guarantees order agnostic of queryCb result ordering
batch.forEach(function (address) {
if (queryResultSet[address]) {
gap = 0
} else {
gap += 1
}
})
if (gap >= gapLimit) {
const used = checked - gap
return done(undefined, used, checked)
} else {
chain.next()
}
cycle()
})
}
cycle()
}