libp2p 0.44.0-53b1645c → 0.44.0-59f34a21

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 (96) hide show
  1. package/dist/index.min.js +14 -14
  2. package/dist/src/autonat/constants.d.ts +16 -2
  3. package/dist/src/autonat/constants.d.ts.map +1 -1
  4. package/dist/src/autonat/constants.js +16 -2
  5. package/dist/src/autonat/constants.js.map +1 -1
  6. package/dist/src/autonat/index.d.ts +9 -30
  7. package/dist/src/autonat/index.d.ts.map +1 -1
  8. package/dist/src/autonat/index.js +35 -29
  9. package/dist/src/autonat/index.js.map +1 -1
  10. package/dist/src/circuit-relay/server/index.d.ts.map +1 -1
  11. package/dist/src/circuit-relay/server/index.js +3 -0
  12. package/dist/src/circuit-relay/server/index.js.map +1 -1
  13. package/dist/src/circuit-relay/transport/discovery.js +2 -2
  14. package/dist/src/circuit-relay/transport/discovery.js.map +1 -1
  15. package/dist/src/circuit-relay/transport/index.d.ts.map +1 -1
  16. package/dist/src/circuit-relay/transport/index.js +4 -6
  17. package/dist/src/circuit-relay/transport/index.js.map +1 -1
  18. package/dist/src/circuit-relay/transport/listener.d.ts +0 -3
  19. package/dist/src/circuit-relay/transport/listener.d.ts.map +1 -1
  20. package/dist/src/circuit-relay/transport/listener.js +27 -24
  21. package/dist/src/circuit-relay/transport/listener.js.map +1 -1
  22. package/dist/src/circuit-relay/transport/reservation-store.d.ts +2 -4
  23. package/dist/src/circuit-relay/transport/reservation-store.d.ts.map +1 -1
  24. package/dist/src/circuit-relay/transport/reservation-store.js +28 -26
  25. package/dist/src/circuit-relay/transport/reservation-store.js.map +1 -1
  26. package/dist/src/config/connection-gater.browser.d.ts +8 -0
  27. package/dist/src/config/connection-gater.browser.d.ts.map +1 -0
  28. package/dist/src/config/connection-gater.browser.js +27 -0
  29. package/dist/src/config/connection-gater.browser.js.map +1 -0
  30. package/dist/src/config/connection-gater.d.ts +6 -0
  31. package/dist/src/config/connection-gater.d.ts.map +1 -0
  32. package/dist/src/config/connection-gater.js +18 -0
  33. package/dist/src/config/connection-gater.js.map +1 -0
  34. package/dist/src/config.d.ts.map +1 -1
  35. package/dist/src/config.js +0 -55
  36. package/dist/src/config.js.map +1 -1
  37. package/dist/src/connection-manager/auto-dial.d.ts.map +1 -1
  38. package/dist/src/connection-manager/auto-dial.js +7 -2
  39. package/dist/src/connection-manager/auto-dial.js.map +1 -1
  40. package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
  41. package/dist/src/connection-manager/dial-queue.js +8 -10
  42. package/dist/src/connection-manager/dial-queue.js.map +1 -1
  43. package/dist/src/fetch/index.d.ts.map +1 -1
  44. package/dist/src/fetch/index.js +2 -8
  45. package/dist/src/fetch/index.js.map +1 -1
  46. package/dist/src/identify/index.d.ts.map +1 -1
  47. package/dist/src/identify/index.js +14 -24
  48. package/dist/src/identify/index.js.map +1 -1
  49. package/dist/src/index.d.ts +2 -6
  50. package/dist/src/index.d.ts.map +1 -1
  51. package/dist/src/index.js +2 -1
  52. package/dist/src/index.js.map +1 -1
  53. package/dist/src/libp2p.d.ts.map +1 -1
  54. package/dist/src/libp2p.js +2 -13
  55. package/dist/src/libp2p.js.map +1 -1
  56. package/dist/src/peer-routing.d.ts +1 -38
  57. package/dist/src/peer-routing.d.ts.map +1 -1
  58. package/dist/src/peer-routing.js +0 -59
  59. package/dist/src/peer-routing.js.map +1 -1
  60. package/dist/src/ping/index.d.ts.map +1 -1
  61. package/dist/src/ping/index.js +7 -9
  62. package/dist/src/ping/index.js.map +1 -1
  63. package/dist/src/transport-manager.d.ts +5 -1
  64. package/dist/src/transport-manager.d.ts.map +1 -1
  65. package/dist/src/transport-manager.js +10 -1
  66. package/dist/src/transport-manager.js.map +1 -1
  67. package/dist/src/upgrader.d.ts.map +1 -1
  68. package/dist/src/upgrader.js +10 -16
  69. package/dist/src/upgrader.js.map +1 -1
  70. package/dist/src/upnp-nat/index.d.ts +2 -2
  71. package/dist/src/upnp-nat/index.d.ts.map +1 -1
  72. package/dist/src/upnp-nat/index.js +1 -1
  73. package/dist/src/upnp-nat/index.js.map +1 -1
  74. package/package.json +8 -9
  75. package/src/autonat/constants.ts +17 -2
  76. package/src/autonat/index.ts +49 -41
  77. package/src/circuit-relay/server/index.ts +4 -0
  78. package/src/circuit-relay/transport/discovery.ts +2 -2
  79. package/src/circuit-relay/transport/index.ts +4 -7
  80. package/src/circuit-relay/transport/listener.ts +35 -29
  81. package/src/circuit-relay/transport/reservation-store.ts +21 -15
  82. package/src/config/connection-gater.browser.ts +31 -0
  83. package/src/config/connection-gater.ts +19 -0
  84. package/src/config.ts +0 -55
  85. package/src/connection-manager/auto-dial.ts +8 -2
  86. package/src/connection-manager/dial-queue.ts +10 -16
  87. package/src/fetch/index.ts +2 -9
  88. package/src/identify/index.ts +16 -26
  89. package/src/index.ts +2 -7
  90. package/src/libp2p.ts +2 -13
  91. package/src/peer-routing.ts +1 -101
  92. package/src/ping/index.ts +7 -9
  93. package/src/transport-manager.ts +13 -1
  94. package/src/upgrader.ts +10 -16
  95. package/src/upnp-nat/index.ts +2 -2
  96. package/src/version.ts +1 -1
