This repository has been archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathlibp2p.js
68 lines (58 loc) · 1.93 KB
/
libp2p.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
'use strict'
// libp2p-nodejs gets replaced by libp2p-browser when webpacked/browserified
const Node = require('../runtime/libp2p-nodejs')
const promisify = require('promisify-es6')
const get = require('lodash.get')
module.exports = function libp2p (self) {
return {
start: promisify((callback) => {
self.config.get(gotConfig)
function gotConfig (err, config) {
if (err) {
return callback(err)
}
const options = {
mdns: get(config, 'Discovery.MDNS.Enabled'),
webRTCStar: get(config, 'Discovery.webRTCStar.Enabled'),
bootstrap: get(config, 'Bootstrap'),
dht: get(self._options, 'EXPERIMENTAL.dht'),
modules: self._libp2pModules,
relay: {
enabled: !get(config, 'EXPERIMENTAL.Swarm.DisableRelay', false),
hop: {
enabled: get(config, 'EXPERIMENTAL.Swarm.EnableRelayHop', false),
active: get(config, 'EXPERIMENTAL.Swarm.RelayHopActive', false)
}
}
}
self._libp2pNode = new Node(self._peerInfo, self._peerInfoBook, options)
self._libp2pNode.on('peer:discovery', (peerInfo) => {
const dial = () => {
self._peerInfoBook.put(peerInfo)
self._libp2pNode.dial(peerInfo, () => {})
}
if (self.isOnline()) {
dial()
} else {
self._libp2pNode.once('start', dial)
}
})
self._libp2pNode.on('peer:connect', (peerInfo) => {
self._peerInfoBook.put(peerInfo)
})
self._libp2pNode.start((err) => {
if (err) {
return callback(err)
}
self._libp2pNode.peerInfo.multiaddrs.forEach((ma) => {
console.log('Swarm listening on', ma.toString())
})
callback()
})
}
}),
stop: promisify((callback) => {
self._libp2pNode.stop(callback)
})
}
}