libp2p 0.39.5 → 0.40.0-030dbc8

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 (170) hide show
  1. package/README.md +14 -2
  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 +19 -6
  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/config.d.ts.map +1 -1
  26. package/dist/src/config.js +0 -11
  27. package/dist/src/config.js.map +1 -1
  28. package/dist/src/connection-manager/auto-dialler.d.ts +9 -2
  29. package/dist/src/connection-manager/auto-dialler.d.ts.map +1 -1
  30. package/dist/src/connection-manager/auto-dialler.js +6 -6
  31. package/dist/src/connection-manager/auto-dialler.js.map +1 -1
  32. package/dist/src/connection-manager/dialer/index.d.ts +12 -6
  33. package/dist/src/connection-manager/dialer/index.d.ts.map +1 -1
  34. package/dist/src/connection-manager/dialer/index.js +12 -17
  35. package/dist/src/connection-manager/dialer/index.js.map +1 -1
  36. package/dist/src/connection-manager/index.d.ts +41 -17
  37. package/dist/src/connection-manager/index.d.ts.map +1 -1
  38. package/dist/src/connection-manager/index.js +80 -81
  39. package/dist/src/connection-manager/index.js.map +1 -1
  40. package/dist/src/content-routing/index.d.ts +7 -2
  41. package/dist/src/content-routing/index.d.ts.map +1 -1
  42. package/dist/src/content-routing/index.js +4 -4
  43. package/dist/src/content-routing/index.js.map +1 -1
  44. package/dist/src/content-routing/utils.d.ts +1 -1
  45. package/dist/src/content-routing/utils.d.ts.map +1 -1
  46. package/dist/src/errors.d.ts +2 -1
  47. package/dist/src/errors.d.ts.map +1 -1
  48. package/dist/src/errors.js +1 -0
  49. package/dist/src/errors.js.map +1 -1
  50. package/dist/src/fetch/index.d.ts +7 -3
  51. package/dist/src/fetch/index.d.ts.map +1 -1
  52. package/dist/src/fetch/index.js +18 -6
  53. package/dist/src/fetch/index.js.map +1 -1
  54. package/dist/src/fetch/pb/proto.d.ts.map +1 -1
  55. package/dist/src/fetch/pb/proto.js +24 -35
  56. package/dist/src/fetch/pb/proto.js.map +1 -1
  57. package/dist/src/identify/index.d.ts +13 -3
  58. package/dist/src/identify/index.d.ts.map +1 -1
  59. package/dist/src/identify/index.js +41 -41
  60. package/dist/src/identify/index.js.map +1 -1
  61. package/dist/src/identify/pb/message.d.ts.map +1 -1
  62. package/dist/src/identify/pb/message.js +23 -34
  63. package/dist/src/identify/pb/message.js.map +1 -1
  64. package/dist/src/index.d.ts +13 -12
  65. package/dist/src/index.d.ts.map +1 -1
  66. package/dist/src/index.js.map +1 -1
  67. package/dist/src/insecure/index.d.ts +2 -8
  68. package/dist/src/insecure/index.d.ts.map +1 -1
  69. package/dist/src/insecure/index.js +5 -3
  70. package/dist/src/insecure/index.js.map +1 -1
  71. package/dist/src/insecure/pb/proto.d.ts.map +1 -1
  72. package/dist/src/insecure/pb/proto.js +24 -29
  73. package/dist/src/insecure/pb/proto.js.map +1 -1
  74. package/dist/src/keychain/index.d.ts +6 -2
  75. package/dist/src/keychain/index.d.ts.map +1 -1
  76. package/dist/src/keychain/index.js +19 -19
  77. package/dist/src/keychain/index.js.map +1 -1
  78. package/dist/src/libp2p.d.ts +1 -2
  79. package/dist/src/libp2p.d.ts.map +1 -1
  80. package/dist/src/libp2p.js +49 -73
  81. package/dist/src/libp2p.js.map +1 -1
  82. package/dist/src/nat-manager.d.ts +9 -2
  83. package/dist/src/nat-manager.d.ts.map +1 -1
  84. package/dist/src/nat-manager.js +3 -3
  85. package/dist/src/nat-manager.js.map +1 -1
  86. package/dist/src/peer-record-updater.d.ts +11 -2
  87. package/dist/src/peer-record-updater.d.ts.map +1 -1
  88. package/dist/src/peer-record-updater.js +10 -10
  89. package/dist/src/peer-record-updater.js.map +1 -1
  90. package/dist/src/peer-routing.d.ts +6 -2
  91. package/dist/src/peer-routing.d.ts.map +1 -1
  92. package/dist/src/peer-routing.js +4 -4
  93. package/dist/src/peer-routing.js.map +1 -1
  94. package/dist/src/ping/index.d.ts +7 -3
  95. package/dist/src/ping/index.d.ts.map +1 -1
  96. package/dist/src/ping/index.js +3 -3
  97. package/dist/src/ping/index.js.map +1 -1
  98. package/dist/src/pnet/index.d.ts +2 -17
  99. package/dist/src/pnet/index.d.ts.map +1 -1
  100. package/dist/src/pnet/index.js +4 -1
  101. package/dist/src/pnet/index.js.map +1 -1
  102. package/dist/src/pubsub/dummy-pubsub.d.ts +2 -1
  103. package/dist/src/pubsub/dummy-pubsub.d.ts.map +1 -1
  104. package/dist/src/pubsub/dummy-pubsub.js +4 -0
  105. package/dist/src/pubsub/dummy-pubsub.js.map +1 -1
  106. package/dist/src/registrar.d.ts +9 -3
  107. package/dist/src/registrar.d.ts.map +1 -1
  108. package/dist/src/registrar.js +6 -6
  109. package/dist/src/registrar.js.map +1 -1
  110. package/dist/src/transport-manager.d.ts +9 -3
  111. package/dist/src/transport-manager.d.ts.map +1 -1
  112. package/dist/src/transport-manager.js +5 -6
  113. package/dist/src/transport-manager.js.map +1 -1
  114. package/dist/src/upgrader.d.ts +17 -5
  115. package/dist/src/upgrader.d.ts.map +1 -1
  116. package/dist/src/upgrader.js +55 -75
  117. package/dist/src/upgrader.js.map +1 -1
  118. package/package.json +39 -40
  119. package/src/address-manager/index.ts +34 -10
  120. package/src/circuit/README.md +6 -6
  121. package/src/circuit/auto-relay.ts +15 -15
  122. package/src/circuit/index.ts +16 -5
  123. package/src/circuit/pb/index.ts +29 -35
  124. package/src/circuit/transport.ts +49 -20
  125. package/src/components.ts +332 -0
  126. package/src/config.ts +0 -11
  127. package/src/connection-manager/auto-dialler.ts +17 -9
  128. package/src/connection-manager/dialer/index.ts +26 -25
  129. package/src/connection-manager/index.ts +136 -93
  130. package/src/content-routing/index.ts +13 -7
  131. package/src/errors.ts +2 -1
  132. package/src/fetch/index.ts +28 -10
  133. package/src/fetch/pb/proto.ts +24 -35
  134. package/src/identify/index.ts +57 -53
  135. package/src/identify/pb/message.ts +23 -35
  136. package/src/index.ts +12 -11
  137. package/src/insecure/index.ts +6 -3
  138. package/src/insecure/pb/proto.ts +24 -29
  139. package/src/keychain/index.ts +27 -22
  140. package/src/libp2p.ts +50 -79
  141. package/src/nat-manager.ts +14 -6
  142. package/src/peer-record-updater.ts +23 -13
  143. package/src/peer-routing.ts +12 -7
  144. package/src/ping/index.ts +12 -7
  145. package/src/pnet/index.ts +5 -1
  146. package/src/pubsub/dummy-pubsub.ts +3 -1
  147. package/src/registrar.ts +17 -10
  148. package/src/transport-manager.ts +16 -10
  149. package/src/upgrader.ts +78 -87
  150. package/src/version.ts +1 -1
  151. package/dist/src/connection-manager/dialer/auto-dialer.d.ts +0 -16
  152. package/dist/src/connection-manager/dialer/auto-dialer.d.ts.map +0 -1
  153. package/dist/src/connection-manager/dialer/auto-dialer.js +0 -43
  154. package/dist/src/connection-manager/dialer/auto-dialer.js.map +0 -1
  155. package/dist/src/metrics/index.d.ts +0 -93
  156. package/dist/src/metrics/index.d.ts.map +0 -1
  157. package/dist/src/metrics/index.js +0 -234
  158. package/dist/src/metrics/index.js.map +0 -1
  159. package/dist/src/metrics/moving-average.d.ts +0 -14
  160. package/dist/src/metrics/moving-average.d.ts.map +0 -1
  161. package/dist/src/metrics/moving-average.js +0 -40
  162. package/dist/src/metrics/moving-average.js.map +0 -1
  163. package/dist/src/metrics/stats.d.ts +0 -87
  164. package/dist/src/metrics/stats.d.ts.map +0 -1
  165. package/dist/src/metrics/stats.js +0 -183
  166. package/dist/src/metrics/stats.js.map +0 -1
  167. package/src/connection-manager/dialer/auto-dialer.ts +0 -65
  168. package/src/metrics/index.ts +0 -311
  169. package/src/metrics/moving-average.ts +0 -53
  170. package/src/metrics/stats.ts +0 -238