@@ -19,11 +19,13 @@ import map from 'it-map'
19
19
  import parallel from 'it-parallel'
20
20
  import { pipe } from 'it-pipe'
21
21
  import isPrivateIp from 'private-ip'
22
- import { TimeoutController } from 'timeout-abort-controller'
23
22
  import {
24
- PROTOCOL
23
+ MAX_INBOUND_STREAMS,
24
+ MAX_OUTBOUND_STREAMS,
25
+ PROTOCOL_NAME, PROTOCOL_PREFIX, PROTOCOL_VERSION, REFRESH_INTERVAL, STARTUP_DELAY, TIMEOUT
25
26
  } from './constants.js'
26
27
  import { Message } from './pb/index.js'
28
+ import { anySignal } from 'any-signal'
27
29
 
28
30
  const log = logger('libp2p:autonat')
29
31
 
@@ -32,45 +34,39 @@ const log = logger('libp2p:autonat')
32
34
  // https://github.com/libp2p/specs/blob/master/autonat/README.md#autonat-protocol
33
35
  const REQUIRED_SUCCESSFUL_DIALS = 4
34
36
 
35
- // Wait this long before we start to query autonat nodes
36
- const AUTONAT_STARTUP_DELAY = 5000
37
-
38
- // Only try to verify our external address this often
39
- const AUTONAT_REFRESH_INTERVAL = 60000
40
-
41
37
  export interface AutonatServiceInit {
42
38
  /**
43
39
  * Allows overriding the protocol prefix used
44
40
  */
45
- protocolPrefix: string
41
+ protocolPrefix?: string
46
42
 
47
43
  /**
48
44
  * How long we should wait for a remote peer to verify our external address
49
45
  */
50
- timeout: number
46
+ timeout?: number
51
47
 
52
48
  /**
53
49
  * How long to wait after startup before trying to verify our external address
54
50
  */
55
- startupDelay: number
51
+ startupDelay?: number
56
52
 
57
53
  /**
58
54
  * Verify our external addresses this often
59
55
  */
60
- refreshInterval: number
56
+ refreshInterval?: number
61
57
 
62
58
  /**
63
59
  * How many parallel inbound autonat streams we allow per-connection
64
60
  */
65
- maxInboundStreams: number
61
+ maxInboundStreams?: number
66
62
 
67
63
  /**
68
64
  * How many parallel outbound autonat streams we allow per-connection
69
65
  */
70
- maxOutboundStreams: number
66
+ maxOutboundStreams?: number
71
67
  }
72
68
 
