libp2p 0.33.0 → 0.35.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 (74) hide show
  1. package/dist/src/circuit/index.d.ts +2 -2
  2. package/dist/src/circuit/index.d.ts.map +1 -1
  3. package/dist/src/circuit/transport.d.ts +1 -1
  4. package/dist/src/circuit/transport.d.ts.map +1 -1
  5. package/dist/src/config.d.ts +0 -1
  6. package/dist/src/connection-manager/auto-dialler.d.ts +56 -0
  7. package/dist/src/connection-manager/auto-dialler.d.ts.map +1 -0
  8. package/dist/src/connection-manager/index.d.ts +0 -10
  9. package/dist/src/connection-manager/index.d.ts.map +1 -1
  10. package/dist/src/content-routing/index.d.ts +4 -2
  11. package/dist/src/content-routing/index.d.ts.map +1 -1
  12. package/dist/src/dht/dht-content-routing.d.ts +30 -0
  13. package/dist/src/dht/dht-content-routing.d.ts.map +1 -0
  14. package/dist/src/dht/dht-peer-routing.d.ts +29 -0
  15. package/dist/src/dht/dht-peer-routing.d.ts.map +1 -0
  16. package/dist/src/dialer/dial-request.d.ts +4 -4
  17. package/dist/src/dialer/dial-request.d.ts.map +1 -1
  18. package/dist/src/dialer/index.d.ts +2 -3
  19. package/dist/src/dialer/index.d.ts.map +1 -1
  20. package/dist/src/errors.d.ts +2 -0
  21. package/dist/src/identify/index.d.ts +1 -1
  22. package/dist/src/identify/index.d.ts.map +1 -1
  23. package/dist/src/index.d.ts +3 -2
  24. package/dist/src/index.d.ts.map +1 -1
  25. package/dist/src/metrics/stats.d.ts +0 -1
  26. package/dist/src/metrics/stats.d.ts.map +1 -1
  27. package/dist/src/nat-manager.d.ts.map +1 -1
  28. package/dist/src/peer-routing.d.ts +8 -1
  29. package/dist/src/peer-routing.d.ts.map +1 -1
  30. package/dist/src/peer-store/address-book.d.ts +1 -1
  31. package/dist/src/peer-store/address-book.d.ts.map +1 -1
  32. package/dist/src/peer-store/index.d.ts +37 -24
  33. package/dist/src/peer-store/index.d.ts.map +1 -1
  34. package/dist/src/peer-store/metadata-book.d.ts +3 -2
  35. package/dist/src/peer-store/metadata-book.d.ts.map +1 -1
  36. package/dist/src/peer-store/persistent/index.d.ts +0 -1
  37. package/dist/src/record/envelope/index.d.ts +23 -0
  38. package/dist/src/record/envelope/index.d.ts.map +1 -1
  39. package/dist/src/record/peer-record/index.d.ts +6 -0
  40. package/dist/src/record/peer-record/index.d.ts.map +1 -1
  41. package/dist/src/registrar.d.ts +1 -1
  42. package/dist/src/registrar.d.ts.map +1 -1
  43. package/dist/src/upgrader.d.ts +1 -1
  44. package/dist/src/upgrader.d.ts.map +1 -1
  45. package/package.json +30 -25
  46. package/src/circuit/auto-relay.js +4 -4
  47. package/src/circuit/circuit/hop.js +2 -2
  48. package/src/circuit/circuit/stop.js +1 -1
  49. package/src/circuit/circuit/utils.js +2 -2
  50. package/src/circuit/index.js +1 -1
  51. package/src/circuit/transport.js +1 -1
  52. package/src/connection-manager/auto-dialler.js +118 -0
  53. package/src/connection-manager/index.js +0 -52
  54. package/src/content-routing/index.js +35 -9
  55. package/src/dht/dht-content-routing.js +44 -0
  56. package/src/dht/dht-peer-routing.js +51 -0
  57. package/src/dialer/dial-request.js +8 -2
  58. package/src/dialer/index.js +3 -4
  59. package/src/errors.js +3 -1
  60. package/src/get-peer.js +1 -1
  61. package/src/identify/index.js +8 -8
  62. package/src/index.js +16 -14
  63. package/src/insecure/plaintext.js +1 -1
  64. package/src/keychain/cms.js +2 -2
  65. package/src/keychain/index.js +9 -9
  66. package/src/nat-manager.js +2 -2
  67. package/src/peer-routing.js +12 -4
  68. package/src/peer-store/address-book.js +1 -1
  69. package/src/peer-store/metadata-book.js +2 -1
  70. package/src/peer-store/persistent/index.js +5 -5
  71. package/src/pnet/crypto.js +1 -1
  72. package/src/pnet/key-generator.js +1 -1
  73. package/src/transport-manager.js +1 -1
  74. package/src/upgrader.js +9 -9
