libp2p 2.10.0-8484de8a2 → 2.10.0-87bc8d4fb

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 (111) hide show
  1. package/dist/index.min.js +17 -13
  2. package/dist/index.min.js.map +4 -4
  3. package/dist/src/address-manager/dns-mappings.d.ts +2 -1
  4. package/dist/src/address-manager/dns-mappings.d.ts.map +1 -1
  5. package/dist/src/address-manager/dns-mappings.js +43 -39
  6. package/dist/src/address-manager/dns-mappings.js.map +1 -1
  7. package/dist/src/address-manager/index.d.ts.map +1 -1
  8. package/dist/src/address-manager/index.js +14 -31
  9. package/dist/src/address-manager/index.js.map +1 -1
  10. package/dist/src/address-manager/ip-mappings.d.ts +0 -1
  11. package/dist/src/address-manager/ip-mappings.d.ts.map +1 -1
  12. package/dist/src/address-manager/ip-mappings.js +40 -51
  13. package/dist/src/address-manager/ip-mappings.js.map +1 -1
  14. package/dist/src/address-manager/observed-addresses.d.ts.map +1 -1
  15. package/dist/src/address-manager/observed-addresses.js +3 -1
  16. package/dist/src/address-manager/observed-addresses.js.map +1 -1
  17. package/dist/src/address-manager/transport-addresses.d.ts.map +1 -1
  18. package/dist/src/address-manager/transport-addresses.js +8 -6
  19. package/dist/src/address-manager/transport-addresses.js.map +1 -1
  20. package/dist/src/config/connection-gater.browser.d.ts.map +1 -1
  21. package/dist/src/config/connection-gater.browser.js +9 -3
  22. package/dist/src/config/connection-gater.browser.js.map +1 -1
  23. package/dist/src/config.js +1 -1
  24. package/dist/src/config.js.map +1 -1
  25. package/dist/src/connection-manager/address-sorter.d.ts.map +1 -1
  26. package/dist/src/connection-manager/address-sorter.js +2 -1
  27. package/dist/src/connection-manager/address-sorter.js.map +1 -1
  28. package/dist/src/connection-manager/connection-pruner.d.ts.map +1 -1
  29. package/dist/src/connection-manager/connection-pruner.js +3 -7
  30. package/dist/src/connection-manager/connection-pruner.js.map +1 -1
  31. package/dist/src/connection-manager/constants.defaults.d.ts +0 -4
  32. package/dist/src/connection-manager/constants.defaults.d.ts.map +1 -1
  33. package/dist/src/connection-manager/constants.defaults.js +0 -4
  34. package/dist/src/connection-manager/constants.defaults.js.map +1 -1
  35. package/dist/src/connection-manager/dial-queue.d.ts +2 -2
  36. package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
  37. package/dist/src/connection-manager/dial-queue.js +23 -11
  38. package/dist/src/connection-manager/dial-queue.js.map +1 -1
  39. package/dist/src/connection-manager/index.d.ts +2 -10
  40. package/dist/src/connection-manager/index.d.ts.map +1 -1
  41. package/dist/src/connection-manager/index.js +26 -44
  42. package/dist/src/connection-manager/index.js.map +1 -1
  43. package/dist/src/connection-manager/reconnect-queue.js +1 -1
  44. package/dist/src/connection-manager/reconnect-queue.js.map +1 -1
  45. package/dist/src/connection-manager/utils.d.ts +3 -31
  46. package/dist/src/connection-manager/utils.d.ts.map +1 -1
  47. package/dist/src/connection-manager/utils.js +18 -99
  48. package/dist/src/connection-manager/utils.js.map +1 -1
  49. package/dist/src/connection-monitor.d.ts +1 -1
  50. package/dist/src/connection-monitor.d.ts.map +1 -1
  51. package/dist/src/connection-monitor.js +3 -2
  52. package/dist/src/connection-monitor.js.map +1 -1
  53. package/dist/src/connection.d.ts +9 -13
  54. package/dist/src/connection.d.ts.map +1 -1
  55. package/dist/src/connection.js +138 -87
  56. package/dist/src/connection.js.map +1 -1
  57. package/dist/src/get-peer.js +3 -3
  58. package/dist/src/get-peer.js.map +1 -1
  59. package/dist/src/index.d.ts +2 -2
  60. package/dist/src/index.js +2 -2
  61. package/dist/src/libp2p.d.ts.map +1 -1
  62. package/dist/src/libp2p.js +5 -5
  63. package/dist/src/libp2p.js.map +1 -1
  64. package/dist/src/peer-routing.js +1 -1
  65. package/dist/src/peer-routing.js.map +1 -1
  66. package/dist/src/random-walk.d.ts.map +1 -1
  67. package/dist/src/random-walk.js +3 -13
  68. package/dist/src/random-walk.js.map +1 -1
  69. package/dist/src/registrar.d.ts +3 -3
  70. package/dist/src/registrar.d.ts.map +1 -1
  71. package/dist/src/registrar.js +41 -50
  72. package/dist/src/registrar.js.map +1 -1
  73. package/dist/src/transport-manager.js +2 -15
  74. package/dist/src/transport-manager.js.map +1 -1
  75. package/dist/src/upgrader.d.ts +16 -26
  76. package/dist/src/upgrader.d.ts.map +1 -1
  77. package/dist/src/upgrader.js +122 -88
  78. package/dist/src/upgrader.js.map +1 -1
  79. package/dist/src/version.d.ts +1 -1
  80. package/dist/src/version.js +1 -1
  81. package/package.json +30 -27
  82. package/src/address-manager/dns-mappings.ts +50 -50
  83. package/src/address-manager/index.ts +17 -37
  84. package/src/address-manager/ip-mappings.ts +44 -64
  85. package/src/address-manager/observed-addresses.ts +3 -1
  86. package/src/address-manager/transport-addresses.ts +9 -7
  87. package/src/config/connection-gater.browser.ts +12 -3
  88. package/src/config.ts +1 -1
  89. package/src/connection-manager/address-sorter.ts +2 -1
  90. package/src/connection-manager/connection-pruner.ts +3 -8
  91. package/src/connection-manager/constants.defaults.ts +0 -5
  92. package/src/connection-manager/dial-queue.ts +27 -12
  93. package/src/connection-manager/index.ts +28 -61
  94. package/src/connection-manager/reconnect-queue.ts +1 -1
  95. package/src/connection-manager/utils.ts +21 -129
  96. package/src/connection-monitor.ts +4 -3
  97. package/src/connection.ts +185 -111
  98. package/src/get-peer.ts +3 -3
  99. package/src/index.ts +2 -2
  100. package/src/libp2p.ts +6 -5
  101. package/src/peer-routing.ts +1 -1
  102. package/src/random-walk.ts +3 -13
  103. package/src/registrar.ts +54 -67
  104. package/src/transport-manager.ts +2 -18
  105. package/src/upgrader.ts +149 -132
  106. package/src/version.ts +1 -1
  107. package/dist/src/utils.d.ts +0 -3
  108. package/dist/src/utils.d.ts.map +0 -1
  109. package/dist/src/utils.js +0 -25
  110. package/dist/src/utils.js.map +0 -1
  111. package/src/utils.ts +0 -31
