@libp2p/kad-dht 0.28.7 → 1.0.2

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 (113) hide show
  1. package/dist/src/content-fetching/index.d.ts +6 -9
  2. package/dist/src/content-fetching/index.d.ts.map +1 -1
  3. package/dist/src/content-fetching/index.js +14 -11
  4. package/dist/src/content-fetching/index.js.map +1 -1
  5. package/dist/src/content-routing/index.d.ts +6 -9
  6. package/dist/src/content-routing/index.d.ts.map +1 -1
  7. package/dist/src/content-routing/index.js +15 -13
  8. package/dist/src/content-routing/index.js.map +1 -1
  9. package/dist/src/dual-kad-dht.d.ts +6 -6
  10. package/dist/src/dual-kad-dht.d.ts.map +1 -1
  11. package/dist/src/dual-kad-dht.js +9 -4
  12. package/dist/src/dual-kad-dht.js.map +1 -1
  13. package/dist/src/index.d.ts +14 -3
  14. package/dist/src/index.d.ts.map +1 -1
  15. package/dist/src/index.js +14 -12
  16. package/dist/src/index.js.map +1 -1
  17. package/dist/src/kad-dht.d.ts +12 -52
  18. package/dist/src/kad-dht.d.ts.map +1 -1
  19. package/dist/src/kad-dht.js +45 -48
  20. package/dist/src/kad-dht.js.map +1 -1
  21. package/dist/src/network.d.ts +7 -7
  22. package/dist/src/network.d.ts.map +1 -1
  23. package/dist/src/network.js +10 -6
  24. package/dist/src/network.js.map +1 -1
  25. package/dist/src/peer-routing/index.d.ts +6 -8
  26. package/dist/src/peer-routing/index.d.ts.map +1 -1
  27. package/dist/src/peer-routing/index.js +18 -16
  28. package/dist/src/peer-routing/index.js.map +1 -1
  29. package/dist/src/providers.d.ts +6 -6
  30. package/dist/src/providers.d.ts.map +1 -1
  31. package/dist/src/providers.js +11 -7
  32. package/dist/src/providers.js.map +1 -1
  33. package/dist/src/query/manager.d.ts +6 -8
  34. package/dist/src/query/manager.d.ts.map +1 -1
  35. package/dist/src/query/manager.js +10 -7
  36. package/dist/src/query/manager.js.map +1 -1
  37. package/dist/src/query/query-path.d.ts.map +1 -1
  38. package/dist/src/query/query-path.js +2 -3
  39. package/dist/src/query/query-path.js.map +1 -1
  40. package/dist/src/query-self.d.ts +6 -6
  41. package/dist/src/query-self.d.ts.map +1 -1
  42. package/dist/src/query-self.js +8 -4
  43. package/dist/src/query-self.js.map +1 -1
  44. package/dist/src/routing-table/index.d.ts +10 -14
  45. package/dist/src/routing-table/index.d.ts.map +1 -1
  46. package/dist/src/routing-table/index.js +12 -10
  47. package/dist/src/routing-table/index.js.map +1 -1
  48. package/dist/src/routing-table/refresh.d.ts +5 -3
  49. package/dist/src/routing-table/refresh.d.ts.map +1 -1
  50. package/dist/src/routing-table/refresh.js +4 -2
  51. package/dist/src/routing-table/refresh.js.map +1 -1
  52. package/dist/src/rpc/handlers/add-provider.d.ts +5 -3
  53. package/dist/src/rpc/handlers/add-provider.d.ts.map +1 -1
  54. package/dist/src/rpc/handlers/add-provider.js +4 -2
  55. package/dist/src/rpc/handlers/add-provider.js.map +1 -1
  56. package/dist/src/rpc/handlers/find-node.d.ts +5 -3
  57. package/dist/src/rpc/handlers/find-node.d.ts.map +1 -1
  58. package/dist/src/rpc/handlers/find-node.js +4 -2
  59. package/dist/src/rpc/handlers/find-node.js.map +1 -1
  60. package/dist/src/rpc/handlers/get-providers.d.ts +6 -6
  61. package/dist/src/rpc/handlers/get-providers.d.ts.map +1 -1
  62. package/dist/src/rpc/handlers/get-providers.js +8 -4
  63. package/dist/src/rpc/handlers/get-providers.js.map +1 -1
  64. package/dist/src/rpc/handlers/get-value.d.ts +6 -9
  65. package/dist/src/rpc/handlers/get-value.d.ts.map +1 -1
  66. package/dist/src/rpc/handlers/get-value.js +10 -7
  67. package/dist/src/rpc/handlers/get-value.js.map +1 -1
  68. package/dist/src/rpc/handlers/ping.d.ts +3 -1
  69. package/dist/src/rpc/handlers/ping.d.ts.map +1 -1
  70. package/dist/src/rpc/handlers/ping.js +2 -0
  71. package/dist/src/rpc/handlers/ping.js.map +1 -1
  72. package/dist/src/rpc/handlers/put-value.d.ts +7 -8
  73. package/dist/src/rpc/handlers/put-value.d.ts.map +1 -1
  74. package/dist/src/rpc/handlers/put-value.js +10 -7
  75. package/dist/src/rpc/handlers/put-value.js.map +1 -1
  76. package/dist/src/rpc/index.d.ts +6 -10
  77. package/dist/src/rpc/index.d.ts.map +1 -1
  78. package/dist/src/rpc/index.js +14 -9
  79. package/dist/src/rpc/index.js.map +1 -1
  80. package/dist/src/topology-listener.d.ts +6 -6
  81. package/dist/src/topology-listener.d.ts.map +1 -1
  82. package/dist/src/topology-listener.js +9 -5
  83. package/dist/src/topology-listener.js.map +1 -1
  84. package/package.json +21 -21
  85. package/src/content-fetching/index.ts +17 -19
  86. package/src/content-routing/index.ts +18 -21
  87. package/src/dual-kad-dht.ts +12 -9
  88. package/src/index.ts +22 -14
  89. package/src/kad-dht.ts +59 -117
  90. package/src/network.ts +14 -12
  91. package/src/peer-routing/index.ts +21 -23
  92. package/src/providers.ts +14 -11
  93. package/src/query/manager.ts +13 -14
  94. package/src/query/query-path.ts +2 -3
  95. package/src/query-self.ts +11 -9
  96. package/src/routing-table/index.ts +20 -23
  97. package/src/routing-table/refresh.ts +9 -4
  98. package/src/rpc/handlers/add-provider.ts +9 -4
  99. package/src/rpc/handlers/find-node.ts +9 -4
  100. package/src/rpc/handlers/get-providers.ts +11 -9
  101. package/src/rpc/handlers/get-value.ts +13 -15
  102. package/src/rpc/handlers/ping.ts +6 -1
  103. package/src/rpc/handlers/put-value.ts +14 -15
  104. package/src/rpc/index.ts +19 -18
  105. package/src/topology-listener.ts +12 -10
  106. package/dist/src/routing-table/types.d.ts +0 -24
  107. package/dist/src/routing-table/types.d.ts.map +0 -1
  108. package/dist/src/rpc/handlers/index.d.ts +0 -13
  109. package/dist/src/rpc/handlers/index.d.ts.map +0 -1
  110. package/dist/src/rpc/types.d.ts +0 -6
  111. package/dist/src/rpc/types.d.ts.map +0 -1
  112. package/dist/src/types.d.ts +0 -143
  113. package/dist/src/types.d.ts.map +0 -1