@@ -0,0 +1,44 @@
1
+ 'use strict'
2
+
3
+ const drain = require('it-drain')
4
+
5
+ /**
6
+ * @typedef {import('peer-id')} PeerId
7
+ * @typedef {import('libp2p-interfaces/src/content-routing/types').ContentRouting} ContentRoutingModule
8
+ * @typedef {import('multiformats/cid').CID} CID
9
+ */
10
+
11
+ /**
12
+ * Wrapper class to convert events into returned values
13
+ *
14
+ * @implements {ContentRoutingModule}
15
+ */
16
+ class DHTContentRouting {
17
+ /**
18
+ * @param {import('libp2p-kad-dht').DHT} dht
19
+ */
20
+ constructor (dht) {
21
+ this._dht = dht
22
+ }
23
+
24
+ /**
25
+ * @param {CID} cid
26
+ */
27
+ async provide (cid) {
28
+ await drain(this._dht.provide(cid))
29
+ }
30
+
31
+ /**
32
+ * @param {CID} cid
33
+ * @param {*} options
34
+ */
35
+ async * findProviders (cid, options) {
36
+ for await (const event of this._dht.findProviders(cid, options)) {
37
+ if (event.name === 'PROVIDER') {
38
+ yield * event.providers
39
+ }
40
+ }
41
+ }
42
+ }
43
+
44
+ module.exports = { DHTContentRouting }
@@ -0,0 +1,51 @@
1
+ 'use strict'
2
+
3
+ const errCode = require('err-code')
4
+ const { messages, codes } = require('../errors')
5
+
6
+ /**
7
+ * @typedef {import('peer-id')} PeerId
8
+ * @typedef {import('libp2p-interfaces/src/peer-routing/types').PeerRouting} PeerRoutingModule
9
+ */
10
+
11
+ /**
12
+ * Wrapper class to convert events into returned values
13
+ *
14
+ * @implements {PeerRoutingModule}
15
+ */
16
+ class DHTPeerRouting {
17
+ /**
18
+ * @param {import('libp2p-kad-dht').DHT} dht
19
+ */
20
+ constructor (dht) {
21
+ this._dht = dht
22
+ }
23
+
24
+ /**
25
+ * @param {PeerId} peerId
26
+ * @param {any} options
27
+ */
28
+ async findPeer (peerId, options = {}) {
29
+ for await (const event of this._dht.findPeer(peerId, options)) {
30
+ if (event.name === 'FINAL_PEER') {
31
+ return event.peer
32
+ }
33
+ }
34
+
35
+ throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND)
36
+ }
37
+
38
+ /**
39
+ * @param {Uint8Array} key
40
+ * @param {any} options
41
+ */
42
+ async * getClosestPeers (key, options = {}) {
43
+ for await (const event of this._dht.getClosestPeers(key, options)) {
44
+ if (event.name === 'PEER_RESPONSE') {
45
+ yield * event.closer
46
+ }
47
+ }
48
+ }
49
+ }
50
+
51
+ module.exports = { DHTPeerRouting }
@@ -1,11 +1,12 @@
1
1
  'use strict'
2
2
 
3
3
  const errCode = require('err-code')
4
- const AbortController = require('abort-controller').default
5
4
  const { anySignal } = require('any-signal')
