@libp2p/kad-dht 7.0.0 → 7.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 (98) hide show
  1. package/dist/index.min.js +19 -19
  2. package/dist/src/content-fetching/index.d.ts +5 -5
  3. package/dist/src/content-fetching/index.d.ts.map +1 -1
  4. package/dist/src/content-fetching/index.js +6 -6
  5. package/dist/src/content-fetching/index.js.map +1 -1
  6. package/dist/src/content-routing/index.d.ts +3 -3
  7. package/dist/src/content-routing/index.d.ts.map +1 -1
  8. package/dist/src/content-routing/index.js +1 -1
  9. package/dist/src/content-routing/index.js.map +1 -1
  10. package/dist/src/dual-kad-dht.d.ts +9 -9
  11. package/dist/src/dual-kad-dht.d.ts.map +1 -1
  12. package/dist/src/dual-kad-dht.js +6 -6
  13. package/dist/src/dual-kad-dht.js.map +1 -1
  14. package/dist/src/kad-dht.d.ts +9 -9
  15. package/dist/src/kad-dht.d.ts.map +1 -1
  16. package/dist/src/kad-dht.js +1 -1
  17. package/dist/src/kad-dht.js.map +1 -1
  18. package/dist/src/message/dht.d.ts.map +1 -1
  19. package/dist/src/message/dht.js.map +1 -1
  20. package/dist/src/message/index.d.ts.map +1 -1
  21. package/dist/src/network.d.ts +3 -2
  22. package/dist/src/network.d.ts.map +1 -1
  23. package/dist/src/network.js +2 -2
  24. package/dist/src/network.js.map +1 -1
  25. package/dist/src/peer-list/index.d.ts.map +1 -1
  26. package/dist/src/peer-list/peer-distance-list.d.ts.map +1 -1
  27. package/dist/src/peer-routing/index.d.ts +6 -6
  28. package/dist/src/peer-routing/index.d.ts.map +1 -1
  29. package/dist/src/peer-routing/index.js +9 -9
  30. package/dist/src/peer-routing/index.js.map +1 -1
  31. package/dist/src/providers.d.ts.map +1 -1
  32. package/dist/src/providers.js +8 -3
  33. package/dist/src/providers.js.map +1 -1
  34. package/dist/src/query/manager.d.ts +2 -2
  35. package/dist/src/query/manager.d.ts.map +1 -1
  36. package/dist/src/query/query-path.d.ts.map +1 -1
  37. package/dist/src/query/query-path.js +2 -2
  38. package/dist/src/query/query-path.js.map +1 -1
  39. package/dist/src/query-self.d.ts.map +1 -1
  40. package/dist/src/routing-table/index.d.ts +1 -1
  41. package/dist/src/routing-table/index.d.ts.map +1 -1
  42. package/dist/src/routing-table/index.js +1 -1
  43. package/dist/src/routing-table/index.js.map +1 -1
  44. package/dist/src/routing-table/refresh.d.ts +3 -2
  45. package/dist/src/routing-table/refresh.d.ts.map +1 -1
  46. package/dist/src/routing-table/refresh.js.map +1 -1
  47. package/dist/src/rpc/handlers/add-provider.d.ts +1 -1
  48. package/dist/src/rpc/handlers/add-provider.d.ts.map +1 -1
  49. package/dist/src/rpc/handlers/add-provider.js +3 -3
  50. package/dist/src/rpc/handlers/add-provider.js.map +1 -1
  51. package/dist/src/rpc/handlers/find-node.d.ts.map +1 -1
  52. package/dist/src/rpc/handlers/get-providers.d.ts +2 -1
  53. package/dist/src/rpc/handlers/get-providers.d.ts.map +1 -1
  54. package/dist/src/rpc/handlers/get-providers.js +2 -2
  55. package/dist/src/rpc/handlers/get-providers.js.map +1 -1
  56. package/dist/src/rpc/handlers/get-value.d.ts +1 -1
  57. package/dist/src/rpc/handlers/get-value.d.ts.map +1 -1
  58. package/dist/src/rpc/handlers/get-value.js +5 -5
  59. package/dist/src/rpc/handlers/get-value.js.map +1 -1
  60. package/dist/src/rpc/handlers/ping.d.ts.map +1 -1
  61. package/dist/src/rpc/handlers/put-value.d.ts.map +1 -1
  62. package/dist/src/rpc/handlers/put-value.js +2 -2
  63. package/dist/src/rpc/handlers/put-value.js.map +1 -1
  64. package/dist/src/rpc/index.d.ts.map +1 -1
  65. package/dist/src/topology-listener.d.ts +1 -1
  66. package/dist/src/topology-listener.d.ts.map +1 -1
  67. package/dist/src/topology-listener.js +1 -1
  68. package/dist/src/topology-listener.js.map +1 -1
  69. package/dist/src/utils.d.ts.map +1 -1
  70. package/dist/src/utils.js +1 -1
  71. package/dist/src/utils.js.map +1 -1
  72. package/dist/typedoc-urls.json +1 -0
  73. package/package.json +4 -7
  74. package/src/content-fetching/index.ts +13 -13
  75. package/src/content-routing/index.ts +4 -4
  76. package/src/dual-kad-dht.ts +20 -20
  77. package/src/kad-dht.ts +16 -16
  78. package/src/message/dht.ts +2 -2
  79. package/src/message/index.ts +5 -5
  80. package/src/network.ts +10 -9
  81. package/src/peer-list/index.ts +5 -5
  82. package/src/peer-list/peer-distance-list.ts +4 -4
  83. package/src/peer-routing/index.ts +17 -17
  84. package/src/providers.ts +19 -14
  85. package/src/query/manager.ts +5 -5
  86. package/src/query/query-path.ts +6 -6
  87. package/src/query-self.ts +4 -4
  88. package/src/routing-table/index.ts +11 -11
  89. package/src/routing-table/refresh.ts +11 -10
  90. package/src/rpc/handlers/add-provider.ts +4 -4
  91. package/src/rpc/handlers/find-node.ts +1 -1
  92. package/src/rpc/handlers/get-providers.ts +6 -5
  93. package/src/rpc/handlers/get-value.ts +7 -7
  94. package/src/rpc/handlers/ping.ts +1 -1
  95. package/src/rpc/handlers/put-value.ts +3 -3
  96. package/src/rpc/index.ts +2 -2
  97. package/src/topology-listener.ts +3 -3
  98. package/src/utils.ts +12 -12
