@streamr/dht 0.0.1-tatum.6 → 0.0.1-tatum.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/dist/src/connection/ConnectionLockHandler.d.ts +1 -1
  2. package/dist/src/connection/ConnectionLockHandler.js.map +1 -1
  3. package/dist/src/connection/ConnectionManager.d.ts +17 -40
  4. package/dist/src/connection/ConnectionManager.js +138 -204
  5. package/dist/src/connection/ConnectionManager.js.map +1 -1
  6. package/dist/src/connection/ConnectivityChecker.js +14 -11
  7. package/dist/src/connection/ConnectivityChecker.js.map +1 -1
  8. package/dist/src/connection/ConnectorFacade.d.ts +49 -0
  9. package/dist/src/connection/ConnectorFacade.js +86 -0
  10. package/dist/src/connection/ConnectorFacade.js.map +1 -0
  11. package/dist/src/connection/ManagedConnection.d.ts +1 -4
  12. package/dist/src/connection/ManagedConnection.js +23 -31
  13. package/dist/src/connection/ManagedConnection.js.map +1 -1
  14. package/dist/src/connection/RemoteConnectionLocker.js +4 -3
  15. package/dist/src/connection/RemoteConnectionLocker.js.map +1 -1
  16. package/dist/src/connection/Simulator/Simulator.d.ts +0 -2
  17. package/dist/src/connection/Simulator/Simulator.js +0 -5
  18. package/dist/src/connection/Simulator/Simulator.js.map +1 -1
  19. package/dist/src/connection/Simulator/SimulatorConnection.js +16 -13
  20. package/dist/src/connection/Simulator/SimulatorConnection.js.map +1 -1
  21. package/dist/src/connection/Simulator/SimulatorConnector.d.ts +2 -2
  22. package/dist/src/connection/Simulator/SimulatorConnector.js +10 -11
  23. package/dist/src/connection/Simulator/SimulatorConnector.js.map +1 -1
  24. package/dist/src/connection/Simulator/SimulatorTransport.js +6 -1
  25. package/dist/src/connection/Simulator/SimulatorTransport.js.map +1 -1
  26. package/dist/src/connection/WebRTC/NodeWebRtcConnection.d.ts +2 -0
  27. package/dist/src/connection/WebRTC/NodeWebRtcConnection.js +12 -12
  28. package/dist/src/connection/WebRTC/NodeWebRtcConnection.js.map +1 -1
  29. package/dist/src/connection/WebRTC/WebRtcConnector.d.ts +9 -9
  30. package/dist/src/connection/WebRTC/WebRtcConnector.js +22 -22
  31. package/dist/src/connection/WebRTC/WebRtcConnector.js.map +1 -1
  32. package/dist/src/connection/WebSocket/RemoteWebSocketConnector.js +2 -1
  33. package/dist/src/connection/WebSocket/RemoteWebSocketConnector.js.map +1 -1
  34. package/dist/src/connection/WebSocket/WebSocketConnector.d.ts +19 -8
  35. package/dist/src/connection/WebSocket/WebSocketConnector.js +67 -46
  36. package/dist/src/connection/WebSocket/WebSocketConnector.js.map +1 -1
  37. package/dist/src/connection/WebSocket/WebSocketServer.d.ts +11 -1
  38. package/dist/src/connection/WebSocket/WebSocketServer.js +15 -10
  39. package/dist/src/connection/WebSocket/WebSocketServer.js.map +1 -1
  40. package/dist/src/dht/DhtNode.d.ts +15 -51
  41. package/dist/src/dht/DhtNode.js +107 -129
  42. package/dist/src/dht/DhtNode.js.map +1 -1
  43. package/dist/src/dht/{DhtPeer.d.ts → RemoteDhtNode.d.ts} +2 -3
  44. package/dist/src/dht/{DhtPeer.js → RemoteDhtNode.js} +21 -19
  45. package/dist/src/dht/RemoteDhtNode.js.map +1 -0
  46. package/dist/src/dht/contact/ContactList.d.ts +0 -1
  47. package/dist/src/dht/contact/ContactList.js +0 -3
  48. package/dist/src/dht/contact/ContactList.js.map +1 -1
  49. package/dist/src/dht/contact/RandomContactList.d.ts +0 -1
  50. package/dist/src/dht/contact/RandomContactList.js +0 -3
  51. package/dist/src/dht/contact/RandomContactList.js.map +1 -1
  52. package/dist/src/dht/contact/SortedContactList.d.ts +0 -3
  53. package/dist/src/dht/contact/SortedContactList.js +0 -9
  54. package/dist/src/dht/contact/SortedContactList.js.map +1 -1
  55. package/dist/src/dht/discovery/DiscoverySession.d.ts +5 -7
  56. package/dist/src/dht/discovery/DiscoverySession.js +9 -10
  57. package/dist/src/dht/discovery/DiscoverySession.js.map +1 -1
  58. package/dist/src/dht/discovery/PeerDiscovery.d.ts +11 -10
  59. package/dist/src/dht/discovery/PeerDiscovery.js +32 -37
  60. package/dist/src/dht/discovery/PeerDiscovery.js.map +1 -1
  61. package/dist/src/dht/find/RecursiveFindSession.d.ts +5 -6
  62. package/dist/src/dht/find/RecursiveFindSession.js +8 -8
  63. package/dist/src/dht/find/RecursiveFindSession.js.map +1 -1
  64. package/dist/src/dht/find/RecursiveFinder.d.ts +2 -4
  65. package/dist/src/dht/find/RecursiveFinder.js +11 -12
  66. package/dist/src/dht/find/RecursiveFinder.js.map +1 -1
  67. package/dist/src/dht/registerExternalApiRpcMethods.d.ts +1 -1
  68. package/dist/src/dht/routing/DuplicateDetector.d.ts +1 -2
  69. package/dist/src/dht/routing/DuplicateDetector.js +2 -7
  70. package/dist/src/dht/routing/DuplicateDetector.js.map +1 -1
  71. package/dist/src/dht/routing/RemoteRouter.js +1 -1
  72. package/dist/src/dht/routing/RemoteRouter.js.map +1 -1
  73. package/dist/src/dht/routing/Router.d.ts +10 -13
  74. package/dist/src/dht/routing/Router.js +28 -29
  75. package/dist/src/dht/routing/Router.js.map +1 -1
  76. package/dist/src/dht/routing/RoutingSession.d.ts +3 -4
  77. package/dist/src/dht/routing/RoutingSession.js +4 -3
  78. package/dist/src/dht/routing/RoutingSession.js.map +1 -1
  79. package/dist/src/dht/store/DataStore.d.ts +2 -2
  80. package/dist/src/dht/store/DataStore.js +7 -7
  81. package/dist/src/dht/store/DataStore.js.map +1 -1
  82. package/dist/src/exports.d.ts +1 -7
  83. package/dist/src/exports.js +2 -14
  84. package/dist/src/exports.js.map +1 -1
  85. package/dist/src/helpers/PeerID.d.ts +0 -1
  86. package/dist/src/helpers/PeerID.js +0 -6
  87. package/dist/src/helpers/PeerID.js.map +1 -1
  88. package/dist/src/helpers/browser/isBrowserEnvironment.d.ts +1 -0
  89. package/dist/src/helpers/browser/isBrowserEnvironment.js +6 -0
  90. package/dist/src/helpers/browser/isBrowserEnvironment.js.map +1 -0
  91. package/dist/src/helpers/browser/isBrowserEnvironment_override.d.ts +1 -0
  92. package/dist/src/helpers/browser/isBrowserEnvironment_override.js +7 -0
  93. package/dist/src/helpers/browser/isBrowserEnvironment_override.js.map +1 -0
  94. package/dist/src/helpers/kademliaId.d.ts +1 -0
  95. package/dist/src/helpers/kademliaId.js +14 -0
  96. package/dist/src/helpers/kademliaId.js.map +1 -0
  97. package/dist/src/helpers/peerIdFromPeerDescriptor.d.ts +1 -1
  98. package/dist/src/helpers/peerIdFromPeerDescriptor.js +3 -3
  99. package/dist/src/helpers/peerIdFromPeerDescriptor.js.map +1 -1
  100. package/dist/src/proto/packages/dht/protos/DhtRpc.d.ts +0 -4
  101. package/dist/src/proto/packages/dht/protos/DhtRpc.js +1 -2
  102. package/dist/src/proto/packages/dht/protos/DhtRpc.js.map +1 -1
  103. package/package.json +10 -9
  104. package/protos/DhtRpc.proto +0 -1
  105. package/src/connection/ConnectionLockHandler.ts +1 -1
  106. package/src/connection/ConnectionManager.ts +157 -254
  107. package/src/connection/ConnectivityChecker.ts +14 -11
  108. package/src/connection/ConnectorFacade.ts +143 -0
  109. package/src/connection/ManagedConnection.ts +23 -34
  110. package/src/connection/RemoteConnectionLocker.ts +4 -3
  111. package/src/connection/Simulator/Simulator.ts +0 -7
  112. package/src/connection/Simulator/SimulatorConnection.ts +16 -13
  113. package/src/connection/Simulator/SimulatorConnector.ts +11 -12
  114. package/src/connection/Simulator/SimulatorTransport.ts +6 -1
  115. package/src/connection/WebRTC/NodeWebRtcConnection.ts +14 -13
  116. package/src/connection/WebRTC/WebRtcConnector.ts +31 -31
  117. package/src/connection/WebSocket/RemoteWebSocketConnector.ts +2 -1
  118. package/src/connection/WebSocket/WebSocketConnector.ts +85 -62
  119. package/src/connection/WebSocket/WebSocketServer.ts +26 -8
  120. package/src/dht/DhtNode.ts +155 -181
  121. package/src/dht/{DhtPeer.ts → RemoteDhtNode.ts} +11 -9
  122. package/src/dht/contact/ContactList.ts +0 -4
  123. package/src/dht/contact/RandomContactList.ts +0 -4
  124. package/src/dht/contact/SortedContactList.ts +0 -12
  125. package/src/dht/discovery/DiscoverySession.ts +20 -23
  126. package/src/dht/discovery/PeerDiscovery.ts +45 -44
  127. package/src/dht/find/RecursiveFindSession.ts +12 -13
  128. package/src/dht/find/RecursiveFinder.ts +16 -19
  129. package/src/dht/registerExternalApiRpcMethods.ts +1 -1
  130. package/src/dht/routing/DuplicateDetector.ts +3 -10
  131. package/src/dht/routing/RemoteRouter.ts +2 -2
  132. package/src/dht/routing/Router.ts +35 -39
  133. package/src/dht/routing/RoutingSession.ts +9 -9
  134. package/src/dht/store/DataStore.ts +11 -11
  135. package/src/exports.ts +1 -7
  136. package/src/helpers/PeerID.ts +0 -7
  137. package/src/helpers/browser/isBrowserEnvironment.ts +1 -0
  138. package/src/helpers/browser/isBrowserEnvironment_override.ts +3 -0
  139. package/src/helpers/kademliaId.ts +8 -0
  140. package/src/helpers/peerIdFromPeerDescriptor.ts +1 -1
  141. package/src/proto/packages/dht/protos/DhtRpc.ts +1 -6
  142. package/test/benchmark/KademliaCorrectness.test.ts +4 -2
  143. package/test/benchmark/RecursiveFind.test.ts +6 -6
  144. package/test/end-to-end/Layer0-Layer1.test.ts +9 -9
  145. package/test/end-to-end/Layer0WebRTC-Layer1.test.ts +5 -5
  146. package/test/end-to-end/Layer0WebRTC.test.ts +5 -6
  147. package/test/end-to-end/Layer1-Scale-WebRTC.test.ts +13 -8
  148. package/test/end-to-end/Layer1-Scale-WebSocket.test.ts +15 -10
  149. package/test/end-to-end/WebSocketConnectionRequest.test.ts +5 -5
  150. package/test/integration/ConnectionLocking.test.ts +32 -26
  151. package/test/integration/ConnectionManager.test.ts +90 -93
  152. package/test/integration/DhtJoinPeerDiscovery.test.ts +53 -0
  153. package/test/integration/DhtRpc.test.ts +4 -6
  154. package/test/integration/Layer1-scale.test.ts +8 -8
  155. package/test/integration/MigrateData.test.ts +9 -9
  156. package/test/integration/Mock-Layer1-Layer0.test.ts +1 -2
  157. package/test/integration/RecursiveFind.test.ts +5 -5
  158. package/test/integration/{DhtPeer.test.ts → RemoteDhtNode.test.ts} +11 -12
  159. package/test/integration/RemoteRouter.test.ts +5 -6
  160. package/test/integration/RemoteStore.test.ts +4 -5
  161. package/test/integration/RouteMessage.test.ts +7 -9
  162. package/test/integration/RpcErrors.test.ts +25 -10
  163. package/test/integration/ScaleDownDht.test.ts +8 -8
  164. package/test/integration/SimultaneousConnections.test.ts +35 -36
  165. package/test/integration/Store.test.ts +8 -9
  166. package/test/integration/StoreAndDelete.test.ts +11 -11
  167. package/test/integration/StoreOnDhtWithTwoNodes.test.ts +7 -7
  168. package/test/integration/WebRtcConnectionManagement.test.ts +26 -19
  169. package/test/integration/WebRtcConnectorRpc.test.ts +6 -8
  170. package/test/integration/WebSocket.test.ts +4 -2
  171. package/test/integration/WebSocketConnectionManagement.test.ts +30 -17
  172. package/test/integration/WebSocketConnectorRpc.test.ts +2 -3
  173. package/test/unit/DuplicateDetector.test.ts +3 -4
  174. package/test/unit/LocalDataStore.test.ts +6 -8
  175. package/test/unit/RandomContactList.test.ts +1 -1
  176. package/test/unit/RecursiveFinder.test.ts +8 -12
  177. package/test/unit/Router.test.ts +18 -21
  178. package/test/unit/WebSocketConnector.test.ts +64 -0
  179. package/test/unit/WebSocketServer.test.ts +24 -12
  180. package/test/utils/mock/RecursiveFinder.ts +2 -2
  181. package/test/utils/mock/Router.ts +9 -11
  182. package/test/utils/mock/Transport.ts +2 -2
  183. package/test/utils/utils.ts +40 -49
  184. package/dist/src/dht/DhtPeer.js.map +0 -1
  185. package/dist/src/helpers/browser/isBrowser.d.ts +0 -1
  186. package/dist/src/helpers/browser/isBrowser.js +0 -6
  187. package/dist/src/helpers/browser/isBrowser.js.map +0 -1
  188. package/dist/src/helpers/browser/isNodeJS.d.ts +0 -1
  189. package/dist/src/helpers/browser/isNodeJS.js +0 -6
  190. package/dist/src/helpers/browser/isNodeJS.js.map +0 -1
  191. package/src/helpers/browser/isBrowser.ts +0 -1
  192. package/src/helpers/browser/isNodeJS.ts +0 -1
  193. package/test/integration/DhtWithMockConnectionLatencies.test.ts +0 -46
  194. package/test/integration/DhtWithMockConnections.test.ts +0 -46
  195. package/test/integration/DhtWithRealConnectionLatencies.test.ts +0 -47
  196. /package/test/unit/{webrtcReplaceInternalIpWithExternalIp.ts → webrtcReplaceInternalIpWithExternalIp.test.ts} +0 -0
