@streamr/dht 100.0.0-pretestnet.4 → 100.0.0-testnet-one.0

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 (233) hide show
  1. package/dist/src/connection/ConnectionLockHandler.js +2 -2
  2. package/dist/src/connection/ConnectionLockHandler.js.map +1 -1
  3. package/dist/src/connection/ConnectionLockRpcRemote.d.ts +2 -2
  4. package/dist/src/connection/ConnectionLockRpcRemote.js +2 -2
  5. package/dist/src/connection/ConnectionLockRpcRemote.js.map +1 -1
  6. package/dist/src/connection/ConnectionManager.js +4 -1
  7. package/dist/src/connection/ConnectionManager.js.map +1 -1
  8. package/dist/src/connection/ConnectorFacade.js.map +1 -1
  9. package/dist/src/connection/ManagedConnection.js +1 -0
  10. package/dist/src/connection/ManagedConnection.js.map +1 -1
  11. package/dist/src/connection/connectivityChecker.d.ts +9 -0
  12. package/dist/src/connection/connectivityChecker.js +121 -0
  13. package/dist/src/connection/connectivityChecker.js.map +1 -0
  14. package/dist/src/connection/connectivityRequestHandler.d.ts +2 -0
  15. package/dist/src/connection/connectivityRequestHandler.js +79 -0
  16. package/dist/src/connection/connectivityRequestHandler.js.map +1 -0
  17. package/dist/src/connection/simulator/Simulator.js +3 -2
  18. package/dist/src/connection/simulator/Simulator.js.map +1 -1
  19. package/dist/src/connection/simulator/SimulatorConnection.js +1 -1
  20. package/dist/src/connection/simulator/SimulatorConnection.js.map +1 -1
  21. package/dist/src/connection/webrtc/NodeWebrtcConnection.js +1 -1
  22. package/dist/src/connection/webrtc/NodeWebrtcConnection.js.map +1 -1
  23. package/dist/src/connection/webrtc/WebrtcConnector.js +1 -1
  24. package/dist/src/connection/webrtc/WebrtcConnector.js.map +1 -1
  25. package/dist/src/connection/webrtc/WebrtcConnectorRpcLocal.js +1 -1
  26. package/dist/src/connection/webrtc/WebrtcConnectorRpcLocal.js.map +1 -1
  27. package/dist/src/connection/webrtc/WebrtcConnectorRpcRemote.d.ts +2 -2
  28. package/dist/src/connection/webrtc/WebrtcConnectorRpcRemote.js +2 -2
  29. package/dist/src/connection/webrtc/WebrtcConnectorRpcRemote.js.map +1 -1
  30. package/dist/src/connection/webrtc/iceServerAsString.js +1 -1
  31. package/dist/src/connection/webrtc/iceServerAsString.js.map +1 -1
  32. package/dist/src/connection/websocket/ClientWebsocket.js +1 -0
  33. package/dist/src/connection/websocket/ClientWebsocket.js.map +1 -1
  34. package/dist/src/connection/websocket/WebsocketConnector.d.ts +0 -1
  35. package/dist/src/connection/websocket/WebsocketConnector.js +41 -7
  36. package/dist/src/connection/websocket/WebsocketConnector.js.map +1 -1
  37. package/dist/src/connection/websocket/WebsocketConnectorRpcRemote.d.ts +2 -2
  38. package/dist/src/connection/websocket/WebsocketConnectorRpcRemote.js +2 -2
  39. package/dist/src/connection/websocket/WebsocketConnectorRpcRemote.js.map +1 -1
  40. package/dist/src/dht/DhtNode.d.ts +9 -19
  41. package/dist/src/dht/DhtNode.js +76 -216
  42. package/dist/src/dht/DhtNode.js.map +1 -1
  43. package/dist/src/dht/DhtNodeRpcLocal.js +3 -3
  44. package/dist/src/dht/DhtNodeRpcLocal.js.map +1 -1
  45. package/dist/src/dht/DhtNodeRpcRemote.d.ts +3 -3
  46. package/dist/src/dht/DhtNodeRpcRemote.js +4 -4
  47. package/dist/src/dht/DhtNodeRpcRemote.js.map +1 -1
  48. package/dist/src/dht/ExternalApiRpcLocal.d.ts +4 -4
  49. package/dist/src/dht/ExternalApiRpcLocal.js +5 -12
  50. package/dist/src/dht/ExternalApiRpcLocal.js.map +1 -1
  51. package/dist/src/dht/ExternalApiRpcRemote.d.ts +3 -3
  52. package/dist/src/dht/ExternalApiRpcRemote.js +5 -5
  53. package/dist/src/dht/ExternalApiRpcRemote.js.map +1 -1
  54. package/dist/src/dht/PeerManager.d.ts +48 -0
  55. package/dist/src/dht/PeerManager.js +208 -0
  56. package/dist/src/dht/PeerManager.js.map +1 -0
  57. package/dist/src/dht/contact/ContactList.d.ts +1 -1
  58. package/dist/src/dht/contact/ContactList.js +1 -0
  59. package/dist/src/dht/contact/ContactList.js.map +1 -1
  60. package/dist/src/dht/contact/{Remote.d.ts → RpcRemote.d.ts} +3 -3
  61. package/dist/src/dht/contact/{Remote.js → RpcRemote.js} +8 -8
  62. package/dist/src/dht/contact/RpcRemote.js.map +1 -0
  63. package/dist/src/dht/discovery/DiscoverySession.d.ts +2 -9
  64. package/dist/src/dht/discovery/DiscoverySession.js +12 -26
  65. package/dist/src/dht/discovery/DiscoverySession.js.map +1 -1
  66. package/dist/src/dht/discovery/PeerDiscovery.d.ts +2 -9
  67. package/dist/src/dht/discovery/PeerDiscovery.js +13 -15
  68. package/dist/src/dht/discovery/PeerDiscovery.js.map +1 -1
  69. package/dist/src/dht/find/FindRpcLocal.js +2 -1
  70. package/dist/src/dht/find/FindRpcLocal.js.map +1 -1
  71. package/dist/src/dht/find/FindSession.d.ts +6 -6
  72. package/dist/src/dht/find/FindSession.js +13 -13
  73. package/dist/src/dht/find/FindSession.js.map +1 -1
  74. package/dist/src/dht/find/FindSessionRpcLocal.d.ts +1 -1
  75. package/dist/src/dht/find/FindSessionRpcRemote.d.ts +2 -2
  76. package/dist/src/dht/find/FindSessionRpcRemote.js +2 -2
  77. package/dist/src/dht/find/FindSessionRpcRemote.js.map +1 -1
  78. package/dist/src/dht/find/Finder.d.ts +4 -4
  79. package/dist/src/dht/find/Finder.js +50 -42
  80. package/dist/src/dht/find/Finder.js.map +1 -1
  81. package/dist/src/dht/routing/FindRpcRemote.d.ts +2 -2
  82. package/dist/src/dht/routing/FindRpcRemote.js +7 -5
  83. package/dist/src/dht/routing/FindRpcRemote.js.map +1 -1
  84. package/dist/src/dht/routing/Router.d.ts +2 -6
  85. package/dist/src/dht/routing/Router.js +21 -18
  86. package/dist/src/dht/routing/Router.js.map +1 -1
  87. package/dist/src/dht/routing/RouterRpcLocal.d.ts +2 -2
  88. package/dist/src/dht/routing/RouterRpcLocal.js +4 -3
  89. package/dist/src/dht/routing/RouterRpcLocal.js.map +1 -1
  90. package/dist/src/dht/routing/RouterRpcRemote.d.ts +2 -2
  91. package/dist/src/dht/routing/RouterRpcRemote.js +13 -8
  92. package/dist/src/dht/routing/RouterRpcRemote.js.map +1 -1
  93. package/dist/src/dht/routing/RoutingSession.d.ts +1 -1
  94. package/dist/src/dht/routing/RoutingSession.js +16 -11
  95. package/dist/src/dht/routing/RoutingSession.js.map +1 -1
  96. package/dist/src/dht/routing/getPreviousPeer.js.map +1 -1
  97. package/dist/src/dht/store/LocalDataStore.d.ts +3 -3
  98. package/dist/src/dht/store/LocalDataStore.js +18 -17
  99. package/dist/src/dht/store/LocalDataStore.js.map +1 -1
  100. package/dist/src/dht/store/StoreRpcLocal.d.ts +10 -9
  101. package/dist/src/dht/store/StoreRpcLocal.js +91 -99
  102. package/dist/src/dht/store/StoreRpcLocal.js.map +1 -1
  103. package/dist/src/dht/store/StoreRpcRemote.d.ts +4 -5
  104. package/dist/src/dht/store/StoreRpcRemote.js +6 -15
  105. package/dist/src/dht/store/StoreRpcRemote.js.map +1 -1
  106. package/dist/src/exports.d.ts +1 -1
  107. package/dist/src/exports.js +4 -4
  108. package/dist/src/exports.js.map +1 -1
  109. package/dist/src/helpers/PeerID.js +2 -2
  110. package/dist/src/helpers/PeerID.js.map +1 -1
  111. package/dist/src/helpers/UUID.js +1 -1
  112. package/dist/src/helpers/UUID.js.map +1 -1
  113. package/dist/src/helpers/nodeId.d.ts +1 -0
  114. package/dist/src/helpers/{kademliaId.js → nodeId.js} +4 -4
  115. package/dist/src/helpers/nodeId.js.map +1 -0
  116. package/dist/src/helpers/peerIdFromPeerDescriptor.js +3 -3
  117. package/dist/src/helpers/peerIdFromPeerDescriptor.js.map +1 -1
  118. package/dist/src/proto/packages/dht/protos/DhtRpc.client.d.ts +5 -16
  119. package/dist/src/proto/packages/dht/protos/DhtRpc.client.js +2 -9
  120. package/dist/src/proto/packages/dht/protos/DhtRpc.client.js.map +1 -1
  121. package/dist/src/proto/packages/dht/protos/DhtRpc.d.ts +80 -95
  122. package/dist/src/proto/packages/dht/protos/DhtRpc.js +67 -66
  123. package/dist/src/proto/packages/dht/protos/DhtRpc.js.map +1 -1
  124. package/dist/src/proto/packages/dht/protos/DhtRpc.server.d.ts +3 -10
  125. package/dist/src/transport/RoutingRpcCommunicator.js +2 -0
  126. package/dist/src/transport/RoutingRpcCommunicator.js.map +1 -1
  127. package/karma.config.js +2 -2
  128. package/package.json +5 -5
  129. package/protos/DhtRpc.proto +36 -36
  130. package/src/connection/ConnectionLockHandler.ts +2 -2
  131. package/src/connection/ConnectionLockRpcRemote.ts +2 -2
  132. package/src/connection/ConnectionManager.ts +4 -1
  133. package/src/connection/ConnectorFacade.ts +5 -4
  134. package/src/connection/ManagedConnection.ts +1 -0
  135. package/src/connection/connectivityChecker.ts +101 -0
  136. package/src/connection/connectivityRequestHandler.ts +79 -0
  137. package/src/connection/simulator/Simulator.ts +3 -2
  138. package/src/connection/simulator/SimulatorConnection.ts +1 -1
  139. package/src/connection/webrtc/BrowserWebrtcConnection.ts +10 -10
  140. package/src/connection/webrtc/NodeWebrtcConnection.ts +1 -1
  141. package/src/connection/webrtc/WebrtcConnector.ts +1 -1
  142. package/src/connection/webrtc/WebrtcConnectorRpcLocal.ts +1 -1
  143. package/src/connection/webrtc/WebrtcConnectorRpcRemote.ts +2 -2
  144. package/src/connection/webrtc/iceServerAsString.ts +1 -1
  145. package/src/connection/websocket/ClientWebsocket.ts +1 -0
  146. package/src/connection/websocket/WebsocketConnector.ts +22 -12
  147. package/src/connection/websocket/WebsocketConnectorRpcRemote.ts +2 -2
  148. package/src/dht/DhtNode.ts +102 -269
  149. package/src/dht/DhtNodeRpcLocal.ts +3 -3
  150. package/src/dht/DhtNodeRpcRemote.ts +4 -4
  151. package/src/dht/ExternalApiRpcLocal.ts +8 -13
  152. package/src/dht/ExternalApiRpcRemote.ts +5 -5
  153. package/src/dht/PeerManager.ts +256 -0
  154. package/src/dht/contact/ContactList.ts +3 -2
  155. package/src/dht/contact/{Remote.ts → RpcRemote.ts} +7 -6
  156. package/src/dht/discovery/DiscoverySession.ts +15 -40
  157. package/src/dht/discovery/PeerDiscovery.ts +18 -23
  158. package/src/dht/find/FindRpcLocal.ts +2 -2
  159. package/src/dht/find/FindSession.ts +20 -20
  160. package/src/dht/find/FindSessionRpcLocal.ts +1 -1
  161. package/src/dht/find/FindSessionRpcRemote.ts +2 -2
  162. package/src/dht/find/Finder.ts +79 -58
  163. package/src/dht/routing/FindRpcRemote.ts +7 -5
  164. package/src/dht/routing/Router.ts +22 -21
  165. package/src/dht/routing/RouterRpcLocal.ts +5 -5
  166. package/src/dht/routing/RouterRpcRemote.ts +13 -10
  167. package/src/dht/routing/RoutingSession.ts +15 -10
  168. package/src/dht/routing/getPreviousPeer.ts +1 -1
  169. package/src/dht/store/LocalDataStore.ts +18 -17
  170. package/src/dht/store/StoreRpcLocal.ts +101 -108
  171. package/src/dht/store/StoreRpcRemote.ts +7 -23
  172. package/src/exports.ts +1 -1
  173. package/src/helpers/PeerID.ts +2 -2
  174. package/src/helpers/UUID.ts +1 -1
  175. package/src/helpers/{kademliaId.ts → nodeId.ts} +1 -1
  176. package/src/helpers/peerIdFromPeerDescriptor.ts +3 -3
  177. package/src/proto/packages/dht/protos/DhtRpc.client.ts +6 -20
  178. package/src/proto/packages/dht/protos/DhtRpc.server.ts +3 -10
  179. package/src/proto/packages/dht/protos/DhtRpc.ts +103 -135
  180. package/src/transport/RoutingRpcCommunicator.ts +2 -0
  181. package/test/benchmark/Find.test.ts +4 -4
  182. package/test/benchmark/KademliaCorrectness.test.ts +2 -2
  183. package/test/benchmark/kademlia-simulation/Contact.ts +1 -1
  184. package/test/benchmark/kademlia-simulation/KademliaSimulation.ts +1 -1
  185. package/test/end-to-end/Layer0-Layer1.test.ts +1 -1
  186. package/test/end-to-end/Layer0MixedConnectionTypes.test.ts +1 -1
  187. package/test/end-to-end/Layer0Webrtc-Layer1.test.ts +2 -2
  188. package/test/end-to-end/Layer0Webrtc.test.ts +2 -2
  189. package/test/end-to-end/Layer1-Scale-WebSocket.test.ts +1 -1
  190. package/test/end-to-end/Layer1-Scale-Webrtc.test.ts +1 -1
  191. package/test/end-to-end/WebsocketConnectionRequest.test.ts +1 -1
  192. package/test/end-to-end/memory-leak.test.ts +8 -12
  193. package/test/integration/ConnectionLocking.test.ts +2 -2
  194. package/test/integration/ConnectionManager.test.ts +14 -14
  195. package/test/integration/DhtJoinPeerDiscovery.test.ts +1 -1
  196. package/test/integration/DhtNodeExternalAPI.test.ts +10 -7
  197. package/test/integration/DhtNodeRpcRemote.test.ts +4 -4
  198. package/test/integration/DhtRpc.test.ts +6 -6
  199. package/test/integration/Find.test.ts +3 -3
  200. package/test/integration/Layer1-scale.test.ts +2 -2
  201. package/test/integration/Mock-Layer1-Layer0.test.ts +1 -1
  202. package/test/integration/{MigrateData.test.ts → ReplicateData.test.ts} +9 -9
  203. package/test/integration/RouteMessage.test.ts +2 -2
  204. package/test/integration/RouterRpcRemote.test.ts +2 -2
  205. package/test/integration/RpcErrors.test.ts +2 -2
  206. package/test/integration/ScaleDownDht.test.ts +4 -2
  207. package/test/integration/SimultaneousConnections.test.ts +8 -8
  208. package/test/integration/Store.test.ts +33 -13
  209. package/test/integration/StoreAndDelete.test.ts +19 -17
  210. package/test/integration/StoreOnDhtWithTwoNodes.test.ts +20 -20
  211. package/test/integration/StoreRpcRemote.test.ts +3 -3
  212. package/test/integration/WebrtcConnectionManagement.test.ts +2 -2
  213. package/test/integration/WebrtcConnectorRpc.test.ts +1 -1
  214. package/test/integration/WebsocketConnectionManagement.test.ts +2 -2
  215. package/test/integration/WebsocketConnectorRpc.test.ts +2 -2
  216. package/test/unit/ConnectivityHelpers.test.ts +4 -4
  217. package/test/unit/Finder.test.ts +69 -23
  218. package/test/unit/LocalDataStore.test.ts +60 -43
  219. package/test/unit/RandomContactList.test.ts +2 -2
  220. package/test/unit/Router.test.ts +19 -11
  221. package/test/unit/RoutingSession.test.ts +76 -0
  222. package/test/unit/SortedContactList.test.ts +2 -2
  223. package/test/unit/WebsocketConnector.test.ts +1 -1
  224. package/test/unit/connectivityRequestHandler.test.ts +71 -0
  225. package/test/utils/mock/Router.ts +1 -1
  226. package/test/utils/utils.ts +24 -22
  227. package/dist/src/connection/ConnectivityChecker.d.ts +0 -17
  228. package/dist/src/connection/ConnectivityChecker.js +0 -208
  229. package/dist/src/connection/ConnectivityChecker.js.map +0 -1
  230. package/dist/src/dht/contact/Remote.js.map +0 -1
  231. package/dist/src/helpers/kademliaId.d.ts +0 -1
  232. package/dist/src/helpers/kademliaId.js.map +0 -1
  233. package/src/connection/ConnectivityChecker.ts +0 -199
