libp2p 0.39.5 → 0.40.0

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 (150) hide show
  1. package/README.md +5 -0
  2. package/dist/src/address-manager/index.d.ts +18 -2
  3. package/dist/src/address-manager/index.d.ts.map +1 -1
  4. package/dist/src/address-manager/index.js +18 -5
  5. package/dist/src/address-manager/index.js.map +1 -1
  6. package/dist/src/circuit/auto-relay.d.ts +2 -2
  7. package/dist/src/circuit/auto-relay.d.ts.map +1 -1
  8. package/dist/src/circuit/auto-relay.js +12 -12
  9. package/dist/src/circuit/auto-relay.js.map +1 -1
  10. package/dist/src/circuit/index.d.ts +13 -3
  11. package/dist/src/circuit/index.d.ts.map +1 -1
  12. package/dist/src/circuit/index.js +1 -1
  13. package/dist/src/circuit/index.js.map +1 -1
  14. package/dist/src/circuit/pb/index.d.ts.map +1 -1
  15. package/dist/src/circuit/pb/index.js +29 -34
  16. package/dist/src/circuit/pb/index.js.map +1 -1
  17. package/dist/src/circuit/transport.d.ts +22 -7
  18. package/dist/src/circuit/transport.d.ts.map +1 -1
  19. package/dist/src/circuit/transport.js +26 -17
  20. package/dist/src/circuit/transport.js.map +1 -1
  21. package/dist/src/components.d.ts +110 -0
  22. package/dist/src/components.d.ts.map +1 -0
  23. package/dist/src/components.js +199 -0
  24. package/dist/src/components.js.map +1 -0
  25. package/dist/src/connection-manager/auto-dialler.d.ts +9 -2
  26. package/dist/src/connection-manager/auto-dialler.d.ts.map +1 -1
  27. package/dist/src/connection-manager/auto-dialler.js +6 -6
  28. package/dist/src/connection-manager/auto-dialler.js.map +1 -1
  29. package/dist/src/connection-manager/dialer/index.d.ts +12 -5
  30. package/dist/src/connection-manager/dialer/index.d.ts.map +1 -1
  31. package/dist/src/connection-manager/dialer/index.js +9 -9
  32. package/dist/src/connection-manager/dialer/index.js.map +1 -1
  33. package/dist/src/connection-manager/index.d.ts +41 -9
  34. package/dist/src/connection-manager/index.d.ts.map +1 -1
  35. package/dist/src/connection-manager/index.js +82 -39
  36. package/dist/src/connection-manager/index.js.map +1 -1
  37. package/dist/src/content-routing/index.d.ts +7 -2
  38. package/dist/src/content-routing/index.d.ts.map +1 -1
  39. package/dist/src/content-routing/index.js +4 -4
  40. package/dist/src/content-routing/index.js.map +1 -1
  41. package/dist/src/content-routing/utils.d.ts +1 -1
  42. package/dist/src/content-routing/utils.d.ts.map +1 -1
  43. package/dist/src/errors.d.ts +2 -1
  44. package/dist/src/errors.d.ts.map +1 -1
  45. package/dist/src/errors.js +1 -0
  46. package/dist/src/errors.js.map +1 -1
  47. package/dist/src/fetch/index.d.ts +7 -3
  48. package/dist/src/fetch/index.d.ts.map +1 -1
  49. package/dist/src/fetch/index.js +3 -3
  50. package/dist/src/fetch/index.js.map +1 -1
  51. package/dist/src/fetch/pb/proto.d.ts.map +1 -1
  52. package/dist/src/fetch/pb/proto.js +24 -35
  53. package/dist/src/fetch/pb/proto.js.map +1 -1
  54. package/dist/src/identify/index.d.ts +13 -3
  55. package/dist/src/identify/index.d.ts.map +1 -1
  56. package/dist/src/identify/index.js +41 -41
  57. package/dist/src/identify/index.js.map +1 -1
  58. package/dist/src/identify/pb/message.d.ts.map +1 -1
  59. package/dist/src/identify/pb/message.js +23 -34
  60. package/dist/src/identify/pb/message.js.map +1 -1
  61. package/dist/src/index.d.ts +10 -9
  62. package/dist/src/index.d.ts.map +1 -1
  63. package/dist/src/index.js.map +1 -1
  64. package/dist/src/insecure/index.d.ts +2 -8
  65. package/dist/src/insecure/index.d.ts.map +1 -1
  66. package/dist/src/insecure/index.js +5 -3
  67. package/dist/src/insecure/index.js.map +1 -1
  68. package/dist/src/insecure/pb/proto.d.ts.map +1 -1
  69. package/dist/src/insecure/pb/proto.js +24 -29
  70. package/dist/src/insecure/pb/proto.js.map +1 -1
  71. package/dist/src/keychain/index.d.ts +6 -2
  72. package/dist/src/keychain/index.d.ts.map +1 -1
  73. package/dist/src/keychain/index.js +19 -19
  74. package/dist/src/keychain/index.js.map +1 -1
  75. package/dist/src/libp2p.d.ts +1 -2
  76. package/dist/src/libp2p.d.ts.map +1 -1
  77. package/dist/src/libp2p.js +48 -71
  78. package/dist/src/libp2p.js.map +1 -1
  79. package/dist/src/nat-manager.d.ts +9 -2
  80. package/dist/src/nat-manager.d.ts.map +1 -1
  81. package/dist/src/nat-manager.js +3 -3
  82. package/dist/src/nat-manager.js.map +1 -1
  83. package/dist/src/peer-record-updater.d.ts +11 -2
  84. package/dist/src/peer-record-updater.d.ts.map +1 -1
  85. package/dist/src/peer-record-updater.js +10 -10
  86. package/dist/src/peer-record-updater.js.map +1 -1
  87. package/dist/src/peer-routing.d.ts +6 -2
  88. package/dist/src/peer-routing.d.ts.map +1 -1
  89. package/dist/src/peer-routing.js +4 -4
  90. package/dist/src/peer-routing.js.map +1 -1
  91. package/dist/src/ping/index.d.ts +7 -3
  92. package/dist/src/ping/index.d.ts.map +1 -1
  93. package/dist/src/ping/index.js +3 -3
  94. package/dist/src/ping/index.js.map +1 -1
  95. package/dist/src/pnet/index.d.ts +2 -17
  96. package/dist/src/pnet/index.d.ts.map +1 -1
  97. package/dist/src/pnet/index.js +4 -1
  98. package/dist/src/pnet/index.js.map +1 -1
  99. package/dist/src/pubsub/dummy-pubsub.d.ts +2 -1
  100. package/dist/src/pubsub/dummy-pubsub.d.ts.map +1 -1
  101. package/dist/src/pubsub/dummy-pubsub.js +4 -0
  102. package/dist/src/pubsub/dummy-pubsub.js.map +1 -1
  103. package/dist/src/registrar.d.ts +9 -3
  104. package/dist/src/registrar.d.ts.map +1 -1
  105. package/dist/src/registrar.js +6 -6
  106. package/dist/src/registrar.js.map +1 -1
  107. package/dist/src/transport-manager.d.ts +9 -3
  108. package/dist/src/transport-manager.d.ts.map +1 -1
  109. package/dist/src/transport-manager.js +4 -4
  110. package/dist/src/transport-manager.js.map +1 -1
  111. package/dist/src/upgrader.d.ts +17 -5
  112. package/dist/src/upgrader.d.ts.map +1 -1
  113. package/dist/src/upgrader.js +55 -43
  114. package/dist/src/upgrader.js.map +1 -1
  115. package/package.json +37 -37
  116. package/src/address-manager/index.ts +31 -8
  117. package/src/circuit/auto-relay.ts +15 -15
  118. package/src/circuit/index.ts +16 -5
  119. package/src/circuit/pb/index.ts +29 -35
  120. package/src/circuit/transport.ts +49 -20
  121. package/src/components.ts +332 -0
  122. package/src/connection-manager/auto-dialler.ts +17 -9
  123. package/src/connection-manager/dialer/index.ts +23 -15
  124. package/src/connection-manager/index.ts +139 -47
  125. package/src/content-routing/index.ts +13 -7
  126. package/src/errors.ts +2 -1
  127. package/src/fetch/index.ts +12 -7
  128. package/src/fetch/pb/proto.ts +24 -35
  129. package/src/identify/index.ts +57 -53
  130. package/src/identify/pb/message.ts +23 -35
  131. package/src/index.ts +10 -9
  132. package/src/insecure/index.ts +6 -3
  133. package/src/insecure/pb/proto.ts +24 -29
  134. package/src/keychain/index.ts +27 -22
  135. package/src/libp2p.ts +49 -77
  136. package/src/nat-manager.ts +14 -6
  137. package/src/peer-record-updater.ts +23 -13
  138. package/src/peer-routing.ts +12 -7
  139. package/src/ping/index.ts +12 -7
  140. package/src/pnet/index.ts +5 -1
  141. package/src/pubsub/dummy-pubsub.ts +3 -1
  142. package/src/registrar.ts +17 -10
  143. package/src/transport-manager.ts +15 -8
  144. package/src/upgrader.ts +75 -49
  145. package/src/version.ts +1 -1
  146. package/dist/src/connection-manager/dialer/auto-dialer.d.ts +0 -16
  147. package/dist/src/connection-manager/dialer/auto-dialer.d.ts.map +0 -1
  148. package/dist/src/connection-manager/dialer/auto-dialer.js +0 -43
  149. package/dist/src/connection-manager/dialer/auto-dialer.js.map +0 -1
  150. package/src/connection-manager/dialer/auto-dialer.ts +0 -65
