This repository has been archived by the owner on Aug 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
transport.js
272 lines (233 loc) · 7.51 KB
/
transport.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
'use strict'
/* eslint no-warning-comments: off */
const parallel = require('async/parallel')
const once = require('once')
const debug = require('debug')
const log = debug('libp2p:switch:transport')
const LimitDialer = require('./limit-dialer')
const { DIAL_TIMEOUT } = require('./constants')
const { uniqueBy } = require('./utils')
// number of concurrent outbound dials to make per peer, same as go-libp2p-swtch
const defaultPerPeerRateLimit = 8
/**
* Manages the transports for the switch. This simplifies dialing and listening across
* multiple transports.
*/
class TransportManager {
constructor (_switch) {
this.switch = _switch
this.dialer = new LimitDialer(defaultPerPeerRateLimit, this.switch._options.dialTimeout || DIAL_TIMEOUT)
}
/**
* Adds a `Transport` to the list of transports on the switch, and assigns it to the given key
*
* @param {String} key
* @param {Transport} transport
* @returns {void}
*/
add (key, transport) {
log('adding %s', key)
if (this.switch.transports[key]) {
throw new Error('There is already a transport with this key')
}
this.switch.transports[key] = transport
if (!this.switch.transports[key].listeners) {
this.switch.transports[key].listeners = []
}
}
/**
* Closes connections for the given transport key
* and removes it from the switch.
*
* @param {String} key
* @param {function(Error)} callback
* @returns {void}
*/
remove (key, callback) {
callback = callback || function () {}
if (!this.switch.transports[key]) {
return callback()
}
this.close(key, (err) => {
delete this.switch.transports[key]
callback(err)
})
}
/**
* Calls `remove` on each transport the switch has
*
* @param {function(Error)} callback
* @returns {void}
*/
removeAll (callback) {
const tasks = Object.keys(this.switch.transports).map((key) => {
return (cb) => {
this.remove(key, cb)
}
})
parallel(tasks, callback)
}
/**
* For a given transport `key`, dial to all that transport multiaddrs
*
* @param {String} key Key of the `Transport` to dial
* @param {PeerInfo} peerInfo
* @param {function(Error, Connection)} callback
* @returns {void}
*/
dial (key, peerInfo, callback) {
const transport = this.switch.transports[key]
let multiaddrs = peerInfo.multiaddrs.toArray()
if (!Array.isArray(multiaddrs)) {
multiaddrs = [multiaddrs]
}
// filter the multiaddrs that are actually valid for this transport
multiaddrs = TransportManager.dialables(transport, multiaddrs, this.switch._peerInfo)
log('dialing %s', key, multiaddrs.map((m) => m.toString()))
// dial each of the multiaddrs with the given transport
this.dialer.dialMany(peerInfo.id, transport, multiaddrs, (errors, success) => {
if (errors) {
return callback(errors)
}
peerInfo.connect(success.multiaddr)
callback(null, success.conn)
})
}
/**
* For a given Transport `key`, listen on all multiaddrs in the switch's `_peerInfo`.
* If a `handler` is not provided, the Switch's `protocolMuxer` will be used.
*
* @param {String} key
* @param {*} _options Currently ignored
* @param {function(Connection)} handler
* @param {function(Error)} callback
* @returns {void}
*/
listen (key, _options, handler, callback) {
handler = this.switch._connectionHandler(key, handler)
const transport = this.switch.transports[key]
let originalAddrs = this.switch._peerInfo.multiaddrs.toArray()
// Until TCP can handle distinct addresses on listen, https://github.com/libp2p/interface-transport/issues/41,
// make sure we aren't trying to listen on duplicate ports. This also applies to websockets.
originalAddrs = uniqueBy(originalAddrs, (addr) => {
// Any non 0 port should register as unique
const port = Number(addr.toOptions().port)
return isNaN(port) || port === 0 ? addr.toString() : port
})
const multiaddrs = TransportManager.dialables(transport, originalAddrs)
if (!transport.listeners) {
transport.listeners = []
}
let freshMultiaddrs = []
const createListeners = multiaddrs.map((ma) => {
return (cb) => {
const done = once(cb)
const listener = transport.createListener(handler)
listener.once('error', done)
listener.listen(ma, (err) => {
if (err) {
return done(err)
}
listener.removeListener('error', done)
listener.getAddrs((err, addrs) => {
if (err) {
return done(err)
}
freshMultiaddrs = freshMultiaddrs.concat(addrs)
transport.listeners.push(listener)
done()
})
})
}
})
parallel(createListeners, (err) => {
if (err) {
return callback(err)
}
// cause we can listen on port 0 or 0.0.0.0
this.switch._peerInfo.multiaddrs.replace(multiaddrs, freshMultiaddrs)
callback()
})
}
/**
* Closes the transport with the given key, by closing all of its listeners
*
* @param {String} key
* @param {function(Error)} callback
* @returns {void}
*/
close (key, callback) {
const transport = this.switch.transports[key]
if (!transport) {
return callback(new Error(`Trying to close non existing transport: ${key}`))
}
parallel(transport.listeners.map((listener) => {
return (cb) => {
listener.close(cb)
}
}), callback)
}
/**
* For a given transport, return its multiaddrs that match the given multiaddrs
*
* @param {Transport} transport
* @param {Array<Multiaddr>} multiaddrs
* @param {PeerInfo} peerInfo Optional - a peer whose addresses should not be returned
* @returns {Array<Multiaddr>}
*/
static dialables (transport, multiaddrs, peerInfo) {
// If we dont have a proper transport, return no multiaddrs
if (!transport || !transport.filter) return []
const transportAddrs = transport.filter(multiaddrs)
if (!peerInfo || !transportAddrs.length) {
return transportAddrs
}
const ourAddrs = ourAddresses(peerInfo)
const result = transportAddrs.filter(transportAddr => {
// If our address is in the destination address, filter it out
return !ourAddrs.some(a => getDestination(transportAddr).startsWith(a))
})
return result
}
}
/**
* Expand addresses in peer info into array of addresses with and without peer
* ID suffix.
*
* @param {PeerInfo} peerInfo Our peer info object
* @returns {String[]}
*/
function ourAddresses (peerInfo) {
const ourPeerId = peerInfo.id.toB58String()
return peerInfo.multiaddrs.toArray()
.reduce((ourAddrs, addr) => {
const peerId = addr.getPeerId()
addr = addr.toString()
const otherAddr = peerId
? addr.slice(0, addr.lastIndexOf(`/ipfs/${peerId}`))
: `${addr}/ipfs/${ourPeerId}`
return ourAddrs.concat([addr, otherAddr])
}, [])
.filter(a => Boolean(a))
.concat(`/ipfs/${ourPeerId}`)
}
const RelayProtos = [
'p2p-circuit',
'p2p-websocket-star',
'p2p-webrtc-star',
'p2p-stardust'
]
/**
* Get the destination address of a (possibly relay) multiaddr as a string
*
* @param {Multiaddr} addr
* @returns {String}
*/
function getDestination (addr) {
const protos = addr.protoNames().reverse()
const splitProto = protos.find(p => RelayProtos.includes(p))
addr = addr.toString()
if (!splitProto) return addr
return addr.slice(addr.lastIndexOf(splitProto) + splitProto.length)
}
module.exports = TransportManager