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
/
Copy pathindex.js
264 lines (236 loc) · 6.98 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
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
'use strict'
const FSM = require('fsm-event')
const EventEmitter = require('events').EventEmitter
const each = require('async/each')
const eachSeries = require('async/eachSeries')
const series = require('async/series')
const TransportManager = require('./transport')
const ConnectionManager = require('./connection/manager')
const getPeerInfo = require('./get-peer-info')
const dial = require('./dialer')
const connectionHandler = require('./connection/handler')
const ProtocolMuxer = require('./protocol-muxer')
const plaintext = require('./plaintext')
const Observer = require('./observer')
const Stats = require('./stats')
const assert = require('assert')
const Errors = require('./errors')
const debug = require('debug')
const log = debug('libp2p:switch')
log.error = debug('libp2p:switch:error')
/**
* @fires Switch#stop Triggered when the switch has stopped
* @fires Switch#start Triggered when the switch has started
* @fires Switch#error Triggered whenever an error occurs
*/
class Switch extends EventEmitter {
constructor (peerInfo, peerBook, options) {
super()
assert(peerInfo, 'You must provide a `peerInfo`')
assert(peerBook, 'You must provide a `peerBook`')
this._peerInfo = peerInfo
this._peerBook = peerBook
this._options = options || {}
this.setMaxListeners(Infinity)
// transports --
// { key: transport }; e.g { tcp: <tcp> }
this.transports = {}
// connections --
// { peerIdB58: { conn: <conn> }}
this.conns = {}
// { protocol: handler }
this.protocols = {}
// { muxerCodec: <muxer> } e.g { '/spdy/0.3.1': spdy }
this.muxers = {}
// is the Identify protocol enabled?
this.identify = false
// Crypto details
this.crypto = plaintext
this.protector = this._options.protector || null
this.transport = new TransportManager(this)
this.connection = new ConnectionManager(this)
this.observer = Observer(this)
this.stats = Stats(this.observer, this._options.stats)
this.protocolMuxer = ProtocolMuxer(this.protocols, this.observer)
// higher level (public) API
this.dial = dial(this)
this.dialFSM = dial(this, true)
// All purpose connection handler for managing incoming connections
this._connectionHandler = connectionHandler(this)
// Setup the internal state
this.state = new FSM('STOPPED', {
STOPPED: {
start: 'STARTING',
stop: 'STOPPING' // ensures that any transports that were manually started are stopped
},
STARTING: {
done: 'STARTED',
stop: 'STOPPING'
},
STARTED: {
stop: 'STOPPING',
start: 'STARTED'
},
STOPPING: {
stop: 'STOPPING',
done: 'STOPPED'
}
})
this.state.on('STARTING', () => {
log('The switch is starting')
this._onStarting()
})
this.state.on('STOPPING', () => {
log('The switch is stopping')
this._onStopping()
})
this.state.on('STARTED', () => {
log('The switch has started')
this.emit('start')
})
this.state.on('STOPPED', () => {
log('The switch has stopped')
this.emit('stop')
})
this.state.on('error', (err) => {
log.error(err)
this.emit('error', err)
})
}
/**
* Returns a list of the transports peerInfo has addresses for
*
* @param {PeerInfo} peerInfo
* @returns {Array<Transport>}
*/
availableTransports (peerInfo) {
const myAddrs = peerInfo.multiaddrs.toArray()
const myTransports = Object.keys(this.transports)
// Only listen on transports we actually have addresses for
return myTransports.filter((ts) => this.transports[ts].filter(myAddrs).length > 0)
// push Circuit to be the last proto to be dialed
.sort((a) => {
return a === 'Circuit' ? 1 : 0
})
}
/**
* Adds the `handlerFunc` and `matchFunc` to the Switch's protocol
* handler list for the given `protocol`. If the `matchFunc` returns
* true for a protocol check, the `handlerFunc` will be called.
*
* @param {string} protocol
* @param {function(string, Connection)} handlerFunc
* @param {function(string, string, function(Error, boolean))} matchFunc
* @returns {void}
*/
handle (protocol, handlerFunc, matchFunc) {
this.protocols[protocol] = {
handlerFunc: handlerFunc,
matchFunc: matchFunc
}
}
/**
* Removes the given protocol from the Switch's protocol list
*
* @param {string} protocol
* @returns {void}
*/
unhandle (protocol) {
if (this.protocols[protocol]) {
delete this.protocols[protocol]
}
}
/**
* If a muxed Connection exists for the given peer, it will be closed
* and its reference on the Switch will be removed.
*
* @param {PeerInfo|Multiaddr|PeerId} peer
* @param {function()} callback
* @returns {void}
*/
hangUp (peer, callback) {
const peerInfo = getPeerInfo(peer, this.peerBook)
const key = peerInfo.id.toB58String()
const conns = [...this.connection.getAllById(key)]
each(conns, (conn, cb) => {
conn.once('close', cb)
conn.close()
}, callback)
}
/**
* Returns whether or not the switch has any transports
*
* @returns {boolean}
*/
hasTransports () {
const transports = Object.keys(this.transports).filter((t) => t !== 'Circuit')
return transports && transports.length > 0
}
/**
* Issues a start on the Switch state.
*
* @param {function} callback deprecated: Listening for the `error` and `start` events are recommended
* @returns {void}
*/
start (callback = () => {}) {
// Add once listener for deprecated callback support
this.once('start', callback)
this.state('start')
}
/**
* Issues a stop on the Switch state.
*
* @param {function} callback deprecated: Listening for the `error` and `stop` events are recommended
* @returns {void}
*/
stop (callback = () => {}) {
// Add once listener for deprecated callback support
this.once('stop', callback)
this.state('stop')
}
/**
* A listener that will start any necessary services and listeners
*
* @private
* @returns {void}
*/
_onStarting () {
this.stats.start()
eachSeries(this.availableTransports(this._peerInfo), (ts, cb) => {
// Listen on the given transport
this.transport.listen(ts, {}, null, cb)
}, (err) => {
if (err) {
log.error(err)
return this.emit('error', err)
}
this.state('done')
})
}
/**
* A listener that will turn off all running services and listeners
*
* @private
* @returns {void}
*/
_onStopping () {
this.stats.stop()
series([
(cb) => {
each(this.transports, (transport, cb) => {
each(transport.listeners, (listener, cb) => {
listener.close(cb)
}, cb)
}, cb)
},
(cb) => each([...this.connection.getAll()], (conn, cb) => {
conn.once('close', cb)
conn.close()
}, cb)
], (_) => {
this.state('done')
})
}
}
module.exports = Switch
module.exports.errors = Errors