@@ -23,7 +23,7 @@ import type { PeerRouting } from '@libp2p/interface-peer-routing'
23
23
  import type { AbortOptions } from '@libp2p/interfaces'
24
24
  import type { Startable } from '@libp2p/interfaces/startable'
25
25
  import type { PeerInfo } from '@libp2p/interface-peer-info'
26
- import type { Components } from '@libp2p/components'
26
+ import type { PeerStore } from '@libp2p/interface-peer-store'
27
27
 
28
28
  const log = logger('libp2p:peer-routing')
29
29
 
@@ -54,15 +54,20 @@ export interface PeerRoutingInit {
54
54
  refreshManager?: RefreshManagerInit
55
55
  }
56
56
 
57
+ export interface DefaultPeerRoutingComponents {
58
+ peerId: PeerId
59
+ peerStore: PeerStore
60
+ }
61
+
57
62
  export class DefaultPeerRouting implements PeerRouting, Startable {
58
- private readonly components: Components
63
+ private readonly components: DefaultPeerRoutingComponents
59
64
  private readonly routers: PeerRouting[]
60
65
  private readonly refreshManagerInit: RefreshManagerInit
61
66
  private timeoutId?: ReturnType<typeof setTimeout>
62
67
  private started: boolean
63
68
  private abortController?: TimeoutController
64
69
 
65
- constructor (components: Components, init: PeerRoutingInit) {
70
+ constructor (components: DefaultPeerRoutingComponents, init: PeerRoutingInit) {
66
71
  this.components = components
67
72
  this.routers = init.routers
68
73
  this.refreshManagerInit = init.refreshManager ?? {}
@@ -110,7 +115,7 @@ export class DefaultPeerRouting implements PeerRouting, Startable {
110
115
  } catch {}
111
116
 
112
117
  // nb getClosestPeers adds the addresses to the address book
113
- await drain(this.getClosestPeers(this.components.getPeerId().toBytes(), { signal: this.abortController.signal }))
118
+ await drain(this.getClosestPeers(this.components.peerId.toBytes(), { signal: this.abortController.signal }))
114
119
  } catch (err: any) {
115
120
  log.error(err)
116
121
  } finally {
@@ -139,7 +144,7 @@ export class DefaultPeerRouting implements PeerRouting, Startable {
139
144
  throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE)
140
145
  }
141
146
 
142
- if (id.toString() === this.components.getPeerId().toString()) {
147
+ if (id.toString() === this.components.peerId.toString()) {
143
148
  throw errCode(new Error('Should not try to find self'), codes.ERR_FIND_SELF)
144
149
  }
145
150
 
@@ -154,7 +159,7 @@ export class DefaultPeerRouting implements PeerRouting, Startable {
154
159
  })())
155
160
  ),
