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.2k
/
Copy pathlibp2p.js
94 lines (83 loc) · 2.89 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'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')
const defaultsDeep = require('@nodeutils/defaults-deep')
module.exports = function libp2p (self) {
return {
start: promisify((callback) => {
self.config.get(gotConfig)
function gotConfig (err, config) {
if (err) {
return callback(err)
}
const libp2pDefaults = {
peerInfo: self._peerInfo,
peerBook: self._peerInfoBook,
config: {
peerDiscovery: {
mdns: {
enabled: get(self._options, 'config.Discovery.MDNS.Enabled',
get(config, 'Discovery.MDNS.Enabled', true))
},
webRTCStar: {
enabled: get(self._options, 'config.Discovery.webRTCStar.Enabled',
get(config, 'Discovery.webRTCStar.Enabled', true))
},
bootstrap: {
list: get(self._options, 'config.Bootstrap',
get(config, 'Bootstrap', []))
}
},
relay: {
enabled: get(self._options, 'relay.enabled',
get(config, 'relay.enabled', false)),
hop: {
enabled: get(self._options, 'relay.hop.enabled',
get(config, 'relay.hop.enabled', false)),
active: get(self._options, 'relay.hop.active',
get(config, 'relay.hop.active', false))
}
},
EXPERIMENTAL: {
dht: get(self._options, 'EXPERIMENTAL.dht', false),
pubsub: get(self._options, 'EXPERIMENTAL.pubsub', false)
}
},
connectionManager: get(self._options, 'connectionManager',
get(config, 'connectionManager', {}))
}
const libp2pOptions = defaultsDeep(
get(self._options, 'libp2p', {}),
libp2pDefaults
)
self._libp2pNode = new Node(libp2pOptions)
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)
})
}
}