package/src/upgrader.ts CHANGED
@@ -2,25 +2,25 @@ import { logger } from '@libp2p/logger'
2
2
  import errCode from 'err-code'
3
3
  import * as mss from '@libp2p/multistream-select'
4
4
  import { pipe } from 'it-pipe'
5
- // @ts-expect-error mutable-proxy does not export types
6
- import mutableProxy from 'mutable-proxy'
7
5
  import { codes } from './errors.js'
8
6
  import { createConnection } from '@libp2p/connection'
9
7
  import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'
10
8
  import { peerIdFromString } from '@libp2p/peer-id'
11
- import type { MultiaddrConnection, Connection, Stream } from '@libp2p/interface-connection'
9
+ import type { MultiaddrConnection, Connection, Stream, ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'
12
10
  import type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interface-connection-encrypter'
13
11
  import type { StreamMuxer, StreamMuxerFactory } from '@libp2p/interface-stream-muxer'
14
12
  import type { PeerId } from '@libp2p/interface-peer-id'
15
- import type { Upgrader, UpgraderEvents } from '@libp2p/interface-transport'
13
+ import type { Upgrader, UpgraderEvents, UpgraderOptions } from '@libp2p/interface-transport'
16
14
  import type { Duplex } from 'it-stream-types'
17
- import { Components, isInitializable } from '@libp2p/components'
18
15
  import type { AbortOptions } from '@libp2p/interfaces'
19
16
  import type { Registrar } from '@libp2p/interface-registrar'
20
17
  import { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js'
21
18
  import { TimeoutController } from 'timeout-abort-controller'
22
19
  import { abortableDuplex } from 'abortable-iterator'
23
20
  import { setMaxListeners } from 'events'
21
+ import type { Metrics } from '@libp2p/interface-metrics'
22
+ import type { ConnectionManager } from '@libp2p/interface-connection-manager'
23
+ import type { PeerStore } from '@libp2p/interface-peer-store'
24
24
 
25
25
  const log = logger('libp2p:upgrader')
26
26
 
@@ -94,13 +94,23 @@ function countStreams (protocol: string, direction: 'inbound' | 'outbound', conn
94
94
  return streamCount
95
95
  }
96
96
 
97
+ export interface DefaultUpgraderComponents {
98
+ peerId: PeerId
99
+ metrics?: Metrics
100
+ connectionManager: ConnectionManager
101
+ connectionGater: ConnectionGater
102
+ connectionProtector?: ConnectionProtector
103
+ registrar: Registrar
104
+ peerStore: PeerStore
105
+ }
106
+
97
107
  export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upgrader {
98
- private readonly components: Components
108
+ private readonly components: DefaultUpgraderComponents
99
109
  private readonly connectionEncryption: Map<string, ConnectionEncrypter>
100
110
  private readonly muxers: Map<string, StreamMuxerFactory>
101
111
  private readonly inboundUpgradeTimeout: number
102
112
 
103
- constructor (components: Components, init: UpgraderInit) {
113
+ constructor (components: DefaultUpgraderComponents, init: UpgraderInit) {
104
114
  super()
105
115
 
106
116
  this.components = components
@@ -123,14 +133,17 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
123
133
  * Upgrades an inbound connection
124
134
  */
125
135
  async upgradeInbound (maConn: MultiaddrConnection): Promise<Connection> {
136
+ const accept = await this.components.connectionManager.acceptIncomingConnection(maConn)
137
+
138
+ if (!accept) {
139
+ throw errCode(new Error('connection denied'), codes.ERR_CONNECTION_DENIED)
140
+ }
141
+
126
142
  let encryptedConn
127
143
  let remotePeer
128
144
  let upgradedConn: Duplex<Uint8Array>
129
145
  let muxerFactory: StreamMuxerFactory | undefined
130
146
  let cryptoProtocol
131
- let setPeer
132
- let proxyPeer
133
- const metrics = this.components.getMetrics()
134
147
 
135
148
  const timeoutController = new TimeoutController(this.inboundUpgradeTimeout)
136
149
 
@@ -144,22 +157,17 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
144
157
  maConn.source = abortableStream.source
145
158
  maConn.sink = abortableStream.sink
146
159
 
147
- if (await this.components.getConnectionGater().denyInboundConnection(maConn)) {
160
+ if (await this.components.connectionGater.denyInboundConnection(maConn)) {
148
161
  throw errCode(new Error('The multiaddr connection is blocked by gater.acceptConnection'), codes.ERR_CONNECTION_INTERCEPTED)
149
162
  }
150
163
 
151
- if (metrics != null) {
152
- ({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())
153
- const idString = `${(Math.random() * 1e9).toString(36)}${Date.now()}`
154
- setPeer({ toString: () => idString })
155
- metrics.trackStream({ stream: maConn, remotePeer: proxyPeer })
156
- }
164
+ this.components.metrics?.trackMultiaddrConnection(maConn)
157
165
 
158
166
  log('starting the inbound connection upgrade')
159
167
 
160
168
  // Protect
161
169
  let protectedConn = maConn
162
- const protector = this.components.getConnectionProtector()
170
+ const protector = this.components.connectionProtector
163
171
 
164
172
  if (protector != null) {
165
173
  log('protecting the inbound connection')
@@ -174,7 +182,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
174
182
  protocol: cryptoProtocol
175
183
  } = await this._encryptInbound(protectedConn))
176
184
 
177
- if (await this.components.getConnectionGater().denyInboundEncryptedConnection(remotePeer, {
185
+ if (await this.components.connectionGater.denyInboundEncryptedConnection(remotePeer, {
178
186
  ...protectedConn,
179
187
  ...encryptedConn
180
188
  })) {
@@ -194,22 +202,16 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
194
202
  }
195
203
  } catch (err: any) {
196
204
  log.error('Failed to upgrade inbound connection', err)
197
- await maConn.close(err)
198
205
  throw err
199
206
  }
200
207
 
201
- if (await this.components.getConnectionGater().denyInboundUpgradedConnection(remotePeer, {
208
+ if (await this.components.connectionGater.denyInboundUpgradedConnection(remotePeer, {
202
209
  ...protectedConn,
203
210
  ...encryptedConn
204
211
  })) {
205
212
  throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)
206
213
  }
207
214
 
208
- if (metrics != null) {
209
- metrics.updatePlaceholder(proxyPeer, remotePeer)
210
- setPeer(remotePeer)
211
- }
212
-
213
215
  log('Successfully upgraded inbound connection')
214
216
 
215
217
  return this._createConnection({
@@ -221,6 +223,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
221
223
  remotePeer
222
224
  })
223
225
  } finally {
226
+ this.components.connectionManager.afterUpgradeInbound()
224
227
  timeoutController.clear()
225
228
  }
226
229
  }
@@ -228,7 +231,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
228
231
  /**
229
232
  * Upgrades an outbound connection
230
233
  */
231
- async upgradeOutbound (maConn: MultiaddrConnection): Promise<Connection> {
234
+ async upgradeOutbound (maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise<Connection> {
232
235
  const idStr = maConn.remoteAddr.getPeerId()
233
236
  if (idStr == null) {
234
237
  throw errCode(new Error('outbound connection must have a peer id'), codes.ERR_INVALID_MULTIADDR)
@@ -236,7 +239,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
236
239
 
237
240
  const remotePeerId = peerIdFromString(idStr)
238
241
 
239
- if (await this.components.getConnectionGater().denyOutboundConnection(remotePeerId, maConn)) {
242
+ if (await this.components.connectionGater.denyOutboundConnection(remotePeerId, maConn)) {
240
243
  throw errCode(new Error('The multiaddr connection is blocked by connectionGater.denyOutboundConnection'), codes.ERR_CONNECTION_INTERCEPTED)
241
244
  }
242
245
 
@@ -245,52 +248,56 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
245
248
  let upgradedConn
246
249
  let cryptoProtocol
247
250
  let muxerFactory
248
- let setPeer
249
- let proxyPeer
250
- const metrics = this.components.getMetrics()
251
-
252
- if (metrics != null) {
253
- ({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())
254
- const idString = `${(Math.random() * 1e9).toString(36)}${Date.now()}`
255
- setPeer({ toB58String: () => idString })
256
- metrics.trackStream({ stream: maConn, remotePeer: proxyPeer })
257
- }
251
+
252
+ this.components.metrics?.trackMultiaddrConnection(maConn)
258
253
 
259
254
  log('Starting the outbound connection upgrade')
260
255
 
256
+ // If the transport natively supports encryption, skip connection
257
+ // protector and encryption
258
+
261
259
  // Protect
262
260
  let protectedConn = maConn
263
- const protector = this.components.getConnectionProtector()
261
+ if (opts?.skipProtection !== true) {
262
+ const protector = this.components.connectionProtector
264
263
 
265
- if (protector != null) {
266
- protectedConn = await protector.protect(maConn)
264
+ if (protector != null) {
265
+ protectedConn = await protector.protect(maConn)
266
+ }
267
267
  }
268
268
 
269
269
  try {
270
270
  // Encrypt the connection
271
- ({
272
- conn: encryptedConn,
273
- remotePeer,
274
- protocol: cryptoProtocol
275
- } = await this._encryptOutbound(protectedConn, remotePeerId))
271
+ encryptedConn = protectedConn
272
+ if (opts?.skipEncryption !== true) {
273
+ ({
274
+ conn: encryptedConn,
275
+ remotePeer,
276
+ protocol: cryptoProtocol
277
+ } = await this._encryptOutbound(protectedConn, remotePeerId))
276
278
 
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)
279
+ if (await this.components.connectionGater.denyOutboundEncryptedConnection(remotePeer, {
280
+ ...protectedConn,
281
+ ...encryptedConn
282
+ })) {
283
+ throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)
284
+ }
285
+ } else {
286
+ cryptoProtocol = 'native'
287
+ remotePeer = remotePeerId
282
288
  }
283
289
 
284
- // Multiplex the connection
285
- if (this.muxers.size > 0) {
290
+ upgradedConn = encryptedConn
291
+ if (opts?.muxerFactory != null) {
292
+ muxerFactory = opts.muxerFactory
293
+ } else if (this.muxers.size > 0) {
294
+ // Multiplex the connection
286
295
  const multiplexed = await this._multiplexOutbound({
287
296
  ...protectedConn,
288
297
  ...encryptedConn
289
298
  }, this.muxers)
290
299
  muxerFactory = multiplexed.muxerFactory
291
300
  upgradedConn = multiplexed.stream
292
- } else {
293
- upgradedConn = encryptedConn
294
301
  }
295
302
  } catch (err: any) {
296
303
  log.error('Failed to upgrade outbound connection', err)
@@ -298,18 +305,13 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
298
305
  throw err
299
306
  }
300
307
 
301
- if (await this.components.getConnectionGater().denyOutboundUpgradedConnection(remotePeer, {
308
+ if (await this.components.connectionGater.denyOutboundUpgradedConnection(remotePeer, {
302
309
  ...protectedConn,
303
310
  ...encryptedConn
304
311
  })) {
305
312
  throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)
306
313
  }
307
314
 
308
- if (metrics != null) {
309
- metrics.updatePlaceholder(proxyPeer, remotePeer)
310
- setPeer(remotePeer)
311
- }
312
-
313
315
  log('Successfully upgraded outbound connection')
314
316
 
315
317
  return this._createConnection({
@@ -351,21 +353,15 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
351
353
 
352
354
  void Promise.resolve()
353
355
  .then(async () => {
354
- const protocols = this.components.getRegistrar().getProtocols()
356
+ const protocols = this.components.registrar.getProtocols()
355
357
  const { stream, protocol } = await mss.handle(muxedStream, protocols)
356
358
  log('%s: incoming stream opened on %s', direction, protocol)
357
359
 
358
- const metrics = this.components.getMetrics()
359
-
360
- if (metrics != null) {
361
- metrics.trackStream({ stream, remotePeer, protocol })
362
- }
363
-
364
360
  if (connection == null) {
365
361
  return
366
362
  }
367
363
 
368
- const incomingLimit = findIncomingStreamLimit(protocol, this.components.getRegistrar())
364
+ const incomingLimit = findIncomingStreamLimit(protocol, this.components.registrar)
369
365
  const streamCount = countStreams(protocol, 'inbound', connection)
370
366
 
371
367
  if (streamCount === incomingLimit) {
@@ -382,9 +378,11 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
382
378
 
383
379
  // If a protocol stream has been successfully negotiated and is to be passed to the application,
384
380
  // 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))
381
+ this.components.peerStore.protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))
386
382
 
387
383
  connection.addStream(muxedStream)
384
+ this.components.metrics?.trackProtocolStream(muxedStream, connection)
385
+
388
386
  this._onStream({ connection, stream: muxedStream, protocol })
389
387
  })
390
388
  .catch(err => {
@@ -401,18 +399,13 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
401
399
  }
402
400
  })
403
401
 
404
- if (isInitializable(muxer)) {
405
- muxer.init(this.components)
406
- }
407
-
408
402
  newStream = async (protocols: string[], options: AbortOptions = {}): Promise<Stream> => {
409
403
  if (muxer == null) {
410
404
  throw errCode(new Error('Stream is not multiplexed'), codes.ERR_MUXER_UNAVAILABLE)
411
405
  }
412
406
 
413
407
  log('%s: starting new stream on %s', direction, protocols)
414
- const muxedStream = muxer.newStream()
415
- const metrics = this.components.getMetrics()
408
+ const muxedStream = await muxer.newStream()
416
409
  let controller: TimeoutController | undefined
417
410
 
418
411
  try {
@@ -430,11 +423,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
430
423
 
431
424
  const { stream, protocol } = await mss.select(muxedStream, protocols, options)
432
425
 
433
- if (metrics != null) {
434
- metrics.trackStream({ stream, remotePeer, protocol })
435
- }
436
-
437
- const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.getRegistrar())
426
+ const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar)
438
427
  const streamCount = countStreams(protocol, 'outbound', connection)
439
428
 
440
429
  if (streamCount === outgoingLimit) {
@@ -446,7 +435,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
446
435
 
447
436
  // If a protocol stream has been successfully negotiated and is to be passed to the application,
448
437
  // 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))
438
+ this.components.peerStore.protoBook.add(remotePeer, [protocol]).catch(err => log.error(err))
450
439
 
451
440
  // after the handshake the returned stream can have early data so override
452
441
  // the souce/sink
@@ -454,6 +443,8 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
454
443
  muxedStream.sink = stream.sink
455
444
  muxedStream.stat.protocol = protocol
456
445
 
446
+ this.components.metrics?.trackProtocolStream(muxedStream, connection)
447
+
457
448
  return muxedStream
458
449
  } catch (err: any) {
459
450
  log.error('could not create new stream', err)
@@ -543,7 +534,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
543
534
  */
544
535
  _onStream (opts: OnStreamOptions): void {
545
536
  const { connection, stream, protocol } = opts
546
- const { handler } = this.components.getRegistrar().getHandler(protocol)
537
+ const { handler } = this.components.registrar.getHandler(protocol)
547
538
 
548
539
  handler({ connection, stream })
549
540
  }
@@ -568,7 +559,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
568
559
  log('encrypting inbound connection...')
569
560
 
570
561
  return {
571
- ...await encrypter.secureInbound(this.components.getPeerId(), stream),
562
+ ...await encrypter.secureInbound(this.components.peerId, stream),
572
563
  protocol
573
564
  }
574
565
  } catch (err: any) {
@@ -597,7 +588,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
597
588
  log('encrypting outbound connection to %p', remotePeerId)
598
589
 
599
590
  return {
600
- ...await encrypter.secureOutbound(this.components.getPeerId(), stream, remotePeerId),
591
+ ...await encrypter.secureOutbound(this.components.peerId, stream, remotePeerId),
601
592
  protocol
602
593
  }
603
594
  } catch (err: any) {
@@ -609,7 +600,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
609
600
  * Selects one of the given muxers via multistream-select. That
610
601
  * muxer will be used for all future streams on the connection.
611
602
  */
612
- async _multiplexOutbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>): Promise<{ stream: Duplex<Uint8Array>, muxerFactory?: StreamMuxerFactory}> {
603
+ async _multiplexOutbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>): Promise<{stream: Duplex<Uint8Array>, muxerFactory?: StreamMuxerFactory}> {
613
604
  const protocols = Array.from(muxers.keys())
614
605
  log('outbound selecting muxer %s', protocols)
615
606
  try {
@@ -629,7 +620,7 @@ export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upg
629
620
  * Registers support for one of the given muxers via multistream-select. The
630
621
  * selected muxer will be used for all future streams on the connection.
631
622
  */
632
- async _multiplexInbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>): Promise<{ stream: Duplex<Uint8Array>, muxerFactory?: StreamMuxerFactory}> {
623
+ async _multiplexInbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>): Promise<{stream: Duplex<Uint8Array>, muxerFactory?: StreamMuxerFactory}> {
633
624
  const protocols = Array.from(muxers.keys())
634
625
  log('inbound handling muxers %s', protocols)
635
626
  try {
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '0.39.5'
1
+ export const version = '0.40.0-030dbc8'
2
2
  export const name = 'libp2p'
@@ -1,16 +0,0 @@
1
- import type { PeerInfo } from '@libp2p/interface-peer-info';
2
- import type { Components } from '@libp2p/components';
3
- export interface AutoDialerInit {
4
- enabled: boolean;
5
- minConnections: number;
6
- dialTimeout: number;
7
- }
8
- export declare class AutoDialer {
9
- private readonly components;
10
- private readonly enabled;
11
- private readonly minConnections;
12
- private readonly dialTimeout;
13
- constructor(components: Components, init: AutoDialerInit);
14
- handle(evt: CustomEvent<PeerInfo>): void;
15
- }
16
- //# sourceMappingURL=auto-dialer.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"auto-dialer.d.ts","sourceRoot":"","sources":["../../../../src/connection-manager/dialer/auto-dialer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAA;AAE3D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAA;AAMpD,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,OAAO,CAAA;IAChB,cAAc,EAAE,MAAM,CAAA;IACtB,WAAW,EAAE,MAAM,CAAA;CACpB;AAED,qBAAa,UAAU;IACrB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAY;IACvC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAQ;IACvC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAQ;gBAEvB,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,cAAc;IAOlD,MAAM,CAAE,GAAG,EAAE,WAAW,CAAC,QAAQ,CAAC;CAqC1C"}
@@ -1,43 +0,0 @@
1
- import { logger } from '@libp2p/logger';
2
- import { TimeoutController } from 'timeout-abort-controller';
3
- import { setMaxListeners } from 'events';
4
- const log = logger('libp2p:dialer:auto-dialer');
5
- export class AutoDialer {
6
- constructor(components, init) {
7
- this.components = components;
8
- this.enabled = init.enabled;
9
- this.minConnections = init.minConnections;
10
- this.dialTimeout = init.dialTimeout;
11
- }
12
- handle(evt) {
13
- const { detail: peer } = evt;
14
- if (!this.enabled) {
15
- return;
16
- }
17
- const connections = this.components.getConnectionManager().getConnections(peer.id);
18
- // If auto dialing is on and we have no connection to the peer, check if we should dial
19
- if (connections.length === 0) {
20
- const minConnections = this.minConnections ?? 0;
21
- const allConnections = this.components.getConnectionManager().getConnections();
22
- if (minConnections > allConnections.length) {
23
- log('auto-dialing discovered peer %p with timeout %d', peer.id, this.dialTimeout);
24
- const controller = new TimeoutController(this.dialTimeout);
25
- try {
26
- // fails on node < 15.4
27
- setMaxListeners?.(Infinity, controller.signal);
28
- }
29
- catch { }
30
- void this.components.getConnectionManager().openConnection(peer.id, {
31
- signal: controller.signal
32
- })
33
- .catch(err => {
34
- log.error('could not connect to discovered peer %p with %o', peer.id, err);
35
- })
36
- .finally(() => {
37
- controller.clear();
38
- });
39
- }
40
- }
41
- }
42
- }
43
- //# sourceMappingURL=auto-dialer.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"auto-dialer.js","sourceRoot":"","sources":["../../../../src/connection-manager/dialer/auto-dialer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAEvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAA;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAA;AAExC,MAAM,GAAG,GAAG,MAAM,CAAC,2BAA2B,CAAC,CAAA;AAQ/C,MAAM,OAAO,UAAU;IAMrB,YAAa,UAAsB,EAAE,IAAoB;QACvD,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAA;QAC3B,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAA;QACzC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAA;IACrC,CAAC;IAEM,MAAM,CAAE,GAA0B;QACvC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,GAAG,CAAA;QAE5B,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;YACjB,OAAM;SACP;QAED,MAAM,WAAW,GAAG,IAAI,CAAC,UAAU,CAAC,oBAAoB,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;QAElF,uFAAuF;QACvF,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE;YAC5B,MAAM,cAAc,GAAG,IAAI,CAAC,cAAc,IAAI,CAAC,CAAA;YAE/C,MAAM,cAAc,GAAG,IAAI,CAAC,UAAU,CAAC,oBAAoB,EAAE,CAAC,cAAc,EAAE,CAAA;YAE9E,IAAI,cAAc,GAAG,cAAc,CAAC,MAAM,EAAE;gBAC1C,GAAG,CAAC,iDAAiD,EAAE,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,WAAW,CAAC,CAAA;gBAEjF,MAAM,UAAU,GAAG,IAAI,iBAAiB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;gBAE1D,IAAI;oBACF,uBAAuB;oBACvB,eAAe,EAAE,CAAC,QAAQ,EAAE,UAAU,CAAC,MAAM,CAAC,CAAA;iBAC/C;gBAAC,MAAM,GAAE;gBAEV,KAAK,IAAI,CAAC,UAAU,CAAC,oBAAoB,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,EAAE,EAAE;oBAClE,MAAM,EAAE,UAAU,CAAC,MAAM;iBAC1B,CAAC;qBACC,KAAK,CAAC,GAAG,CAAC,EAAE;oBACX,GAAG,CAAC,KAAK,CAAC,iDAAiD,EAAE,IAAI,CAAC,EAAE,EAAE,GAAG,CAAC,CAAA;gBAC5E,CAAC,CAAC;qBACD,OAAO,CAAC,GAAG,EAAE;oBACZ,UAAU,CAAC,KAAK,EAAE,CAAA;gBACpB,CAAC,CAAC,CAAA;aACL;SACF;IACH,CAAC;CACF"}
@@ -1,93 +0,0 @@
1
- import { DefaultStats } from './stats.js';
2
- import type { ComponentMetricsUpdate, Metrics, Stats, TrackedMetric, TrackStreamOptions } from '@libp2p/interface-metrics';
3
- import type { PeerId } from '@libp2p/interface-peer-id';
4
- import type { Startable } from '@libp2p/interfaces/startable';
5
- export interface OnMessageOptions {
6
- remotePeer: PeerId;
7
- protocol?: string;
8
- direction: 'in' | 'out';
9
- dataLength: number;
10
- }
11
- export interface MetricsInit {
12
- enabled: boolean;
13
- computeThrottleMaxQueueSize: number;
14
- computeThrottleTimeout: number;
15
- movingAverageIntervals: number[];
16
- maxOldPeersRetention: number;
17
- }
18
- export declare class DefaultMetrics implements Metrics, Startable {
19
- globalStats: DefaultStats;
20
- private readonly enabled;
21
- private readonly peerStats;
22
- private readonly protocolStats;
23
- private readonly oldPeers;
24
- private running;
25
- private readonly systems;
26
- private readonly statsInit;
27
- constructor(init: MetricsInit);
28
- isStarted(): boolean;
29
- /**
30
- * Must be called for stats to saved. Any data pushed for tracking
31
- * will be ignored.
32
- */
33
- start(): Promise<void>;
34
- /**
35
- * Stops all averages timers and prevents new data from being tracked.
36
- * Once `stop` is called, `start` must be called to resume stats tracking.
37
- */
38
- stop(): Promise<void>;
39
- /**
40
- * Gets the global `Stats` object
41
- */
42
- getGlobal(): DefaultStats;
43
- /**
44
- * Returns a list of `PeerId` strings currently being tracked
45
- */
46
- getPeers(): string[];
47
- getComponentMetrics(): Map<string, Map<string, Map<string, TrackedMetric>>>;
48
- updateComponentMetric(update: ComponentMetricsUpdate): void;
49
- /**
50
- * Returns the `Stats` object for the given `PeerId` whether it
51
- * is a live peer, or in the disconnected peer LRU cache.
52
- */
53
- forPeer(peerId: PeerId): Stats | undefined;
54
- /**
55
- * Returns a list of all protocol strings currently being tracked
56
- */
57
- getProtocols(): string[];
58
- /**
59
- * Returns the `Stats` object for the given `protocol`
60
- */
61
- forProtocol(protocol: string): Stats | undefined;
62
- /**
63
- * Should be called when all connections to a given peer
64
- * have closed. The `Stats` collection for the peer will
65
- * be stopped and moved to an LRU for temporary retention.
66
- */
67
- onPeerDisconnected(peerId: PeerId): void;
68
- /**
69
- * Takes the metadata for a message and tracks it in the
70
- * appropriate categories. If the protocol is present, protocol
71
- * stats will also be tracked.
72
- */
73
- _onMessage(opts: OnMessageOptions): void;
74
- /**
75
- * Replaces the `PeerId` string with the given `peerId`.
76
- * If stats are already being tracked for the given `peerId`, the
77
- * placeholder stats will be merged with the existing stats.
78
- *
79
- * @param {PeerId} placeholder - A peerId string
80
- * @param {PeerId} peerId
81
- * @returns {void}
82
- */
83
- updatePlaceholder(placeholder: PeerId, peerId: PeerId): void;
84
- /**
85
- * Tracks data running through a given Duplex Iterable `stream`. If
86
- * the `peerId` is not provided, a placeholder string will be created and
87
- * returned. This allows lazy tracking of a peer when the peer is not yet known.
88
- * When the `PeerId` is known, `Metrics.updatePlaceholder` should be called
89
- * with the placeholder string returned from here, and the known `PeerId`.
90
- */
91
- trackStream(opts: TrackStreamOptions): void;
92
- }
93
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/metrics/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAa,MAAM,YAAY,CAAA;AACpD,OAAO,KAAK,EAAE,sBAAsB,EAAE,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAA;AAC1H,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAA;AACvD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAA;AAY7D,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,SAAS,EAAE,IAAI,GAAG,KAAK,CAAA;IACvB,UAAU,EAAE,MAAM,CAAA;CACnB;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,OAAO,CAAA;IAChB,2BAA2B,EAAE,MAAM,CAAA;IACnC,sBAAsB,EAAE,MAAM,CAAA;IAC9B,sBAAsB,EAAE,MAAM,EAAE,CAAA;IAChC,oBAAoB,EAAE,MAAM,CAAA;CAC7B;AAED,qBAAa,cAAe,YAAW,OAAO,EAAE,SAAS;IAChD,WAAW,EAAE,YAAY,CAAA;IAEhC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA2B;IACrD,OAAO,CAAC,QAAQ,CAAC,aAAa,CAA2B;IACzD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAwB;IACjD,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAsD;IAC9E,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAW;gBAExB,IAAI,EAAE,WAAW;IAe9B,SAAS;IAIT;;;OAGG;IACG,KAAK;IAQX;;;OAGG;IACG,IAAI;IAiBV;;OAEG;IACH,SAAS;IAIT;;OAEG;IACH,QAAQ;IAIR,mBAAmB;IAInB,qBAAqB,CAAE,MAAM,EAAE,sBAAsB;IA8BrD;;;OAGG;IACH,OAAO,CAAE,MAAM,EAAE,MAAM,GAAG,KAAK,GAAG,SAAS;IAK3C;;OAEG;IACH,YAAY,IAAK,MAAM,EAAE;IAIzB;;OAEG;IACH,WAAW,CAAE,QAAQ,EAAE,MAAM,GAAG,KAAK,GAAG,SAAS;IAIjD;;;;OAIG;IACH,kBAAkB,CAAE,MAAM,EAAE,MAAM;IAYlC;;;;OAIG;IACH,UAAU,CAAE,IAAI,EAAE,gBAAgB;IAkClC;;;;;;;;OAQG;IACH,iBAAiB,CAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAwBtD;;;;;;OAMG;IACH,WAAW,CAAE,IAAI,EAAE,kBAAkB,GAAG,IAAI;CA+B7C"}