@@ -1,8 +1,8 @@
1
1
  /* eslint-disable max-depth */
2
2
  import { TimeoutError, DialError, AbortError } from '@libp2p/interface'
3
3
  import { PeerMap } from '@libp2p/peer-collections'
4
- import { PriorityQueue } from '@libp2p/utils'
5
- import { CODE_P2P, multiaddr } from '@multiformats/multiaddr'
4
+ import { PriorityQueue } from '@libp2p/utils/priority-queue'
5
+ import { multiaddr } from '@multiformats/multiaddr'
6
6
  import { Circuit } from '@multiformats/multiaddr-matcher'
7
7
  import { anySignal } from 'any-signal'
8
8
  import { setMaxListeners } from 'main-event'
@@ -20,11 +20,10 @@ import {
20
20
  LAST_DIAL_SUCCESS_KEY
21
21
  } from './constants.js'
22
22
  import { resolveMultiaddr, dnsaddrResolver } from './resolvers/index.js'
23
- import { findExistingConnection } from './utils.ts'
24
23
  import { DEFAULT_DIAL_PRIORITY } from './index.js'
25
24
  import type { AddressSorter, ComponentLogger, Logger, Connection, ConnectionGater, Metrics, PeerId, Address, PeerStore, PeerRouting, IsDialableOptions, OpenConnectionProgressEvents, MultiaddrResolver } from '@libp2p/interface'
