This repository was archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathindex.js
63 lines (50 loc) · 1.44 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
'use strict'
const PeerId = require('peer-id')
const PeerInfo = require('peer-info')
const multiaddr = require('multiaddr')
const mafmt = require('mafmt')
const EventEmitter = require('events').EventEmitter
const debug = require('debug')
const setImmediate = require('async/setImmediate')
const log = debug('libp2p:railing')
log.error = debug('libp2p:railing:error')
function isIPFS (addr) {
try {
return mafmt.IPFS.matches(addr)
} catch (e) {
return false
}
}
class Bootstrap extends EventEmitter {
constructor (options) {
super()
this._list = options.list
this._interval = options.interval || 10000
this._timer = null
}
start (callback) {
setImmediate(() => callback())
if (this._timer) { return }
this._timer = setInterval(() => {
this._list.forEach((candidate) => {
if (!isIPFS(candidate)) { return log.error('Invalid multiaddr') }
const ma = multiaddr(candidate)
const peerId = PeerId.createFromB58String(ma.getPeerId())
PeerInfo.create(peerId, (err, peerInfo) => {
if (err) { return log.error('Invalid bootstrap peer id', err) }
peerInfo.multiaddrs.add(ma)
this.emit('peer', peerInfo)
})
})
}, this._interval)
}
stop (callback) {
setImmediate(callback)
if (this._timer) {
clearInterval(this._timer)
this._timer = null
}
}
}
exports = module.exports = Bootstrap
exports.tag = 'bootstrap'