156
161
  (source) => filter(source, Boolean),
157
- (source) => storeAddresses(source, this.components.getPeerStore()),
162
+ (source) => storeAddresses(source, this.components.peerStore),
158
163
  async (source) => await first(source)
159
164
  )
160
165
 
@@ -177,7 +182,7 @@ export class DefaultPeerRouting implements PeerRouting, Startable {
177
182
  merge(
178
183
  ...this.routers.map(router => router.getClosestPeers(key, options))
179
184
  ),
180
- (source) => storeAddresses(source, this.components.getPeerStore()),
185
+ (source) => storeAddresses(source, this.components.peerStore),
181
186
  (source) => uniquePeers(source),
182
187
  (source) => requirePeers(source)
183
188
  )
package/src/ping/index.ts CHANGED
@@ -6,15 +6,15 @@ import { pipe } from 'it-pipe'
6
6
  import first from 'it-first'
7
7
  import { equals as uint8ArrayEquals } from 'uint8arrays/equals'
8
8
  import { PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION } from './constants.js'
9
- import type { IncomingStreamData } from '@libp2p/interface-registrar'
9
+ import type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'
10
10
  import type { PeerId } from '@libp2p/interface-peer-id'
11
11
  import type { Startable } from '@libp2p/interfaces/startable'
12
- import type { Components } from '@libp2p/components'
13
12
  import type { AbortOptions } from '@libp2p/interfaces'
14
13
  import { abortableDuplex } from 'abortable-iterator'
15
14
  import { TimeoutController } from 'timeout-abort-controller'
16
15
  import type { Stream } from '@libp2p/interface-connection'
17
16
  import { setMaxListeners } from 'events'
17
+ import type { ConnectionManager } from '@libp2p/interface-connection-manager'
18
18
 
19
19
  const log = logger('libp2p:ping')
20
20
 
@@ -29,13 +29,18 @@ export interface PingServiceInit {
29
29
  timeout: number
30
30
  }
31
31
 