73
- export interface DefaultAutonatComponents {
69
+ export interface AutonatComponents {
74
70
  registrar: Registrar
75
71
  addressManager: AddressManager
76
72
  transportManager: TransportManager
@@ -79,21 +75,26 @@ export interface DefaultAutonatComponents {
79
75
  peerRouting: PeerRouting
80
76
  }
81
77
 
82
- export class AutonatService implements Startable {
83
- private readonly components: DefaultAutonatComponents
84
- private readonly _init: AutonatServiceInit
78
+ class DefaultAutonatService implements Startable {
79
+ private readonly components: AutonatComponents
85
80
  private readonly startupDelay: number
86
81
  private readonly refreshInterval: number
82
+ private readonly protocol: string
83
+ private readonly timeout: number
84
+ private readonly maxInboundStreams: number
85
+ private readonly maxOutboundStreams: number
87
86
  private verifyAddressTimeout?: ReturnType<typeof setTimeout>
88
87
  private started: boolean
89
88
 
90
- constructor (components: DefaultAutonatComponents, init: AutonatServiceInit) {
89
+ constructor (components: AutonatComponents, init: AutonatServiceInit) {
91
90
  this.components = components
92
91
  this.started = false
93
- this._init = init
94
- this.startupDelay = init.startupDelay ?? AUTONAT_STARTUP_DELAY
95
- this.refreshInterval = init.refreshInterval ?? AUTONAT_REFRESH_INTERVAL
96
-
92
+ this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`
93
+ this.timeout = init.timeout ?? TIMEOUT
94
+ this.maxInboundStreams = init.maxInboundStreams ?? MAX_INBOUND_STREAMS
95
+ this.maxOutboundStreams = init.maxOutboundStreams ?? MAX_OUTBOUND_STREAMS
96
+ this.startupDelay = init.startupDelay ?? STARTUP_DELAY
97
+ this.refreshInterval = init.refreshInterval ?? REFRESH_INTERVAL
97
98
  this._verifyExternalAddresses = this._verifyExternalAddresses.bind(this)
98
99
  }
99
100
 
@@ -106,14 +107,14 @@ export class AutonatService implements Startable {
106
107
  return
107
108
  }
108
109
 
109
- await this.components.registrar.handle(PROTOCOL, (data) => {
110
+ await this.components.registrar.handle(this.protocol, (data) => {
110
111
  void this.handleIncomingAutonatStream(data)
111
112
  .catch(err => {
112
113
  log.error(err)
113
114
  })
114
115
  }, {
115
- maxInboundStreams: this._init.maxInboundStreams,
116
- maxOutboundStreams: this._init.maxOutboundStreams
116
+ maxInboundStreams: this.maxInboundStreams,
117
+ maxOutboundStreams: this.maxOutboundStreams
117
118
  })
118
119
 
119
120
  this.verifyAddressTimeout = setTimeout(this._verifyExternalAddresses, this.startupDelay)
@@ -122,7 +123,7 @@ export class AutonatService implements Startable {
122
123
  }
123
124
 
124
125
  async stop (): Promise<void> {
125
- await this.components.registrar.unhandle(PROTOCOL)
126
+ await this.components.registrar.unhandle(this.protocol)
126
127
  clearTimeout(this.verifyAddressTimeout)
127
128
 
128
129
  this.started = false
@@ -132,20 +133,20 @@ export class AutonatService implements Startable {
132
133
  * Handle an incoming autonat request
133
134
  */
134
135
  async handleIncomingAutonatStream (data: IncomingStreamData): Promise<void> {
135
- const controller = new TimeoutController(this._init.timeout)
136
+ const signal = anySignal([AbortSignal.timeout(this.timeout)])
136
137
 
137
138
  // this controller may be used while dialing lots of peers so prevent MaxListenersExceededWarning
138
139
  // appearing in the console
139
140
  try {
140
141
  // fails on node < 15.4
141
- setMaxListeners?.(Infinity, controller.signal)
142
+ setMaxListeners?.(Infinity, signal)
142
143
  } catch {}
143
144
 
144
145
  const ourHosts = this.components.addressManager.getAddresses()
145
146
  .map(ma => ma.toOptions().host)
146
147
 
147
148
  try {
148
- const source = abortableDuplex(data.stream, controller.signal)
149
+ const source = abortableDuplex(data.stream, signal)
149
150
  const self = this
150
151
 
151
152
  await pipe(
@@ -319,7 +320,7 @@ export class AutonatService implements Startable {
319
320
 
320
321
  try {
321
322
  connection = await self.components.connectionManager.openConnection(multiaddr, {
322
- signal: controller.signal
323
+ signal
323
324
  })
324
325
 
325
326
  if (!connection.remoteAddr.equals(multiaddr)) {
@@ -362,8 +363,10 @@ export class AutonatService implements Startable {
362
363
  // can't tell the remote when a dial timed out..
363
364
  data.stream
364
365
  )
366
+ } catch (err) {
367
+ log.error(err)
365
368
  } finally {
366
- controller.clear()
369
+ signal.clear()
367
370
  }
368
371
  }
369
372
 
@@ -401,13 +404,13 @@ export class AutonatService implements Startable {
401
404
  return
402
405
  }
403
406
 
404
- const controller = new TimeoutController(this._init.timeout)
407
+ const signal = AbortSignal.timeout(this.timeout)
405
408
 
406
409
  // this controller may be used while dialing lots of peers so prevent MaxListenersExceededWarning
407
410
  // appearing in the console
408
411
  try {
409
412
  // fails on node < 15.4
410
- setMaxListeners?.(Infinity, controller.signal)
413
+ setMaxListeners?.(Infinity, signal)
411
414
  } catch {}
412
415
 
413
416
  const self = this
@@ -431,18 +434,18 @@ export class AutonatService implements Startable {
431
434
  const results: Record<string, { success: number, failure: number }> = {}
432
435
  const networkSegments: string[] = []
433
436
 
434
- async function verifyAddress (peer: PeerInfo): Promise<Message.DialResponse | undefined> {
437
+ const verifyAddress = async (peer: PeerInfo): Promise<Message.DialResponse | undefined> => {
435
438
  try {
436
439
  log('Asking %p to verify multiaddr', peer.id)
437
440
 
438
441
  const connection = await self.components.connectionManager.openConnection(peer.id, {
439
- signal: controller.signal
442
+ signal
440
443
  })
441
444
 
442
- const stream = await connection.newStream(PROTOCOL, {
443
- signal: controller.signal
445
+ const stream = await connection.newStream(this.protocol, {
446
+ signal
444
447
  })
445
- const source = abortableDuplex(stream, controller.signal)
448
+ const source = abortableDuplex(stream, signal)
446
449
 
447
450
  const buf = await pipe(
448
451
  [request],
@@ -493,7 +496,7 @@ export class AutonatService implements Startable {
493
496
  }
494
497
 
495
498
  for await (const dialResponse of parallel(map(this.components.peerRouting.getClosestPeers(randomCid, {
496
- signal: controller.signal
499
+ signal
497
500
  }), (peer) => async () => await verifyAddress(peer)), {
498
501
  concurrency: REQUIRED_SUCCESSFUL_DIALS
499
502
  })) {
@@ -557,8 +560,13 @@ export class AutonatService implements Startable {
557
560
  }
558
561
  }
559
562
  } finally {
560
- controller.clear()
561
563
  this.verifyAddressTimeout = setTimeout(this._verifyExternalAddresses, this.refreshInterval)
562
564
  }
563
565
  }
564
566
  }
567
+
568
+ export function autonatService (init: AutonatServiceInit = {}): (components: AutonatComponents) => {} {
569
+ return (components) => {
570
+ return new DefaultAutonatService(components, init)
571
+ }
572
+ }
@@ -287,6 +287,10 @@ class CircuitRelayServer extends EventEmitter<RelayServerEvents> implements Star
287
287
  const addrs = []
288
288
 
289
289
  for (const relayAddr of this.addressManager.getAddresses()) {
290
+ if (relayAddr.toString().includes('/p2p-circuit')) {
291
+ continue
292
+ }
293
+
290
294
  addrs.push(relayAddr.bytes)
291
295
  }
292
296
 
@@ -91,7 +91,7 @@ export class RelayDiscovery extends EventEmitter<RelayDiscoveryEvents> implement
91
91
  log('searching peer store for relays')
92
92
  const peers = (await this.peerStore.all())
93
93
  // filter by a list of peers supporting RELAY_V2_HOP and ones we are not listening on
94
- .filter(({ id, protocols }) => protocols.includes(RELAY_V2_HOP_CODEC))
94
+ .filter(({ protocols }) => protocols.includes(RELAY_V2_HOP_CODEC))
95
95
  .sort(() => Math.random() - 0.5)
96
96
 
97
97
  for (const peer of peers) {
@@ -112,11 +112,11 @@ export class RelayDiscovery extends EventEmitter<RelayDiscoveryEvents> implement
112
112
  const peerId = provider.id
113
113
 
114
114
  found++
115
- log('found relay peer %p in content routing', peerId)
116
115
  await this.peerStore.merge(peerId, {
117
116
  multiaddrs: provider.multiaddrs
118
117
  })
119
118
 
119
+ log('found relay peer %p in content routing', peerId)
120
120
  this.safeDispatchEvent('relay:discover', { detail: peerId })
121
121
  }
122
122
  }
@@ -84,7 +84,6 @@ class CircuitRelayTransport implements Transport {
84
84
  private readonly upgrader: Upgrader
85
85
  private readonly addressManager: AddressManager
86
86
  private readonly connectionGater: ConnectionGater
87
- private readonly events: EventEmitter<Libp2pEvents>
88
87
  private readonly reservationStore: ReservationStore
89
88
  private started: boolean
90
89
 
@@ -96,7 +95,6 @@ class CircuitRelayTransport implements Transport {
96
95
  this.upgrader = components.upgrader
97
96
  this.addressManager = components.addressManager
98
97
  this.connectionGater = components.connectionGater
99
- this.events = components.events
100
98
 
101
99
  if (init.discoverRelays != null && init.discoverRelays > 0) {
102
100
  this.discovery = new RelayDiscovery(components)
@@ -170,7 +168,7 @@ class CircuitRelayTransport implements Transport {
170
168
  const destinationId = destinationAddr.getPeerId()
171
169
 
172
170
  if (relayId == null || destinationId == null) {
173
- const errMsg = 'Circuit relay dial failed as addresses did not have peer id'
171
+ const errMsg = `Circuit relay dial to ${ma.toString()} failed as address did not have peer ids`
174
172
  log.error(errMsg)
175
173
  throw new CodeError(errMsg, codes.ERR_RELAYED_DIAL)
176
174
  }
@@ -203,7 +201,7 @@ class CircuitRelayTransport implements Transport {
203
201
  disconnectOnFailure
204
202
  })
205
203
  } catch (err: any) {
206
- log.error('Circuit relay dial failed', err)
204
+ log.error(`Circuit relay dial to destination ${destinationPeer.toString()} via relay ${relayPeer.toString()} failed`, err)
207
205
  disconnectOnFailure && await relayConnection.close()
208
206
  throw err
209
207
  }
@@ -244,7 +242,7 @@ class CircuitRelayTransport implements Transport {
244
242
  log('new outbound connection %s', maConn.remoteAddr)
245
243
  return await this.upgrader.upgradeOutbound(maConn)
246
244
  } catch (err) {
247
- log.error('Circuit relay dial failed', err)
245
+ log.error(`Circuit relay dial to destination ${destinationPeer.toString()} via relay ${connection.remotePeer.toString()} failed`, err)
248
246
  disconnectOnFailure && await connection.close()
249
247
  throw err
250
248
  }
@@ -256,8 +254,7 @@ class CircuitRelayTransport implements Transport {
256
254
  createListener (options: CreateListenerOptions): Listener {
257
255
  return createListener({
258
256
  connectionManager: this.connectionManager,
259
- relayStore: this.reservationStore,
260
- events: this.events
257
+ relayStore: this.reservationStore
261
258
  })
262
259
  }
263
260
 
@@ -7,47 +7,57 @@ import type { ReservationStore } from './reservation-store.js'
7
7
  import type { PeerId } from '@libp2p/interface-peer-id'
8
8
  import { PeerMap } from '@libp2p/peer-collections'
9
9
  import { logger } from '@libp2p/logger'
10
- import type { Libp2pEvents } from '@libp2p/interface-libp2p'
10
+ import { peerIdFromString } from '@libp2p/peer-id'
11
+ import type { Connection } from '@libp2p/interface-connection'
12
+ import { CodeError } from '@libp2p/interfaces/errors'
11
13
 
12
14
  const log = logger('libp2p:circuit-relay:transport:listener')
13
15
 
14
16
  export interface CircuitRelayTransportListenerComponents {
15
17
  connectionManager: ConnectionManager
16
18
  relayStore: ReservationStore
17
- events: EventEmitter<Libp2pEvents>
18
19
  }
19
20
 
20
21
  class CircuitRelayTransportListener extends EventEmitter<ListenerEvents> implements Listener {
21
22
  private readonly connectionManager: ConnectionManager
22
23
  private readonly relayStore: ReservationStore
23
- private readonly listeningAddrs: PeerMap<Multiaddr>
24
- private readonly events: EventEmitter<Libp2pEvents>
24
+ private readonly listeningAddrs: PeerMap<Multiaddr[]>
25
25
 
26
26
  constructor (components: CircuitRelayTransportListenerComponents) {
27
27
  super()
28
28
 
29
29
  this.connectionManager = components.connectionManager
30
30
  this.relayStore = components.relayStore
31
- this.events = components.events
32
31
  this.listeningAddrs = new PeerMap()
33
32
 
34
33
  // remove listening addrs when a relay is removed
35
34
  this.relayStore.addEventListener('relay:removed', (evt) => {
36
35
  this.#removeRelayPeer(evt.detail)
37
36
  })
38
-
39
- // remove listening addrs when a peer disconnects
40
- this.events.addEventListener('connection:close', (evt) => {
41
- this.#removeRelayPeer(evt.detail.remotePeer)
42
- })
43
37
  }
44
38
 
45
39
  async listen (addr: Multiaddr): Promise<void> {
46
40
  log('listen on %s', addr)
47
41
 
48
- const addrString = addr.toString().split('/p2p-circuit').find(a => a !== '')
49
- const ma = multiaddr(addrString)
50
- const relayConn = await this.connectionManager.openConnection(ma)
42
+ const relayPeerStr = addr.getPeerId()
43
+ let relayConn: Connection | undefined
44
+
45
+ // check if we already have a connection to the relay
46
+ if (relayPeerStr != null) {
47
+ const relayPeer = peerIdFromString(relayPeerStr)
48
+ const connections = this.connectionManager.getConnectionsMap().get(relayPeer) ?? []
49
+
50
+ if (connections.length > 0) {
51
+ relayConn = connections[0]
52
+ }
53
+ }
54
+
55
+ // open a new connection as we don't already have one
56
+ if (relayConn == null) {
57
+ const addrString = addr.toString().split('/p2p-circuit').find(a => a !== '')
58
+ const ma = multiaddr(addrString)
59
+ relayConn = await this.connectionManager.openConnection(ma)
60
+ }
51
61
 
52
62
  if (!this.relayStore.hasReservation(relayConn.remotePeer)) {
53
63
  // addRelay calls transportManager.listen which calls this listen method
@@ -55,31 +65,27 @@ class CircuitRelayTransportListener extends EventEmitter<ListenerEvents> impleme
55
65
  return
56
66
  }
57
67
 
68
+ const reservation = this.relayStore.getReservation(relayConn.remotePeer)
69
+
70
+ if (reservation == null) {
71
+ throw new CodeError('Did not have reservation after making reservation', 'ERR_NO_RESERVATION')
72
+ }
73
+
58
74
  if (this.listeningAddrs.has(relayConn.remotePeer)) {
59
75
  log('already listening on relay %p', relayConn.remotePeer)
60
76
  return
61
77
  }
62
78
 
63
- this.listeningAddrs.set(relayConn.remotePeer, addr)
79
+ // add all addresses from the relay reservation
80
+ this.listeningAddrs.set(relayConn.remotePeer, reservation.addrs.map(buf => {
81
+ return multiaddr(buf).encapsulate('/p2p-circuit')
82
+ }))
83
+
64
84
  this.safeDispatchEvent('listening', {})
65
85
  }
66
86
 
67
- /**
68
- * Get fixed up multiaddrs
69
- *
70
- * NOTE: This method will grab the peers multiaddrs and expand them such that:
71
- *
72
- * a) If it's an existing /p2p-circuit address for a specific relay i.e.
73
- * `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit` this method will expand the
74
- * address to `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit/ipfs/QmPeer` where
75
- * `QmPeer` is this peers id
76
- * b) If it's not a /p2p-circuit address, it will encapsulate the address as a /p2p-circuit
77
- * addr, such when dialing over a relay with this address, it will create the circuit using
78
- * the encapsulated transport address. This is useful when for example, a peer should only
79
- * be dialed over TCP rather than any other transport
80
- */
81
87
  getAddrs (): Multiaddr[] {
82
- return [...this.listeningAddrs.values()]
88
+ return [...this.listeningAddrs.values()].flat()
83
89
  }
84
90
 
85
91
  async close (): Promise<void> {
@@ -96,8 +96,8 @@ export class ReservationStore extends EventEmitter<ReservationStoreEvents> imple
96
96
  // When a peer disconnects, if we had a reservation on that peer
97
97
  // remove the reservation and multiaddr and maybe trigger search
98
98
  // for new relays
99
- this.events.addEventListener('connection:close', (evt) => {
100
- this.removeRelay(evt.detail.remotePeer)
99
+ this.events.addEventListener('peer:disconnect', (evt) => {
100
+ this.#removeRelay(evt.detail)
101
101
  })
102
102
  }
103
103
 
@@ -125,15 +125,15 @@ export class ReservationStore extends EventEmitter<ReservationStoreEvents> imple
125
125
  * on the remote peer
126
126
  */
127
127
  async addRelay (peerId: PeerId, type: RelayType): Promise<void> {
128
- log('add relay', this.reserveQueue.size)
128
+ if (this.peerId.equals(peerId)) {
129
+ log('not trying to use self as relay')
130
+ return
131
+ }
132
+
133
+ log('add relay %p', peerId)
129
134
 
130
135
  await this.reserveQueue.add(async () => {
131
136
  try {
132
- if (this.peerId.equals(peerId)) {
133
- log('not trying to use self as relay')
134
- return
135
- }
136
-
137
137
  // allow refresh of an existing reservation if it is about to expire
138
138
  const existingReservation = this.reservations.get(peerId)
139
139
 
@@ -181,6 +181,7 @@ export class ReservationStore extends EventEmitter<ReservationStoreEvents> imple
181
181
  })
182
182
  }, timeoutDuration)
183
183
 
184
+ // we've managed to create a reservation successfully
184
185
  this.reservations.set(peerId, {
185
186
  timeout,
186
187
  reservation,
@@ -197,13 +198,13 @@ export class ReservationStore extends EventEmitter<ReservationStoreEvents> imple
197
198
  }
198
199
  })
199
200
 
200
- await this.transportManager.listen(
201
- reservation.addrs.map(ma => {
202
- return multiaddr(ma).encapsulate('/p2p-circuit')
203
- })
204
- )
201
+ // listen on multiaddr that only the circuit transport is listening for
202
+ await this.transportManager.listen([multiaddr(`/p2p/${peerId.toString()}/p2p-circuit`)])
205
203
  } catch (err) {
206
204
  log.error('could not reserve slot on %p', peerId, err)
205
+
206
+ // if listening failed, remove the reservation
207
+ this.reservations.delete(peerId)
207
208
  }
208
209
  })
209
210
  }
@@ -212,6 +213,10 @@ export class ReservationStore extends EventEmitter<ReservationStoreEvents> imple
212
213
  return this.reservations.has(peerId)
213
214
  }
214
215
 
216
+ getReservation (peerId: PeerId): Reservation | undefined {
217
+ return this.reservations.get(peerId)?.reservation
218
+ }
219
+
215
220
  async #createReservation (connection: Connection): Promise<Reservation> {
216
221
  log('requesting reservation from %s', connection.remotePeer)
217
222
  const stream = await connection.newStream(RELAY_V2_HOP_CODEC)
@@ -243,14 +248,14 @@ export class ReservationStore extends EventEmitter<ReservationStoreEvents> imple
243
248
  /**
244
249
  * Remove listen relay
245
250
  */
246
- removeRelay (peerId: PeerId): void {
251
+ #removeRelay (peerId: PeerId): void {
247
252
  const existingReservation = this.reservations.get(peerId)
248
253
 
249
254
  if (existingReservation == null) {
250
255
  return
251
256
  }
252
257
 
253
- log('removing relay %p', peerId)
258
+ log('connection to relay %p closed, removing reservation from local store', peerId)
254
259
 
255
260
  clearTimeout(existingReservation.timeout)
256
261
  this.reservations.delete(peerId)
@@ -258,6 +263,7 @@ export class ReservationStore extends EventEmitter<ReservationStoreEvents> imple
258
263
  this.safeDispatchEvent('relay:removed', { detail: peerId })
259
264
 
260
265
  if (this.reservations.size < this.maxDiscoveredRelays) {
266
+ log('not enough relays %d/%d', this.reservations.size, this.maxDiscoveredRelays)
261
267
  this.safeDispatchEvent('relay:not-enough-relays', {})
262
268
  }
263
269
  }
@@ -0,0 +1,31 @@
1
+ import type { ConnectionGater } from '@libp2p/interface-connection-gater'
2
+ import type { Multiaddr } from '@multiformats/multiaddr'
3
+ import isPrivate from 'private-ip'
4
+
5
+ /**
6
+ * Returns a connection gater that disallows dialling private addresses by
7
+ * default. Browsers are severely limited in their resource usage so don't
8
+ * waste time trying to dial undiallable addresses.
9
+ */
10
+ export function connectionGater (gater: ConnectionGater = {}): ConnectionGater {
11
+ return {
12
+ denyDialPeer: async () => false,
13
+ denyDialMultiaddr: async (multiaddr: Multiaddr) => {
14
+ const tuples = multiaddr.stringTuples()
15
+
16
+ if (tuples[0][0] === 4 || tuples[0][0] === 41) {
17
+ return Boolean(isPrivate(`${tuples[0][1]}`))
18
+ }
19
+
20
+ return false
21
+ },
22
+ denyInboundConnection: async () => false,
23
+ denyOutboundConnection: async () => false,
24
+ denyInboundEncryptedConnection: async () => false,
25
+ denyOutboundEncryptedConnection: async () => false,
26
+ denyInboundUpgradedConnection: async () => false,
27
+ denyOutboundUpgradedConnection: async () => false,
28
+ filterMultiaddrForPeer: async () => true,
29
+ ...gater
30
+ }
31
+ }
@@ -0,0 +1,19 @@
1
+ import type { ConnectionGater } from '@libp2p/interface-connection-gater'
2
+
3
+ /**
4
+ * Returns a default connection gater implementation that allows everything
5
+ */
6
+ export function connectionGater (gater: ConnectionGater = {}): ConnectionGater {
7
+ return {
8
+ denyDialPeer: async () => false,
9
+ denyDialMultiaddr: async () => false,
10
+ denyInboundConnection: async () => false,
11
+ denyOutboundConnection: async () => false,
12
+ denyInboundEncryptedConnection: async () => false,
13
+ denyOutboundEncryptedConnection: async () => false,
14
+ denyInboundUpgradedConnection: async () => false,
15
+ denyOutboundUpgradedConnection: async () => false,
16
+ filterMultiaddrForPeer: async () => true,
17
+ ...gater
18
+ }
19
+ }
package/src/config.ts CHANGED
@@ -24,62 +24,7 @@ const DefaultConfig: Partial<Libp2pInit> = {
24
24
  },
25
25
  transportManager: {
26
26
  faultTolerance: FaultTolerance.FATAL_ALL
27
- },
28
- peerRouting: {
29
- refreshManager: {
30
- enabled: true,
31
- interval: 6e5,
32
- bootDelay: 10e3
33
- }
34
27
  }
35
- /*
36
-
37
- nat: {
38
- enabled: true,
39
- ttl: 7200,
40
- keepAlive: true
41
- },
42
- identify: {
43
- protocolPrefix: 'ipfs',
44
- host: {
45
- agentVersion: AGENT_VERSION
46
- },
47
- // https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L48
48
- timeout: 60000,
49
- maxInboundStreams: 1,
50
- maxOutboundStreams: 1,
51
- maxPushIncomingStreams: 1,
52
- maxPushOutgoingStreams: 1,
53
- maxObservedAddresses: 10
54
- },
55
- ping: {
56
- protocolPrefix: 'ipfs',
57
- // See https://github.com/libp2p/specs/blob/d4b5fb0152a6bb86cfd9ea/ping/ping.md?plain=1#L38-L43
58
- // The dialing peer MUST NOT keep more than one outbound stream for the ping protocol per peer.
59
- // The listening peer SHOULD accept at most two streams per peer since cross-stream behavior is
60
- // non-linear and stream writes occur asynchronously. The listening peer may perceive the
61
- // dialing peer closing and opening the wrong streams (for instance, closing stream B and
62
- // opening stream A even though the dialing peer is opening stream B and closing stream A).
63
- maxInboundStreams: 2,
64
- maxOutboundStreams: 1,
65
- timeout: 10000
66
- },
67
- fetch: {
68
- protocolPrefix: 'libp2p',
69
- maxInboundStreams: 1,
70
- maxOutboundStreams: 1,
71
- timeout: 10000
72
- },
73
- autonat: {
74
- protocolPrefix: 'libp2p',
75
- maxInboundStreams: 1,
76
- maxOutboundStreams: 1,
77
- timeout: 30000,
78
- startupDelay: 5000,
79
- refreshInterval: 60000
80
- }
81
-
82
- */
83
28
  }
84
29
 
85
30
  export function validateConfig <T extends ServiceMap = {}> (opts: RecursivePartial<Libp2pInit<T>>): Libp2pInit<T> {
@@ -101,7 +101,8 @@ export class AutoDial implements Startable {
101
101
  return
102
102
  }
103
103
 
104
- const numConnections = this.connectionManager.getConnections().length
104
+ const connections = this.connectionManager.getConnectionsMap()
105
+ const numConnections = connections.size
105
106
 
106
107
  // Already has enough connections
107
108
  if (numConnections >= this.minConnections) {
@@ -121,6 +122,11 @@ export class AutoDial implements Startable {
121
122
  return false
122
123
  }
123
124
 
125
+ // remove peers we are already connected to
126
+ if (connections.has(peer.id)) {
127
+ return false
128
+ }
129
+
124
130
  return true
125
131
  })
126
132
 
@@ -161,7 +167,7 @@ export class AutoDial implements Startable {
161
167
 
162
168
  for (const peer of sortedPeers) {
163
169
  this.queue.add(async () => {
164
- const numConnections = this.connectionManager.getConnections().length
170
+ const numConnections = this.connectionManager.getConnectionsMap().size
165
171
 
166
172
  // Check to see if we still need to auto dial
167
173
  if (numConnections >= this.minConnections) {