26
25
  import type { OpenConnectionOptions, TransportManager } from '@libp2p/interface-internal'
27
- import type { PriorityQueueJobOptions } from '@libp2p/utils'
26
+ import type { PriorityQueueJobOptions } from '@libp2p/utils/priority-queue'
28
27
  import type { DNS } from '@multiformats/dns'
29
28
  import type { Multiaddr } from '@multiformats/multiaddr'
30
29
  import type { ProgressOptions } from 'progress-events'
@@ -104,7 +103,7 @@ export class DialQueue {
104
103
  // a started job errored
105
104
  this.queue.addEventListener('failure', (event) => {
106
105
  if (event.detail?.error.name !== AbortError.name) {
107
- this.log.error('error in dial queue - %e', event.detail.error)
106
+ this.log.error('error in dial queue - %e', event.detail)
108
107
  }
109
108
  })
110
109
  }
@@ -137,14 +136,30 @@ export class DialQueue {
137
136
  async dial (peerIdOrMultiaddr: PeerId | Multiaddr | Multiaddr[], options: OpenConnectionOptions = {}): Promise<Connection> {
138
137
  const { peerId, multiaddrs } = getPeerAddress(peerIdOrMultiaddr)
139
138
 
140
- if (peerId != null && options.force !== true) {
141
- const existingConnection = findExistingConnection(peerId, this.connections.get(peerId), multiaddrs)
139
+ // make sure we don't have an existing non-limited connection to any of the
140
+ // addresses we are about to dial
141
+ const existingConnection = Array.from(this.connections.values()).flat().find(conn => {
142
+ if (options.force === true) {
143
+ return false
144
+ }
145
+
146
+ if (conn.limits != null) {
147
+ return false
148
+ }
142
149
 
143
- if (existingConnection != null) {
144
- this.log('already connected to %a', existingConnection.remoteAddr)
145
- options.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'))
146
- return existingConnection
150
+ if (conn.remotePeer.equals(peerId)) {
151
+ return true
147
152
  }
153
+
154
+ return multiaddrs.find(addr => {
155
+ return addr.equals(conn.remoteAddr)
156
+ })
157
+ })
158
+
159
+ if (existingConnection?.status === 'open') {
160
+ this.log('already connected to %a', existingConnection.remoteAddr)
161
+ options.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'))
162
+ return existingConnection
148
163
  }
149
164
 
150
165
  // ready to dial, all async work finished - make sure we don't have any
@@ -446,7 +461,7 @@ export class DialQueue {
446
461
  // if the resolved multiaddr has a PeerID but it's the wrong one, ignore it
447
462
  // - this can happen with addresses like bootstrap.libp2p.io that resolve
448
463
  // to multiple different peers
449
- const addrPeerId = addr.multiaddr.getComponents().findLast(c => c.code === CODE_P2P)?.value
464
+ const addrPeerId = addr.multiaddr.getPeerId()
450
465
  if (peerId != null && addrPeerId != null) {
451
466
  return peerId.equals(addrPeerId)
452
467
  }
@@ -1,8 +1,7 @@
1
1
  import { ConnectionClosedError, InvalidMultiaddrError, InvalidParametersError, InvalidPeerIdError, NotStartedError, start, stop } from '@libp2p/interface'
2
2
  import { PeerMap } from '@libp2p/peer-collections'
3
- import { getNetConfig, isNetworkAddress, RateLimiter } from '@libp2p/utils'
3
+ import { RateLimiter } from '@libp2p/utils/rate-limiter'
4
4
  import { multiaddr } from '@multiformats/multiaddr'
5
- import { pEvent } from 'p-event'
6
5
  import { CustomProgressEvent } from 'progress-events'
7
6
  import { getPeerAddress } from '../get-peer.js'
8
7
  import { ConnectionPruner } from './connection-pruner.js'
@@ -10,11 +9,11 @@ import { DIAL_TIMEOUT, INBOUND_CONNECTION_THRESHOLD, MAX_CONNECTIONS, MAX_DIAL_Q
10
9
  import { DialQueue } from './dial-queue.js'
11
10
  import { ReconnectQueue } from './reconnect-queue.js'
12
11
  import { dnsaddrResolver } from './resolvers/index.ts'
13
- import { findExistingConnection, multiaddrToIpNet } from './utils.js'
12
+ import { multiaddrToIpNet } from './utils.js'
14
13
  import type { IpNet } from '@chainsafe/netmask'
15
- import type { PendingDial, AddressSorter, Libp2pEvents, AbortOptions, ComponentLogger, Logger, Connection, MultiaddrConnection, ConnectionGater, Metrics, PeerId, PeerStore, Startable, PendingDialStatus, PeerRouting, IsDialableOptions, MultiaddrResolver, Stream, NewStreamOptions } from '@libp2p/interface'
14
+ import type { PendingDial, AddressSorter, Libp2pEvents, AbortOptions, ComponentLogger, Logger, Connection, MultiaddrConnection, ConnectionGater, Metrics, PeerId, PeerStore, Startable, PendingDialStatus, PeerRouting, IsDialableOptions, MultiaddrResolver } from '@libp2p/interface'
16
15
  import type { ConnectionManager, OpenConnectionOptions, TransportManager } from '@libp2p/interface-internal'
17
- import type { JobStatus } from '@libp2p/utils'
16
+ import type { JobStatus } from '@libp2p/utils/queue'
18
17
  import type { Multiaddr } from '@multiformats/multiaddr'
19
18
  import type { TypedEventTarget } from 'main-event'
20
19
 
@@ -66,14 +65,6 @@ export interface ConnectionManagerInit {
66
65
  */
67
66
  dialTimeout?: number
68
67
 
69
- /**
70
- * How many ms to wait when closing a connection if an abort signal is not
71
- * passed
72
- *
73
- * @default 1_000
74
- */
75
- connectionCloseTimeout?: number
76
-
77
68
  /**
78
69
  * When a new incoming connection is opened, the upgrade process (e.g.
79
70
  * protect, encrypt, multiplex etc) must complete within this number of ms.
@@ -250,8 +241,8 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
250
241
  this.onDisconnect = this.onDisconnect.bind(this)
251
242
 
252
243
  // allow/deny lists
253
- this.allow = (init.allow ?? []).map(str => multiaddrToIpNet(multiaddr(str)))
254
- this.deny = (init.deny ?? []).map(str => multiaddrToIpNet(multiaddr(str)))
244
+ this.allow = (init.allow ?? []).map(str => multiaddrToIpNet(str))
245
+ this.deny = (init.deny ?? []).map(str => multiaddrToIpNet(str))
255
246
 
256
247
  this.incomingPendingConnections = 0
257
248
  this.maxIncomingPendingConnections = init.maxIncomingPendingConnections ?? defaultOptions.maxIncomingPendingConnections
@@ -408,22 +399,16 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
408
399
  )
409
400
 
410
401
  // Close all connections we're tracking
411
- const tasks: Array<Promise<any>> = []
402
+ const tasks: Array<Promise<void>> = []
412
403
  for (const connectionList of this.connections.values()) {
413
404
  for (const connection of connectionList) {
414
- tasks.push(
415
- Promise.all([
416
- pEvent(connection, 'close', {
417
- signal: AbortSignal.timeout(500)
418
- }),
419
- connection.close({
420
- signal: AbortSignal.timeout(500)
421
- })
422
- ])
423
- .catch(err => {
424
- connection.abort(err)
425
- })
426
- )
405
+ tasks.push((async () => {
406
+ try {
407
+ await connection.close()
408
+ } catch (err) {
409
+ this.log.error(err)
410
+ }
411
+ })())
427
412
  }
428
413
  }
429
414
 
@@ -519,7 +504,7 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
519
504
  this.connections.delete(peerId)
520
505
 
521
506
  // broadcast disconnect event
522
- this.events.safeDispatchEvent('peer:disconnect', { detail: peerId })
507
+ this.events.safeDispatchEvent('peer:disconnect', { detail: connection.remotePeer })
523
508
  }
524
509
  }
525
510
 
@@ -551,7 +536,7 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
551
536
  try {
552
537
  options.signal?.throwIfAborted()
553
538
 
554
- const { peerId, multiaddrs } = getPeerAddress(peerIdOrMultiaddr)
539
+ const { peerId } = getPeerAddress(peerIdOrMultiaddr)
555
540
 
556
541
  if (this.peerId.equals(peerId)) {
557
542
  throw new InvalidPeerIdError('Can not dial self')
@@ -559,10 +544,11 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
559
544
 
560
545
  if (peerId != null && options.force !== true) {
561
546
  this.log('dial %p', peerId)
562
- const existingConnection = findExistingConnection(peerId, this.getConnections(peerId), multiaddrs)
547
+ const existingConnection = this.getConnections(peerId)
548
+ .find(conn => conn.limits == null)
563
549
 
564
550
  if (existingConnection != null) {
565
- this.log('had an existing connection to %p as %a', peerId, existingConnection.remoteAddr)
551
+ this.log('had an existing non-limited connection to %p as %a', peerId, existingConnection.remoteAddr)
566
552
 
567
553
  options.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'))
568
554
  return existingConnection
@@ -614,22 +600,13 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
614
600
  }
615
601
  }
616
602
 
617
- async openStream (peerIdOrMultiaddr: PeerId | Multiaddr | Multiaddr[], protocol: string | string[], options: OpenConnectionOptions & NewStreamOptions = {}): Promise<Stream> {
618
- const connection = await this.openConnection(peerIdOrMultiaddr, options)
619
-
620
- return connection.newStream(protocol, options)
621
- }
622
-
623
603
  async closeConnections (peerId: PeerId, options: AbortOptions = {}): Promise<void> {
624
604
  const connections = this.connections.get(peerId) ?? []
625
605
 
626
606
  await Promise.all(
627
607
  connections.map(async connection => {
628
608
  try {
629
- await Promise.all([
630
- pEvent(connection, 'close', options),
631
- connection.close(options)
632
- ])
609
+ await connection.close(options)
633
610
  } catch (err: any) {
634
611
  connection.abort(err)
635
612
  }
@@ -637,15 +614,10 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
637
614
  )
638
615
  }
639
616
 
640
- acceptIncomingConnection (maConn: MultiaddrConnection): boolean {
617
+ async acceptIncomingConnection (maConn: MultiaddrConnection): Promise<boolean> {
641
618
  // check deny list
642
- const denyConnection = this.deny.some(ipNet => {
643
- if (isNetworkAddress(maConn.remoteAddr)) {
644
- const config = getNetConfig(maConn.remoteAddr)
645
- return ipNet.contains(config.host)
646
- }
647
-
648
- return false
619
+ const denyConnection = this.deny.some(ma => {
620
+ return ma.contains(maConn.remoteAddr.nodeAddress().address)
649
621
  })
650
622
 
651
623
  if (denyConnection) {
@@ -655,12 +627,7 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
655
627
 
656
628
  // check allow list
657
629
  const allowConnection = this.allow.some(ipNet => {
658
- if (isNetworkAddress(maConn.remoteAddr)) {
659
- const config = getNetConfig(maConn.remoteAddr)
660
- return ipNet.contains(config.host)
661
- }
662
-
663
- return true
630
+ return ipNet.contains(maConn.remoteAddr.nodeAddress().address)
664
631
  })
665
632
 
666
633
  if (allowConnection) {
@@ -675,13 +642,13 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
675
642
  return false
676
643
  }
677
644
 
678
- if (isNetworkAddress(maConn.remoteAddr)) {
679
- const config = getNetConfig(maConn.remoteAddr)
645
+ if (maConn.remoteAddr.isThinWaistAddress()) {
646
+ const host = maConn.remoteAddr.nodeAddress().address
680
647
 
681
648
  try {
682
- this.inboundConnectionRateLimiter.consume(config.host, 1)
649
+ await this.inboundConnectionRateLimiter.consume(host, 1)
683
650
  } catch {
684
- this.log('connection from %a refused - inboundConnectionThreshold exceeded by host %s', maConn.remoteAddr, config.host)
651
+ this.log('connection from %a refused - inboundConnectionThreshold exceeded by host %s', maConn.remoteAddr, host)
685
652
  return false
686
653
  }
687
654
  }
@@ -1,5 +1,5 @@
1
1
  import { KEEP_ALIVE } from '@libp2p/interface'
2
- import { PeerQueue } from '@libp2p/utils'
2
+ import { PeerQueue } from '@libp2p/utils/peer-queue'
3
3
  import pRetry from 'p-retry'
4
4
  import { MAX_PARALLEL_RECONNECTS } from './constants.js'
5
5
  import type { ComponentLogger, Libp2pEvents, Logger, Metrics, Peer, PeerId, PeerStore, Startable } from '@libp2p/interface'
@@ -1,146 +1,38 @@
1
- import { IpNet } from '@chainsafe/netmask'
2
- import { InvalidParametersError } from '@libp2p/interface'
3
- import { getNetConfig } from '@libp2p/utils'
4
- import { Circuit } from '@multiformats/multiaddr-matcher'
5
- import type { Connection, AbortOptions, PeerId } from '@libp2p/interface'
1
+ import { multiaddr } from '@multiformats/multiaddr'
2
+ import { convertToIpNet } from '@multiformats/multiaddr/convert'
3
+ import type { IpNet } from '@chainsafe/netmask'
6
4
  import type { Multiaddr } from '@multiformats/multiaddr'
7
5
 
8
- /**
9
- * These are speculative protocols that are run automatically on connection open
10
- * so are usually not the reason the connection was opened.
11
- *
12
- * Consequently when requested it should be safe to close connections that only
13
- * have these protocol streams open.
14
- */
15
- const DEFAULT_CLOSABLE_PROTOCOLS = [
16
- // identify
17
- '/ipfs/id/1.0.0',
18
-
19
- // identify-push
20
- '/ipfs/id/push/1.0.0',
21
-
22
- // autonat
23
- '/libp2p/autonat/1.0.0',
24
-
25
- // dcutr
26
- '/libp2p/dcutr'
27
- ]
28
-
29
- export interface SafelyCloseConnectionOptions extends AbortOptions {
30
- /**
31
- * Only close the stream if it either has no protocol streams open or only
32
- * ones in this list.
33
- *
34
- * @default ['/ipfs/id/1.0.0']
35
- */
36
- closableProtocols?: string[]
37
- }
38
-
39
- /**
40
- * Close the passed connection if it has no streams, or only closable protocol
41
- * streams, falling back to aborting the connection if closing it cleanly fails.
42
- */
43
- export async function safelyCloseConnectionIfUnused (connection?: Connection, options?: SafelyCloseConnectionOptions): Promise<void> {
44
- const streamProtocols = connection?.streams?.map(stream => stream.protocol) ?? []
45
- const closableProtocols = options?.closableProtocols ?? DEFAULT_CLOSABLE_PROTOCOLS
46
-
47
- // if the connection has protocols not in the closable protocols list, do not
48
- // close the connection
49
- if (streamProtocols.filter(proto => proto != null && !closableProtocols.includes(proto)).length > 0) {
50
- return
51
- }
52
-
53
- try {
54
- await connection?.close(options)
55
- } catch (err: any) {
56
- connection?.abort(err)
57
- }
58
- }
59
-
60
6
  /**
61
7
  * Converts a multiaddr string or object to an IpNet object.
62
8
  * If the multiaddr doesn't include /ipcidr, it will encapsulate with the appropriate CIDR:
63
9
  * - /ipcidr/32 for IPv4
64
10
  * - /ipcidr/128 for IPv6
65
11
  *
66
- * @param {string | Multiaddr} ma - The multiaddr object to convert.
12
+ * @param {string | Multiaddr} ma - The multiaddr string or object to convert.
67
13
  * @returns {IpNet} The converted IpNet object.
68
14
  * @throws {Error} Throws an error if the multiaddr is not valid.
69
15
  */
70
- export function multiaddrToIpNet (ma: Multiaddr): IpNet {
71
- const config = getNetConfig(ma)
72
- let mask = config.cidr
73
-
74
- if (config.type !== 'ip4' && config.type !== 'ip6') {
75
- throw new InvalidParametersError(`Multiaddr ${ma} was not an IPv4 or IPv6 address`)
76
- }
77
-
78
- // Check if /ipcidr is already present
79
- if (mask == null) {
80
- switch (config.type) {
81
- case 'ip4': {
82
- mask = 32
83
- break
84
- }
85
- case 'ip6': {
86
- mask = 128
87
- break
88
- }
89
- default: {
90
- throw new InvalidParametersError(`Multiaddr ${ma} was not an IPv4 or IPv6 address`)
91
- }
16
+ export function multiaddrToIpNet (ma: string | Multiaddr): IpNet {
17
+ try {
18
+ let parsedMa: Multiaddr
19
+ if (typeof ma === 'string') {
20
+ parsedMa = multiaddr(ma)
21
+ } else {
22
+ parsedMa = ma
92
23
  }
93
- }
94
-
95
- return new IpNet(config.host, mask)
96
- }
97
-
98
- /**
99
- * Returns true if the passed multiaddr would result in a direct connection to
100
- * the peer.
101
- *
102
- * Currently only circuit relay addresses are supported as indirect connections.
103
- */
104
- export function isDirect (ma: Multiaddr): boolean {
105
- return !Circuit.exactMatch(ma)
106
- }
107
24
 
108
- /**
109
- * If there is an existing non-limited connection to the remote peer return it,
110
- * unless it is indirect and at least one of the passed dial addresses would
111
- * result in a direct connection
112
- */
113
- export function findExistingConnection (peerId?: PeerId, connections?: Connection[], dialAddresses?: Multiaddr[]): Connection | undefined {
114
- if (peerId == null || connections == null) {
115
- return
116
- }
117
-
118
- const existingConnection = connections
119
- .sort((a, b) => {
120
- if (a.direct) {
121
- return -1
122
- }
123
-
124
- if (b.direct) {
125
- return 1
126
- }
25
+ const protoNames = new Set([...parsedMa.getComponents().map(component => component.name)])
127
26
 
128
- return 0
129
- })
130
- .find(con => con.limits == null)
131
-
132
- if (existingConnection == null || existingConnection.direct || dialAddresses == null) {
133
- return existingConnection
134
- }
135
-
136
- // we have an indirect, but unlimited connection - test the dial addresses to
137
- // see if any of them would result in a direct connection, in which case allow
138
- // the attempt to upgrade to a direct connection
139
- const wouldUpgradeToDirect = dialAddresses.some(ma => isDirect(ma))
27
+ // Check if /ipcidr is already present
28
+ if (!protoNames.has('ipcidr')) {
29
+ const isIPv6 = protoNames.has('ip6')
30
+ const cidr = isIPv6 ? '/ipcidr/128' : '/ipcidr/32'
31
+ parsedMa = parsedMa.encapsulate(cidr)
32
+ }
140
33
 
141
- if (wouldUpgradeToDirect) {
142
- return
34
+ return convertToIpNet(parsedMa)
35
+ } catch (error) {
36
+ throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${ma}`)
143
37
  }
144
-
145
- return existingConnection
146
38
  }
@@ -1,10 +1,11 @@
1
1
  import { randomBytes } from '@libp2p/crypto'
2
2
  import { serviceCapabilities } from '@libp2p/interface'
3
- import { AdaptiveTimeout, byteStream } from '@libp2p/utils'
3
+ import { AdaptiveTimeout } from '@libp2p/utils/adaptive-timeout'
4
+ import { byteStream } from 'it-byte-stream'
4
5
  import { setMaxListeners } from 'main-event'
5
6
  import type { ComponentLogger, Logger, Metrics, Startable } from '@libp2p/interface'
6
7
  import type { ConnectionManager } from '@libp2p/interface-internal'
7
- import type { AdaptiveTimeoutInit } from '@libp2p/utils'
8
+ import type { AdaptiveTimeoutInit } from '@libp2p/utils/adaptive-timeout'
8
9
 
9
10
  const DEFAULT_PING_INTERVAL_MS = 10000
10
11
  const PROTOCOL_VERSION = '1.0.0'
@@ -119,7 +120,7 @@ export class ConnectionMonitor implements Startable {
119
120
 
120
121
  conn.rtt = Date.now() - start
121
122
 
122
- await stream.close({
123
+ await bs.unwrap().close({
123
124
  signal
124
125
  })
125
126
  } catch (err: any) {