6
5
  // @ts-ignore p-fifo does not export types
7
6
  const FIFO = require('p-fifo')
8
7
  const pAny = require('p-any')
8
+ // @ts-expect-error setMaxListeners is missing from the types
9
+ const { setMaxListeners } = require('events')
9
10
 
10
11
  /**
11
12
  * @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
@@ -59,7 +60,12 @@ class DialRequest {
59
60
 
60
61
  const tokenHolder = new FIFO()
61
62
  tokens.forEach(token => tokenHolder.push(token))
62
- const dialAbortControllers = this.addrs.map(() => new AbortController())
63
+ const dialAbortControllers = this.addrs.map(() => {
64
+ const controller = new AbortController()
65
+ setMaxListeners && setMaxListeners(Infinity, controller.signal)
66
+
67
+ return controller
68
+ })
63
69
  let completedDials = 0
64
70
 
65
71
  try {
@@ -6,8 +6,7 @@ const log = Object.assign(debug('libp2p:dialer'), {
6
6
  })
7
7
  const errCode = require('err-code')
8
8
  const { Multiaddr } = require('multiaddr')
9
- // @ts-ignore timeout-abourt-controles does not export types
10
- const TimeoutController = require('timeout-abort-controller')
9
+ const { TimeoutController } = require('timeout-abort-controller')
11
10
  const { AbortError } = require('abortable-iterator')
12
11
  const { anySignal } = require('any-signal')
13
12
 
@@ -95,7 +94,7 @@ class Dialer {
95
94
  for (const dial of this._pendingDials.values()) {
96
95
  try {
97
96
  dial.controller.abort()
98
- } catch (err) {
97
+ } catch (/** @type {any} */ err) {
99
98
  log.error(err)
100
99
  }
101
100
  }