32
+ export interface PingServiceComponents {
33
+ registrar: Registrar
34
+ connectionManager: ConnectionManager
35
+ }
36
+
32
37
  export class PingService implements Startable {
33
38
  public readonly protocol: string
34
- private readonly components: Components
39
+ private readonly components: PingServiceComponents
35
40
  private started: boolean
36
41
  private readonly init: PingServiceInit
37
42
 
38
- constructor (components: Components, init: PingServiceInit) {
43
+ constructor (components: PingServiceComponents, init: PingServiceInit) {
39
44
  this.components = components
40
45
  this.started = false
41
46
  this.protocol = `/${init.protocolPrefix}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`
@@ -43,7 +48,7 @@ export class PingService implements Startable {
43
48
  }
44
49
 
45
50
  async start () {
46
- await this.components.getRegistrar().handle(this.protocol, this.handleMessage, {
51
+ await this.components.registrar.handle(this.protocol, this.handleMessage, {
47
52
  maxInboundStreams: this.init.maxInboundStreams,
48
53
  maxOutboundStreams: this.init.maxOutboundStreams
49
54
  })
@@ -51,7 +56,7 @@ export class PingService implements Startable {
51
56
  }
52
57
 
53
58
  async stop () {
54
- await this.components.getRegistrar().unhandle(this.protocol)
59
+ await this.components.registrar.unhandle(this.protocol)
55
60
  this.started = false
56
61
  }
57
62
 
@@ -82,7 +87,7 @@ export class PingService implements Startable {
82
87
 
83
88
  const start = Date.now()
84
89
  const data = randomBytes(PING_LENGTH)
85
- const connection = await this.components.getConnectionManager().openConnection(peer, options)
90
+ const connection = await this.components.connectionManager.openConnection(peer, options)
86
91
  let timeoutController
87
92
  let signal = options.signal
88
93
  let stream: Stream | undefined
package/src/pnet/index.ts CHANGED
@@ -24,7 +24,7 @@ export interface ProtectorInit {
24
24
  psk: Uint8Array
25
25
  }
26
26
 
27
- export class PreSharedKeyConnectionProtector implements ConnectionProtector {
27
+ class PreSharedKeyConnectionProtector implements ConnectionProtector {
28
28
  public tag: string
29
29
  private readonly psk: Uint8Array
30
30
  private readonly enabled: boolean
@@ -96,3 +96,7 @@ export class PreSharedKeyConnectionProtector implements ConnectionProtector {
96
96
  }
97
97
  }
98
98
  }
99
+
100
+ export function preSharedKey (init: ProtectorInit): () => ConnectionProtector {
101
+ return () => new PreSharedKeyConnectionProtector(init)
102
+ }
@@ -1,10 +1,12 @@
1
1
  import { EventEmitter } from '@libp2p/interfaces/events'
2
2
  import type { PeerId } from '@libp2p/interface-peer-id'
3
- import type { PublishResult, PubSub, PubSubEvents, StrictNoSign, StrictSign } from '@libp2p/interface-pubsub'
3
+ import type { PublishResult, PubSub, PubSubEvents, StrictNoSign, StrictSign, TopicValidatorFn } from '@libp2p/interface-pubsub'
4
4
  import errCode from 'err-code'
5
5
  import { messages, codes } from '../errors.js'
6
6
 
7
7
  export class DummyPubSub extends EventEmitter<PubSubEvents> implements PubSub {
8
+ public topicValidators = new Map<string, TopicValidatorFn>()
9
+
8
10
  isStarted (): boolean {
9
11
  return false
10
12
  }
package/src/registrar.ts CHANGED
@@ -4,24 +4,31 @@ import { codes } from './errors.js'
4
4
  import { isTopology, StreamHandlerOptions, StreamHandlerRecord } from '@libp2p/interface-registrar'
5
5
  import merge from 'merge-options'
6
6
  import type { Registrar, StreamHandler, Topology } from '@libp2p/interface-registrar'
7
- import type { PeerProtocolsChangeData } from '@libp2p/interface-peer-store'
7
+ import type { PeerProtocolsChangeData, PeerStore } from '@libp2p/interface-peer-store'
8
8
  import type { Connection } from '@libp2p/interface-connection'
9
- import type { Components } from '@libp2p/components'
9
+ import type { ConnectionManager } from '@libp2p/interface-connection-manager'
10
+ import type { PeerId } from '@libp2p/interface-peer-id'
10
11
 
11
12
  const log = logger('libp2p:registrar')
12
13
 
13
14
  export const DEFAULT_MAX_INBOUND_STREAMS = 32
14
15
  export const DEFAULT_MAX_OUTBOUND_STREAMS = 64
15
16
 
17
+ export interface RegistrarComponents {
18
+ peerId: PeerId
19
+ connectionManager: ConnectionManager
20
+ peerStore: PeerStore
21
+ }
22
+
16
23
  /**
17
24
  * Responsible for notifying registered protocols of events in the network.
18
25
  */
19
26
  export class DefaultRegistrar implements Registrar {
20
27
  private readonly topologies: Map<string, Map<string, Topology>>
21
28
  private readonly handlers: Map<string, StreamHandlerRecord>
22
- private readonly components: Components
29
+ private readonly components: RegistrarComponents
23
30
 
24
- constructor (components: Components) {
31
+ constructor (components: RegistrarComponents) {
25
32
  this.topologies = new Map()
26
33
  this.handlers = new Map()
27
34
  this.components = components
@@ -29,10 +36,10 @@ export class DefaultRegistrar implements Registrar {
29
36
  this._onDisconnect = this._onDisconnect.bind(this)
30
37
  this._onProtocolChange = this._onProtocolChange.bind(this)
31
38
 
32
- this.components.getConnectionManager().addEventListener('peer:disconnect', this._onDisconnect)
39
+ this.components.connectionManager.addEventListener('peer:disconnect', this._onDisconnect)
33
40
 
34
41
  // happens after identify
35
- this.components.getPeerStore().addEventListener('change:protocols', this._onProtocolChange)
42
+ this.components.peerStore.addEventListener('change:protocols', this._onProtocolChange)
36
43
  }
37
44
 
38
45
  getProtocols () {
@@ -83,7 +90,7 @@ export class DefaultRegistrar implements Registrar {
83
90
  })
84
91
 
85
92
  // Add new protocols to self protocols in the Protobook
86
- await this.components.getPeerStore().protoBook.add(this.components.getPeerId(), [protocol])
93
+ await this.components.peerStore.protoBook.add(this.components.peerId, [protocol])
87
94
  }
88
95
 
89
96
  /**
@@ -98,7 +105,7 @@ export class DefaultRegistrar implements Registrar {
98
105
  })
99
106
 
100
107
  // Remove protocols from self protocols in the Protobook
101
- await this.components.getPeerStore().protoBook.remove(this.components.getPeerId(), protocolList)
108
+ await this.components.peerStore.protoBook.remove(this.components.peerId, protocolList)
102
109
  }
103
110
 
104
111
  /**
@@ -149,7 +156,7 @@ export class DefaultRegistrar implements Registrar {
149
156
  _onDisconnect (evt: CustomEvent<Connection>) {
150
157
  const connection = evt.detail
151
158
 
152
- void this.components.getPeerStore().protoBook.get(connection.remotePeer)
159
+ void this.components.peerStore.protoBook.get(connection.remotePeer)
153
160
  .then(peerProtocols => {
154
161
  for (const protocol of peerProtocols) {
155
162
  const topologies = this.topologies.get(protocol)
@@ -200,7 +207,7 @@ export class DefaultRegistrar implements Registrar {
200
207
  }
201
208
 
202
209
  for (const topology of topologies.values()) {
203
- const connection = this.components.getConnectionManager().getConnections(peerId)[0]
210
+ const connection = this.components.connectionManager.getConnections(peerId)[0]
204
211
 
205
212
  if (connection == null) {
206
213
  continue
@@ -2,14 +2,15 @@ import { logger } from '@libp2p/logger'
2
2
  import pSettle from 'p-settle'
3
3
  import { codes } from './errors.js'
4
4
  import errCode from 'err-code'
5
- import type { Listener, Transport, TransportManager, TransportManagerEvents } from '@libp2p/interface-transport'
5
+ import type { Listener, Transport, TransportManager, TransportManagerEvents, Upgrader } from '@libp2p/interface-transport'
6
6
  import type { Multiaddr } from '@multiformats/multiaddr'
7
7
  import type { Connection } from '@libp2p/interface-connection'
8
8
  import type { AbortOptions } from '@libp2p/interfaces'
9
9
  import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'
10
10
  import type { Startable } from '@libp2p/interfaces/startable'
11
- import type { Components } from '@libp2p/components'
12
11
  import { trackedMap } from '@libp2p/tracked-map'
12
+ import type { Metrics } from '@libp2p/interface-metrics'
13
+ import type { AddressManager } from '@libp2p/interface-address-manager'
13
14
 
14
15
  const log = logger('libp2p:transports')
15
16
 
@@ -17,14 +18,20 @@ export interface TransportManagerInit {
17
18
  faultTolerance?: FaultTolerance
18
19
  }
19
20
 
21
+ export interface DefaultTransportManagerComponents {
22
+ metrics?: Metrics
23
+ addressManager: AddressManager
24
+ upgrader: Upgrader
25
+ }
26
+
20
27
  export class DefaultTransportManager extends EventEmitter<TransportManagerEvents> implements TransportManager, Startable {
21
- private readonly components: Components
28
+ private readonly components: DefaultTransportManagerComponents
22
29
  private readonly transports: Map<string, Transport>
23
30
  private readonly listeners: Map<string, Listener[]>
24
31
  private readonly faultTolerance: FaultTolerance
25
32
  private started: boolean
26
33
 
27
- constructor (components: Components, init: TransportManagerInit = {}) {
34
+ constructor (components: DefaultTransportManagerComponents, init: TransportManagerInit = {}) {
28
35
  super()
29
36
 
30
37
  this.components = components
@@ -33,7 +40,7 @@ export class DefaultTransportManager extends EventEmitter<TransportManagerEvents
33
40
  this.listeners = trackedMap({
34
41
  component: 'transport-manager',
35
42
  metric: 'listeners',
36
- metrics: this.components.getMetrics()
43
+ metrics: this.components.metrics
37
44
  })
38
45
  this.faultTolerance = init.faultTolerance ?? FaultTolerance.FATAL_ALL
39
46
  }
@@ -67,7 +74,7 @@ export class DefaultTransportManager extends EventEmitter<TransportManagerEvents
67
74
 
68
75
  async start () {
69
76
  // Listen on the provided transports for the provided addresses
70
- const addrs = this.components.getAddressManager().getListenAddrs()
77
+ const addrs = this.components.addressManager.getListenAddrs()
71
78
 
72
79
  await this.listen(addrs)
73
80
 
@@ -114,7 +121,7 @@ export class DefaultTransportManager extends EventEmitter<TransportManagerEvents
114
121
  try {
115
122
  return await transport.dial(ma, {
116
123
  ...options,
117
- upgrader: this.components.getUpgrader()
124
+ upgrader: this.components.upgrader
118
125
  })
119
126
  } catch (err: any) {
120
127
  if (err.code == null) {
@@ -177,7 +184,7 @@ export class DefaultTransportManager extends EventEmitter<TransportManagerEvents
177
184
  for (const addr of supportedAddrs) {
178
185
  log('creating listener for %s on %s', key, addr)
179
186
  const listener = transport.createListener({
180
- upgrader: this.components.getUpgrader()
187
+ upgrader: this.components.upgrader
181
188
  })
182
189
 
183
190
  let listeners = this.listeners.get(key)
package/src/upgrader.ts CHANGED
@@ -8,19 +8,21 @@ import { codes } from './errors.js'
8
8
  import { createConnection } from '@libp2p/connection'
9
9
  import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'
10
10
  import { peerIdFromString } from '@libp2p/peer-id'
11
- import type { MultiaddrConnection, Connection, Stream } from '@libp2p/interface-connection'
11
+ import type { MultiaddrConnection, Connection, Stream, ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'
12
12
  import type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interface-connection-encrypter'
13
13
  import type { StreamMuxer, StreamMuxerFactory } from '@libp2p/interface-stream-muxer'
14
14
  import type { PeerId } from '@libp2p/interface-peer-id'
15
- import type { Upgrader, UpgraderEvents } from '@libp2p/interface-transport'
15
+ import type { Upgrader, UpgraderEvents, UpgraderOptions } from '@libp2p/interface-transport'
16
16
  import type { Duplex } from 'it-stream-types'
17
- import { Components, isInitializable } from '@libp2p/components'
18
17
  import type { AbortOptions } from '@libp2p/interfaces'
19
18
  import type { Registrar } from '@libp2p/interface-registrar'
20
19
  import { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js'
21
20
  import { TimeoutController } from 'timeout-abort-controller'
22
21
  import { abortableDuplex } from 'abortable-iterator'
23
22
  import { setMaxListeners } from 'events'
23
+ import type { Metrics } from '@libp2p/interface-metrics'
24
+ import type { ConnectionManager } from '@libp2p/interface-connection-manager'
25
+ import type { PeerStore } from '@libp2p/interface-peer-store'
24
26
 
25
27
  const log = logger('libp2p:upgrader')
26
28
 
@@ -94,13 +96,23 @@ function countStreams (protocol: string, direction: 'inbound' | 'outbound', conn
94
96
  return streamCount
95
97
  }
96
98
 
99
+ export interface DefaultUpgraderComponents {
100
+ peerId: PeerId
101
+ metrics?: Metrics
102
+ connectionManager: ConnectionManager
103
+ connectionGater: ConnectionGater
104
+ connectionProtector?: ConnectionProtector
105
+ registrar: Registrar
106
+ peerStore: PeerStore
107
+ }
108
+
97
109
  export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upgrader {
98
- private readonly components: Components
110
+ private readonly components: DefaultUpgraderComponents
99
111
  private readonly connectionEncryption: Map<string, ConnectionEncrypter>
100
112
  private readonly muxers: Map<string, StreamMuxerFactory>
101
113
  private readonly inboundUpgradeTimeout: number
102
114
 
103
- constructor (components: Components, init: UpgraderInit) {
115
+ constructor (components: DefaultUpgraderComponents, init: UpgraderInit) {
104
116
  super()
105
117
 
106
118
  this.components = components
@@ -123,6 +135,12 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
123
135
  * Upgrades an inbound connection
124
136
  */
125
137
  async upgradeInbound (maConn: MultiaddrConnection): Promise<Connection> {
138
+ const accept = await this.components.connectionManager.acceptIncomingConnection(maConn)
139
+
140
+ if (!accept) {
141
+ throw errCode(new Error('connection denied'), codes.ERR_CONNECTION_DENIED)
142
+ }
143
+
126
144
  let encryptedConn
127
145
  let remotePeer
128
146
  let upgradedConn: Duplex<Uint8Array>
@@ -130,7 +148,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
130
148
  let cryptoProtocol
131
149
  let setPeer
132
150
  let proxyPeer
133
- const metrics = this.components.getMetrics()
151
+ const metrics = this.components.metrics
134
152
 
135
153
  const timeoutController = new TimeoutController(this.inboundUpgradeTimeout)
136
154
 
@@ -144,7 +162,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
144
162
  maConn.source = abortableStream.source
145
163
  maConn.sink = abortableStream.sink
146
164
 
147
- if (await this.components.getConnectionGater().denyInboundConnection(maConn)) {
165
+ if (await this.components.connectionGater.denyInboundConnection(maConn)) {
148
166
  throw errCode(new Error('The multiaddr connection is blocked by gater.acceptConnection'), codes.ERR_CONNECTION_INTERCEPTED)
149
167
  }
150
168
 
@@ -159,7 +177,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
159
177
 
160
178
  // Protect
161
179
  let protectedConn = maConn
162
- const protector = this.components.getConnectionProtector()
180
+ const protector = this.components.connectionProtector
163
181
 
164
182
  if (protector != null) {
165
183
  log('protecting the inbound connection')
@@ -174,7 +192,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
174
192
  protocol: cryptoProtocol
175
193
  } = await this._encryptInbound(protectedConn))
176
194
 
177
- if (await this.components.getConnectionGater().denyInboundEncryptedConnection(remotePeer, {
195
+ if (await this.components.connectionGater.denyInboundEncryptedConnection(remotePeer, {
178
196
  ...protectedConn,
179
197
  ...encryptedConn
180
198
  })) {
@@ -194,11 +212,10 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
194
212
  }
195
213
  } catch (err: any) {
196
214
  log.error('Failed to upgrade inbound connection', err)
197
- await maConn.close(err)
198
215
  throw err
199
216
  }
200
217
 
201
- if (await this.components.getConnectionGater().denyInboundUpgradedConnection(remotePeer, {
218
+ if (await this.components.connectionGater.denyInboundUpgradedConnection(remotePeer, {
202
219
  ...protectedConn,
203
220
  ...encryptedConn
204
221
  })) {
@@ -221,6 +238,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
221
238
  remotePeer
222
239
  })
223
240
  } finally {
241
+ this.components.connectionManager.afterUpgradeInbound()
224
242
  timeoutController.clear()
225
243
  }
226
244
  }
@@ -228,7 +246,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
228
246
  /**
229
247
  * Upgrades an outbound connection
230
248
  */
231
- async upgradeOutbound (maConn: MultiaddrConnection): Promise<Connection> {
249
+ async upgradeOutbound (maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise<Connection> {
232
250
  const idStr = maConn.remoteAddr.getPeerId()
233
251
  if (idStr == null) {
234
252
  throw errCode(new Error('outbound connection must have a peer id'), codes.ERR_INVALID_MULTIADDR)
@@ -236,7 +254,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
236
254
 
237
255
  const remotePeerId = peerIdFromString(idStr)
238
256
 
239
- if (await this.components.getConnectionGater().denyOutboundConnection(remotePeerId, maConn)) {
257
+ if (await this.components.connectionGater.denyOutboundConnection(remotePeerId, maConn)) {
240
258
  throw errCode(new Error('The multiaddr connection is blocked by connectionGater.denyOutboundConnection'), codes.ERR_CONNECTION_INTERCEPTED)
241
259
  }
242
260
 
@@ -247,7 +265,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
247
265
  let muxerFactory
248
266
  let setPeer
249
267
  let proxyPeer
250
- const metrics = this.components.getMetrics()
268
+ const metrics = this.components.metrics
251
269
 
252
270
  if (metrics != null) {
253
271
  ({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())
@@ -258,39 +276,51 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
258
276
 
259
277
  log('Starting the outbound connection upgrade')
260
278
 
279
+ // If the transport natively supports encryption, skip connection
280
+ // protector and encryption
281
+
261
282
  // Protect
262
283
  let protectedConn = maConn
263
- const protector = this.components.getConnectionProtector()
284
+ if (opts?.skipProtection !== true) {
285
+ const protector = this.components.connectionProtector
264
286
 
265
- if (protector != null) {
266
- protectedConn = await protector.protect(maConn)
287
+ if (protector != null) {
288
+ protectedConn = await protector.protect(maConn)
289
+ }
267
290
  }
268
291
 
269
292
  try {
270
293
  // Encrypt the connection
271
- ({
272
- conn: encryptedConn,
273
- remotePeer,
274
- protocol: cryptoProtocol
275
- } = await this._encryptOutbound(protectedConn, remotePeerId))
294
+ encryptedConn = protectedConn
295
+ if (opts?.skipEncryption !== true) {
296
+ ({
297
+ conn: encryptedConn,
298
+ remotePeer,
299
+ protocol: cryptoProtocol
300
+ } = await this._encryptOutbound(protectedConn, remotePeerId))
276
301
 
277
- if (await this.components.getConnectionGater().denyOutboundEncryptedConnection(remotePeer, {
278
- ...protectedConn,
279
- ...encryptedConn
280
- })) {
281
- throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)
302
+ if (await this.components.connectionGater.denyOutboundEncryptedConnection(remotePeer, {
303
+ ...protectedConn,
304
+ ...encryptedConn
305
+ })) {
306
+ throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)
307
+ }
308
+ } else {
309
+ cryptoProtocol = 'native'
310
+ remotePeer = remotePeerId
282
311
  }
283
312
 
284
- // Multiplex the connection
285
- if (this.muxers.size > 0) {
313
+ upgradedConn = encryptedConn
314
+ if (opts?.muxerFactory != null) {
315
+ muxerFactory = opts.muxerFactory
316
+ } else if (this.muxers.size > 0) {
317
+ // Multiplex the connection
286
318
  const multiplexed = await this._multiplexOutbound({
287
319
  ...protectedConn,
288
320
  ...encryptedConn
289
321
  }, this.muxers)
290
322
  muxerFactory = multiplexed.muxerFactory
291
323
  upgradedConn = multiplexed.stream
292
- } else {
293
- upgradedConn = encryptedConn
294
324
  }
295
325
  } catch (err: any) {
296
326
  log.error('Failed to upgrade outbound connection', err)
@@ -298,7 +328,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
298
328
  throw err
299
329
  }
300
330
 
301
- if (await this.components.getConnectionGater().denyOutboundUpgradedConnection(remotePeer, {
331
+ if (await this.components.connectionGater.denyOutboundUpgradedConnection(remotePeer, {
302
332
  ...protectedConn,
303
333
  ...encryptedConn
304
334
  })) {
@@ -351,11 +381,11 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
351
381
 
352
382
  void Promise.resolve()
353
383
  .then(async () => {
354
- const protocols = this.components.getRegistrar().getProtocols()
384
+ const protocols = this.components.registrar.getProtocols()
355
385
  const { stream, protocol } = await mss.handle(muxedStream, protocols)
356
386
  log('%s: incoming stream opened on %s', direction, protocol)
357
387
 
358
- const metrics = this.components.getMetrics()
388
+ const metrics = this.components.metrics
359
389
 
360
390
  if (metrics != null) {
361
391
  metrics.trackStream({ stream, remotePeer, protocol })
@@ -365,7 +395,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
365
395
  return
366
396
  }
367
397
 
368
- const incomingLimit = findIncomingStreamLimit(protocol, this.components.getRegistrar())
398
+ const incomingLimit = findIncomingStreamLimit(protocol, this.components.registrar)
369
399
  const streamCount = countStreams(protocol, 'inbound', connection)
370
400
 
371
401
  if (streamCount === incomingLimit) {
@@ -382,7 +412,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
382
412
 
383
413
  // If a protocol stream has been successfully negotiated and is to be passed to the application,
384
414
  // the peerstore should ensure that the peer is registered with that protocol
385
- this.components.getPeerStore().protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))
415
+ this.components.peerStore.protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))
386
416
 
387
417
  connection.addStream(muxedStream)
388
418
  this._onStream({ connection, stream: muxedStream, protocol })
@@ -401,18 +431,14 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
401
431
  }
402
432
  })
403
433
 
404
- if (isInitializable(muxer)) {
405
- muxer.init(this.components)
406
- }
407
-
408
434
  newStream = async (protocols: string[], options: AbortOptions = {}): Promise<Stream> => {
409
435
  if (muxer == null) {
410
436
  throw errCode(new Error('Stream is not multiplexed'), codes.ERR_MUXER_UNAVAILABLE)
411
437
  }
412
438
 
413
439
  log('%s: starting new stream on %s', direction, protocols)
414
- const muxedStream = muxer.newStream()
415
- const metrics = this.components.getMetrics()
440
+ const muxedStream = await muxer.newStream()
441
+ const metrics = this.components.metrics
416
442
  let controller: TimeoutController | undefined
417
443
 
418
444
  try {
@@ -434,7 +460,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
434
460
  metrics.trackStream({ stream, remotePeer, protocol })
435
461
  }
436
462
 
437
- const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.getRegistrar())
463
+ const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar)
438
464
  const streamCount = countStreams(protocol, 'outbound', connection)
439
465
 
440
466
  if (streamCount === outgoingLimit) {
@@ -446,7 +472,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
446
472
 
447
473
  // If a protocol stream has been successfully negotiated and is to be passed to the application,
448
474
  // the peerstore should ensure that the peer is registered with that protocol
449
- this.components.getPeerStore().protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))
475
+ this.components.peerStore.protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))
450
476
 
451
477
  // after the handshake the returned stream can have early data so override
452
478
  // the souce/sink
@@ -543,7 +569,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
543
569
  */
544
570
  _onStream (opts: OnStreamOptions): void {
545
571
  const { connection, stream, protocol } = opts
546
- const { handler } = this.components.getRegistrar().getHandler(protocol)
572
+ const { handler } = this.components.registrar.getHandler(protocol)
547
573
 
548
574
  handler({ connection, stream })
549
575
  }
@@ -568,7 +594,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
568
594
  log('encrypting inbound connection...')
569
595
 
570
596
  return {
571
- ...await encrypter.secureInbound(this.components.getPeerId(), stream),
597
+ ...await encrypter.secureInbound(this.components.peerId, stream),
572
598
  protocol
573
599
  }
574
600
  } catch (err: any) {
@@ -597,7 +623,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
597
623
  log('encrypting outbound connection to %p', remotePeerId)
598
624
 
599
625
  return {
600
- ...await encrypter.secureOutbound(this.components.getPeerId(), stream, remotePeerId),
626
+ ...await encrypter.secureOutbound(this.components.peerId, stream, remotePeerId),
601
627
  protocol
602
628
  }
603
629
  } catch (err: any) {
@@ -609,7 +635,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
609
635
  * Selects one of the given muxers via multistream-select. That
610
636
  * muxer will be used for all future streams on the connection.
611
637
  */
612
- async _multiplexOutbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>): Promise<{ stream: Duplex<Uint8Array>, muxerFactory?: StreamMuxerFactory}> {
638
+ async _multiplexOutbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>): Promise<{stream: Duplex<Uint8Array>, muxerFactory?: StreamMuxerFactory}> {
613
639
  const protocols = Array.from(muxers.keys())
614
640
  log('outbound selecting muxer %s', protocols)
615
641
  try {
@@ -629,7 +655,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
629
655
  * Registers support for one of the given muxers via multistream-select. The
630
656
  * selected muxer will be used for all future streams on the connection.
631
657
  */
632
- async _multiplexInbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>): Promise<{ stream: Duplex<Uint8Array>, muxerFactory?: StreamMuxerFactory}> {
658
+ async _multiplexInbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>): Promise<{stream: Duplex<Uint8Array>, muxerFactory?: StreamMuxerFactory}> {
633
659
  const protocols = Array.from(muxers.keys())
634
660
  log('inbound handling muxers %s', protocols)
635
661
  try {
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '0.39.5'
1
+ export const version = '0.40.0'
2
2
  export const name = 'libp2p'