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
/
base.js
125 lines (110 loc) · 2.51 KB
/
base.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
'use strict'
const EventEmitter = require('events').EventEmitter
const debug = require('debug')
const withIs = require('class-is')
class BaseConnection extends EventEmitter {
constructor ({ _switch, name }) {
super()
this.switch = _switch
this.ourPeerInfo = this.switch._peerInfo
this.log = debug(`libp2p:conn:${name}`)
this.log.error = debug(`libp2p:conn:${name}:error`)
}
/**
* Puts the state into its disconnecting flow
*
* @param {Error} err Will be emitted if provided
* @returns {void}
*/
close (err) {
this.log(`closing connection to ${this.theirB58Id}`)
if (err && this._events.error) {
this.emit('error', err)
}
this._state('disconnect')
}
emit (eventName, ...args) {
if (eventName === 'error' && !this._events.error) {
this.log.error(...args)
} else {
super.emit(eventName, ...args)
}
}
/**
* Gets the current state of the connection
*
* @returns {string} The current state of the connection
*/
getState () {
return this._state._state
}
/**
* Puts the state into encrypting mode
*
* @returns {void}
*/
encrypt () {
this._state('encrypt')
}
/**
* Puts the state into privatizing mode
*
* @returns {void}
*/
protect () {
this._state('privatize')
}
/**
* Puts the state into muxing mode
*
* @returns {void}
*/
upgrade () {
this._state('upgrade')
}
/**
* Event handler for disconnected.
*
* @fires BaseConnection#close
* @returns {void}
*/
_onDisconnected () {
this.log(`disconnected from ${this.theirB58Id}`)
this.emit('close')
this.removeAllListeners()
}
/**
* Event handler for privatized
*
* @fires BaseConnection#private
* @returns {void}
*/
_onPrivatized () {
this.log(`successfully privatized incoming connection`)
this.emit('private', this.conn)
}
/**
* Wraps this.conn with the Switch.protector for private connections
*
* @private
* @fires ConnectionFSM#error
* @returns {void}
*/
_onPrivatizing () {
if (!this.switch.protector) {
return this._state('done')
}
this.conn = this.switch.protector.protect(this.conn, (err) => {
if (err) {
return this.close(err)
}
this.log(`successfully privatized conn to ${this.theirB58Id}`)
this.conn.setPeerInfo(this.theirPeerInfo)
this._state('done')
})
}
}
module.exports = withIs(BaseConnection, {
className: 'BaseConnection',
symbolName: 'libp2p-switch/BaseConnection'
})