@@ -129,7 +128,7 @@ class Dialer {
129
128
  const connection = await pendingDial.promise
130
129
  log('dial succeeded to %s', dialTarget.id)
131
130
  return connection
132
- } catch (err) {
131
+ } catch (/** @type {any} */ err) {
133
132
  // Error is a timeout
134
133
  if (pendingDial.controller.signal.aborted) {
135
134
  err.code = codes.ERR_TIMEOUT
package/src/errors.js CHANGED
@@ -3,7 +3,8 @@
3
3
  exports.messages = {
4
4
  NOT_STARTED_YET: 'The libp2p node is not started yet',
5
5
  DHT_DISABLED: 'DHT is not available',
6
- CONN_ENCRYPTION_REQUIRED: 'At least one connection encryption module is required'
6
+ CONN_ENCRYPTION_REQUIRED: 'At least one connection encryption module is required',
7
+ NOT_FOUND: 'Not found'
7
8
  }
8
9
 
9
10
  exports.codes = {
@@ -29,6 +30,7 @@ exports.codes = {
29
30
  ERR_INVALID_PARAMETERS: 'ERR_INVALID_PARAMETERS',
30
31
  ERR_INVALID_PEER: 'ERR_INVALID_PEER',
31
32
  ERR_MUXER_UNAVAILABLE: 'ERR_MUXER_UNAVAILABLE',
33
+ ERR_NOT_FOUND: 'ERR_NOT_FOUND',
32
34
  ERR_TIMEOUT: 'ERR_TIMEOUT',
33
35
  ERR_TRANSPORT_UNAVAILABLE: 'ERR_TRANSPORT_UNAVAILABLE',
34
36
  ERR_TRANSPORT_DIAL_FAILED: 'ERR_TRANSPORT_DIAL_FAILED',
package/src/get-peer.js CHANGED
@@ -32,7 +32,7 @@ function getPeer (peer) {
32
32
 
33
33
  try {
34
34
  peer = PeerId.createFromB58String(idStr)
35
- } catch (err) {
35
+ } catch (/** @type {any} */ err) {
36
36
  throw errCode(
37
37
  new Error(`${peer} is not a valid peer type`),
38
38
  codes.ERR_INVALID_MULTIADDR
@@ -124,7 +124,7 @@ class IdentifyService {
124
124
  stream,
125
125
  consume
126
126
  )
127
- } catch (err) {
127
+ } catch (/** @type {any} */ err) {
128
128
  // Just log errors
129
129
  log.error('could not push identify update to peer', err)
130
130
  }
@@ -182,7 +182,7 @@ class IdentifyService {
182
182
  let message
183
183
  try {
184
184
  message = Message.Identify.decode(data)
185
- } catch (err) {
185
+ } catch (/** @type {any} */ err) {
186
186
  throw errCode(err, codes.ERR_INVALID_MESSAGE)
187
187
  }
188
188
 
@@ -211,14 +211,14 @@ class IdentifyService {
211
211
  this.peerStore.metadataBook.set(id, 'ProtocolVersion', uint8ArrayFromString(message.protocolVersion))
212
212
  return
213
213
  }
214
- } catch (err) {
214
+ } catch (/** @type {any} */ err) {
215
215
  log('received invalid envelope, discard it and fallback to listenAddrs is available', err)
216
216
  }
217
217
 
218
218
  // LEGACY: Update peers data in PeerStore
219
219
  try {
220
220
  this.peerStore.addressBook.set(id, listenAddrs.map((addr) => new Multiaddr(addr)))
221
- } catch (err) {
221
+ } catch (/** @type {any} */ err) {
222
222
  log.error('received invalid addrs', err)
223
223
  }
224
224
 
@@ -287,7 +287,7 @@ class IdentifyService {
287
287
  stream,
288
288
  consume
289
289
  )
290
- } catch (err) {
290
+ } catch (/** @type {any} */ err) {
291
291
  log.error('could not respond to identify request', err)
292
292
  }
293
293
  }
@@ -313,7 +313,7 @@ class IdentifyService {
313
313
  collect
314
314
  )
315
315
  message = Message.Identify.decode(data)
316
- } catch (err) {
316
+ } catch (/** @type {any} */ err) {
317
317
  return log.error('received invalid message', err)
318
318
  }
319
319
 
@@ -325,7 +325,7 @@ class IdentifyService {
325
325
  this.peerStore.protoBook.set(id, message.protocols)
326
326
  return
327
327
  }
328
- } catch (err) {
328
+ } catch (/** @type {any} */ err) {
329
329
  log('received invalid envelope, discard it and fallback to listenAddrs is available', err)
330
330
  }
331
331
 
@@ -333,7 +333,7 @@ class IdentifyService {
333
333
  try {
334
334
  this.peerStore.addressBook.set(id,
335
335
  message.listenAddrs.map((addr) => new Multiaddr(addr)))
336
- } catch (err) {
336
+ } catch (/** @type {any} */ err) {
337
337
  log.error('received invalid addrs', err)
338
338
  }
339
339
 
package/src/index.js CHANGED
@@ -18,6 +18,7 @@ const { codes, messages } = require('./errors')
18
18
 
19
19
  const AddressManager = require('./address-manager')
20
20
  const ConnectionManager = require('./connection-manager')
21
+ const AutoDialler = require('./connection-manager/auto-dialler')
21
22
  const Circuit = require('./circuit/transport')
22
23
  const Relay = require('./circuit')
23
24
  const Dialer = require('./dialer')
@@ -193,9 +194,13 @@ class Libp2p extends EventEmitter {
193
194
 
194
195
  // Create the Connection Manager
195
196
  this.connectionManager = new ConnectionManager(this, {
196
- autoDial: this._config.peerDiscovery.autoDial,
197
197
  ...this._options.connectionManager
198
198
  })
199
+ this._autodialler = new AutoDialler(this, {
200
+ enabled: this._config.peerDiscovery.autoDial,
201
+ minConnections: this._options.connectionManager.minConnections,
202
+ autoDialInterval: this._options.connectionManager.autoDialInterval
203
+ })
199
204
 
200
205
  // Create Metrics
201
206
  if (this._options.metrics.enabled) {
@@ -301,14 +306,9 @@ class Libp2p extends EventEmitter {
301
306
  // dht provided components (peerRouting, contentRouting, dht)
302
307
  if (this._modules.dht) {
303
308
  const DHT = this._modules.dht
304
- // @ts-ignore Object is not constructable
305
- this._dht = new DHT({
309
+ // @ts-ignore TODO: types need fixing - DHT is an `object` which has no `create` method
310
+ this._dht = DHT.create({
306
311
  libp2p: this,
307
- dialer: this.dialer,
308
- peerId: this.peerId,
309
- peerStore: this.peerStore,
310
- registrar: this.registrar,
311
- datastore: this.datastore,
312
312
  ...this._config.dht
313
313
  })
314
314
  }
@@ -363,7 +363,7 @@ class Libp2p extends EventEmitter {
363
363
  await this._onStarting()
364
364
  await this._onDidStart()
365
365
  log('libp2p has started')
366
- } catch (err) {
366
+ } catch (/** @type {any} */ err) {
367
367
  this.emit('error', err)
368
368
  log.error('An error occurred starting libp2p', err)
369
369
  await this.stop()
@@ -385,6 +385,8 @@ class Libp2p extends EventEmitter {
385
385
 
386
386
  this.relay && this.relay.stop()
387
387
  this.peerRouting.stop()
388
+ this._autodialler.stop()
389
+ await (this._dht && this._dht.stop())
388
390
 
389
391
  for (const service of this._discovery.values()) {
390
392
  service.removeListener('peer', this._onDiscoveryPeer)
@@ -399,7 +401,6 @@ class Libp2p extends EventEmitter {
399
401
 
400
402
  await Promise.all([
401
403
  this.pubsub && this.pubsub.stop(),
402
- this._dht && this._dht.stop(),
403
404
  this.metrics && this.metrics.stop()
404
405
  ])
405
406
 
@@ -408,7 +409,7 @@ class Libp2p extends EventEmitter {
408
409
 
409
410
  ping.unmount(this)
410
411
  this.dialer.destroy()
411
- } catch (err) {
412
+ } catch (/** @type {any} */ err) {
412
413
  if (err) {
413
414
  log.error(err)
414
415
  this.emit('error', err)
@@ -431,7 +432,7 @@ class Libp2p extends EventEmitter {
431
432
 
432
433
  try {
433
434
  await this.keychain.findKeyByName('self')
434
- } catch (err) {
435
+ } catch (/** @type {any} */ err) {
435
436
  await this.keychain.importPeer('self', this.peerId)
436
437
  }
437
438
  }
@@ -624,7 +625,7 @@ class Libp2p extends EventEmitter {
624
625
 
625
626
  // DHT subsystem
626
627
  if (this._config.dht.enabled) {
627
- this._dht && this._dht.start()
628
+ this._dht && await this._dht.start()
628
629
 
629
630
  // TODO: this should be modified once random-walk is used as
630
631
  // the other discovery modules
@@ -655,6 +656,7 @@ class Libp2p extends EventEmitter {
655
656
  }
656
657
 
657
658
  this.connectionManager.start()
659
+ this._autodialler.start()
658
660
 
659
661
  // Peer discovery
660
662
  await this._setupPeerDiscovery()
@@ -698,7 +700,7 @@ class Libp2p extends EventEmitter {
698
700
  log('connecting to discovered peer %s', peerId.toB58String())
699
701
  try {
700
702
  await this.dialer.connectToPeer(peerId)
701
- } catch (err) {
703
+ } catch (/** @type {any} */ err) {
702
704
  log.error(`could not connect to discovered peer ${peerId.toB58String()} with ${err}`)
703
705
  }
704
706
  }
@@ -55,7 +55,7 @@ async function encrypt (localId, conn, remoteId) {
55
55
  let peerId
56
56
  try {
57
57
  peerId = await PeerId.createFromPubKey(id.pubkey.Data)
58
- } catch (err) {
58
+ } catch (/** @type {any} */ err) {
59
59
  log.error(err)
60
60
  throw new InvalidCryptoExchangeError('Remote did not provide its public key')
61
61
  }
@@ -90,7 +90,7 @@ class CMS {
90
90
  const obj = forge.asn1.fromDer(buf)
91
91
  // @ts-ignore not defined
92
92
  cms = forge.pkcs7.messageFromAsn1(obj)
93
- } catch (err) {
93
+ } catch (/** @type {any} */ err) {
94
94
  throw errcode(new Error('Invalid CMS: ' + err.message), 'ERR_INVALID_CMS')
95
95
  }
96
96
 
@@ -114,7 +114,7 @@ class CMS {
114
114
  try {
115
115
  const key = await this.keychain.findKeyById(recipient.keyId)
116
116
  if (key) return true
117
- } catch (err) {
117
+ } catch (/** @type {any} */ err) {
118
118
  return false
119
119
  }
120
120
  return false
@@ -248,7 +248,7 @@ class Keychain {
248
248
  batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))
249
249
 
250
250
  await batch.commit()
251
- } catch (err) {
251
+ } catch (/** @type {any} */ err) {
252
252
  return throwDelayed(err)
253
253
  }
254
254
 
@@ -284,7 +284,7 @@ class Keychain {
284
284
  try {
285
285
  const keys = await this.listKeys()
286
286
  return keys.find((k) => k.id === id)
287
- } catch (err) {
287
+ } catch (/** @type {any} */ err) {
288
288
  return throwDelayed(err)
289
289
  }
290
290
  }
@@ -304,7 +304,7 @@ class Keychain {
304
304
  try {
305
305
  const res = await this.store.get(dsname)
306
306
  return JSON.parse(uint8ArrayToString(res))
307
- } catch (err) {
307
+ } catch (/** @type {any} */ err) {
308
308
  return throwDelayed(errcode(new Error(`Key '${name}' does not exist. ${err.message}`), 'ERR_KEY_NOT_FOUND'))
309
309
  }
310
310
  }
@@ -365,7 +365,7 @@ class Keychain {
365
365
  batch.delete(oldInfoName)
366
366
  await batch.commit()
367
367
  return keyInfo
368
- } catch (err) {
368
+ } catch (/** @type {any} */ err) {
369
369
  return throwDelayed(err)
370
370
  }
371
371
  }
@@ -393,7 +393,7 @@ class Keychain {
393
393
  const dek = privates.get(this).dek
394
394
  const privateKey = await crypto.keys.import(pem, dek)
395
395
  return privateKey.export(password)
396
- } catch (err) {
396
+ } catch (/** @type {any} */ err) {
397
397
  return throwDelayed(err)
398
398
  }
399
399
  }
@@ -421,7 +421,7 @@ class Keychain {
421
421
  let privateKey
422
422
  try {
423
423
  privateKey = await crypto.keys.import(pem, password)
424
- } catch (err) {
424
+ } catch (/** @type {any} */ err) {
425
425
  return throwDelayed(errcode(new Error('Cannot read the key, most likely the password is wrong'), 'ERR_CANNOT_READ_KEY'))
426
426
  }
427
427
 
@@ -431,7 +431,7 @@ class Keychain {
431
431
  /** @type {string} */
432
432
  const dek = privates.get(this).dek
433
433
  pem = await privateKey.export(dek)
434
- } catch (err) {
434
+ } catch (/** @type {any} */ err) {
435
435
  return throwDelayed(err)
436
436
  }
437
437
 
@@ -482,7 +482,7 @@ class Keychain {
482
482
  batch.put(DsInfoName(name), uint8ArrayFromString(JSON.stringify(keyInfo)))
483
483
  await batch.commit()
484
484
  return keyInfo
485
- } catch (err) {
485
+ } catch (/** @type {any} */ err) {
486
486
  return throwDelayed(err)
487
487
  }
488
488
  }
@@ -502,7 +502,7 @@ class Keychain {
502
502
  const dsname = DsName(name)
503
503
  const res = await this.store.get(dsname)
504
504
  return uint8ArrayToString(res)
505
- } catch (err) {
505
+ } catch (/** @type {any} */ err) {
506
506
  return throwDelayed(errcode(new Error(`Key '${name}' does not exist. ${err.message}`), 'ERR_KEY_NOT_FOUND'))
507
507
  }
508
508
  }
@@ -10,7 +10,6 @@ const log = Object.assign(debug('libp2p:nat'), {
10
10
  })
11
11
  const { isBrowser } = require('wherearewe')
12
12
  const retry = require('p-retry')
13
- // @ts-ignore private-api does not export types
14
13
  const isPrivateIp = require('private-ip')
15
14
  const pkg = require('../package.json')
16
15
  const errcode = require('err-code')
@@ -115,6 +114,7 @@ class NatManager {
115
114
  const client = this._getClient()
116
115
  const publicIp = this._externalIp || await client.externalIp()
117
116
 
117
+ // @ts-expect-error types are wrong
118
118
  if (isPrivateIp(publicIp)) {
119
119
  throw new Error(`${publicIp} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`)
120
120
  }
@@ -188,7 +188,7 @@ class NatManager {
188
188
  try {
189
189
  await this._client.destroy()
190
190
  this._client = null
191
- } catch (err) {
191
+ } catch (/** @type {any} */ err) {
192
192
  log.error(err)
193
193
  }
194
194
  }
@@ -10,6 +10,7 @@ const {
10
10
  uniquePeers,
11
11
  requirePeers
12
12
  } = require('./content-routing/utils')
13
+ const { TimeoutController } = require('timeout-abort-controller')
13
14
 
14
15
  const merge = require('it-merge')
15
16
  const { pipe } = require('it-pipe')
@@ -21,6 +22,7 @@ const {
21
22
  clearDelayedInterval
22
23
  // @ts-ignore module with no types
23
24
  } = require('set-delayed-interval')
25
+ const { DHTPeerRouting } = require('./dht/dht-peer-routing')
24
26
 
25
27
  /**
26
28
  * @typedef {import('peer-id')} PeerId
@@ -33,6 +35,7 @@ const {
33
35
  * @property {boolean} [enabled = true] - Whether to enable the Refresh manager
34
36
  * @property {number} [bootDelay = 6e5] - Boot delay to start the Refresh Manager (in ms)
35
37
  * @property {number} [interval = 10e3] - Interval between each Refresh Manager run (in ms)
38
+ * @property {number} [timeout = 10e3] - How long to let each refresh run (in ms)
36
39
  *
37
40
  * @typedef {Object} PeerRoutingOptions
38
41
  * @property {RefreshManagerOptions} [refreshManager]
@@ -51,7 +54,7 @@ class PeerRouting {
51
54
 
52
55
  // If we have the dht, add it to the available peer routers
53
56
  if (libp2p._dht && libp2p._config.dht.enabled) {
54
- this._routers.push(libp2p._dht)
57
+ this._routers.push(new DHTPeerRouting(libp2p._dht))
55
58
  }
56
59
 
57
60
  this._refreshManagerOptions = libp2p._options.peerRouting.refreshManager
@@ -78,8 +81,8 @@ class PeerRouting {
78
81
  async _findClosestPeersTask () {
79
82
  try {
80
83
  // nb getClosestPeers adds the addresses to the address book
81
- await drain(this.getClosestPeers(this._peerId.id))
82
- } catch (err) {
84
+ await drain(this.getClosestPeers(this._peerId.id, { timeout: this._refreshManagerOptions.timeout || 10e3 }))
85
+ } catch (/** @type {any} */ err) {
83
86
  log.error(err)
84
87
  }
85
88
  }
@@ -130,7 +133,8 @@ class PeerRouting {
130
133
  *
131
134
  * @param {Uint8Array} key - A CID like key
132
135
  * @param {Object} [options]
133
- * @param {number} [options.timeout=30e3] - How long the query can take.
136
+ * @param {number} [options.timeout=30e3] - How long the query can take
137
+ * @param {AbortSignal} [options.signal] - An AbortSignal to abort the request
134
138
  * @returns {AsyncIterable<{ id: PeerId, multiaddrs: Multiaddr[] }>}
135
139
  */
136
140
  async * getClosestPeers (key, options = { timeout: 30e3 }) {
@@ -138,6 +142,10 @@ class PeerRouting {
138
142
  throw errCode(new Error('No peer routers available'), 'NO_ROUTERS_AVAILABLE')
139
143
  }
140
144
 
145
+ if (options.timeout) {
146
+ options.signal = new TimeoutController(options.timeout).signal
147
+ }
148
+
141
149
  yield * pipe(
142
150
  merge(
143
151
  ...this._routers.map(router => router.getClosestPeers(key, options))
@@ -83,7 +83,7 @@ class AddressBook extends Book {
83
83
  let peerRecord
84
84
  try {
85
85
  peerRecord = PeerRecord.createFromProtobuf(envelope.payload)
86
- } catch (err) {
86
+ } catch (/** @type {any} */ err) {
87
87
  log.error('invalid peer record received')
88
88
  return false
89
89
  }
@@ -80,10 +80,11 @@ class MetadataBook extends Book {
80
80
  /**
81
81
  * Set data into the datastructure
82
82
  *
83
- * @override
84
83
  * @param {PeerId} peerId
85
84
  * @param {string} key
86
85
  * @param {Uint8Array} value
86
+ * @param {object} [opts]
87
+ * @param {boolean} [opts.emit]
87
88
  */
88
89
  _setValue (peerId, key, value, { emit = true } = {}) {
89
90
  const id = peerId.toB58String()
@@ -249,7 +249,7 @@ class PersistentPeerStore extends PeerStore {
249
249
  }).finish()
250
250
 
251
251
  batch.put(key, encodedData)
252
- } catch (err) {
252
+ } catch (/** @type {any} */ err) {
253
253
  log.error(err)
254
254
  }
255
255
  }
@@ -275,7 +275,7 @@ class PersistentPeerStore extends PeerStore {
275
275
  const encodedData = peerId.marshalPubKey()
276
276
 
277
277
  batch.put(key, encodedData)
278
- } catch (err) {
278
+ } catch (/** @type {any} */ err) {
279
279
  log.error(err)
280
280
  }
281
281
  }
@@ -302,7 +302,7 @@ class PersistentPeerStore extends PeerStore {
302
302
  batch.delete(key)
303
303
  }
304
304
  })
305
- } catch (err) {
305
+ } catch (/** @type {any} */ err) {
306
306
  log.error(err)
307
307
  }
308
308
  }
@@ -330,7 +330,7 @@ class PersistentPeerStore extends PeerStore {
330
330
  const encodedData = Protocols.encode({ protocols }).finish()
331
331
 
332
332
  batch.put(key, encodedData)
333
- } catch (err) {
333
+ } catch (/** @type {any} */ err) {
334
334
  log.error(err)
335
335
  }
336
336
  }
@@ -399,7 +399,7 @@ class PersistentPeerStore extends PeerStore {
399
399
  default:
400
400
  log('invalid data persisted for: ', key.toString())
401
401
  }
402
- } catch (err) {
402
+ } catch (/** @type {any} */ err) {
403
403
  log.error(err)
404
404
  }
405
405
  }
@@ -77,7 +77,7 @@ module.exports.decodeV1PSK = (pskBuffer) => {
77
77
  codecName: codec,
78
78
  psk: psk
79
79
  }
80
- } catch (err) {
80
+ } catch (/** @type {any} */ err) {
81
81
  log.error(err)
82
82
  throw new Error(Errors.INVALID_PSK)
83
83
  }
@@ -28,6 +28,6 @@ try {
28
28
  // @ts-ignore
29
29
  generate(process.stdout)
30
30
  }
31
- } catch (error) {
31
+ } catch (/** @type {any} */ error) {
32
32
 
33
33
  }
@@ -109,7 +109,7 @@ class TransportManager {
109
109
 
110
110
  try {
111
111
  return await transport.dial(ma, options)
112
- } catch (err) {
112
+ } catch (/** @type {any} */ err) {
113
113
  if (!err.code) err.code = codes.ERR_TRANSPORT_DIAL_FAILED
114
114
  throw err
115
115
  }