@@ -1,6 +1,19 @@
1
+ import { toProtoRpcClient } from '@streamr/proto-rpc'
2
+ import { CountMetric, LevelMetric, Logger, Metric, MetricsContext, MetricsDefinition, RateMetric, waitForEvent3 } from '@streamr/utils'
1
3
  import { EventEmitter } from 'eventemitter3'
4
+ import { Contact } from '../dht/contact/Contact'
5
+ import { SortedContactList } from '../dht/contact/SortedContactList'
6
+ import { DuplicateDetector } from '../dht/routing/DuplicateDetector'
7
+ import { PeerIDKey } from '../helpers/PeerID'
8
+ import * as Err from '../helpers/errors'
9
+ import {
10
+ areEqualPeerDescriptors,
11
+ keyFromPeerDescriptor,
12
+ peerIdFromPeerDescriptor
13
+ } from '../helpers/peerIdFromPeerDescriptor'
14
+ import { protoToString } from '../helpers/protoToString'
15
+ import { Empty } from '../proto/google/protobuf/empty'
2
16
  import {
3
- ConnectivityResponse,
4
17
  DisconnectMode,
5
18
  DisconnectNotice,
6
19
  DisconnectNoticeResponse,
@@ -8,69 +21,22 @@ import {
8
21
  LockResponse,
9
22
  Message,
10
23
  MessageType,
11
- NodeType,
12
24
  PeerDescriptor,
13
25
  UnlockRequest
14
26
  } from '../proto/packages/dht/protos/DhtRpc'
15
- import { WebSocketConnector } from './WebSocket/WebSocketConnector'
16
- import { PeerIDKey } from '../helpers/PeerID'
17
- import { protoToString } from '../helpers/protoToString'
27
+ import { ConnectionLockerClient } from '../proto/packages/dht/protos/DhtRpc.client'
18
28
  import { DisconnectionType, ITransport, TransportEvents } from '../transport/ITransport'
19
- import { IceServer, WebRtcConnector } from './WebRTC/WebRtcConnector'
20
- import { CountMetric, LevelMetric, Logger, Metric, MetricsContext, MetricsDefinition, RateMetric, waitForEvent3 } from '@streamr/utils'
21
- import * as Err from '../helpers/errors'
22
- import { WEB_RTC_CLEANUP } from './WebRTC/NodeWebRtcConnection'
23
- import { ManagedConnection, Events as ManagedConnectionEvents } from './ManagedConnection'
24
29
  import { RoutingRpcCommunicator } from '../transport/RoutingRpcCommunicator'
25
- import { toProtoRpcClient } from '@streamr/proto-rpc'
26
- import { ConnectionLockerClient } from '../proto/packages/dht/protos/DhtRpc.client'
27
- import { RemoteConnectionLocker } from './RemoteConnectionLocker'
28
- import { ServerCallContext } from '@protobuf-ts/runtime-rpc'
29
- import { Empty } from '../proto/google/protobuf/empty'
30
- import { Simulator } from './Simulator/Simulator'
31
- import { SimulatorConnector } from './Simulator/SimulatorConnector'
32
30
  import { ConnectionLockHandler } from './ConnectionLockHandler'
33
- import { DuplicateDetector } from '../dht/routing/DuplicateDetector'
34
- import { SortedContactList } from '../dht/contact/SortedContactList'
35
- import { Contact } from '../dht/contact/Contact'
36
- import {
37
- isSamePeerDescriptor,
38
- keyFromPeerDescriptor,
39
- peerIdFromPeerDescriptor
40
- } from '../helpers/peerIdFromPeerDescriptor'
41
- import { isPrivateIPv4 } from '../helpers/AddressTools'
42
-
43
- export class ConnectionManagerConfig {
44
- transportLayer?: ITransport
45
- websocketHost?: string
46
- websocketPortRange?: PortRange
47
- entryPoints?: PeerDescriptor[]
48
- maxConnections: number = 80
49
- iceServers?: IceServer[]
50
- metricsContext?: MetricsContext
51
- webrtcAllowPrivateAddresses?: boolean
52
- webrtcDatachannelBufferThresholdLow?: number
53
- webrtcDatachannelBufferThresholdHigh?: number
54
- webrtcNewConnectionTimeout?: number
55
- externalIp?: string
56
- webrtcPortRange?: PortRange
57
- tlsCertificate?: TlsCertificate
58
-
59
- // the following fields are used in simulation only
60
- simulator?: Simulator
61
- ownPeerDescriptor?: PeerDescriptor
62
- serviceIdPrefix?: string
63
-
64
- constructor(conf: Partial<ConnectionManagerConfig>) {
65
- // assign given non-undefined config vars over defaults
66
- let k: keyof typeof conf
67
- for (k in conf) {
68
- if (conf[k] === undefined) {
69
- delete conf[k]
70
- }
71
- }
72
- Object.assign(this, conf)
73
- }
31
+ import { ConnectorFacade } from './ConnectorFacade'
32
+ import { ManagedConnection, Events as ManagedConnectionEvents } from './ManagedConnection'
33
+ import { RemoteConnectionLocker } from './RemoteConnectionLocker'
34
+ import { WEB_RTC_CLEANUP } from './WebRTC/NodeWebRtcConnection'
35
+
36
+ export interface ConnectionManagerConfig {
37
+ maxConnections?: number
38
+ metricsContext: MetricsContext
39
+ createConnectorFacade: () => ConnectorFacade
74
40
  }
75
41
 
76
42
  export enum NatType {
@@ -87,10 +53,9 @@ interface ConnectionManagerMetrics extends MetricsDefinition {
87
53
  connectionTotalFailureCount: Metric
88
54
  }
89
55
 
56
+ // TODO move this type identifiers.ts and use also in other classes (and rename to ServiceID)
90
57
  type ServiceId = string
91
58
 
92
- export type PeerDescriptorGeneratorCallback = (connectivityResponse: ConnectivityResponse) => PeerDescriptor
93
-
94
59
  const logger = new Logger(module)
95
60
 
96
61
  enum ConnectionManagerState {
@@ -123,28 +88,44 @@ export interface TlsCertificate {
123
88
 
124
89
  export type Events = TransportEvents & ConnectionManagerEvents
125
90
 
91
+ const INTERNAL_SERVICE_ID = 'system/connection-manager'
92
+
93
+ // Form an string representation from a peer description which can be undefined. This output
94
+ // should only be used only for log output. TODO remove this method if we no longer use
95
+ // peerDescriptors which can be undefined, e.g.
96
+ // - if we refactor ConnectionManager so that it doesn't process handshake requests too early
97
+ // and therefore this.ownPeerDescriptor can't be undefine (NET-1129)
98
+ // - if the peerDescriptor of ManagedConnection is always available
99
+ // - if we create stricter types for incoming messages (message.sourceDescriptor or
100
+ // disconnectNotice.peerDescriptor)
101
+ // - if ManagedConnection#peerDescriptor is never undefined
102
+ export const keyOrUnknownFromPeerDescriptor = (peerDescriptor: PeerDescriptor | undefined): string => {
103
+ if (peerDescriptor !== undefined) {
104
+ return keyFromPeerDescriptor(peerDescriptor)
105
+ } else {
106
+ return 'unknown'
107
+ }
108
+ }
109
+
126
110
  export class ConnectionManager extends EventEmitter<Events> implements ITransport, ConnectionLocker {
111
+
127
112
  public static PROTOCOL_VERSION = '1.0'
128
113
  private config: ConnectionManagerConfig
129
114
  private readonly metricsContext: MetricsContext
130
- private ownPeerDescriptor?: PeerDescriptor
131
- private readonly messageDuplicateDetector: DuplicateDetector = new DuplicateDetector(100000, 100)
115
+ private readonly duplicateMessageDetector: DuplicateDetector = new DuplicateDetector(100000, 100)
132
116
  private readonly metrics: ConnectionManagerMetrics
133
117
  private locks = new ConnectionLockHandler()
134
118
  private connections: Map<PeerIDKey, ManagedConnection> = new Map()
135
- private webSocketConnector?: WebSocketConnector
136
- private webrtcConnector?: WebRtcConnector
137
- private simulatorConnector?: SimulatorConnector
119
+ private readonly connectorFacade: ConnectorFacade
138
120
  private rpcCommunicator?: RoutingRpcCommunicator
139
121
  private disconnectorIntervalRef?: NodeJS.Timeout
140
- private serviceId: ServiceId
141
122
  private state = ConnectionManagerState.IDLE
142
123
 
143
- constructor(conf: Partial<ConnectionManagerConfig>) {
124
+ constructor(config: ConnectionManagerConfig) {
144
125
  super()
145
- this.config = new ConnectionManagerConfig(conf)
126
+ this.config = config
146
127
  this.onData = this.onData.bind(this)
147
- this.incomingConnectionCallback = this.incomingConnectionCallback.bind(this)
128
+ this.onIncomingConnection = this.onIncomingConnection.bind(this)
148
129
  this.metricsContext = this.config.metricsContext || new MetricsContext()
149
130
  this.metrics = {
150
131
  sendMessagesPerSecond: new RateMetric(),
@@ -155,97 +136,55 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
155
136
  connectionTotalFailureCount: new CountMetric()
156
137
  }
157
138
  this.metricsContext.addMetrics('node', this.metrics)
158
- if (this.config.simulator) {
159
- logger.trace(`Creating SimulatorConnector`)
160
- this.simulatorConnector = new SimulatorConnector(
161
- ConnectionManager.PROTOCOL_VERSION,
162
- this.config.ownPeerDescriptor!,
163
- this.config.simulator,
164
- this.incomingConnectionCallback
165
- )
166
- this.config.simulator.addConnector(this.simulatorConnector)
167
- this.ownPeerDescriptor = this.config.ownPeerDescriptor
168
- this.state = ConnectionManagerState.RUNNING
169
- } else {
170
- logger.trace(`Creating WebSocketConnector`)
171
- this.webSocketConnector = new WebSocketConnector(
172
- ConnectionManager.PROTOCOL_VERSION,
173
- this.config.transportLayer!,
174
- this.canConnect.bind(this),
175
- this.incomingConnectionCallback,
176
- this.config.websocketPortRange,
177
- this.config.websocketHost,
178
- this.config.entryPoints,
179
- this.config.tlsCertificate
180
- )
181
- logger.trace(`Creating WebRTCConnector`)
182
- this.webrtcConnector = new WebRtcConnector({
183
- rpcTransport: this.config.transportLayer!,
184
- protocolVersion: ConnectionManager.PROTOCOL_VERSION,
185
- iceServers: this.config.iceServers,
186
- allowPrivateAddresses: this.config.webrtcAllowPrivateAddresses,
187
- bufferThresholdLow: this.config.webrtcDatachannelBufferThresholdLow,
188
- bufferThresholdHigh: this.config.webrtcDatachannelBufferThresholdHigh,
189
- connectionTimeout: this.config.webrtcNewConnectionTimeout,
190
- externalIp: this.config.externalIp,
191
- portRange: this.config.webrtcPortRange
192
- }, this.incomingConnectionCallback)
193
- }
194
- this.serviceId = (this.config.serviceIdPrefix ? this.config.serviceIdPrefix : '') + 'ConnectionManager'
139
+ this.connectorFacade = this.config.createConnectorFacade()
195
140
  this.send = this.send.bind(this)
196
- this.rpcCommunicator = new RoutingRpcCommunicator(this.serviceId, this.send, {
141
+ this.rpcCommunicator = new RoutingRpcCommunicator(INTERNAL_SERVICE_ID, this.send, {
197
142
  rpcRequestTimeout: 10000
198
143
  })
199
144
  this.rpcCommunicator.registerRpcMethod(LockRequest, LockResponse, 'lockRequest',
200
- (req: LockRequest, context) => this.lockRequest(req, context))
145
+ (req: LockRequest) => this.lockRequest(req))
201
146
  this.rpcCommunicator.registerRpcNotification(UnlockRequest, 'unlockRequest',
202
- (req: UnlockRequest, context) => this.unlockRequest(req, context))
147
+ (req: UnlockRequest) => this.unlockRequest(req))
203
148
  this.rpcCommunicator.registerRpcMethod(DisconnectNotice, DisconnectNoticeResponse, 'gracefulDisconnect',
204
- (req: DisconnectNotice, context) => this.gracefulDisconnect(req, context))
149
+ (req: DisconnectNotice) => this.gracefulDisconnect(req))
205
150
  }
206
151
 
207
152
  public garbageCollectConnections(maxConnections: number, lastUsedLimit: number): void {
208
153
  if (this.connections.size <= maxConnections) {
209
154
  return
210
155
  }
211
- const disconnectionCandidates = new SortedContactList<Contact>(peerIdFromPeerDescriptor(this.ownPeerDescriptor!), 100000)
156
+ const disconnectionCandidates = new SortedContactList<Contact>(peerIdFromPeerDescriptor(this.getOwnPeerDescriptor()), 100000)
212
157
  this.connections.forEach((connection) => {
213
158
  if (!this.locks.isLocked(connection.peerIdKey) && Date.now() - connection.getLastUsed() > lastUsedLimit) {
214
- logger.trace('disconnecting in timeout interval: ' + this.ownPeerDescriptor?.nodeName + ', '
215
- + connection.getPeerDescriptor()?.nodeName + ' ')
159
+ logger.trace('disconnecting in timeout interval: ' + keyOrUnknownFromPeerDescriptor(connection.getPeerDescriptor()))
216
160
  disconnectionCandidates.addContact(new Contact(connection.getPeerDescriptor()!))
217
161
  }
218
162
  })
219
163
  const sortedCandidates = disconnectionCandidates.getAllContacts()
220
164
  const targetNum = this.connections.size - maxConnections
221
165
  for (let i = 0; i < sortedCandidates.length && i < targetNum; i++) {
222
- logger.trace(this.ownPeerDescriptor?.nodeName + ' garbageCollecting '
223
- + sortedCandidates[sortedCandidates.length - 1 - i].getPeerDescriptor().nodeName)
166
+ logger.trace('garbageCollecting ' + keyFromPeerDescriptor(sortedCandidates[sortedCandidates.length - 1 - i].getPeerDescriptor()))
224
167
  this.gracefullyDisconnectAsync(sortedCandidates[sortedCandidates.length - 1 - i].getPeerDescriptor(),
225
168
  DisconnectMode.NORMAL).catch((_e) => { })
226
169
  }
227
170
  }
228
171
 
229
- public async start(peerDescriptorGeneratorCallback?: PeerDescriptorGeneratorCallback): Promise<void> {
172
+ public async start(): Promise<void> {
230
173
  if (this.state === ConnectionManagerState.RUNNING || this.state === ConnectionManagerState.STOPPED) {
231
174
  throw new Err.CouldNotStart(`Cannot start already ${this.state} module`)
232
175
  }
233
176
  this.state = ConnectionManagerState.RUNNING
234
177
  logger.trace(`Starting ConnectionManager...`)
178
+ await this.connectorFacade.start(
179
+ (connection: ManagedConnection) => this.onIncomingConnection(connection),
180
+ (peerDescriptor: PeerDescriptor) => this.canConnect(peerDescriptor)
181
+ )
235
182
  // Garbage collection of connections
236
183
  this.disconnectorIntervalRef = setInterval(() => {
237
184
  logger.trace('disconnectorInterval')
238
185
  const LAST_USED_LIMIT = 20000
239
- this.garbageCollectConnections(this.config.maxConnections, LAST_USED_LIMIT)
186
+ this.garbageCollectConnections(this.config.maxConnections ?? 80, LAST_USED_LIMIT)
240
187
  }, 5000)
241
- if (!this.config.simulator) {
242
- await this.webSocketConnector!.start()
243
- const connectivityResponse = await this.webSocketConnector!.checkConnectivity()
244
- const ownPeerDescriptor = peerDescriptorGeneratorCallback!(connectivityResponse)
245
- this.ownPeerDescriptor = ownPeerDescriptor
246
- this.webSocketConnector!.setOwnPeerDescriptor(ownPeerDescriptor)
247
- this.webrtcConnector!.setOwnPeerDescriptor(ownPeerDescriptor)
248
- }
249
188
  }
250
189
 
251
190
  public async stop(): Promise<void> {
@@ -257,15 +196,7 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
257
196
  if (this.disconnectorIntervalRef) {
258
197
  clearInterval(this.disconnectorIntervalRef)
259
198
  }
260
- if (!this.config.simulator) {
261
- await this.webSocketConnector!.destroy()
262
- this.webSocketConnector = undefined
263
- await this.webrtcConnector!.stop()
264
- this.webrtcConnector = undefined
265
- } else {
266
- await this.simulatorConnector!.stop()
267
- this.simulatorConnector = undefined
268
- }
199
+ await this.connectorFacade.stop()
269
200
 
270
201
  await Promise.all(Array.from(this.connections.values()).map(async (peer) => {
271
202
  if (peer.isHandshakeCompleted()) {
@@ -289,18 +220,13 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
289
220
 
290
221
  this.state = ConnectionManagerState.STOPPED
291
222
  this.rpcCommunicator!.stop()
292
- this.config.transportLayer = undefined
293
- this.messageDuplicateDetector.clear()
223
+ this.duplicateMessageDetector.clear()
294
224
  this.locks.clear()
295
225
  this.removeAllListeners()
296
- if (!this.config.simulator) {
297
-
298
- WEB_RTC_CLEANUP.cleanUp()
299
- }
300
- }
301
-
302
- public getConnectionTo(id: PeerIDKey): ManagedConnection {
303
- return this.connections.get(id)!
226
+ // TODO would it make sense to move this call to WebRtcConnector#stop()?
227
+ // - but note that we should call this only after connections have been closed
228
+ // (i.e the this.gracefullyDisconnectAsync() calls above)
229
+ WEB_RTC_CLEANUP.cleanUp()
304
230
  }
305
231
 
306
232
  public getNumberOfLocalLockedConnections(): number {
@@ -324,17 +250,17 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
324
250
  if (this.isConnectionToSelf(peerDescriptor)) {
325
251
  throw new Err.CannotConnectToSelf('Cannot send to self')
326
252
  }
327
- logger.trace(`Sending message to: ${peerDescriptor.kademliaId.toString()}`)
253
+ logger.trace(`Sending message to: ${keyFromPeerDescriptor(peerDescriptor)}`)
328
254
  message = {
329
255
  ...message,
330
256
  targetDescriptor: message.targetDescriptor || peerDescriptor,
331
- sourceDescriptor: message.sourceDescriptor || this.ownPeerDescriptor,
257
+ sourceDescriptor: message.sourceDescriptor || this.getOwnPeerDescriptor(),
332
258
  }
333
- const hexId = keyFromPeerDescriptor(peerDescriptor)
334
- let connection = this.connections.get(hexId)
259
+ const peerIdKey = keyFromPeerDescriptor(peerDescriptor)
260
+ let connection = this.connections.get(peerIdKey)
335
261
  if (!connection && !doNotConnect) {
336
- connection = this.createConnection(peerDescriptor)
337
- this.incomingConnectionCallback(connection)
262
+ connection = this.connectorFacade.createConnection(peerDescriptor)
263
+ this.onIncomingConnection(connection)
338
264
  } else if (!connection) {
339
265
  throw new Err.SendFailed('No connection to target, doNotConnect flag is true')
340
266
  }
@@ -345,66 +271,49 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
345
271
  }
346
272
 
347
273
  private isConnectionToSelf(peerDescriptor: PeerDescriptor): boolean {
348
- return isSamePeerDescriptor(peerDescriptor, this.ownPeerDescriptor!) || this.isOwnWebSocketServer(peerDescriptor)
274
+ return areEqualPeerDescriptors(peerDescriptor, this.getOwnPeerDescriptor()) || this.isOwnWebSocketServer(peerDescriptor)
349
275
  }
350
276
 
351
277
  private isOwnWebSocketServer(peerDescriptor: PeerDescriptor): boolean {
352
- if ((peerDescriptor.websocket !== undefined) && (this.ownPeerDescriptor!.websocket !== undefined)) {
353
- return ((peerDescriptor.websocket.port === this.ownPeerDescriptor!.websocket.port)
354
- && (peerDescriptor.websocket.host === this.ownPeerDescriptor!.websocket.host))
278
+ const ownPeerDescriptor = this.getOwnPeerDescriptor()
279
+ if ((peerDescriptor.websocket !== undefined) && (ownPeerDescriptor.websocket !== undefined)) {
280
+ return ((peerDescriptor.websocket.port === ownPeerDescriptor.websocket.port)
281
+ && (peerDescriptor.websocket.host === ownPeerDescriptor.websocket.host))
355
282
  } else {
356
283
  return false
357
284
  }
358
285
  }
359
286
 
360
- private createConnection(peerDescriptor: PeerDescriptor): ManagedConnection {
361
- if (this.simulatorConnector) {
362
- return this.simulatorConnector.connect(peerDescriptor)
363
- } else if ((peerDescriptor.websocket || this.ownPeerDescriptor!.websocket)) {
364
- if (this.canOpenWsConnection(peerDescriptor)) {
365
- return this.webSocketConnector!.connect(peerDescriptor)
366
- }
367
- }
368
- return this.webrtcConnector!.connect(peerDescriptor)
369
- }
370
-
371
- private canOpenWsConnection(peerDescriptor: PeerDescriptor): boolean {
372
- if (!(this.ownPeerDescriptor!.type === NodeType.BROWSER || peerDescriptor.type === NodeType.BROWSER)) {
373
- return true
374
- }
375
- if (this.ownPeerDescriptor!.websocket) {
376
- return (peerDescriptor.type === NodeType.BROWSER && this.ownPeerDescriptor!.websocket!.tls)
377
- || (this.ownPeerDescriptor!.websocket!.host === 'localhost' || (isPrivateIPv4(this.ownPeerDescriptor!.websocket!.host)))
378
- }
379
- return (this.ownPeerDescriptor!.type === NodeType.BROWSER && peerDescriptor.websocket!.tls)
380
- || (peerDescriptor.websocket!.host === 'localhost' || (isPrivateIPv4(peerDescriptor.websocket!.host)))
381
- }
382
-
383
287
  public getConnection(peerDescriptor: PeerDescriptor): ManagedConnection | undefined {
384
- const hexId = keyFromPeerDescriptor(peerDescriptor)
385
- return this.connections.get(hexId)
288
+ const peerIdKey = keyFromPeerDescriptor(peerDescriptor)
289
+ return this.connections.get(peerIdKey)
386
290
  }
387
291
 
292
+ // TODO remove this method or getOwnPeerDescriptor
388
293
  public getPeerDescriptor(): PeerDescriptor {
389
- return this.ownPeerDescriptor!
294
+ return this.getOwnPeerDescriptor()
295
+ }
296
+
297
+ private getOwnPeerDescriptor(): PeerDescriptor {
298
+ return this.connectorFacade.getOwnPeerDescriptor()!
390
299
  }
391
300
 
392
301
  public hasConnection(peerDescriptor: PeerDescriptor): boolean {
393
- const hexId = keyFromPeerDescriptor(peerDescriptor)
394
- return this.connections.has(hexId)
302
+ const peerIdKey = keyFromPeerDescriptor(peerDescriptor)
303
+ return this.connections.has(peerIdKey)
395
304
  }
396
305
 
397
- public hasLocalLockedConnection(peerDescriptor: PeerDescriptor, _serviceId?: ServiceId): boolean {
398
- const hexId = keyFromPeerDescriptor(peerDescriptor)
399
- return this.locks.isLocalLocked(hexId)
306
+ public hasLocalLockedConnection(peerDescriptor: PeerDescriptor): boolean {
307
+ const peerIdKey = keyFromPeerDescriptor(peerDescriptor)
308
+ return this.locks.isLocalLocked(peerIdKey)
400
309
  }
401
310
 
402
- public hasRemoteLockedConnection(peerDescriptor: PeerDescriptor, _serviceId?: ServiceId): boolean {
403
- const hexId = keyFromPeerDescriptor(peerDescriptor)
404
- return this.locks.isRemoteLocked(hexId)
311
+ public hasRemoteLockedConnection(peerDescriptor: PeerDescriptor): boolean {
312
+ const peerIdKey = keyFromPeerDescriptor(peerDescriptor)
313
+ return this.locks.isRemoteLocked(peerIdKey)
405
314
  }
406
315
 
407
- public canConnect(peerDescriptor: PeerDescriptor, _ip: string, _port: number): boolean {
316
+ private canConnect(peerDescriptor: PeerDescriptor): boolean {
408
317
  // Perhaps the connection's state should be checked here
409
318
  return !this.hasConnection(peerDescriptor) // TODO: Add port range check
410
319
  }
@@ -415,17 +324,16 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
415
324
  logger.trace('Filtered out non-RPC message of type ' + message.messageType)
416
325
  return
417
326
  }
418
- if (this.messageDuplicateDetector.isMostLikelyDuplicate(message.messageId)) {
419
- logger.trace('handleMessage filtered duplicate ' + this.ownPeerDescriptor?.nodeName + ', '
420
- + message.sourceDescriptor?.nodeName + ' ' + message.serviceId + ' ' + message.messageId)
327
+ if (this.duplicateMessageDetector.isMostLikelyDuplicate(message.messageId)) {
328
+ logger.trace('handleMessage filtered duplicate ' + keyFromPeerDescriptor(message.sourceDescriptor!)
329
+ + ' ' + message.serviceId + ' ' + message.messageId)
421
330
  return
422
331
  }
423
- this.messageDuplicateDetector.add(message.messageId, message.sourceDescriptor!.nodeName!, message)
424
- if (message.serviceId === this.serviceId) {
332
+ this.duplicateMessageDetector.add(message.messageId)
333
+ if (message.serviceId === INTERNAL_SERVICE_ID) {
425
334
  this.rpcCommunicator?.handleMessageFromPeer(message)
426
335
  } else {
427
- logger.trace('emit "message" ' + this.ownPeerDescriptor?.nodeName + ', ' + message.sourceDescriptor?.nodeName
428
- + ' ' + message.serviceId + ' ' + message.messageId)
336
+ logger.trace('emit "message" ' + keyFromPeerDescriptor(message.sourceDescriptor!) + ' ' + message.serviceId + ' ' + message.messageId)
429
337
  this.emit('message', message)
430
338
  }
431
339
  }
@@ -439,7 +347,7 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
439
347
  let message: Message | undefined
440
348
  try {
441
349
  message = Message.fromBinary(data)
442
- logger.trace(`${this.ownPeerDescriptor?.nodeName} received protojson: ${protoToString(message, Message)}`)
350
+ logger.trace(`received protojson: ${protoToString(message, Message)}`)
443
351
  } catch (e) {
444
352
  logger.debug(`Parsing incoming data into Message failed: ${e}`)
445
353
  return
@@ -455,52 +363,51 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
455
363
  private onConnected = (connection: ManagedConnection) => {
456
364
  const peerDescriptor = connection.getPeerDescriptor()!
457
365
  this.emit('connected', peerDescriptor)
458
- logger.trace(' ' + this.ownPeerDescriptor?.nodeName + ', ' + peerDescriptor.nodeName + ' onConnected() ' + connection.connectionType)
366
+ logger.trace(keyFromPeerDescriptor(peerDescriptor) + ' onConnected() ' + connection.connectionType)
459
367
  this.onConnectionCountChange()
460
368
  }
461
369
 
462
370
  private onDisconnected = (connection: ManagedConnection, disconnectionType: DisconnectionType) => {
463
- logger.trace(' ' + this.ownPeerDescriptor?.nodeName + ', ' + connection.getPeerDescriptor()?.nodeName +
464
- ' onDisconnected() ' + disconnectionType)
371
+ logger.trace(keyOrUnknownFromPeerDescriptor(connection.getPeerDescriptor()) + ' onDisconnected() ' + disconnectionType)
465
372
 
466
- const hexKey = keyFromPeerDescriptor(connection.getPeerDescriptor()!)
467
- const storedConnection = this.connections.get(hexKey)
373
+ const peerIdKey = keyFromPeerDescriptor(connection.getPeerDescriptor()!)
374
+ const storedConnection = this.connections.get(peerIdKey)
468
375
  if (storedConnection && storedConnection.connectionId.equals(connection.connectionId)) {
469
- this.locks.clearAllLocks(hexKey)
470
- this.connections.delete(hexKey)
471
- logger.trace(' ' + this.ownPeerDescriptor?.nodeName + ', ' + connection.getPeerDescriptor()?.nodeName +
472
- ' deleted connection in onDisconnected() ' + disconnectionType)
376
+ this.locks.clearAllLocks(peerIdKey)
377
+ this.connections.delete(peerIdKey)
378
+ logger.trace(keyOrUnknownFromPeerDescriptor(connection.getPeerDescriptor())
379
+ + ' deleted connection in onDisconnected() ' + disconnectionType)
473
380
  this.emit('disconnected', connection.getPeerDescriptor()!, disconnectionType)
474
381
  this.onConnectionCountChange()
475
382
  } else {
476
- logger.trace(' ' + this.ownPeerDescriptor?.nodeName + ', ' + connection.getPeerDescriptor()?.nodeName +
477
- ' onDisconnected() did nothing, no such connection in connectionManager')
383
+ logger.trace(keyOrUnknownFromPeerDescriptor(connection.getPeerDescriptor())
384
+ + ' onDisconnected() did nothing, no such connection in connectionManager')
478
385
  if (storedConnection) {
479
- logger.trace(this.ownPeerDescriptor?.nodeName + ', ' + connection.getPeerDescriptor()?.nodeName +
480
- ' connectionIds do not match ' + storedConnection.connectionId + ' ' + connection.connectionId)
386
+ logger.trace(keyOrUnknownFromPeerDescriptor(connection.getPeerDescriptor())
387
+ + ' connectionIds do not match ' + storedConnection.connectionId + ' ' + connection.connectionId)
481
388
  }
482
389
  }
483
390
 
484
391
  }
485
392
 
486
- private incomingConnectionCallback(connection: ManagedConnection): boolean {
393
+ private onIncomingConnection(connection: ManagedConnection): boolean {
487
394
  if (this.state === ConnectionManagerState.STOPPED) {
488
395
  return false
489
396
  }
490
- logger.trace('incomingConnectionCallback() objectId ' + connection.objectId)
397
+ logger.trace('onIncomingConnection()')
491
398
  connection.offeredAsIncoming = true
492
399
  if (!this.acceptIncomingConnection(connection)) {
493
400
  return false
494
401
  }
495
402
  connection.on('managedData', this.onData)
496
- connection.on('disconnected', (disconnectionType: DisconnectionType, _code?: number, _reason?: string) => {
403
+ connection.on('disconnected', (disconnectionType: DisconnectionType) => {
497
404
  this.onDisconnected(connection, disconnectionType)
498
405
  })
499
406
  this.emit('newConnection', connection)
500
407
  if (connection.isHandshakeCompleted()) {
501
408
  this.onConnected(connection)
502
409
  } else {
503
- connection.once('handshakeCompleted', (_peerDescriptor: PeerDescriptor) => {
410
+ connection.once('handshakeCompleted', ()=> {
504
411
  this.onConnected(connection)
505
412
  })
506
413
  }
@@ -508,16 +415,16 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
508
415
  }
509
416
 
510
417
  private acceptIncomingConnection(newConnection: ManagedConnection): boolean {
511
- logger.trace(' ' + this.ownPeerDescriptor?.nodeName + ', ' + newConnection.getPeerDescriptor()?.nodeName + ' acceptIncomingConnection()')
418
+ logger.trace(keyFromPeerDescriptor(newConnection.getPeerDescriptor()!) + ' acceptIncomingConnection()')
512
419
  const newPeerID = peerIdFromPeerDescriptor(newConnection.getPeerDescriptor()!)
513
- const hexKey = keyFromPeerDescriptor(newConnection.getPeerDescriptor()!)
514
- if (this.connections.has(hexKey)) {
515
- if (newPeerID.hasSmallerHashThan(peerIdFromPeerDescriptor(this.ownPeerDescriptor!))) {
516
- logger.trace(' ' + this.ownPeerDescriptor?.nodeName + ', ' + newConnection.getPeerDescriptor()?.nodeName +
517
- ' acceptIncomingConnection() replace current connection')
420
+ const peerIdKey = keyFromPeerDescriptor(newConnection.getPeerDescriptor()!)
421
+ if (this.connections.has(peerIdKey)) {
422
+ if (newPeerID.hasSmallerHashThan(peerIdFromPeerDescriptor(this.getOwnPeerDescriptor()))) {
423
+ logger.trace(keyOrUnknownFromPeerDescriptor(newConnection.getPeerDescriptor())
424
+ + ' acceptIncomingConnection() replace current connection')
518
425
  // replace the current connection
519
426
  const oldConnection = this.connections.get(newPeerID.toKey())!
520
- logger.trace('replaced: ' + this.ownPeerDescriptor?.nodeName + ', ' + newConnection.getPeerDescriptor()?.nodeName + ' ')
427
+ logger.trace('replaced: ' + keyFromPeerDescriptor(newConnection.getPeerDescriptor()!))
521
428
  const buffer = oldConnection.stealOutputBuffer()
522
429
 
523
430
  for (const data of buffer) {
@@ -532,15 +439,14 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
532
439
  }
533
440
  }
534
441
 
535
- logger.trace(' ' + this.ownPeerDescriptor?.nodeName + ', ' + newConnection.getPeerDescriptor()?.nodeName +
536
- ' added to connections at acceptIncomingConnection')
537
- this.connections.set(hexKey, newConnection)
442
+ logger.trace(keyFromPeerDescriptor(newConnection.getPeerDescriptor()!) + ' added to connections at acceptIncomingConnection')
443
+ this.connections.set(peerIdKey, newConnection)
538
444
 
539
445
  return true
540
446
  }
541
447
 
542
448
  private async closeConnection(peerDescriptor: PeerDescriptor, disconnectionType: DisconnectionType, reason?: string): Promise<void> {
543
- logger.trace(' ' + this.ownPeerDescriptor?.nodeName + ', ' + peerDescriptor.nodeName + ' ' + 'closeConnection() ' + reason)
449
+ logger.trace(keyFromPeerDescriptor(peerDescriptor) + ' ' + 'closeConnection() ' + reason)
544
450
  const id = keyFromPeerDescriptor(peerDescriptor)
545
451
  this.locks.clearAllLocks(id)
546
452
  if (this.connections.has(id)) {
@@ -548,60 +454,59 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
548
454
  await connectionToClose.close(disconnectionType)
549
455
 
550
456
  } else {
551
- logger.trace(' ' + this.ownPeerDescriptor?.nodeName + ', ' + peerDescriptor.nodeName + ' ' +
552
- 'closeConnection() this.connections did not have the id')
457
+ logger.trace(keyFromPeerDescriptor(peerDescriptor) + ' ' + 'closeConnection() this.connections did not have the id')
553
458
  this.emit('disconnected', peerDescriptor, 'OTHER')
554
459
  }
555
460
  }
556
461
 
557
462
  public lockConnection(targetDescriptor: PeerDescriptor, serviceId: ServiceId): void {
558
- if (this.state === ConnectionManagerState.STOPPED || isSamePeerDescriptor(targetDescriptor, this.ownPeerDescriptor!)) {
463
+ if (this.state === ConnectionManagerState.STOPPED || areEqualPeerDescriptors(targetDescriptor, this.getOwnPeerDescriptor())) {
559
464
  return
560
465
  }
561
- const hexKey = keyFromPeerDescriptor(targetDescriptor)
466
+ const peerIdKey = keyFromPeerDescriptor(targetDescriptor)
562
467
  const remoteConnectionLocker = new RemoteConnectionLocker(
563
- this.ownPeerDescriptor!,
468
+ this.getOwnPeerDescriptor(),
564
469
  targetDescriptor,
565
470
  ConnectionManager.PROTOCOL_VERSION,
566
471
  toProtoRpcClient(new ConnectionLockerClient(this.rpcCommunicator!.getRpcClientTransport()))
567
472
  )
568
- this.locks.addLocalLocked(hexKey, serviceId)
473
+ this.locks.addLocalLocked(peerIdKey, serviceId)
569
474
  remoteConnectionLocker.lockRequest(serviceId)
570
475
  .then((_accepted) => logger.trace('LockRequest successful'))
571
476
  .catch((err) => { logger.debug(err) })
572
477
  }
573
478
 
574
479
  public unlockConnection(targetDescriptor: PeerDescriptor, serviceId: ServiceId): void {
575
- if (this.state === ConnectionManagerState.STOPPED || isSamePeerDescriptor(targetDescriptor, this.ownPeerDescriptor!)) {
480
+ if (this.state === ConnectionManagerState.STOPPED || areEqualPeerDescriptors(targetDescriptor, this.getOwnPeerDescriptor())) {
576
481
  return
577
482
  }
578
- const hexKey = keyFromPeerDescriptor(targetDescriptor)
579
- this.locks.removeLocalLocked(hexKey, serviceId)
483
+ const peerIdKey = keyFromPeerDescriptor(targetDescriptor)
484
+ this.locks.removeLocalLocked(peerIdKey, serviceId)
580
485
  const remoteConnectionLocker = new RemoteConnectionLocker(
581
- this.ownPeerDescriptor!,
486
+ this.getOwnPeerDescriptor(),
582
487
  targetDescriptor,
583
488
  ConnectionManager.PROTOCOL_VERSION,
584
489
  toProtoRpcClient(new ConnectionLockerClient(this.rpcCommunicator!.getRpcClientTransport()))
585
490
  )
586
- if (this.connections.has(hexKey)) {
491
+ if (this.connections.has(peerIdKey)) {
587
492
  remoteConnectionLocker.unlockRequest(serviceId)
588
493
  }
589
494
  }
590
495
 
591
496
  public weakLockConnection(targetDescriptor: PeerDescriptor): void {
592
- if (this.state === ConnectionManagerState.STOPPED || isSamePeerDescriptor(targetDescriptor, this.ownPeerDescriptor!)) {
497
+ if (this.state === ConnectionManagerState.STOPPED || areEqualPeerDescriptors(targetDescriptor, this.getOwnPeerDescriptor())) {
593
498
  return
594
499
  }
595
- const hexKey = keyFromPeerDescriptor(targetDescriptor)
596
- this.locks.addWeakLocked(hexKey)
500
+ const peerIdKey = keyFromPeerDescriptor(targetDescriptor)
501
+ this.locks.addWeakLocked(peerIdKey)
597
502
  }
598
503
 
599
504
  public weakUnlockConnection(targetDescriptor: PeerDescriptor): void {
600
- if (this.state === ConnectionManagerState.STOPPED || isSamePeerDescriptor(targetDescriptor, this.ownPeerDescriptor!)) {
505
+ if (this.state === ConnectionManagerState.STOPPED || areEqualPeerDescriptors(targetDescriptor, this.getOwnPeerDescriptor())) {
601
506
  return
602
507
  }
603
- const hexKey = keyFromPeerDescriptor(targetDescriptor)
604
- this.locks.removeWeakLocked(hexKey)
508
+ const peerIdKey = keyFromPeerDescriptor(targetDescriptor)
509
+ this.locks.removeWeakLocked(peerIdKey)
605
510
 
606
511
  }
607
512
 
@@ -640,9 +545,9 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
640
545
  }
641
546
 
642
547
  private async doGracefullyDisconnectAsync(targetDescriptor: PeerDescriptor, disconnectMode: DisconnectMode): Promise<void> {
643
- logger.trace(' ' + this.ownPeerDescriptor?.nodeName + ', ' + targetDescriptor.nodeName + ' gracefullyDisconnectAsync()')
548
+ logger.trace(keyFromPeerDescriptor(targetDescriptor) + ' gracefullyDisconnectAsync()')
644
549
  const remoteConnectionLocker = new RemoteConnectionLocker(
645
- this.ownPeerDescriptor!,
550
+ this.getOwnPeerDescriptor(),
646
551
  targetDescriptor,
647
552
  ConnectionManager.PROTOCOL_VERSION,
648
553
  toProtoRpcClient(new ConnectionLockerClient(this.rpcCommunicator!.getRpcClientTransport()))
@@ -650,8 +555,7 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
650
555
  try {
651
556
  await remoteConnectionLocker.gracefulDisconnect(disconnectMode)
652
557
  } catch (ex) {
653
- logger.trace(' ' + this.ownPeerDescriptor?.nodeName + ', ' + targetDescriptor.nodeName +
654
- ' remoteConnectionLocker.gracefulDisconnect() failed' + ex)
558
+ logger.trace(keyFromPeerDescriptor(targetDescriptor) + ' remoteConnectionLocker.gracefulDisconnect() failed' + ex)
655
559
  }
656
560
  }
657
561
 
@@ -662,9 +566,9 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
662
566
  }
663
567
 
664
568
  // IConnectionLocker server implementation
665
- private async lockRequest(lockRequest: LockRequest, _context: ServerCallContext): Promise<LockResponse> {
569
+ private async lockRequest(lockRequest: LockRequest): Promise<LockResponse> {
666
570
  const remotePeerId = peerIdFromPeerDescriptor(lockRequest.peerDescriptor!)
667
- if (isSamePeerDescriptor(lockRequest.peerDescriptor!, this.ownPeerDescriptor!)) {
571
+ if (areEqualPeerDescriptors(lockRequest.peerDescriptor!, this.getOwnPeerDescriptor())) {
668
572
  const response: LockResponse = {
669
573
  accepted: false
670
574
  }
@@ -678,16 +582,15 @@ export class ConnectionManager extends EventEmitter<Events> implements ITranspor
678
582
  }
679
583
 
680
584
  // IConnectionLocker server implementation
681
- private async unlockRequest(unlockRequest: UnlockRequest, _context: ServerCallContext): Promise<Empty> {
682
- const hexKey = keyFromPeerDescriptor(unlockRequest.peerDescriptor!)
683
- this.locks.removeRemoteLocked(hexKey, unlockRequest.serviceId)
585
+ private async unlockRequest(unlockRequest: UnlockRequest): Promise<Empty> {
586
+ const peerIdKey = keyFromPeerDescriptor(unlockRequest.peerDescriptor!)
587
+ this.locks.removeRemoteLocked(peerIdKey, unlockRequest.serviceId)
684
588
  return {}
685
589
  }
686
590
 
687
591
  // IConnectionLocker server implementation
688
- private async gracefulDisconnect(disconnectNotice: DisconnectNotice, _context: ServerCallContext): Promise<Empty> {
689
- logger.trace(' ' + this.ownPeerDescriptor?.nodeName + ', ' + disconnectNotice.peerDescriptor?.nodeName
690
- + ' received gracefulDisconnect notice')
592
+ private async gracefulDisconnect(disconnectNotice: DisconnectNotice): Promise<Empty> {
593
+ logger.trace(keyOrUnknownFromPeerDescriptor(disconnectNotice.peerDescriptor) + ' received gracefulDisconnect notice')
691
594
 
692
595
  if (disconnectNotice.disconnecMode === DisconnectMode.LEAVING) {
693
596
  this.closeConnection(disconnectNotice.peerDescriptor!, 'INCOMING_GRACEFUL_LEAVE', 'graceful leave notified')