@@ -2,7 +2,7 @@ import Queue from 'p-queue'
2
2
  import { xor } from 'uint8arrays/xor'
3
3
  import { toString } from 'uint8arrays/to-string'
4
4
  import defer from 'p-defer'
5
- import errCode from 'err-code'
5
+ import { CodeError } from '@libp2p/interfaces/errors'
6
6
  import { convertPeerId, convertBuffer } from '../utils.js'
7
7
  import { TimeoutController } from 'timeout-abort-controller'
8
8
  import { anySignal } from 'any-signal'
@@ -83,7 +83,7 @@ export interface QueryPathOptions {
83
83
  * Walks a path through the DHT, calling the passed query function for
84
84
  * every peer encountered that we have not seen before
85
85
  */
86
- export async function * queryPath (options: QueryPathOptions) {
86
+ export async function * queryPath (options: QueryPathOptions): AsyncGenerator<QueryEvent, void, undefined> {
87
87
  const { key, startingPeer, ourPeerId, signal, query, alpha, pathIndex, numPaths, cleanUp, queryFuncTimeout, log, peersSeen } = options
88
88
  // Only ALPHA node/value lookups are allowed at any given time for each process
89
89
  // https://github.com/libp2p/specs/tree/master/kad-dht#alpha-concurrency-parameter-%CE%B1
@@ -98,7 +98,7 @@ export async function * queryPath (options: QueryPathOptions) {
98
98
  * Adds the passed peer to the query queue if it's not us and no
99
99
  * other path has passed through this peer
100
100
  */
101
- function queryPeer (peer: PeerId, peerKadId: Uint8Array) {
101
+ function queryPeer (peer: PeerId, peerKadId: Uint8Array): void {
102
102
  if (peer == null) {
103
103
  return
104
104
  }
@@ -196,12 +196,12 @@ export async function * queryPath (options: QueryPathOptions) {
196
196
  yield * toGenerator(queue, signal, cleanUp, log)
197
197
  }
198
198
 
199
- async function * toGenerator (queue: Queue, signal: AbortSignal, cleanUp: EventEmitter<CleanUpEvents>, log: Logger) {
199
+ async function * toGenerator (queue: Queue, signal: AbortSignal, cleanUp: EventEmitter<CleanUpEvents>, log: Logger): AsyncGenerator<QueryEvent, void, undefined> {
200
200
  let deferred = defer()
201
201
  let running = true
202
202
  const results: QueryEvent[] = []
203
203
 
204
- const cleanup = () => {
204
+ const cleanup = (): void => {
205
205
  if (!running) {
206
206
  return
207
207
  }
@@ -235,7 +235,7 @@ async function * toGenerator (queue: Queue, signal: AbortSignal, cleanUp: EventE
235
235
  cleanup()
236
236
 
237
237
  if (wasRunning) {
238
- deferred.reject(errCode(new Error('Query aborted'), 'ERR_QUERY_ABORTED'))
238
+ deferred.reject(new CodeError('Query aborted', 'ERR_QUERY_ABORTED'))
239
239
  }
240
240
  })
241
241
 
package/src/query-self.ts CHANGED
@@ -44,11 +44,11 @@ export class QuerySelf implements Startable {
44
44
  this.queryTimeout = queryTimeout ?? QUERY_SELF_TIMEOUT
45
45
  }
46
46
 
47
- isStarted () {
47
+ isStarted (): boolean {
48
48
  return this.running
49
49
  }
50
50
 
51
- async start () {
51
+ async start (): Promise<void> {
52
52
  if (this.running) {
53
53
  return
54
54
  }
@@ -57,7 +57,7 @@ export class QuerySelf implements Startable {
57
57
  this._querySelf()
58
58
  }
59
59
 
60
- async stop () {
60
+ async stop (): Promise<void> {
61
61
  this.running = false
62
62
 
63
63
  if (this.timeoutId != null) {
@@ -69,7 +69,7 @@ export class QuerySelf implements Startable {
69
69
  }
70
70
  }
71
71
 
72
- _querySelf () {
72
+ _querySelf (): void {
73
73
  Promise.resolve().then(async () => {
74
74
  const timeoutController = new TimeoutController(this.queryTimeout)
75
75
 
@@ -51,7 +51,7 @@ export interface KBucketTree {
51
51
  add: (peer: KBucketPeer) => void
52
52
  get: (key: Uint8Array) => Uint8Array
53
53
  count: () => number
54
- toIterable: () => Iterable<KBucket>
54
+ toIterable: () => Iterable<KBucketPeer>
55
55
  }
56
56
 
57
57
  export interface RoutingTableInit {
@@ -109,7 +109,7 @@ export class RoutingTable implements Startable {
109
109
  this.tagName = tagName ?? KAD_CLOSE_TAG_NAME
110
110
  this.tagValue = tagValue ?? KAD_CLOSE_TAG_VALUE
111
111
 
112
- const updatePingQueueSizeMetric = () => {
112
+ const updatePingQueueSizeMetric = (): void => {
113
113
  this.metrics?.pingQueueSize.update(this.pingQueue.size)
114
114
  this.metrics?.pingRunning.update(this.pingQueue.pending)
115
115
  }
@@ -121,11 +121,11 @@ export class RoutingTable implements Startable {
121
121
  this._onPing = this._onPing.bind(this)
122
122
  }
123
123
 
124
- isStarted () {
124
+ isStarted (): boolean {
125
125
  return this.running
126
126
  }
127
127
 
128
- async start () {
128
+ async start (): Promise<void> {
129
129
  this.running = true
130
130
 
131
131
  if (this.components.metrics != null) {
@@ -150,7 +150,7 @@ export class RoutingTable implements Startable {
150
150
  this._tagPeers(kBuck)
151
151
  }
152
152
 
153
- async stop () {
153
+ async stop (): Promise<void> {
154
154
  this.running = false
155
155
  this.pingQueue.clear()
156
156
  this.kb = undefined
@@ -161,7 +161,7 @@ export class RoutingTable implements Startable {
161
161
  * - this will lower the chances that connections to them get closed when
162
162
  * we reach connection limits
163
163
  */
164
- _tagPeers (kBuck: KBucketTree) {
164
+ _tagPeers (kBuck: KBucketTree): void {
165
165
  let kClosest = new PeerSet()
166
166
 
167
167
  const updatePeerTags = utils.debounce(() => {
@@ -208,7 +208,7 @@ export class RoutingTable implements Startable {
208
208
  * `oldContacts` will not be empty and is the list of contacts that
209
209
  * have not been contacted for the longest.
210
210
  */
211
- _onPing (oldContacts: KBucketPeer[], newContact: KBucketPeer) {
211
+ _onPing (oldContacts: KBucketPeer[], newContact: KBucketPeer): void {
212
212
  // add to a queue so multiple ping requests do not overlap and we don't
213
213
  // flood the network with ping requests if lots of newContact requests
214
214
  // are received
@@ -272,7 +272,7 @@ export class RoutingTable implements Startable {
272
272
  /**
273
273
  * Amount of currently stored peers
274
274
  */
275
- get size () {
275
+ get size (): number {
276
276
  if (this.kb == null) {
277
277
  return 0
278
278
  }
@@ -323,14 +323,14 @@ export class RoutingTable implements Startable {
323
323
  /**
324
324
  * Add or update the routing table with the given peer
325
325
  */
326
- async add (peer: PeerId) {
326
+ async add (peer: PeerId): Promise<void> {
327
327
  if (this.kb == null) {
328
328
  throw new Error('RoutingTable is not started')
329
329
  }
330
330
 
331
331
  const id = await utils.convertPeerId(peer)
332
332
 
333
- this.kb.add({ id: id, peer: peer })
333
+ this.kb.add({ id, peer })
334
334
 
335
335
  this.log('added %p with kad id %b', peer, id)
336
336
 
@@ -340,7 +340,7 @@ export class RoutingTable implements Startable {
340
340
  /**
341
341
  * Remove a given peer from the table
342
342
  */
343
- async remove (peer: PeerId) {
343
+ async remove (peer: PeerId): Promise<void> {
344
344
  if (this.kb == null) {
345
345
  throw new Error('RoutingTable is not started')
346
346
  }
@@ -10,6 +10,7 @@ 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 { PeerId } from '@libp2p/interface-peer-id'
13
14
 
14
15
  /**
15
16
  * Cannot generate random KadIds longer than this + 1
@@ -49,12 +50,12 @@ export class RoutingTableRefresh {
49
50
  this.refreshTable = this.refreshTable.bind(this)
50
51
  }
51
52
 
52
- async start () {
53
+ async start (): Promise<void> {
53
54
  this.log(`refreshing routing table every ${this.refreshInterval}ms`)
54
55
  this.refreshTable(true)
55
56
  }
56
57
 
57
- async stop () {
58
+ async stop (): Promise<void> {
58
59
  if (this.refreshTimeoutId != null) {
59
60
  clearTimeout(this.refreshTimeoutId)
60
61
  }
@@ -66,7 +67,7 @@ export class RoutingTableRefresh {
66
67
  * that is close to the requested peer ID and query that, then network
67
68
  * peers will tell us who they know who is close to the fake ID
68
69
  */
69
- refreshTable (force: boolean = false) {
70
+ refreshTable (force: boolean = false): void {
70
71
  this.log('refreshing routing table')
71
72
 
72
73
  const prefixLength = this._maxCommonPrefix()
@@ -123,7 +124,7 @@ export class RoutingTableRefresh {
123
124
  })
124
125
  }
125
126
 
126
- async _refreshCommonPrefixLength (cpl: number, lastRefresh: Date, force: boolean) {
127
+ async _refreshCommonPrefixLength (cpl: number, lastRefresh: Date, force: boolean): Promise<void> {
127
128
  if (!force && lastRefresh.getTime() > (Date.now() - this.refreshInterval)) {
128
129
  this.log('not running refresh for cpl %s as time since last refresh not above interval', cpl)
129
130
  return
@@ -146,7 +147,7 @@ export class RoutingTableRefresh {
146
147
  }
147
148
  }
148
149
 
149
- _getTrackedCommonPrefixLengthsForRefresh (maxCommonPrefix: number) {
150
+ _getTrackedCommonPrefixLengthsForRefresh (maxCommonPrefix: number): Date[] {
150
151
  if (maxCommonPrefix > MAX_COMMON_PREFIX_LENGTH) {
151
152
  maxCommonPrefix = MAX_COMMON_PREFIX_LENGTH
152
153
  }
@@ -161,7 +162,7 @@ export class RoutingTableRefresh {
161
162
  return dates
162
163
  }
163
164
 
164
- async _generateRandomPeerId (targetCommonPrefixLength: number) {
165
+ async _generateRandomPeerId (targetCommonPrefixLength: number): Promise<PeerId> {
165
166
  if (this.routingTable.kb == null) {
166
167
  throw new Error('Routing table not started')
167
168
  }
@@ -174,7 +175,7 @@ export class RoutingTableRefresh {
174
175
  return peerIdFromBytes(key)
175
176
  }
176
177
 
177
- async _makePeerId (localKadId: Uint8Array, randomPrefix: number, targetCommonPrefixLength: number) {
178
+ async _makePeerId (localKadId: Uint8Array, randomPrefix: number, targetCommonPrefixLength: number): Promise<Uint8Array> {
178
179
  if (targetCommonPrefixLength > MAX_COMMON_PREFIX_LENGTH) {
179
180
  throw new Error(`Cannot generate peer ID for common prefix length greater than ${MAX_COMMON_PREFIX_LENGTH}`)
180
181
  }
@@ -208,7 +209,7 @@ export class RoutingTableRefresh {
208
209
  * returns the maximum common prefix length between any peer in the table
209
210
  * and the current peer
210
211
  */
211
- _maxCommonPrefix () {
212
+ _maxCommonPrefix (): number {
212
213
  // xor our KadId with every KadId in the k-bucket tree,
213
214
  // return the longest id prefix that is the same
214
215
  let prefixLength = 0
@@ -225,7 +226,7 @@ export class RoutingTableRefresh {
225
226
  /**
226
227
  * Returns the number of peers in the table with a given prefix length
227
228
  */
228
- _numPeersForCpl (prefixLength: number) {
229
+ _numPeersForCpl (prefixLength: number): number {
229
230
  let count = 0
230
231
 
231
232
  for (const length of this._prefixLengths()) {
@@ -240,7 +241,7 @@ export class RoutingTableRefresh {
240
241
  /**
241
242
  * Yields the common prefix length of every peer in the table
242
243
  */
243
- * _prefixLengths () {
244
+ * _prefixLengths (): Generator<number> {
244
245
  if (this.routingTable.kb == null) {
245
246
  return
246
247
  }
@@ -1,5 +1,5 @@
1
1
  import { CID } from 'multiformats/cid'
2
- import errcode from 'err-code'
2
+ import { CodeError } from '@libp2p/interfaces/errors'
3
3
  import { logger } from '@libp2p/logger'
4
4
  import type { Providers } from '../../providers'
5
5
  import type { PeerId } from '@libp2p/interface-peer-id'
@@ -20,11 +20,11 @@ export class AddProviderHandler implements DHTMessageHandler {
20
20
  this.providers = providers
21
21
  }
22
22
 
23
- async handle (peerId: PeerId, msg: Message) {
23
+ async handle (peerId: PeerId, msg: Message): Promise<Message | undefined> {
24
24
  log('start')
25
25
 
26
26
  if (msg.key == null || msg.key.length === 0) {
27
- throw errcode(new Error('Missing key'), 'ERR_MISSING_KEY')
27
+ throw new CodeError('Missing key', 'ERR_MISSING_KEY')
28
28
  }
29
29
 
30
30
  let cid: CID
@@ -32,7 +32,7 @@ export class AddProviderHandler implements DHTMessageHandler {
32
32
  // this is actually just the multihash, not the whole CID
33
33
  cid = CID.decode(msg.key)
34
34
  } catch (err: any) {
35
- throw errcode(new Error('Invalid CID'), 'ERR_INVALID_CID')
35
+ throw new CodeError('Invalid CID', 'ERR_INVALID_CID')
36
36
  }
37
37
 
38
38
  if (msg.providerPeers == null || msg.providerPeers.length === 0) {
@@ -40,7 +40,7 @@ export class FindNodeHandler implements DHTMessageHandler {
40
40
  /**
41
41
  * Process `FindNode` DHT messages
42
42
  */
43
- async handle (peerId: PeerId, msg: Message) {
43
+ async handle (peerId: PeerId, msg: Message): Promise<Message> {
44
44
  log('incoming request from %p for peers closer to %b', peerId, msg.key)
45
45
 
46
46
  let closer: PeerInfo[] = []
@@ -1,5 +1,5 @@
1
1
  import { CID } from 'multiformats/cid'
2
- import errcode from 'err-code'
2
+ import { CodeError } from '@libp2p/interfaces/errors'
3
3
  import { Message } from '../../message/index.js'
4
4
  import {
5
5
  removePrivateAddresses,
@@ -12,6 +12,7 @@ import type { PeerRouting } from '../../peer-routing/index.js'
12
12
  import type { PeerId } from '@libp2p/interface-peer-id'
13
13
  import type { PeerInfo } from '@libp2p/interface-peer-info'
14
14
  import type { PeerStore } from '@libp2p/interface-peer-store'
15
+ import type { Multiaddr } from '@multiformats/multiaddr'
15
16
 
16
17
  const log = logger('libp2p:kad-dht:rpc:handlers:get-providers')
17
18
 
@@ -40,12 +41,12 @@ export class GetProvidersHandler implements DHTMessageHandler {
40
41
  this.lan = Boolean(lan)
41
42
  }
42
43
 
43
- async handle (peerId: PeerId, msg: Message) {
44
+ async handle (peerId: PeerId, msg: Message): Promise<Message> {
44
45
  let cid
45
46
  try {
46
47
  cid = CID.decode(msg.key)
47
48
  } catch (err: any) {
48
- throw errcode(new Error('Invalid CID'), 'ERR_INVALID_CID')
49
+ throw new CodeError('Invalid CID', 'ERR_INVALID_CID')
49
50
  }
50
51
 
51
52
  log('%p asking for providers for %s', peerId, cid)
@@ -71,13 +72,13 @@ export class GetProvidersHandler implements DHTMessageHandler {
71
72
  return response
72
73
  }
73
74
 
74
- async _getAddresses (peerId: PeerId) {
75
+ async _getAddresses (peerId: PeerId): Promise<Multiaddr[]> {
75
76
  const addrs = await this.components.peerStore.addressBook.get(peerId)
76
77
 
77
78
  return addrs.map(address => address.multiaddr)
78
79
  }
79
80
 
80
- async _getPeers (peerIds: PeerId[]) {
81
+ async _getPeers (peerIds: PeerId[]): Promise<PeerInfo[]> {
81
82
  const output: PeerInfo[] = []
82
83
  const addrFilter = this.lan ? removePublicAddresses : removePrivateAddresses
83
84
 
@@ -1,5 +1,5 @@
1
1
  import { Libp2pRecord } from '@libp2p/record'
2
- import errcode from 'err-code'
2
+ import { CodeError } from '@libp2p/interfaces/errors'
3
3
  import { Message, MESSAGE_TYPE } from '../../message/index.js'
4
4
  import {
5
5
  MAX_RECORD_AGE
@@ -34,13 +34,13 @@ export class GetValueHandler implements DHTMessageHandler {
34
34
  this.peerRouting = peerRouting
35
35
  }
36
36
 
37
- async handle (peerId: PeerId, msg: Message) {
37
+ async handle (peerId: PeerId, msg: Message): Promise<Message> {
38
38
  const key = msg.key
39
39
 
40
40
  log('%p asked for key %b', peerId, key)
41
41
 
42
42
  if (key == null || key.length === 0) {
43
- throw errcode(new Error('Invalid key'), 'ERR_INVALID_KEY')
43
+ throw new CodeError('Invalid key', 'ERR_INVALID_KEY')
44
44
  }
45
45
 
46
46
  const response = new Message(MESSAGE_TYPE.GET_VALUE, key, msg.clusterLevel)
@@ -54,7 +54,7 @@ export class GetValueHandler implements DHTMessageHandler {
54
54
  const key = await this.components.peerStore.keyBook.get(idFromKey)
55
55
 
56
56
  if (key == null) {
57
- throw errcode(new Error('No public key found in key book'), 'ERR_NOT_FOUND')
57
+ throw new CodeError('No public key found in key book', 'ERR_NOT_FOUND')
58
58
  }
59
59
 
60
60
  pubKey = key
@@ -91,11 +91,11 @@ export class GetValueHandler implements DHTMessageHandler {
91
91
 
92
92
  /**
93
93
  * Try to fetch a given record by from the local datastore.
94
- * Returns the record iff it is still valid, meaning
94
+ * Returns the record if it is still valid, meaning
95
95
  * - it was either authored by this node, or
96
96
  * - it was received less than `MAX_RECORD_AGE` ago.
97
97
  */
98
- async _checkLocalDatastore (key: Uint8Array) {
98
+ async _checkLocalDatastore (key: Uint8Array): Promise<Libp2pRecord | undefined> {
99
99
  log('checkLocalDatastore looking for %b', key)
100
100
  const dsKey = bufferToRecordKey(key)
101
101
 
@@ -114,7 +114,7 @@ export class GetValueHandler implements DHTMessageHandler {
114
114
  const record = Libp2pRecord.deserialize(rawRecord)
115
115
 
116
116
  if (record == null) {
117
- throw errcode(new Error('Invalid record'), 'ERR_INVALID_RECORD')
117
+ throw new CodeError('Invalid record', 'ERR_INVALID_RECORD')
118
118
  }
119
119
 
120
120
  // Check validity: compare time received with max record age
@@ -6,7 +6,7 @@ import type { PeerId } from '@libp2p/interface-peer-id'
6
6
  const log = logger('libp2p:kad-dht:rpc:handlers:ping')
7
7
 
8
8
  export class PingHandler implements DHTMessageHandler {
9
- async handle (peerId: PeerId, msg: Message) {
9
+ async handle (peerId: PeerId, msg: Message): Promise<Message> {
10
10
  log('ping from %p', peerId)
11
11
  return msg
12
12
  }
@@ -1,5 +1,5 @@
1
1
  import { bufferToRecordKey } from '../../utils.js'
2
- import errcode from 'err-code'
2
+ import { CodeError } from '@libp2p/interfaces/errors'
3
3
  import { verifyRecord } from '@libp2p/record/validators'
4
4
  import { Logger, logger } from '@libp2p/logger'
5
5
  import type { DHTMessageHandler } from '../index.js'
@@ -29,7 +29,7 @@ export class PutValueHandler implements DHTMessageHandler {
29
29
  this.validators = validators
30
30
  }
31
31
 
32
- async handle (peerId: PeerId, msg: Message) {
32
+ async handle (peerId: PeerId, msg: Message): Promise<Message> {
33
33
  const key = msg.key
34
34
  this.log('%p asked us to store value for key %b', peerId, key)
35
35
 
@@ -39,7 +39,7 @@ export class PutValueHandler implements DHTMessageHandler {
39
39
  const errMsg = `Empty record from: ${peerId.toString()}`
40
40
 
41
41
  this.log.error(errMsg)
42
- throw errcode(new Error(errMsg), 'ERR_EMPTY_RECORD')
42
+ throw new CodeError(errMsg, 'ERR_EMPTY_RECORD')
43
43
  }
44
44
 
45
45
  try {
package/src/rpc/index.ts CHANGED
@@ -54,7 +54,7 @@ export class RPC {
54
54
  /**
55
55
  * Process incoming DHT messages
56
56
  */
57
- async handleMessage (peerId: PeerId, msg: Message) {
57
+ async handleMessage (peerId: PeerId, msg: Message): Promise<Message | undefined> {
58
58
  try {
59
59
  await this.routingTable.add(peerId)
60
60
  } catch (err: any) {
@@ -75,7 +75,7 @@ export class RPC {
75
75
  /**
76
76
  * Handle incoming streams on the dht protocol
77
77
  */
78
- onIncomingStream (data: IncomingStreamData) {
78
+ onIncomingStream (data: IncomingStreamData): void {
79
79
  Promise.resolve().then(async () => {
80
80
  const { stream, connection } = data
81
81
  const peerId = connection.remotePeer
@@ -36,14 +36,14 @@ export class TopologyListener extends EventEmitter<TopologyListenerEvents> imple
36
36
  this.protocol = protocol
37
37
  }
38
38
 
39
- isStarted () {
39
+ isStarted (): boolean {
40
40
  return this.running
41
41
  }
42
42
 
43
43
  /**
44
44
  * Start the network
45
45
  */
46
- async start () {
46
+ async start (): Promise<void> {
47
47
  if (this.running) {
48
48
  return
49
49
  }
@@ -65,7 +65,7 @@ export class TopologyListener extends EventEmitter<TopologyListenerEvents> imple
65
65
  /**
66
66
  * Stop all network activity
67
67
  */
68
- stop () {
68
+ async stop (): Promise<void> {
69
69
  this.running = false
70
70
 
71
71
  // unregister protocol and handlers
package/src/utils.ts CHANGED
@@ -82,7 +82,7 @@ export function removePublicAddresses (peer: PeerInfo): PeerInfo {
82
82
  /**
83
83
  * Creates a DHT ID by hashing a given Uint8Array
84
84
  */
85
- export async function convertBuffer (buf: Uint8Array) {
85
+ export async function convertBuffer (buf: Uint8Array): Promise<Uint8Array> {
86
86
  const multihash = await sha256.digest(buf)
87
87
 
88
88
  return multihash.digest
@@ -91,61 +91,61 @@ export async function convertBuffer (buf: Uint8Array) {
91
91
  /**
92
92
  * Creates a DHT ID by hashing a Peer ID
93
93
  */
94
- export async function convertPeerId (peerId: PeerId) {
94
+ export async function convertPeerId (peerId: PeerId): Promise<Uint8Array> {
95
95
  return await convertBuffer(peerId.toBytes())
96
96
  }
97
97
 
98
98
  /**
99
99
  * Convert a Uint8Array to their SHA2-256 hash
100
100
  */
101
- export function bufferToKey (buf: Uint8Array) {
101
+ export function bufferToKey (buf: Uint8Array): Key {
102
102
  return new Key('/' + uint8ArrayToString(buf, 'base32'), false)
103
103
  }
104
104
 
105
105
  /**
106
106
  * Convert a Uint8Array to their SHA2-256 hash
107
107
  */
108
- export function bufferToRecordKey (buf: Uint8Array) {
108
+ export function bufferToRecordKey (buf: Uint8Array): Key {
109
109
  return new Key(`${RECORD_KEY_PREFIX}/${uint8ArrayToString(buf, 'base32')}`, false)
110
110
  }
111
111
 
112
112
  /**
113
113
  * Generate the key for a public key.
114
114
  */
115
- export function keyForPublicKey (peer: PeerId) {
115
+ export function keyForPublicKey (peer: PeerId): Uint8Array {
116
116
  return uint8ArrayConcat([
117
117
  PK_PREFIX,
118
118
  peer.toBytes()
119
119
  ])
120
120
  }
121
121
 
122
- export function isPublicKeyKey (key: Uint8Array) {
122
+ export function isPublicKeyKey (key: Uint8Array): boolean {
123
123
  return uint8ArrayToString(key.subarray(0, 4)) === '/pk/'
124
124
  }
125
125
 
126
- export function isIPNSKey (key: Uint8Array) {
126
+ export function isIPNSKey (key: Uint8Array): boolean {
127
127
  return uint8ArrayToString(key.subarray(0, 4)) === '/ipns/'
128
128
  }
129
129
 
130
- export function fromPublicKeyKey (key: Uint8Array) {
130
+ export function fromPublicKeyKey (key: Uint8Array): PeerId {
131
131
  return peerIdFromBytes(key.subarray(4))
132
132
  }
133
133
 
134
134
  /**
135
135
  * Create a new put record, encodes and signs it if enabled
136
136
  */
137
- export function createPutRecord (key: Uint8Array, value: Uint8Array) {
137
+ export function createPutRecord (key: Uint8Array, value: Uint8Array): Uint8Array {
138
138
  const timeReceived = new Date()
139
139
  const rec = new Libp2pRecord(key, value, timeReceived)
140
140
 
141
141
  return rec.serialize()
142
142
  }
143
143
 
144
- export function debounce (callback: () => void, wait: number = 100) {
144
+ export function debounce (callback: () => void, wait: number = 100): () => void {
145
145
  let timeout: ReturnType<typeof setTimeout>
146
146
 
147
- return () => {
147
+ return (): void => {
148
148
  clearTimeout(timeout)
149
- timeout = setTimeout(() => callback(), wait)
149
+ timeout = setTimeout(() => { callback() }, wait)
150
150
  }
151
151
  }