@@ -12,7 +12,6 @@ import type { EventEmitter } from '@libp2p/interfaces'
12
12
  import type { CleanUpEvents } from './manager.js'
13
13
  import type { Logger } from '@libp2p/logger'
14
14
  import type { QueryFunc } from '../query/types.js'
15
- import { base58btc } from 'multiformats/bases/base58'
16
15
  import type { QueryEvent } from '@libp2p/interfaces/dht'
17
16
 
18
17
  const MAX_XOR = BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF')
@@ -101,7 +100,7 @@ export async function * queryPath (options: QueryPathOptions) {
101
100
  return
102
101
  }
103
102
 
104
- peersSeen.add(peer.toString(base58btc))
103
+ peersSeen.add(peer.toString())
105
104
 
106
105
  const peerXor = BigInt('0x' + toString(xor(peerKadId, kadId), 'base16'))
107
106
 
@@ -131,7 +130,7 @@ export async function * queryPath (options: QueryPathOptions) {
131
130
  // if there are closer peers and the query has not completed, continue the query
132
131
  if (event.name === 'PEER_RESPONSE') {
133
132
  for (const closerPeer of event.closer) {
134
- if (peersSeen.has(closerPeer.id.toString(base58btc))) { // eslint-disable-line max-depth
133
+ if (peersSeen.has(closerPeer.id.toString())) { // eslint-disable-line max-depth
135
134
  log('already seen %p in query', closerPeer.id)
136
135
  continue
137
136
  }
package/src/query-self.ts CHANGED
@@ -7,12 +7,11 @@ import { TimeoutController } from 'timeout-abort-controller'
7
7
  import { anySignal } from 'any-signal'
8
8
  import { logger, Logger } from '@libp2p/logger'
9
9
  import type { PeerRouting } from './peer-routing/index.js'
10
- import type { PeerId } from '@libp2p/interfaces/peer-id'
11
10
  import type { Startable } from '@libp2p/interfaces'
12
11
  import { pipe } from 'it-pipe'
12
+ import { Components, Initializable } from '@libp2p/interfaces/components'
13
13
 
14
- export interface QuerySelfOptions {
15
- peerId: PeerId
14
+ export interface QuerySelfInit {
16
15
  lan: boolean
17
16
  peerRouting: PeerRouting
18
17
  count?: number
@@ -23,9 +22,9 @@ export interface QuerySelfOptions {
23
22
  /**
24
23
  * Receives notifications of new peers joining the network that support the DHT protocol
25
24
  */
26
- export class QuerySelf implements Startable {
25
+ export class QuerySelf implements Startable, Initializable {
27
26
  private readonly log: Logger
28
- private readonly peerId: PeerId
27
+ private components: Components = new Components()
29
28
  private readonly peerRouting: PeerRouting
30
29
  private readonly count: number
31
30
  private readonly interval: number
@@ -34,18 +33,21 @@ export class QuerySelf implements Startable {
34
33
  private timeoutId?: NodeJS.Timer
35
34
  private controller?: AbortController
36
35
 
37
- constructor (options: QuerySelfOptions) {
38
- const { peerId, peerRouting, lan, count, interval, queryTimeout } = options
36
+ constructor (init: QuerySelfInit) {
37
+ const { peerRouting, lan, count, interval, queryTimeout } = init
39
38
 
40
39
  this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:query-self`)
41
40
  this.running = false
42
- this.peerId = peerId
43
41
  this.peerRouting = peerRouting
44
42
  this.count = count ?? K
45
43
  this.interval = interval ?? QUERY_SELF_INTERVAL
46
44
  this.queryTimeout = queryTimeout ?? QUERY_SELF_TIMEOUT
47
45
  }
48
46
 
47
+ init (components: Components): void {
48
+ this.components = components
49
+ }
50
+
49
51
  isStarted () {
50
52
  return this.running
51
53
  }
@@ -85,7 +87,7 @@ export class QuerySelf implements Startable {
85
87
  }
86
88
  } catch {} // fails on node < 15.4
87
89
  const found = await pipe(
88
- this.peerRouting.getClosestPeers(this.peerId.toBytes(), {
90
+ this.peerRouting.getClosestPeers(this.components.getPeerId().toBytes(), {
89
91
  signal
90
92
  }),
91
93
  (source) => take(source, this.count),
@@ -6,9 +6,9 @@ import { PROTOCOL_DHT } from '../constants.js'
6
6
  import { TimeoutController } from 'timeout-abort-controller'
7
7
  import { logger } from '@libp2p/logger'
8
8
  import type { PeerId } from '@libp2p/interfaces/peer-id'
9
- import type { Dialer, Startable } from '@libp2p/interfaces'
10
- import type { ComponentMetricsTracker } from '@libp2p/interfaces/metrics'
9
+ import type { Startable } from '@libp2p/interfaces'
11
10
  import type { Logger } from '@libp2p/logger'
11
+ import { Components, Initializable } from '@libp2p/interfaces/components'
12
12
 
13
13
  export interface KBucketPeer {
14
14
  id: Uint8Array
@@ -38,11 +38,8 @@ export interface KBucketTree {
38
38
 
39
39
  const METRIC_ROUTING_TABLE_SIZE = 'routing-table-size'
40
40
 
41
- export interface RoutingTableOptions {
42
- peerId: PeerId
43
- dialer: Dialer
41
+ export interface RoutingTableInit {
44
42
  lan: boolean
45
- metrics?: ComponentMetricsTracker
46
43
  kBucketSize?: number
47
44
  pingTimeout?: number
48
45
  }
@@ -51,34 +48,34 @@ export interface RoutingTableOptions {
51
48
  * A wrapper around `k-bucket`, to provide easy store and
52
49
  * retrieval for peers.
53
50
  */
54
- export class RoutingTable implements Startable {
51
+ export class RoutingTable implements Startable, Initializable {
52
+ public kBucketSize: number
53
+ public kb?: KBucketTree
54
+ public pingQueue: Queue
55
+
55
56
  private readonly log: Logger
56
- private readonly peerId: PeerId
57
- public dialer: Dialer
57
+ private components: Components = new Components()
58
58
  private readonly lan: boolean
59
- private readonly metrics?: ComponentMetricsTracker
60
- public kBucketSize: number
61
59
  private readonly pingTimeout: number
62
- public kb?: KBucketTree
63
60
  private running: boolean
64
- public pingQueue: Queue
65
61
 
66
- constructor (options: RoutingTableOptions) {
67
- const { peerId, dialer, kBucketSize, pingTimeout, lan, metrics } = options
62
+ constructor (init: RoutingTableInit) {
63
+ const { kBucketSize, pingTimeout, lan } = init
68
64
 
69
65
  this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:routing-table`)
70
- this.peerId = peerId
71
- this.dialer = dialer
72
66
  this.kBucketSize = kBucketSize ?? 20
73
67
  this.pingTimeout = pingTimeout ?? 10000
74
68
  this.lan = lan
75
- this.metrics = metrics
76
69
  this.pingQueue = new Queue({ concurrency: 1 })
77
70
  this.running = false
78
71
 
79
72
  this._onPing = this._onPing.bind(this)
80
73
  }
81
74
 
75
+ init (components: Components): void {
76
+ this.components = components
77
+ }
78
+
82
79
  isStarted () {
83
80
  return this.running
84
81
  }
@@ -87,7 +84,7 @@ export class RoutingTable implements Startable {
87
84
  this.running = true
88
85
 
89
86
  const kBuck = new KBuck({
90
- localNodeId: await utils.convertPeerId(this.peerId),
87
+ localNodeId: await utils.convertPeerId(this.components.getPeerId()),
91
88
  numberOfNodesPerKBucket: this.kBucketSize,
92
89
  numberOfNodesToPing: 1
93
90
  })
@@ -131,7 +128,7 @@ export class RoutingTable implements Startable {
131
128
  timeoutController = new TimeoutController(this.pingTimeout)
132
129
 
133
130
  this.log('pinging old contact %p', oldContact.peer)
134
- const { stream } = await this.dialer.dialProtocol(oldContact.peer, PROTOCOL_DHT, {
131
+ const { stream } = await this.components.getDialer().dialProtocol(oldContact.peer, PROTOCOL_DHT, {
135
132
  signal: timeoutController.signal
136
133
  })
137
134
  await stream.close()
@@ -149,7 +146,7 @@ export class RoutingTable implements Startable {
149
146
  timeoutController.clear()
150
147
  }
151
148
 
152
- this.metrics?.updateComponentMetric({
149
+ this.components.getMetrics()?.updateComponentMetric({
153
150
  system: 'libp2p',
154
151
  component: `kad-dht-${this.lan ? 'lan' : 'wan'}`,
155
152
  metric: METRIC_ROUTING_TABLE_SIZE,
@@ -235,7 +232,7 @@ export class RoutingTable implements Startable {
235
232
 
236
233
  this.log('added %p with kad id %b', peer, id)
237
234
 
238
- this.metrics?.updateComponentMetric({
235
+ this.components.getMetrics()?.updateComponentMetric({
239
236
  system: 'libp2p',
240
237
  component: `kad-dht-${this.lan ? 'lan' : 'wan'}`,
241
238
  metric: METRIC_ROUTING_TABLE_SIZE,
@@ -255,7 +252,7 @@ export class RoutingTable implements Startable {
255
252
 
256
253
  this.kb.remove(id)
257
254
 
258
- this.metrics?.updateComponentMetric({
255
+ this.components.getMetrics()?.updateComponentMetric({
259
256
  system: 'libp2p',
260
257
  component: `kad-dht-${this.lan ? 'lan' : 'wan'}`,
261
258
  metric: METRIC_ROUTING_TABLE_SIZE,
@@ -10,13 +10,14 @@ import { TABLE_REFRESH_INTERVAL, TABLE_REFRESH_QUERY_TIMEOUT } from '../constant
10
10
  import type { RoutingTable } from './index.js'
11
11
  import type { Logger } from '@libp2p/logger'
12
12
  import type { PeerRouting } from '../peer-routing/index.js'
13
+ import type { Components, Initializable } from '@libp2p/interfaces/components'
13
14
 
14
15
  /**
15
16
  * Cannot generate random KadIds longer than this + 1
16
17
  */
17
18
  const MAX_COMMON_PREFIX_LENGTH = 15
18
19
 
19
- export interface RoutingTableRefreshOptions {
20
+ export interface RoutingTableRefreshInit {
20
21
  peerRouting: PeerRouting
21
22
  routingTable: RoutingTable
22
23
  lan: boolean
@@ -28,7 +29,7 @@ export interface RoutingTableRefreshOptions {
28
29
  * A wrapper around `k-bucket`, to provide easy store and
29
30
  * retrieval for peers.
30
31
  */
31
- export class RoutingTableRefresh {
32
+ export class RoutingTableRefresh implements Initializable {
32
33
  private readonly log: Logger
33
34
  private readonly peerRouting: PeerRouting
34
35
  private readonly routingTable: RoutingTable
@@ -37,8 +38,8 @@ export class RoutingTableRefresh {
37
38
  private readonly commonPrefixLengthRefreshedAt: Date[]
38
39
  private refreshTimeoutId?: NodeJS.Timer
39
40
 
40
- constructor (options: RoutingTableRefreshOptions) {
41
- const { peerRouting, routingTable, refreshInterval, refreshQueryTimeout, lan } = options
41
+ constructor (init: RoutingTableRefreshInit) {
42
+ const { peerRouting, routingTable, refreshInterval, refreshQueryTimeout, lan } = init
42
43
  this.log = logger(`libp2p:kad-dht:${lan ? 'lan' : 'wan'}:routing-table:refresh`)
43
44
  this.peerRouting = peerRouting
44
45
  this.routingTable = routingTable
@@ -49,6 +50,10 @@ export class RoutingTableRefresh {
49
50
  this.refreshTable = this.refreshTable.bind(this)
50
51
  }
51
52
 
53
+ init (components: Components): void {
54
+
55
+ }
56
+
52
57
  async start () {
53
58
  this.log(`refreshing routing table every ${this.refreshInterval}ms`)
54
59
  this.refreshTable(true)
@@ -5,21 +5,26 @@ import type { Providers } from '../../providers'
5
5
  import type { PeerId } from '@libp2p/interfaces/peer-id'
6
6
  import type { DHTMessageHandler } from '../index.js'
7
7
  import type { Message } from '../../message/index.js'
8
+ import type { Initializable } from '@libp2p/interfaces/components'
8
9
 
9
10
  const log = logger('libp2p:kad-dht:rpc:handlers:add-provider')
10
11
 
11
- export interface AddProviderHandlerOptions {
12
+ export interface AddProviderHandlerInit {
12
13
  providers: Providers
13
14
  }
14
15
 
15
- export class AddProviderHandler implements DHTMessageHandler {
16
+ export class AddProviderHandler implements DHTMessageHandler, Initializable {
16
17
  private readonly providers: Providers
17
18
 
18
- constructor (options: AddProviderHandlerOptions) {
19
- const { providers } = options
19
+ constructor (init: AddProviderHandlerInit) {
20
+ const { providers } = init
20
21
  this.providers = providers
21
22
  }
22
23
 
24
+ init (): void {
25
+
26
+ }
27
+
23
28
  async handle (peerId: PeerId, msg: Message) {
24
29
  log('start')
25
30
 
@@ -11,24 +11,29 @@ import type { PeerId } from '@libp2p/interfaces/peer-id'
11
11
  import map from 'it-map'
12
12
  import filter from 'it-filter'
13
13
  import all from 'it-all'
14
+ import type { Initializable } from '@libp2p/interfaces/components'
14
15
 
15
16
  const log = logger('libp2p:kad-dht:rpc:handlers:find-node')
16
17
 
17
- export interface FindNodeHandlerOptions {
18
+ export interface FindNodeHandlerInit {
18
19
  peerRouting: PeerRouting
19
20
  lan: boolean
20
21
  }
21
22
 
22
- export class FindNodeHandler implements DHTMessageHandler {
23
+ export class FindNodeHandler implements DHTMessageHandler, Initializable {
23
24
  private readonly peerRouting: PeerRouting
24
25
  private readonly lan: boolean
25
26
 
26
- constructor (options: FindNodeHandlerOptions) {
27
- const { peerRouting, lan } = options
27
+ constructor (init: FindNodeHandlerInit) {
28
+ const { peerRouting, lan } = init
28
29
  this.peerRouting = peerRouting
29
30
  this.lan = Boolean(lan)
30
31
  }
31
32
 
33
+ init (): void {
34
+
35
+ }
36
+
32
37
  /**
33
38
  * Process `FindNode` DHT messages
34
39
  */
@@ -8,35 +8,37 @@ import {
8
8
  import { logger } from '@libp2p/logger'
9
9
  import type { DHTMessageHandler } from '../index.js'
10
10
  import type { Providers } from '../../providers.js'
11
- import type { AddressBook } from '@libp2p/interfaces/peer-store'
12
11
  import type { PeerRouting } from '../../peer-routing/index.js'
13
12
  import type { PeerId } from '@libp2p/interfaces/peer-id'
14
13
  import type { PeerData } from '@libp2p/interfaces/peer-data'
14
+ import { Components, Initializable } from '@libp2p/interfaces/components'
15
15
 
16
16
  const log = logger('libp2p:kad-dht:rpc:handlers:get-providers')
17
17
 
18
- export interface GetProvidersHandlerOptions {
18
+ export interface GetProvidersHandlerInit {
19
19
  peerRouting: PeerRouting
20
20
  providers: Providers
21
- addressBook: AddressBook
22
21
  lan: boolean
23
22
  }
24
23
 
25
- export class GetProvidersHandler implements DHTMessageHandler {
24
+ export class GetProvidersHandler implements DHTMessageHandler, Initializable {
25
+ private components: Components = new Components()
26
26
  private readonly peerRouting: PeerRouting
27
27
  private readonly providers: Providers
28
- private readonly addressBook: AddressBook
29
28
  private readonly lan: boolean
30
29
 
31
- constructor (options: GetProvidersHandlerOptions) {
32
- const { peerRouting, providers, addressBook, lan } = options
30
+ constructor (init: GetProvidersHandlerInit) {
31
+ const { peerRouting, providers, lan } = init
33
32
 
34
33
  this.peerRouting = peerRouting
35
34
  this.providers = providers
36
- this.addressBook = addressBook
37
35
  this.lan = Boolean(lan)
38
36
  }
39
37
 
38
+ init (components: Components): void {
39
+ this.components = components
40
+ }
41
+
40
42
  async handle (peerId: PeerId, msg: Message) {
41
43
  let cid
42
44
  try {
@@ -69,7 +71,7 @@ export class GetProvidersHandler implements DHTMessageHandler {
69
71
  }
70
72
 
71
73
  async _getAddresses (peerId: PeerId) {
72
- const addrs = await this.addressBook.get(peerId)
74
+ const addrs = await this.components.getPeerStore().addressBook.get(peerId)
73
75
 
74
76
  return addrs.map(address => address.multiaddr)
75
77
  }
@@ -7,30 +7,28 @@ import {
7
7
  import { bufferToRecordKey, isPublicKeyKey, fromPublicKeyKey } from '../../utils.js'
8
8
  import { logger } from '@libp2p/logger'
9
9
  import type { DHTMessageHandler } from '../index.js'
10
- import type { Datastore } from 'interface-datastore'
11
10
  import type { PeerId } from '@libp2p/interfaces/peer-id'
12
- import type { KeyBook } from '@libp2p/interfaces/peer-store'
13
11
  import type { PeerRouting } from '../../peer-routing/index.js'
12
+ import { Components, Initializable } from '@libp2p/interfaces/components'
14
13
 
15
14
  const log = logger('libp2p:kad-dht:rpc:handlers:get-value')
16
15
 
17
- export interface GetValueHandlerOptions {
18
- keyBook: KeyBook
16
+ export interface GetValueHandlerInit {
19
17
  peerRouting: PeerRouting
20
- datastore: Datastore
21
18
  }
22
19
 
23
- export class GetValueHandler implements DHTMessageHandler {
24
- private readonly keyBook: KeyBook
20
+ export class GetValueHandler implements DHTMessageHandler, Initializable {
21
+ private components: Components = new Components()
25
22
  private readonly peerRouting: PeerRouting
26
- private readonly datastore: Datastore
27
23
 
28
- constructor (options: GetValueHandlerOptions) {
29
- const { keyBook, peerRouting, datastore } = options
24
+ constructor (init: GetValueHandlerInit) {
25
+ const { peerRouting } = init
30
26
 
31
- this.keyBook = keyBook
32
27
  this.peerRouting = peerRouting
33
- this.datastore = datastore
28
+ }
29
+
30
+ init (components: Components): void {
31
+ this.components = components
34
32
  }
35
33
 
36
34
  async handle (peerId: PeerId, msg: Message) {
@@ -50,7 +48,7 @@ export class GetValueHandler implements DHTMessageHandler {
50
48
  let pubKey: Uint8Array | undefined
51
49
 
52
50
  try {
53
- const key = await this.keyBook.get(idFromKey)
51
+ const key = await this.components.getPeerStore().keyBook.get(idFromKey)
54
52
 
55
53
  if (key == null) {
56
54
  throw errcode(new Error('No public key found in key book'), 'ERR_NOT_FOUND')
@@ -101,7 +99,7 @@ export class GetValueHandler implements DHTMessageHandler {
101
99
  // Fetch value from ds
102
100
  let rawRecord
103
101
  try {
104
- rawRecord = await this.datastore.get(dsKey)
102
+ rawRecord = await this.components.getDatastore().get(dsKey)
105
103
  } catch (err: any) {
106
104
  if (err.code === 'ERR_NOT_FOUND') {
107
105
  return undefined
@@ -120,7 +118,7 @@ export class GetValueHandler implements DHTMessageHandler {
120
118
  if (record.timeReceived == null ||
121
119
  Date.now() - record.timeReceived.getTime() > MAX_RECORD_AGE) {
122
120
  // If record is bad delete it and return
123
- await this.datastore.delete(dsKey)
121
+ await this.components.getDatastore().delete(dsKey)
124
122
  return undefined
125
123
  }
126
124
 
@@ -2,12 +2,17 @@ import { logger } from '@libp2p/logger'
2
2
  import type { Message } from '../../message/index.js'
3
3
  import type { DHTMessageHandler } from '../index.js'
4
4
  import type { PeerId } from '@libp2p/interfaces/peer-id'
5
+ import type { Initializable } from '@libp2p/interfaces/components'
5
6
 
6
7
  const log = logger('libp2p:kad-dht:rpc:handlers:ping')
7
8
 
8
- export class PingHandler implements DHTMessageHandler {
9
+ export class PingHandler implements DHTMessageHandler, Initializable {
9
10
  async handle (peerId: PeerId, msg: Message) {
10
11
  log('ping from %p', peerId)
11
12
  return msg
12
13
  }
14
+
15
+ init (): void {
16
+
17
+ }
13
18
  }
@@ -4,29 +4,28 @@ import { verifyRecord } from '@libp2p/record/validators'
4
4
  import { Logger, logger } from '@libp2p/logger'
5
5
  import type { DHTMessageHandler } from '../index.js'
6
6
  import type { Validators } from '@libp2p/interfaces/dht'
7
- import type { Datastore } from 'interface-datastore'
8
7
  import type { PeerId } from '@libp2p/interfaces/peer-id'
9
8
  import type { Message } from '../../message/index.js'
10
- import { base58btc } from 'multiformats/bases/base58'
9
+ import { Components, Initializable } from '@libp2p/interfaces/components'
11
10
 
12
- export interface PutValueHandlerOptions {
13
- peerId: PeerId
11
+ export interface PutValueHandlerInit {
14
12
  validators: Validators
15
- datastore: Datastore
16
13
  }
17
14
 
18
- export class PutValueHandler implements DHTMessageHandler {
19
- private readonly validators: Validators
20
- private readonly datastore: Datastore
15
+ export class PutValueHandler implements DHTMessageHandler, Initializable {
21
16
  private readonly log: Logger
17
+ private components: Components = new Components()
18
+ private readonly validators: Validators
22
19
 
23
- constructor (options: PutValueHandlerOptions) {
24
- const { validators, datastore, peerId } = options
25
-
26
- this.log = logger('libp2p:kad-dht:rpc:handlers:put-value:' + peerId.toString())
20
+ constructor (init: PutValueHandlerInit) {
21
+ const { validators } = init
27
22
 
23
+ this.log = logger('libp2p:kad-dht:rpc:handlers:put-value')
28
24
  this.validators = validators
29
- this.datastore = datastore
25
+ }
26
+
27
+ init (components: Components): void {
28
+ this.components = components
30
29
  }
31
30
 
32
31
  async handle (peerId: PeerId, msg: Message) {
@@ -36,7 +35,7 @@ export class PutValueHandler implements DHTMessageHandler {
36
35
  const record = msg.record
37
36
 
38
37
  if (record == null) {
39
- const errMsg = `Empty record from: ${peerId.toString(base58btc)}`
38
+ const errMsg = `Empty record from: ${peerId.toString()}`
40
39
 
41
40
  this.log.error(errMsg)
42
41
  throw errcode(new Error(errMsg), 'ERR_EMPTY_RECORD')
@@ -47,7 +46,7 @@ export class PutValueHandler implements DHTMessageHandler {
47
46
 
48
47
  record.timeReceived = new Date()
49
48
  const recordKey = bufferToRecordKey(record.key)
50
- await this.datastore.put(recordKey, record.serialize())
49
+ await this.components.getDatastore().put(recordKey, record.serialize())
51
50
  this.log('put record for %b into datastore under key %k', key, recordKey)
52
51
  } catch (err: any) {
53
52
  this.log('did not put record for key %b into datastore %o', key, err)
package/src/rpc/index.ts CHANGED
@@ -11,49 +11,50 @@ import { GetValueHandler } from './handlers/get-value.js'
11
11
  import { PingHandler } from './handlers/ping.js'
12
12
  import { PutValueHandler } from './handlers/put-value.js'
13
13
  import type { IncomingStreamData } from '@libp2p/interfaces/registrar'
14
- import type { KeyBook, AddressBook } from '@libp2p/interfaces/peer-store'
15
14
  import type { Providers } from '../providers'
16
15
  import type { PeerRouting } from '../peer-routing'
17
- import type { Datastore } from 'interface-datastore'
18
16
  import type { Validators } from '@libp2p/interfaces/dht'
17
+ import type { Components, Initializable } from '@libp2p/interfaces/components'
19
18
 
20
19
  export interface DHTMessageHandler {
21
20
  handle: (peerId: PeerId, msg: Message) => Promise<Message | undefined>
22
21
  }
23
22
 
24
- export interface RPCOptions {
25
- peerId: PeerId
23
+ export interface RPCInit {
26
24
  routingTable: RoutingTable
27
- keyBook: KeyBook
28
- addressBook: AddressBook
29
25
  providers: Providers
30
26
  peerRouting: PeerRouting
31
- datastore: Datastore
32
27
  validators: Validators
33
28
  lan: boolean
34
29
  }
35
30
 
36
- export class RPC {
37
- private readonly handlers: Record<number, DHTMessageHandler>
31
+ export class RPC implements Initializable {
32
+ private readonly handlers: Record<number, DHTMessageHandler & Initializable>
38
33
  private readonly routingTable: RoutingTable
39
34
  private readonly log: Logger
40
35
 
41
- constructor (options: RPCOptions) {
42
- const { keyBook, addressBook, providers, peerRouting, datastore, validators, lan, peerId } = options
36
+ constructor (init: RPCInit) {
37
+ const { providers, peerRouting, validators, lan } = init
43
38
 
44
- this.log = logger('libp2p:kad-dht:rpc:' + peerId.toString())
39
+ this.log = logger('libp2p:kad-dht:rpc')
45
40
 
46
- this.routingTable = options.routingTable
41
+ this.routingTable = init.routingTable
47
42
  this.handlers = {
48
- [MESSAGE_TYPE.GET_VALUE]: new GetValueHandler({ keyBook, peerRouting, datastore }),
49
- [MESSAGE_TYPE.PUT_VALUE]: new PutValueHandler({ peerId, validators, datastore }),
43
+ [MESSAGE_TYPE.GET_VALUE]: new GetValueHandler({ peerRouting }),
44
+ [MESSAGE_TYPE.PUT_VALUE]: new PutValueHandler({ validators }),
50
45
  [MESSAGE_TYPE.FIND_NODE]: new FindNodeHandler({ peerRouting, lan }),
51
46
  [MESSAGE_TYPE.ADD_PROVIDER]: new AddProviderHandler({ providers }),
52
- [MESSAGE_TYPE.GET_PROVIDERS]: new GetProvidersHandler({ peerRouting, providers, addressBook, lan }),
47
+ [MESSAGE_TYPE.GET_PROVIDERS]: new GetProvidersHandler({ peerRouting, providers, lan }),
53
48
  [MESSAGE_TYPE.PING]: new PingHandler()
54
49
  }
55
50
  }
56
51
 
52
+ init (components: Components): void {
53
+ for (const handler of Object.values(this.handlers)) {
54
+ handler.init(components)
55
+ }
56
+ }
57
+
57
58
  /**
58
59
  * Process incoming DHT messages
59
60
  */
@@ -78,9 +79,9 @@ export class RPC {
78
79
  /**
79
80
  * Handle incoming streams on the dht protocol
80
81
  */
81
- onIncomingStream (evt: CustomEvent<IncomingStreamData>) {
82
+ onIncomingStream (data: IncomingStreamData) {
82
83
  Promise.resolve().then(async () => {
83
- const { stream, connection } = evt.detail
84
+ const { stream, connection } = data
84
85
  const peerId = connection.remotePeer
85
86
 
86
87
  try {
@@ -1,13 +1,12 @@
1
1
  import { createTopology } from '@libp2p/topology'
2
2
  import { CustomEvent, EventEmitter } from '@libp2p/interfaces'
3
3
  import { logger } from '@libp2p/logger'
4
- import type { Registrar } from '@libp2p/interfaces/registrar'
5
4
  import type { Logger } from '@libp2p/logger'
6
5
  import type { Startable } from '@libp2p/interfaces'
7
6
  import type { PeerId } from '@libp2p/interfaces/peer-id'
7
+ import { Components, Initializable } from '@libp2p/interfaces/components'
8
8
 
9
- export interface TopologyListenerOptions {
10
- registrar: Registrar
9
+ export interface TopologyListenerInit {
11
10
  protocol: string
12
11
  lan: boolean
13
12
  }
@@ -19,24 +18,27 @@ export interface TopologyListenerEvents {
19
18
  /**
20
19
  * Receives notifications of new peers joining the network that support the DHT protocol
21
20
  */
22
- export class TopologyListener extends EventEmitter<TopologyListenerEvents> implements Startable {
21
+ export class TopologyListener extends EventEmitter<TopologyListenerEvents> implements Startable, Initializable {
23
22
  private readonly log: Logger
24
- private readonly registrar: Registrar
23
+ private components: Components = new Components()
25
24
  private readonly protocol: string
26
25
  private running: boolean
27
26
  private registrarId?: string
28
27
 
29
- constructor (options: TopologyListenerOptions) {
28
+ constructor (init: TopologyListenerInit) {
30
29
  super()
31
30
 
32
- const { registrar, protocol, lan } = options
31
+ const { protocol, lan } = init
33
32
 
34
33
  this.log = logger(`libp2p:kad-dht:topology-listener:${lan ? 'lan' : 'wan'}`)
35
34
  this.running = false
36
- this.registrar = registrar
37
35
  this.protocol = protocol
38
36
  }
39
37
 
38
+ init (components: Components): void {
39
+ this.components = components
40
+ }
41
+
40
42
  isStarted () {
41
43
  return this.running
42
44
  }
@@ -60,7 +62,7 @@ export class TopologyListener extends EventEmitter<TopologyListenerEvents> imple
60
62
  }))
61
63
  }
62
64
  })
63
- this.registrarId = await this.registrar.register(this.protocol, topology)
65
+ this.registrarId = await this.components.getRegistrar().register(this.protocol, topology)
64
66
  }
65
67
 
66
68
  /**
@@ -71,7 +73,7 @@ export class TopologyListener extends EventEmitter<TopologyListenerEvents> imple
71
73
 
72
74
  // unregister protocol and handlers
73
75
  if (this.registrarId != null) {
74
- this.registrar.unregister(this.registrarId)
76
+ this.components.getRegistrar().unregister(this.registrarId)
75
77
  this.registrarId = undefined
76
78
  }
77
79
  }