@@ -1,9 +1,7 @@
1
1
  import { DhtNodeRpcRemote } from './DhtNodeRpcRemote'
2
- import KBucket from 'k-bucket'
3
2
  import { EventEmitter } from 'eventemitter3'
4
- import { SortedContactList } from './contact/SortedContactList'
5
3
  import { RoutingRpcCommunicator } from '../transport/RoutingRpcCommunicator'
6
- import { PeerID, PeerIDKey } from '../helpers/PeerID'
4
+ import { PeerID } from '../helpers/PeerID'
7
5
  import {
8
6
  ClosestPeersRequest,
9
7
  ClosestPeersResponse,
@@ -19,6 +17,7 @@ import {
19
17
  ExternalFindDataResponse,
20
18
  ExternalStoreDataRequest,
21
19
  ExternalStoreDataResponse,
20
+ FindAction,
22
21
  } from '../proto/packages/dht/protos/DhtRpc'
23
22
  import { ITransport, TransportEvents } from '../transport/ITransport'
24
23
  import { ConnectionManager, PortRange, TlsCertificate } from '../connection/ConnectionManager'
@@ -31,12 +30,10 @@ import {
31
30
  waitForCondition
32
31
  } from '@streamr/utils'
33
32
  import { toProtoRpcClient } from '@streamr/proto-rpc'
34
- import { RandomContactList } from './contact/RandomContactList'
35
33
  import { Any } from '../proto/google/protobuf/any'
36
34
  import {
37
35
  areEqualPeerDescriptors,
38
36
  getNodeIdFromPeerDescriptor,
39
- keyFromPeerDescriptor,
40
37
  peerIdFromPeerDescriptor
41
38
  } from '../helpers/peerIdFromPeerDescriptor'
42
39
  import { Router } from './routing/Router'
@@ -54,6 +51,7 @@ import { MarkRequired } from 'ts-essentials'
54
51
  import { DhtNodeRpcLocal } from './DhtNodeRpcLocal'
55
52
  import { ServerCallContext } from '@protobuf-ts/runtime-rpc'
56
53
  import { ExternalApiRpcLocal } from './ExternalApiRpcLocal'
54
+ import { PeerManager } from './PeerManager'
57
55
 
58
56
  export interface DhtNodeEvents {
59
57
  newContact: (peerDescriptor: PeerDescriptor, closestPeers: PeerDescriptor[]) => void
@@ -100,7 +98,7 @@ export interface DhtNodeOptions {
100
98
  autoCertifierConfigFile?: string
101
99
  }
102
100
 
103
- type StrictDhtNodeOptions = MarkRequired<DhtNodeOptions,
101
+ type StrictDhtNodeOptions = MarkRequired<DhtNodeOptions,
104
102
  'serviceId' |
105
103
  'joinParallelism' |
106
104
  'maxNeighborListSize' |
@@ -121,14 +119,14 @@ const logger = new Logger(module)
121
119
  export type Events = TransportEvents & DhtNodeEvents
122
120
 
123
121
  export const createPeerDescriptor = (msg?: ConnectivityResponse, peerId?: string): PeerDescriptor => {
124
- let kademliaId: Uint8Array
122
+ let nodeId: Uint8Array
125
123
  if (msg) {
126
- kademliaId = peerId ? hexToBinary(peerId) : PeerID.fromIp(msg.host).value
124
+ nodeId = (peerId !== undefined) ? hexToBinary(peerId) : PeerID.fromIp(msg.host).value
127
125
  } else {
128
- kademliaId = hexToBinary(peerId!)
126
+ nodeId = hexToBinary(peerId!)
129
127
  }
130
- const nodeType = isBrowserEnvironment() ? NodeType.BROWSER : NodeType.NODEJS
131
- const ret: PeerDescriptor = { kademliaId, type: nodeType }
128
+ const nodeType = isBrowserEnvironment() ? NodeType.BROWSER : NodeType.NODEJS
129
+ const ret: PeerDescriptor = { nodeId, type: nodeType }
132
130
  if (msg && msg.websocket) {
133
131
  ret.websocket = { host: msg.websocket.host, port: msg.websocket.port, tls: msg.websocket.tls }
134
132
  }
@@ -138,10 +136,6 @@ export const createPeerDescriptor = (msg?: ConnectivityResponse, peerId?: string
138
136
  export class DhtNode extends EventEmitter<Events> implements ITransport {
139
137
 
140
138
  private readonly config: StrictDhtNodeOptions
141
- private bucket?: KBucket<DhtNodeRpcRemote>
142
- private connections: Map<PeerIDKey, DhtNodeRpcRemote> = new Map()
143
- private neighborList?: SortedContactList<DhtNodeRpcRemote>
144
- private randomPeers?: RandomContactList<DhtNodeRpcRemote>
145
139
  private rpcCommunicator?: RoutingRpcCommunicator
146
140
  private transport?: ITransport
147
141
  private localPeerDescriptor?: PeerDescriptor
@@ -150,6 +144,7 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
150
144
  private localDataStore = new LocalDataStore()
151
145
  private finder?: Finder
152
146
  private peerDiscovery?: PeerDiscovery
147
+ private peerManager?: PeerManager
153
148
 
154
149
  public connectionManager?: ConnectionManager
155
150
  private started = false
@@ -218,12 +213,12 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
218
213
  // If own PeerDescriptor is given in config, create a ConnectionManager with ws server
219
214
  if (this.config.peerDescriptor?.websocket) {
220
215
  connectorFacadeConfig.websocketHost = this.config.peerDescriptor.websocket.host
221
- connectorFacadeConfig.websocketPortRange = {
216
+ connectorFacadeConfig.websocketPortRange = {
222
217
  min: this.config.peerDescriptor.websocket.port,
223
218
  max: this.config.peerDescriptor.websocket.port
224
219
  }
225
220
  // If websocketPortRange is given, create ws server using it, websocketHost can be undefined
226
- } else if (this.config.websocketPortRange) {
221
+ } else if (this.config.websocketPortRange) {
227
222
  connectorFacadeConfig.websocketHost = this.config.websocketHost
228
223
  connectorFacadeConfig.websocketPortRange = this.config.websocketPortRange
229
224
  }
@@ -246,26 +241,23 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
246
241
 
247
242
  this.transport.on('message', (message: Message) => this.handleMessage(message))
248
243
 
249
- this.initKBuckets(peerIdFromPeerDescriptor(this.localPeerDescriptor!))
244
+ this.initPeerManager()
245
+
250
246
  this.peerDiscovery = new PeerDiscovery({
251
- rpcCommunicator: this.rpcCommunicator,
252
247
  localPeerDescriptor: this.localPeerDescriptor!,
253
- bucket: this.bucket!,
254
- neighborList: this.neighborList!,
255
248
  joinNoProgressLimit: this.config.joinNoProgressLimit,
256
249
  peerDiscoveryQueryBatchSize: this.config.peerDiscoveryQueryBatchSize,
257
250
  joinTimeout: this.config.dhtJoinTimeout,
258
251
  serviceId: this.config.serviceId,
259
252
  parallelism: this.config.joinParallelism,
260
- addContact: this.addNewContact.bind(this),
261
253
  connectionManager: this.connectionManager,
262
- rpcRequestTimeout: this.config.rpcRequestTimeout
254
+ peerManager: this.peerManager!
263
255
  })
264
256
  this.router = new Router({
265
257
  rpcCommunicator: this.rpcCommunicator,
266
- connections: this.connections,
258
+ connections: this.peerManager!.connections,
267
259
  localPeerDescriptor: this.localPeerDescriptor!,
268
- addContact: this.addNewContact.bind(this),
260
+ addContact: (contact: PeerDescriptor, setActive?: boolean) => this.peerManager!.handleNewPeers([contact], setActive),
269
261
  serviceId: this.config.serviceId,
270
262
  connectionManager: this.connectionManager
271
263
  })
@@ -273,10 +265,10 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
273
265
  rpcCommunicator: this.rpcCommunicator,
274
266
  router: this.router,
275
267
  sessionTransport: this,
276
- connections: this.connections,
268
+ connections: this.peerManager!.connections,
277
269
  localPeerDescriptor: this.localPeerDescriptor!,
278
270
  serviceId: this.config.serviceId,
279
- addContact: this.addNewContact.bind(this),
271
+ addContact: (contact: PeerDescriptor) => this.peerManager!.handleNewPeers([contact]),
280
272
  isPeerCloserToIdThanSelf: this.isPeerCloserToIdThanSelf.bind(this),
281
273
  localDataStore: this.localDataStore
282
274
  })
@@ -291,115 +283,63 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
291
283
  localDataStore: this.localDataStore,
292
284
  dhtNodeEmitter: this,
293
285
  getNodesClosestToIdFromBucket: (id: Uint8Array, n?: number) => {
294
- return this.bucket!.closest(id, n)
286
+ return this.peerManager!.bucket!.closest(id, n)
295
287
  },
296
288
  rpcRequestTimeout: this.config.rpcRequestTimeout
297
289
  })
298
290
  this.bindRpcLocalMethods()
299
- if (this.connectionManager! && this.config.entryPoints && this.config.entryPoints.length > 0
291
+ if ((this.connectionManager !== undefined) && (this.config.entryPoints !== undefined) && this.config.entryPoints.length > 0
300
292
  && !areEqualPeerDescriptors(this.config.entryPoints[0], this.localPeerDescriptor!)) {
301
293
  this.connectToEntryPoint(this.config.entryPoints[0])
302
294
  }
303
295
  }
304
296
 
305
- private initKBuckets(selfId: PeerID) {
306
- this.bucket = new KBucket<DhtNodeRpcRemote>({
307
- localNodeId: selfId.value,
297
+ private initPeerManager() {
298
+ this.peerManager = new PeerManager({
308
299
  numberOfNodesPerKBucket: this.config.numberOfNodesPerKBucket,
309
- numberOfNodesToPing: this.config.numberOfNodesPerKBucket
300
+ maxNeighborListSize: this.config.maxNeighborListSize,
301
+ ownPeerId: this.getNodeId(),
302
+ connectionManager: this.connectionManager!,
303
+ peerDiscoveryQueryBatchSize: this.config.peerDiscoveryQueryBatchSize,
304
+ isLayer0: (this.connectionManager !== undefined),
305
+ createDhtNodeRpcRemote: (peerDescriptor: PeerDescriptor) => this.createDhtNodeRpcRemote(peerDescriptor)
310
306
  })
311
- this.bucket.on('ping', (oldContacts: DhtNodeRpcRemote[], newContact: DhtNodeRpcRemote) => this.onKBucketPing(oldContacts, newContact))
312
- this.bucket.on('removed', (contact: DhtNodeRpcRemote) => this.onKBucketRemoved(contact))
313
- this.bucket.on('added', (contact: DhtNodeRpcRemote) => this.onKBucketAdded(contact))
314
- this.bucket.on('updated', () => {
315
- // TODO: Update contact info to the connection manager and reconnect
307
+ this.peerManager.on('contactRemoved', (peerDescriptor: PeerDescriptor, activeContacts: PeerDescriptor[]) => {
308
+ this.emit('contactRemoved', peerDescriptor, activeContacts)
316
309
  })
317
- this.neighborList = new SortedContactList(selfId, this.config.maxNeighborListSize)
318
- this.neighborList.on('contactRemoved', (removedContact: DhtNodeRpcRemote, activeContacts: DhtNodeRpcRemote[]) => {
319
- if (this.stopped) {
320
- return
310
+ this.peerManager.on('newContact', (peerDescriptor: PeerDescriptor, activeContacts: PeerDescriptor[]) =>
311
+ this.emit('newContact', peerDescriptor, activeContacts)
312
+ )
313
+ this.peerManager.on('randomContactRemoved', (peerDescriptor: PeerDescriptor, activeContacts: PeerDescriptor[]) =>
314
+ this.emit('randomContactRemoved', peerDescriptor, activeContacts)
315
+ )
316
+ this.peerManager.on('newRandomContact', (peerDescriptor: PeerDescriptor, activeContacts: PeerDescriptor[]) =>
317
+ this.emit('newRandomContact', peerDescriptor, activeContacts)
318
+ )
319
+ this.peerManager.on('kBucketEmpty', () => {
320
+ if (!this.peerDiscovery!.isJoinOngoing()
321
+ && this.config.entryPoints
322
+ && this.config.entryPoints.length > 0
323
+ ) {
324
+ setImmediate(async () => {
325
+ // TODO should we catch possible promise rejection?
326
+ await Promise.all(this.config.entryPoints!.map((entryPoint) =>
327
+ this.peerDiscovery!.rejoinDht(entryPoint)
328
+ ))
329
+ })
321
330
  }
322
- this.emit('contactRemoved', removedContact.getPeerDescriptor(), activeContacts.map((c) => c.getPeerDescriptor()))
323
- this.randomPeers!.addContact(
324
- new DhtNodeRpcRemote(
325
- this.localPeerDescriptor!,
326
- removedContact.getPeerDescriptor(),
327
- toProtoRpcClient(new DhtNodeRpcClient(this.rpcCommunicator!.getRpcClientTransport())),
328
- this.config.serviceId,
329
- this.config.rpcRequestTimeout
330
- )
331
- )
332
331
  })
333
- this.neighborList.on('newContact', (newContact: DhtNodeRpcRemote, activeContacts: DhtNodeRpcRemote[]) =>
334
- this.emit('newContact', newContact.getPeerDescriptor(), activeContacts.map((c) => c.getPeerDescriptor()))
335
- )
336
- this.transport!.on('connected', (peerDescriptor: PeerDescriptor) => this.onTransportConnected(peerDescriptor))
337
-
332
+ this.transport!.on('connected', (peerDescriptor: PeerDescriptor) => {
333
+ this.peerManager!.handleConnected(peerDescriptor)
334
+ this.emit('connected', peerDescriptor)
335
+ })
338
336
  this.transport!.on('disconnected', (peerDescriptor: PeerDescriptor, gracefulLeave: boolean) => {
339
- this.onTransportDisconnected(peerDescriptor, gracefulLeave)
337
+ this.peerManager!.handleDisconnected(peerDescriptor, gracefulLeave)
338
+ this.emit('disconnected', peerDescriptor, gracefulLeave)
340
339
  })
341
-
342
340
  this.transport!.getAllConnectionPeerDescriptors().forEach((peer) => {
343
- const rpcRemote = new DhtNodeRpcRemote(
344
- this.localPeerDescriptor!,
345
- peer,
346
- toProtoRpcClient(new DhtNodeRpcClient(this.rpcCommunicator!.getRpcClientTransport())),
347
- this.config.serviceId,
348
- this.config.rpcRequestTimeout
349
- )
350
- if (areEqualPeerDescriptors(peer, this.localPeerDescriptor!)) {
351
- logger.error('own peerdescriptor added to connections in initKBucket')
352
- }
353
- this.connections.set(keyFromPeerDescriptor(peer), rpcRemote)
341
+ this.peerManager!.handleConnected(peer)
354
342
  })
355
- this.randomPeers = new RandomContactList(selfId, this.config.maxNeighborListSize)
356
- this.randomPeers.on('contactRemoved', (removedContact: DhtNodeRpcRemote, activeContacts: DhtNodeRpcRemote[]) =>
357
- this.emit('randomContactRemoved', removedContact.getPeerDescriptor(), activeContacts.map((c) => c.getPeerDescriptor()))
358
- )
359
- this.randomPeers.on('newContact', (newContact: DhtNodeRpcRemote, activeContacts: DhtNodeRpcRemote[]) =>
360
- this.emit('newRandomContact', newContact.getPeerDescriptor(), activeContacts.map((c) => c.getPeerDescriptor()))
361
- )
362
- }
363
-
364
- private onTransportConnected(peerDescriptor: PeerDescriptor): void {
365
-
366
- if (areEqualPeerDescriptors(this.localPeerDescriptor!, peerDescriptor)) {
367
- logger.error('onTransportConnected() to self')
368
- }
369
-
370
- const rpcRemote = new DhtNodeRpcRemote(
371
- this.localPeerDescriptor!,
372
- peerDescriptor,
373
- toProtoRpcClient(new DhtNodeRpcClient(this.rpcCommunicator!.getRpcClientTransport())),
374
- this.config.serviceId,
375
- this.config.rpcRequestTimeout
376
- )
377
- if (!this.connections.has(PeerID.fromValue(rpcRemote.id).toKey())) {
378
- this.connections.set(PeerID.fromValue(rpcRemote.id).toKey(), rpcRemote)
379
- logger.trace('connectionschange add ' + this.connections.size)
380
- } else {
381
- logger.trace('new connection not set to connections, there is already a connection with the peer ID')
382
- }
383
- logger.trace('connected: ' + getNodeIdFromPeerDescriptor(peerDescriptor) + ' ' + this.connections.size)
384
- this.emit('connected', peerDescriptor)
385
- }
386
-
387
- private onTransportDisconnected(peerDescriptor: PeerDescriptor, gracefulLeave: boolean): void {
388
- logger.trace('disconnected: ' + getNodeIdFromPeerDescriptor(peerDescriptor))
389
- this.connections.delete(keyFromPeerDescriptor(peerDescriptor))
390
- // only remove from bucket if we are on layer 0
391
- if (this.connectionManager) {
392
- this.bucket!.remove(peerDescriptor.kademliaId)
393
-
394
- if (gracefulLeave === true) {
395
- logger.trace(getNodeIdFromPeerDescriptor(peerDescriptor) + ' ' + 'onTransportDisconnected with gracefulLeave ' + gracefulLeave)
396
- this.removeContact(peerDescriptor)
397
- } else {
398
- logger.trace(getNodeIdFromPeerDescriptor(peerDescriptor) + ' ' + 'onTransportDisconnected with gracefulLeave ' + gracefulLeave)
399
- }
400
- }
401
-
402
- this.emit('disconnected', peerDescriptor, gracefulLeave)
403
343
  }
404
344
 
405
345
  private bindRpcLocalMethods(): void {
@@ -407,10 +347,10 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
407
347
  return
408
348
  }
409
349
  const dhtNodeRpcLocal = new DhtNodeRpcLocal({
410
- bucket: this.bucket!,
350
+ bucket: this.peerManager!.bucket!,
411
351
  serviceId: this.config.serviceId,
412
352
  peerDiscoveryQueryBatchSize: this.config.peerDiscoveryQueryBatchSize,
413
- addNewContact: (contact: PeerDescriptor) => this.addNewContact(contact),
353
+ addNewContact: (contact: PeerDescriptor) => this.peerManager!.handleNewPeers([contact]),
414
354
  removeContact: (contact: PeerDescriptor) => this.removeContact(contact)
415
355
  })
416
356
  this.rpcCommunicator!.registerRpcMethod(ClosestPeersRequest, ClosestPeersResponse, 'getClosestPeers',
@@ -420,15 +360,15 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
420
360
  this.rpcCommunicator!.registerRpcNotification(LeaveNotice, 'leaveNotice',
421
361
  (req: LeaveNotice, context) => dhtNodeRpcLocal.leaveNotice(req, context))
422
362
  const externalApiRpcLocal = new ExternalApiRpcLocal({
423
- startFind: (idToFind: Uint8Array, fetchData: boolean, excludedPeer: PeerDescriptor) => {
424
- return this.startFind(idToFind, fetchData, excludedPeer)
363
+ startFind: (key: Uint8Array, action: FindAction, excludedPeer: PeerDescriptor) => {
364
+ return this.startFind(key, action, excludedPeer)
425
365
  },
426
- storeDataToDht: (key: Uint8Array, data: Any) => this.storeDataToDht(key, data)
366
+ storeDataToDht: (key: Uint8Array, data: Any, creator?: PeerDescriptor) => this.storeDataToDht(key, data, creator)
427
367
  })
428
368
  this.rpcCommunicator!.registerRpcMethod(
429
369
  ExternalFindDataRequest,
430
370
  ExternalFindDataResponse,
431
- 'externalFindData',
371
+ 'externalFindData',
432
372
  (req: ExternalFindDataRequest, context: ServerCallContext) => externalApiRpcLocal.externalFindData(req, context),
433
373
  { timeout: 10000 }
434
374
  )
@@ -436,14 +376,14 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
436
376
  ExternalStoreDataRequest,
437
377
  ExternalStoreDataResponse,
438
378
  'externalStoreData',
439
- (req: ExternalStoreDataRequest) => externalApiRpcLocal.externalStoreData(req),
379
+ (req: ExternalStoreDataRequest, context: ServerCallContext) => externalApiRpcLocal.externalStoreData(req, context),
440
380
  { timeout: 10000 }
441
381
  )
442
382
  }
443
383
 
444
384
  private isPeerCloserToIdThanSelf(peer1: PeerDescriptor, compareToId: PeerID): boolean {
445
- const distance1 = this.bucket!.distance(peer1.kademliaId, compareToId.value)
446
- const distance2 = this.bucket!.distance(this.localPeerDescriptor!.kademliaId, compareToId.value)
385
+ const distance1 = this.peerManager!.bucket!.distance(peer1.nodeId, compareToId.value)
386
+ const distance2 = this.peerManager!.bucket!.distance(this.localPeerDescriptor!.nodeId, compareToId.value)
447
387
  return distance1 < distance2
448
388
  }
449
389
 
@@ -468,88 +408,8 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
468
408
  return this.localPeerDescriptor
469
409
  }
470
410
 
471
- private onKBucketPing(oldContacts: DhtNodeRpcRemote[], newContact: DhtNodeRpcRemote): void {
472
- if (this.stopped) {
473
- return
474
- }
475
- const sortingList: SortedContactList<DhtNodeRpcRemote> = new SortedContactList(this.getNodeId(), 100)
476
- sortingList.addContacts(oldContacts)
477
- const sortedContacts = sortingList.getAllContacts()
478
- this.connectionManager?.weakUnlockConnection(sortedContacts[sortedContacts.length - 1].getPeerDescriptor())
479
- this.bucket?.remove(sortedContacts[sortedContacts.length - 1].getPeerId().value)
480
- this.bucket!.add(newContact)
481
- }
482
-
483
- private onKBucketRemoved(contact: DhtNodeRpcRemote): void {
484
- if (this.stopped) {
485
- return
486
- }
487
- this.connectionManager?.weakUnlockConnection(contact.getPeerDescriptor())
488
- logger.trace(`Removed contact ${getNodeIdFromPeerDescriptor(contact.getPeerDescriptor())}`)
489
- if (this.bucket!.count() === 0
490
- && !this.peerDiscovery!.isJoinOngoing()
491
- && this.config.entryPoints
492
- && this.config.entryPoints.length > 0
493
- ) {
494
- setImmediate(async () => {
495
- await Promise.all(this.config.entryPoints!.map((entryPoint) =>
496
- this.peerDiscovery!.rejoinDht(entryPoint)
497
- ))
498
- })
499
- }
500
- }
501
-
502
- private onKBucketAdded(contact: DhtNodeRpcRemote): void {
503
- if (this.stopped) {
504
- return
505
- }
506
- if (!contact.getPeerId().equals(this.getNodeId())) {
507
- // Important to lock here, before the ping result is known
508
- this.connectionManager?.weakLockConnection(contact.getPeerDescriptor())
509
- if (this.connections.has(contact.getPeerId().toKey())) {
510
- logger.trace(`Added new contact ${getNodeIdFromPeerDescriptor(contact.getPeerDescriptor())}`)
511
- } else { // open connection by pinging
512
- logger.trace('starting ping ' + getNodeIdFromPeerDescriptor(contact.getPeerDescriptor()))
513
- contact.ping().then((result) => {
514
- if (result) {
515
- logger.trace(`Added new contact ${getNodeIdFromPeerDescriptor(contact.getPeerDescriptor())}`)
516
- } else {
517
- logger.trace('ping failed ' + getNodeIdFromPeerDescriptor(contact.getPeerDescriptor()))
518
- this.connectionManager?.weakUnlockConnection(contact.getPeerDescriptor())
519
- this.removeContact(contact.getPeerDescriptor())
520
- this.addClosestContactToBucket()
521
- }
522
- return
523
- }).catch((_e) => {
524
- this.connectionManager?.weakUnlockConnection(contact.getPeerDescriptor())
525
- this.removeContact(contact.getPeerDescriptor())
526
- this.addClosestContactToBucket()
527
- })
528
- }
529
- }
530
- }
531
-
532
- private addClosestContactToBucket(): void {
533
- if (!this.started || this.stopped) {
534
- return
535
- }
536
- const closest = this.getClosestActiveContactNotInBucket()
537
- if (closest) {
538
- this.addNewContact(closest.getPeerDescriptor())
539
- }
540
- }
541
-
542
- private getClosestActiveContactNotInBucket(): DhtNodeRpcRemote | undefined {
543
- for (const contactId of this.neighborList!.getContactIds()) {
544
- if (!this.bucket!.get(contactId.value) && this.neighborList!.isActive(contactId)) {
545
- return this.neighborList!.getContact(contactId).contact
546
- }
547
- }
548
- return undefined
549
- }
550
-
551
411
  public getClosestContacts(maxCount?: number): PeerDescriptor[] {
552
- return this.neighborList!.getClosestContacts(maxCount).map((c) => c.getPeerDescriptor())
412
+ return this.peerManager!.neighborList!.getClosestContacts(maxCount).map((c) => c.getPeerDescriptor())
553
413
  }
554
414
 
555
415
  public getNodeId(): PeerID {
@@ -557,33 +417,7 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
557
417
  }
558
418
 
559
419
  public getBucketSize(): number {
560
- return this.bucket!.count()
561
- }
562
-
563
- private addNewContact(contact: PeerDescriptor, setActive = false): void {
564
- if (!this.started || this.stopped) {
565
- return
566
- }
567
- if (!areEqualPeerDescriptors(contact, this.localPeerDescriptor!)) {
568
- logger.trace(`Adding new contact ${getNodeIdFromPeerDescriptor(contact)}`)
569
- const rpcRemote = new DhtNodeRpcRemote(
570
- this.localPeerDescriptor!,
571
- contact,
572
- toProtoRpcClient(new DhtNodeRpcClient(this.rpcCommunicator!.getRpcClientTransport())),
573
- this.config.serviceId,
574
- this.config.rpcRequestTimeout
575
- )
576
- if (!this.bucket!.get(contact.kademliaId) && !this.neighborList!.getContact(peerIdFromPeerDescriptor(contact))) {
577
- this.neighborList!.addContact(rpcRemote)
578
- if (setActive) {
579
- const peerId = peerIdFromPeerDescriptor(contact)
580
- this.neighborList!.setActive(peerId)
581
- }
582
- this.bucket!.add(rpcRemote)
583
- } else {
584
- this.randomPeers!.addContact(rpcRemote)
585
- }
586
- }
420
+ return this.peerManager!.bucket!.count()
587
421
  }
588
422
 
589
423
  private connectToEntryPoint(entryPoint: PeerDescriptor): void {
@@ -594,14 +428,10 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
594
428
  }
595
429
 
596
430
  public removeContact(contact: PeerDescriptor): void {
597
- if (!this.started || this.stopped) {
431
+ if (!this.started) { // the stopped state is checked in PeerManager
598
432
  return
599
433
  }
600
- logger.trace(`Removing contact ${getNodeIdFromPeerDescriptor(contact)}`)
601
- const peerId = peerIdFromPeerDescriptor(contact)
602
- this.bucket!.remove(peerId.value)
603
- this.neighborList!.removeContact(peerId)
604
- this.randomPeers!.removeContact(peerId)
434
+ this.peerManager!.handlePeerLeaving(contact)
605
435
  }
606
436
 
607
437
  public async send(msg: Message): Promise<void> {
@@ -609,27 +439,27 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
609
439
  return
610
440
  }
611
441
  const reachableThrough = this.peerDiscovery!.isJoinOngoing() ? this.config.entryPoints ?? [] : []
612
- await this.router!.send(msg, reachableThrough)
442
+ this.router!.send(msg, reachableThrough)
613
443
  }
614
444
 
615
445
  public async joinDht(entryPointDescriptors: PeerDescriptor[], doAdditionalRandomPeerDiscovery?: boolean, retry?: boolean): Promise<void> {
616
446
  if (!this.started) {
617
447
  throw new Error('Cannot join DHT before calling start() on DhtNode')
618
448
  }
619
- await Promise.all(entryPointDescriptors.map((entryPoint) =>
449
+ await Promise.all(entryPointDescriptors.map((entryPoint) =>
620
450
  this.peerDiscovery!.joinDht(entryPoint, doAdditionalRandomPeerDiscovery, retry)
621
451
  ))
622
452
  }
623
453
 
624
- public async startFind(idToFind: Uint8Array, fetchData?: boolean, excludedPeer?: PeerDescriptor): Promise<FindResult> {
625
- return this.finder!.startFind(idToFind, fetchData, excludedPeer)
454
+ public async startFind(key: Uint8Array, action?: FindAction, excludedPeer?: PeerDescriptor): Promise<FindResult> {
455
+ return this.finder!.startFind(key, action, excludedPeer)
626
456
  }
627
457
 
628
- public async storeDataToDht(key: Uint8Array, data: Any): Promise<PeerDescriptor[]> {
458
+ public async storeDataToDht(key: Uint8Array, data: Any, creator?: PeerDescriptor): Promise<PeerDescriptor[]> {
629
459
  if (this.peerDiscovery!.isJoinOngoing() && this.config.entryPoints && this.config.entryPoints.length > 0) {
630
460
  return this.storeDataViaPeer(key, data, sample(this.config.entryPoints)!)
631
461
  }
632
- return this.storeRpcLocal!.storeDataToDht(key, data)
462
+ return this.storeRpcLocal!.storeDataToDht(key, data, creator ?? this.localPeerDescriptor!)
633
463
  }
634
464
 
635
465
  public async storeDataViaPeer(key: Uint8Array, data: Any, peer: PeerDescriptor): Promise<PeerDescriptor[]> {
@@ -642,28 +472,28 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
642
472
  return await rpcRemote.storeData(key, data)
643
473
  }
644
474
 
645
- public async getDataFromDht(idToFind: Uint8Array): Promise<DataEntry[]> {
475
+ public async getDataFromDht(key: Uint8Array): Promise<DataEntry[]> {
646
476
  if (this.peerDiscovery!.isJoinOngoing() && this.config.entryPoints && this.config.entryPoints.length > 0) {
647
- return this.findDataViaPeer(idToFind, sample(this.config.entryPoints)!)
477
+ return this.findDataViaPeer(key, sample(this.config.entryPoints)!)
648
478
  }
649
- const result = await this.finder!.startFind(idToFind, true)
650
- return result.dataEntries ?? []
479
+ const result = await this.finder!.startFind(key, FindAction.FETCH_DATA)
480
+ return result.dataEntries ?? [] // TODO is this fallback needed?
651
481
  }
652
482
 
653
- public async deleteDataFromDht(idToDelete: Uint8Array): Promise<void> {
483
+ public async deleteDataFromDht(key: Uint8Array, waitForCompletion: boolean): Promise<void> {
654
484
  if (!this.stopped) {
655
- return this.storeRpcLocal!.deleteDataFromDht(idToDelete)
485
+ await this.finder!.startFind(key, FindAction.DELETE_DATA, undefined, waitForCompletion)
656
486
  }
657
487
  }
658
488
 
659
- public async findDataViaPeer(idToFind: Uint8Array, peer: PeerDescriptor): Promise<DataEntry[]> {
489
+ public async findDataViaPeer(key: Uint8Array, peer: PeerDescriptor): Promise<DataEntry[]> {
660
490
  const rpcRemote = new ExternalApiRpcRemote(
661
491
  this.localPeerDescriptor!,
662
492
  peer,
663
493
  this.config.serviceId,
664
494
  toProtoRpcClient(new ExternalApiRpcClient(this.rpcCommunicator!.getRpcClientTransport()))
665
495
  )
666
- return await rpcRemote.externalFindData(idToFind)
496
+ return await rpcRemote.externalFindData(key)
667
497
  }
668
498
 
669
499
  public getTransport(): ITransport {
@@ -675,15 +505,15 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
675
505
  }
676
506
 
677
507
  public getAllConnectionPeerDescriptors(): PeerDescriptor[] {
678
- return Array.from(this.connections.values()).map((peer) => peer.getPeerDescriptor())
508
+ return Array.from(this.peerManager!.connections.values()).map((peer) => peer.getPeerDescriptor())
679
509
  }
680
510
 
681
511
  public getKBucketPeers(): PeerDescriptor[] {
682
- return this.bucket!.toArray().map((rpcRemote: DhtNodeRpcRemote) => rpcRemote.getPeerDescriptor())
512
+ return this.peerManager!.bucket!.toArray().map((rpcRemote: DhtNodeRpcRemote) => rpcRemote.getPeerDescriptor())
683
513
  }
684
514
 
685
515
  public getNumberOfConnections(): number {
686
- return this.connections.size
516
+ return this.peerManager!.getNumberOfConnections()
687
517
  }
688
518
 
689
519
  public getNumberOfLocalLockedConnections(): number {
@@ -699,7 +529,7 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
699
529
  }
700
530
 
701
531
  public async waitForNetworkConnectivity(): Promise<void> {
702
- await waitForCondition(() => this.connections.size > 0, this.config.networkConnectivityTimeout)
532
+ await waitForCondition(() => this.peerManager!.connections.size > 0, this.config.networkConnectivityTimeout)
703
533
  }
704
534
 
705
535
  public hasJoined(): boolean {
@@ -712,30 +542,33 @@ export class DhtNode extends EventEmitter<Events> implements ITransport {
712
542
  }
713
543
  logger.trace('stop()')
714
544
  this.stopped = true
715
-
545
+ await this.storeRpcLocal!.destroy()
716
546
  if (this.entryPointDisconnectTimeout) {
717
547
  clearTimeout(this.entryPointDisconnectTimeout)
718
548
  }
719
- this.bucket!.toArray().forEach((rpcRemote: DhtNodeRpcRemote) => {
720
- rpcRemote.leaveNotice()
721
- this.bucket!.remove(rpcRemote.id)
722
- })
723
- this.bucket!.removeAllListeners()
724
549
  this.localDataStore.clear()
725
- this.neighborList!.stop()
726
- this.randomPeers!.stop()
550
+ this.peerManager?.stop()
727
551
  this.rpcCommunicator!.stop()
728
552
  this.router!.stop()
729
553
  this.finder!.stop()
730
554
  this.peerDiscovery!.stop()
731
555
  if (this.config.transport === undefined) {
732
- // if the transport was not given in config, the instance was created in start() and
556
+ // if the transport was not given in config, the instance was created in start() and
733
557
  // this component is responsible for stopping it
734
558
  await this.transport!.stop()
735
559
  }
736
560
  this.transport = undefined
737
561
  this.connectionManager = undefined
738
- this.connections.clear()
739
562
  this.removeAllListeners()
740
563
  }
564
+
565
+ private createDhtNodeRpcRemote(peerDescriptor: PeerDescriptor) {
566
+ return new DhtNodeRpcRemote(
567
+ this.localPeerDescriptor!,
568
+ peerDescriptor,
569
+ toProtoRpcClient(new DhtNodeRpcClient(this.rpcCommunicator!.getRpcClientTransport())),
570
+ this.config.serviceId,
571
+ this.config.rpcRequestTimeout
572
+ )
573
+ }
741
574
  }
@@ -36,14 +36,14 @@ export class DhtNodeRpcLocal implements IDhtNodeRpc {
36
36
  async getClosestPeers(request: ClosestPeersRequest, context: ServerCallContext): Promise<ClosestPeersResponse> {
37
37
  this.config.addNewContact((context as DhtCallContext).incomingSourceDescriptor!)
38
38
  const response = {
39
- peers: this.getClosestPeerDescriptors(request.kademliaId, this.config.peerDiscoveryQueryBatchSize),
39
+ peers: this.getClosestPeerDescriptors(request.nodeId, this.config.peerDiscoveryQueryBatchSize),
40
40
  requestId: request.requestId
41
41
  }
42
42
  return response
43
43
  }
44
44
 
45
- private getClosestPeerDescriptors(kademliaId: Uint8Array, limit: number): PeerDescriptor[] {
46
- const closestPeers = this.config.bucket.closest(kademliaId, limit)
45
+ private getClosestPeerDescriptors(nodeId: Uint8Array, limit: number): PeerDescriptor[] {
46
+ const closestPeers = this.config.bucket.closest(nodeId, limit)
47
47
  return closestPeers.map((rpcRemote: DhtNodeRpcRemote) => rpcRemote.getPeerDescriptor())
48
48
  }
49
49