libp2p 2.10.0 → 3.0.0-049bfa0fa

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 (121) hide show
  1. package/README.md +39 -37
  2. package/dist/index.min.js +14 -17
  3. package/dist/index.min.js.map +4 -4
  4. package/dist/src/address-manager/dns-mappings.d.ts +1 -2
  5. package/dist/src/address-manager/dns-mappings.d.ts.map +1 -1
  6. package/dist/src/address-manager/dns-mappings.js +39 -43
  7. package/dist/src/address-manager/dns-mappings.js.map +1 -1
  8. package/dist/src/address-manager/index.d.ts.map +1 -1
  9. package/dist/src/address-manager/index.js +31 -14
  10. package/dist/src/address-manager/index.js.map +1 -1
  11. package/dist/src/address-manager/ip-mappings.d.ts +1 -0
  12. package/dist/src/address-manager/ip-mappings.d.ts.map +1 -1
  13. package/dist/src/address-manager/ip-mappings.js +51 -40
  14. package/dist/src/address-manager/ip-mappings.js.map +1 -1
  15. package/dist/src/address-manager/observed-addresses.d.ts.map +1 -1
  16. package/dist/src/address-manager/observed-addresses.js +1 -3
  17. package/dist/src/address-manager/observed-addresses.js.map +1 -1
  18. package/dist/src/address-manager/transport-addresses.d.ts.map +1 -1
  19. package/dist/src/address-manager/transport-addresses.js +6 -8
  20. package/dist/src/address-manager/transport-addresses.js.map +1 -1
  21. package/dist/src/config/connection-gater.browser.d.ts.map +1 -1
  22. package/dist/src/config/connection-gater.browser.js +8 -22
  23. package/dist/src/config/connection-gater.browser.js.map +1 -1
  24. package/dist/src/config/connection-gater.d.ts.map +1 -1
  25. package/dist/src/config/connection-gater.js +1 -12
  26. package/dist/src/config/connection-gater.js.map +1 -1
  27. package/dist/src/config.d.ts.map +1 -1
  28. package/dist/src/config.js +3 -22
  29. package/dist/src/config.js.map +1 -1
  30. package/dist/src/connection-manager/address-sorter.d.ts.map +1 -1
  31. package/dist/src/connection-manager/address-sorter.js +1 -2
  32. package/dist/src/connection-manager/address-sorter.js.map +1 -1
  33. package/dist/src/connection-manager/connection-pruner.d.ts.map +1 -1
  34. package/dist/src/connection-manager/connection-pruner.js +7 -3
  35. package/dist/src/connection-manager/connection-pruner.js.map +1 -1
  36. package/dist/src/connection-manager/constants.defaults.d.ts +4 -0
  37. package/dist/src/connection-manager/constants.defaults.d.ts.map +1 -1
  38. package/dist/src/connection-manager/constants.defaults.js +4 -0
  39. package/dist/src/connection-manager/constants.defaults.js.map +1 -1
  40. package/dist/src/connection-manager/dial-queue.d.ts +2 -2
  41. package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
  42. package/dist/src/connection-manager/dial-queue.js +11 -23
  43. package/dist/src/connection-manager/dial-queue.js.map +1 -1
  44. package/dist/src/connection-manager/index.d.ts +10 -18
  45. package/dist/src/connection-manager/index.d.ts.map +1 -1
  46. package/dist/src/connection-manager/index.js +44 -26
  47. package/dist/src/connection-manager/index.js.map +1 -1
  48. package/dist/src/connection-manager/reconnect-queue.js +1 -1
  49. package/dist/src/connection-manager/reconnect-queue.js.map +1 -1
  50. package/dist/src/connection-manager/utils.d.ts +31 -3
  51. package/dist/src/connection-manager/utils.d.ts.map +1 -1
  52. package/dist/src/connection-manager/utils.js +99 -18
  53. package/dist/src/connection-manager/utils.js.map +1 -1
  54. package/dist/src/connection-monitor.d.ts +1 -1
  55. package/dist/src/connection-monitor.d.ts.map +1 -1
  56. package/dist/src/connection-monitor.js +2 -3
  57. package/dist/src/connection-monitor.js.map +1 -1
  58. package/dist/src/connection.d.ts +14 -9
  59. package/dist/src/connection.d.ts.map +1 -1
  60. package/dist/src/connection.js +118 -139
  61. package/dist/src/connection.js.map +1 -1
  62. package/dist/src/get-peer.js +3 -3
  63. package/dist/src/get-peer.js.map +1 -1
  64. package/dist/src/index.d.ts +2 -2
  65. package/dist/src/index.js +2 -2
  66. package/dist/src/libp2p.d.ts +3 -1
  67. package/dist/src/libp2p.d.ts.map +1 -1
  68. package/dist/src/libp2p.js +13 -7
  69. package/dist/src/libp2p.js.map +1 -1
  70. package/dist/src/peer-routing.js +1 -1
  71. package/dist/src/peer-routing.js.map +1 -1
  72. package/dist/src/random-walk.d.ts.map +1 -1
  73. package/dist/src/random-walk.js +13 -3
  74. package/dist/src/random-walk.js.map +1 -1
  75. package/dist/src/registrar.d.ts +8 -4
  76. package/dist/src/registrar.d.ts.map +1 -1
  77. package/dist/src/registrar.js +66 -46
  78. package/dist/src/registrar.js.map +1 -1
  79. package/dist/src/transport-manager.js +15 -2
  80. package/dist/src/transport-manager.js.map +1 -1
  81. package/dist/src/upgrader.d.ts +26 -16
  82. package/dist/src/upgrader.d.ts.map +1 -1
  83. package/dist/src/upgrader.js +88 -122
  84. package/dist/src/upgrader.js.map +1 -1
  85. package/dist/src/utils.d.ts +3 -0
  86. package/dist/src/utils.d.ts.map +1 -0
  87. package/dist/src/utils.js +25 -0
  88. package/dist/src/utils.js.map +1 -0
  89. package/dist/src/version.d.ts +1 -1
  90. package/dist/src/version.d.ts.map +1 -1
  91. package/dist/src/version.js +1 -1
  92. package/dist/src/version.js.map +1 -1
  93. package/package.json +27 -30
  94. package/src/address-manager/dns-mappings.ts +50 -50
  95. package/src/address-manager/index.ts +37 -17
  96. package/src/address-manager/ip-mappings.ts +64 -44
  97. package/src/address-manager/observed-addresses.ts +1 -3
  98. package/src/address-manager/transport-addresses.ts +7 -9
  99. package/src/config/connection-gater.browser.ts +8 -24
  100. package/src/config/connection-gater.ts +1 -12
  101. package/src/config.ts +3 -25
  102. package/src/connection-manager/address-sorter.ts +1 -2
  103. package/src/connection-manager/connection-pruner.ts +8 -3
  104. package/src/connection-manager/constants.defaults.ts +5 -0
  105. package/src/connection-manager/dial-queue.ts +12 -27
  106. package/src/connection-manager/index.ts +60 -45
  107. package/src/connection-manager/reconnect-queue.ts +1 -1
  108. package/src/connection-manager/utils.ts +129 -21
  109. package/src/connection-monitor.ts +3 -4
  110. package/src/connection.ts +142 -179
  111. package/src/get-peer.ts +3 -3
  112. package/src/index.ts +2 -2
  113. package/src/libp2p.ts +16 -9
  114. package/src/peer-routing.ts +1 -1
  115. package/src/random-walk.ts +13 -3
  116. package/src/registrar.ts +87 -61
  117. package/src/transport-manager.ts +18 -2
  118. package/src/upgrader.ts +132 -149
  119. package/src/utils.ts +31 -0
  120. package/src/version.ts +1 -1
  121. package/dist/typedoc-urls.json +0 -24
package/src/upgrader.ts CHANGED
@@ -1,15 +1,16 @@
1
1
  import { InvalidMultiaddrError, InvalidPeerIdError } from '@libp2p/interface'
2
2
  import * as mss from '@libp2p/multistream-select'
3
3
  import { peerIdFromString } from '@libp2p/peer-id'
4
- import { trackedMap } from '@libp2p/utils/tracked-map'
4
+ import { trackedMap } from '@libp2p/utils'
5
+ import { CODE_P2P } from '@multiformats/multiaddr'
5
6
  import { anySignal } from 'any-signal'
6
7
  import { setMaxListeners } from 'main-event'
7
8
  import { CustomProgressEvent } from 'progress-events'
8
9
  import { raceSignal } from 'race-signal'
9
- import { PROTOCOL_NEGOTIATION_TIMEOUT, INBOUND_UPGRADE_TIMEOUT } from './connection-manager/constants.js'
10
+ import { PROTOCOL_NEGOTIATION_TIMEOUT, INBOUND_UPGRADE_TIMEOUT, CONNECTION_CLOSE_TIMEOUT } from './connection-manager/constants.js'
10
11
  import { createConnection } from './connection.js'
11
12
  import { ConnectionDeniedError, ConnectionInterceptedError, EncryptionFailedError, MuxerUnavailableError } from './errors.js'
12
- import type { Libp2pEvents, AbortOptions, ComponentLogger, MultiaddrConnection, Connection, ConnectionProtector, ConnectionEncrypter, SecuredConnection, ConnectionGater, Metrics, PeerId, PeerStore, StreamMuxerFactory, Upgrader as UpgraderInterface, UpgraderOptions, ConnectionLimits, SecureConnectionOptions, CounterGroup, ClearableSignal } from '@libp2p/interface'
13
+ import type { Libp2pEvents, AbortOptions, ComponentLogger, MultiaddrConnection, Connection, ConnectionProtector, ConnectionEncrypter, ConnectionGater, Metrics, PeerId, PeerStore, StreamMuxerFactory, Upgrader as UpgraderInterface, UpgraderOptions, ConnectionLimits, CounterGroup, ClearableSignal, MessageStream, SecuredConnection, StreamMuxer, UpgraderWithoutEncryptionOptions, SecureConnectionOptions } from '@libp2p/interface'
13
14
  import type { ConnectionManager, Registrar } from '@libp2p/interface-internal'
14
15
  import type { TypedEventTarget } from 'main-event'
15
16
 
@@ -17,15 +18,21 @@ interface CreateConnectionOptions {
17
18
  id: string
18
19
  cryptoProtocol: string
19
20
  direction: 'inbound' | 'outbound'
21
+
22
+ /**
23
+ * The raw underlying connection
24
+ */
20
25
  maConn: MultiaddrConnection
21
- upgradedConn: MultiaddrConnection
26
+
27
+ /**
28
+ * The encrypted, multiplexed connection
29
+ */
30
+ stream: MessageStream
31
+
22
32
  remotePeer: PeerId
23
- muxerFactory?: StreamMuxerFactory
33
+ muxer?: StreamMuxer
24
34
  limits?: ConnectionLimits
25
- }
26
-
27
- export interface CryptoResult extends SecuredConnection<MultiaddrConnection> {
28
- protocol: string
35
+ closeTimeout?: number
29
36
  }
30
37
 
31
38
  export interface UpgraderInit {
@@ -54,6 +61,13 @@ export interface UpgraderInit {
54
61
  * @default 2000
55
62
  */
56
63
  outboundStreamProtocolNegotiationTimeout?: number
64
+
65
+ /**
66
+ * How long to wait before closing a connection
67
+ *
68
+ * @default 1_000
69
+ */
70
+ connectionCloseTimeout?: number
57
71
  }
58
72
 
59
73
  export interface UpgraderComponents {
@@ -68,6 +82,10 @@ export interface UpgraderComponents {
68
82
  logger: ComponentLogger
69
83
  }
70
84
 
85
+ interface EncryptedConnection extends SecuredConnection {
86
+ protocol: string
87
+ }
88
+
71
89
  type ConnectionDeniedType = keyof Pick<ConnectionGater, 'denyOutboundConnection' | 'denyInboundEncryptedConnection' | 'denyOutboundEncryptedConnection' | 'denyInboundUpgradedConnection' | 'denyOutboundUpgradedConnection'>
72
90
 
73
91
  export class Upgrader implements UpgraderInterface {
@@ -85,6 +103,8 @@ export class Upgrader implements UpgraderInterface {
85
103
  outboundErrors?: CounterGroup
86
104
  }
87
105
 
106
+ private readonly connectionCloseTimeout?: number
107
+
88
108
  constructor (components: UpgraderComponents, init: UpgraderInit) {
89
109
  this.components = components
90
110
  this.connectionEncrypters = trackedMap({
@@ -108,6 +128,7 @@ export class Upgrader implements UpgraderInterface {
108
128
  this.inboundUpgradeTimeout = init.inboundUpgradeTimeout ?? INBOUND_UPGRADE_TIMEOUT
109
129
  this.inboundStreamProtocolNegotiationTimeout = init.inboundStreamProtocolNegotiationTimeout ?? PROTOCOL_NEGOTIATION_TIMEOUT
110
130
  this.outboundStreamProtocolNegotiationTimeout = init.outboundStreamProtocolNegotiationTimeout ?? PROTOCOL_NEGOTIATION_TIMEOUT
131
+ this.connectionCloseTimeout = init.connectionCloseTimeout ?? CONNECTION_CLOSE_TIMEOUT
111
132
  this.events = components.events
112
133
  this.metrics = {
113
134
  dials: components.metrics?.registerCounterGroup('libp2p_connection_manager_dials_total'),
@@ -148,7 +169,9 @@ export class Upgrader implements UpgraderInterface {
148
169
  /**
149
170
  * Upgrades an inbound connection
150
171
  */
151
- async upgradeInbound (maConn: MultiaddrConnection, opts: UpgraderOptions): Promise<void> {
172
+ async upgradeInbound (maConn: MultiaddrConnection, opts: UpgraderOptions): Promise<void>
173
+ async upgradeInbound (maConn: MultiaddrConnection, opts: UpgraderWithoutEncryptionOptions): Promise<void>
174
+ async upgradeInbound (maConn: MultiaddrConnection, opts: UpgraderOptions | UpgraderWithoutEncryptionOptions): Promise<void> {
152
175
  let accepted = false
153
176
 
154
177
  // always apply upgrade timeout for incoming upgrades
@@ -159,7 +182,7 @@ export class Upgrader implements UpgraderInterface {
159
182
  inbound: true
160
183
  })
161
184
 
162
- accepted = await raceSignal(this.components.connectionManager.acceptIncomingConnection(maConn), signal)
185
+ accepted = this.components.connectionManager.acceptIncomingConnection(maConn)
163
186
 
164
187
  if (!accepted) {
165
188
  throw new ConnectionDeniedError('Connection denied')
@@ -192,13 +215,15 @@ export class Upgrader implements UpgraderInterface {
192
215
  /**
193
216
  * Upgrades an outbound connection
194
217
  */
195
- async upgradeOutbound (maConn: MultiaddrConnection, opts: UpgraderOptions): Promise<Connection> {
218
+ async upgradeOutbound (maConn: MultiaddrConnection, opts: UpgraderOptions): Promise<Connection>
219
+ async upgradeOutbound (maConn: MultiaddrConnection, opts: UpgraderWithoutEncryptionOptions): Promise<Connection>
220
+ async upgradeOutbound (maConn: MultiaddrConnection, opts: UpgraderOptions | UpgraderWithoutEncryptionOptions): Promise<Connection> {
196
221
  try {
197
222
  this.metrics.dials?.increment({
198
223
  outbound: true
199
224
  })
200
225
 
201
- const idStr = maConn.remoteAddr.getPeerId()
226
+ const idStr = maConn.remoteAddr.getComponents().findLast(c => c.code === CODE_P2P)?.value
202
227
  let remotePeerId: PeerId | undefined
203
228
 
204
229
  if (idStr != null) {
@@ -226,11 +251,11 @@ export class Upgrader implements UpgraderInterface {
226
251
  }
227
252
  }
228
253
 
229
- private async _performUpgrade (maConn: MultiaddrConnection, direction: 'inbound' | 'outbound', opts: UpgraderOptions): Promise<Connection> {
230
- let encryptedConn: MultiaddrConnection
254
+ private async _performUpgrade (maConn: MultiaddrConnection, direction: 'inbound' | 'outbound', opts: UpgraderOptions | UpgraderWithoutEncryptionOptions): Promise<Connection> {
255
+ let stream: MessageStream = maConn
231
256
  let remotePeer: PeerId
232
- let upgradedConn: MultiaddrConnection
233
257
  let muxerFactory: StreamMuxerFactory | undefined
258
+ let muxer: StreamMuxer | undefined
234
259
  let cryptoProtocol
235
260
 
236
261
  const id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`
@@ -241,50 +266,49 @@ export class Upgrader implements UpgraderInterface {
241
266
  maConn.log.trace('starting the %s connection upgrade', direction)
242
267
 
243
268
  // Protect
244
- let protectedConn = maConn
245
-
246
269
  if (opts?.skipProtection !== true) {
247
270
  const protector = this.components.connectionProtector
248
271
 
249
272
  if (protector != null) {
250
273
  maConn.log('protecting the %s connection', direction)
251
- protectedConn = await protector.protect(maConn, opts)
274
+ stream = await protector.protect(stream, opts)
252
275
  }
253
276
  }
254
277
 
255
278
  try {
256
279
  // Encrypt the connection
257
- encryptedConn = protectedConn
258
- if (opts?.skipEncryption !== true) {
280
+ if (isEncryptionSkipped(opts)) {
281
+ if (opts.remotePeer == null) {
282
+ throw new InvalidMultiaddrError(`${direction} connection that skipped encryption must have a peer id`)
283
+ }
284
+
285
+ cryptoProtocol = 'native'
286
+ remotePeer = opts.remotePeer
287
+ } else {
288
+ const peerIdString = maConn.remoteAddr.getComponents().findLast(c => c.code === CODE_P2P)?.value
289
+ let remotePeerFromMultiaddr: PeerId | undefined
290
+
291
+ if (peerIdString != null) {
292
+ remotePeerFromMultiaddr = peerIdFromString(peerIdString)
293
+ }
294
+
259
295
  opts?.onProgress?.(new CustomProgressEvent(`upgrader:encrypt-${direction}-connection`));
260
296
 
261
297
  ({
262
- conn: encryptedConn,
298
+ connection: stream,
263
299
  remotePeer,
264
300
  protocol: cryptoProtocol,
265
301
  streamMuxer: muxerFactory
266
302
  } = await (direction === 'inbound'
267
- ? this._encryptInbound(protectedConn, opts)
268
- : this._encryptOutbound(protectedConn, opts)
303
+ ? this._encryptInbound(stream, {
304
+ ...opts,
305
+ remotePeer: remotePeerFromMultiaddr
306
+ })
307
+ : this._encryptOutbound(stream, {
308
+ ...opts,
309
+ remotePeer: remotePeerFromMultiaddr
310
+ })
269
311
  ))
270
-
271
- const maConn: MultiaddrConnection = {
272
- ...protectedConn,
273
- ...encryptedConn
274
- }
275
-
276
- await this.shouldBlockConnection(direction === 'inbound' ? 'denyInboundEncryptedConnection' : 'denyOutboundEncryptedConnection', remotePeer, maConn)
277
- } else {
278
- const idStr = maConn.remoteAddr.getPeerId()
279
-
280
- if (idStr == null) {
281
- throw new InvalidMultiaddrError(`${direction} connection that skipped encryption must have a peer id`)
282
- }
283
-
284
- const remotePeerId = peerIdFromString(idStr)
285
-
286
- cryptoProtocol = 'native'
287
- remotePeer = remotePeerId
288
312
  }
289
313
 
290
314
  // this can happen if we dial a multiaddr without a peer id, we only find
@@ -295,30 +319,32 @@ export class Upgrader implements UpgraderInterface {
295
319
  throw err
296
320
  }
297
321
 
298
- upgradedConn = encryptedConn
322
+ // stream.pause()
323
+ await this.shouldBlockConnection(direction === 'inbound' ? 'denyInboundEncryptedConnection' : 'denyOutboundEncryptedConnection', remotePeer, maConn)
324
+ // stream.resume()
325
+
299
326
  if (opts?.muxerFactory != null) {
300
327
  muxerFactory = opts.muxerFactory
301
328
  } else if (muxerFactory == null && this.streamMuxers.size > 0) {
302
329
  opts?.onProgress?.(new CustomProgressEvent(`upgrader:multiplex-${direction}-connection`))
303
330
 
304
331
  // Multiplex the connection
305
- const multiplexed = await (direction === 'inbound'
306
- ? this._multiplexInbound({
307
- ...protectedConn,
308
- ...encryptedConn
309
- }, this.streamMuxers, opts)
310
- : this._multiplexOutbound({
311
- ...protectedConn,
312
- ...encryptedConn
313
- }, this.streamMuxers, opts))
314
- muxerFactory = multiplexed.muxerFactory
315
- upgradedConn = multiplexed.stream
332
+ muxerFactory = await (direction === 'inbound'
333
+ ? this._multiplexInbound(stream, this.streamMuxers, opts)
334
+ : this._multiplexOutbound(stream, this.streamMuxers, opts))
316
335
  }
317
336
  } catch (err: any) {
318
- maConn.log.error('failed to upgrade inbound connection %s %a - %e', direction === 'inbound' ? 'from' : 'to', maConn.remoteAddr, err)
337
+ maConn.log.error('failed to upgrade %s connection %s %a - %e', direction, direction === 'inbound' ? 'from' : 'to', maConn.remoteAddr, err)
319
338
  throw err
320
339
  }
321
340
 
341
+ // create the connection muxer if one is configured
342
+ if (muxerFactory != null) {
343
+ maConn.log('create muxer %s', muxerFactory.protocol)
344
+ muxer = muxerFactory.createStreamMuxer(stream)
345
+ }
346
+
347
+ // stream.pause()
322
348
  await this.shouldBlockConnection(direction === 'inbound' ? 'denyInboundUpgradedConnection' : 'denyOutboundUpgradedConnection', remotePeer, maConn)
323
349
 
324
350
  const conn = this._createConnection({
@@ -326,13 +352,16 @@ export class Upgrader implements UpgraderInterface {
326
352
  cryptoProtocol,
327
353
  direction,
328
354
  maConn,
329
- upgradedConn,
330
- muxerFactory,
355
+ stream,
356
+ muxer,
331
357
  remotePeer,
332
- limits: opts?.limits
358
+ limits: opts?.limits,
359
+ closeTimeout: this.connectionCloseTimeout
333
360
  })
334
361
 
335
- conn.log('successfully upgraded %s connection', direction)
362
+ conn.log('successfully upgraded connection')
363
+
364
+ // stream.resume()
336
365
 
337
366
  return conn
338
367
  }
@@ -341,59 +370,19 @@ export class Upgrader implements UpgraderInterface {
341
370
  * A convenience method for generating a new `Connection`
342
371
  */
343
372
  _createConnection (opts: CreateConnectionOptions): Connection {
344
- const {
345
- id,
346
- cryptoProtocol,
347
- direction,
348
- maConn,
349
- upgradedConn,
350
- remotePeer,
351
- muxerFactory,
352
- limits
353
- } = opts
354
-
355
- let connection: Connection // eslint-disable-line prefer-const
356
-
357
- const _timeline = maConn.timeline
358
- maConn.timeline = new Proxy(_timeline, {
359
- set: (...args) => {
360
- if (args[1] === 'close' && args[2] != null && _timeline.close == null) {
361
- // Wait for close to finish before notifying of the closure
362
- (async () => {
363
- try {
364
- if (connection.status === 'open') {
365
- await connection.close()
366
- }
367
- } catch (err: any) {
368
- connection.log.error('error closing connection after timeline close %e', err)
369
- } finally {
370
- this.events.safeDispatchEvent('connection:close', {
371
- detail: connection
372
- })
373
- }
374
- })().catch(err => {
375
- connection.log.error('error thrown while dispatching connection:close event %e', err)
376
- })
377
- }
378
-
379
- return Reflect.set(...args)
380
- }
381
- })
382
- maConn.timeline.upgraded = Date.now()
383
-
384
373
  // Create the connection
385
- connection = createConnection(this.components, {
386
- id,
387
- maConn: upgradedConn,
388
- remotePeer,
389
- direction,
390
- muxerFactory,
391
- encryption: cryptoProtocol,
392
- limits,
374
+ const connection = createConnection(this.components, {
375
+ ...opts,
393
376
  outboundStreamProtocolNegotiationTimeout: this.outboundStreamProtocolNegotiationTimeout,
394
377
  inboundStreamProtocolNegotiationTimeout: this.inboundStreamProtocolNegotiationTimeout
395
378
  })
396
379
 
380
+ connection.addEventListener('close', () => {
381
+ this.events.safeDispatchEvent('connection:close', {
382
+ detail: connection
383
+ })
384
+ })
385
+
397
386
  this.events.safeDispatchEvent('connection:open', {
398
387
  detail: connection
399
388
  })
@@ -404,28 +393,24 @@ export class Upgrader implements UpgraderInterface {
404
393
  /**
405
394
  * Attempts to encrypt the incoming `connection` with the provided `cryptos`
406
395
  */
407
- async _encryptInbound (connection: MultiaddrConnection, options?: AbortOptions): Promise<CryptoResult> {
396
+ async _encryptInbound (connection: MessageStream, options?: SecureConnectionOptions): Promise<EncryptedConnection> {
408
397
  const protocols = Array.from(this.connectionEncrypters.keys())
409
398
 
410
399
  try {
411
- const { stream, protocol } = await mss.handle(connection, protocols, {
412
- ...options,
413
- log: connection.log
414
- })
400
+ const protocol = await mss.handle(connection, protocols, options)
415
401
  const encrypter = this.connectionEncrypters.get(protocol)
416
402
 
417
403
  if (encrypter == null) {
418
404
  throw new EncryptionFailedError(`no crypto module found for ${protocol}`)
419
405
  }
420
406
 
421
- connection.log('encrypting inbound connection to %a using %s', connection.remoteAddr, protocol)
407
+ connection.log('encrypting inbound connection using %s', protocol)
422
408
 
423
409
  return {
424
- ...await encrypter.secureInbound(stream, options),
410
+ ...await encrypter.secureInbound(connection, options),
425
411
  protocol
426
412
  }
427
413
  } catch (err: any) {
428
- connection.log.error('encrypting inbound connection from %a failed', connection.remoteAddr, err)
429
414
  throw new EncryptionFailedError(err.message)
430
415
  }
431
416
  }
@@ -434,31 +419,26 @@ export class Upgrader implements UpgraderInterface {
434
419
  * Attempts to encrypt the given `connection` with the provided connection encrypters.
435
420
  * The first `ConnectionEncrypter` module to succeed will be used
436
421
  */
437
- async _encryptOutbound (connection: MultiaddrConnection, options: SecureConnectionOptions): Promise<CryptoResult> {
422
+ async _encryptOutbound (connection: MessageStream, options?: SecureConnectionOptions): Promise<EncryptedConnection> {
438
423
  const protocols = Array.from(this.connectionEncrypters.keys())
439
424
 
440
425
  try {
441
426
  connection.log.trace('selecting encrypter from %s', protocols)
442
427
 
443
- const { stream, protocol } = await mss.select(connection, protocols, {
444
- ...options,
445
- log: connection.log,
446
- yieldBytes: true
447
- })
428
+ const protocol = await mss.select(connection, protocols, options)
448
429
  const encrypter = this.connectionEncrypters.get(protocol)
449
430
 
450
431
  if (encrypter == null) {
451
432
  throw new EncryptionFailedError(`no crypto module found for ${protocol}`)
452
433
  }
453
434
 
454
- connection.log('encrypting outbound connection to %a using %s', connection.remoteAddr, protocol)
435
+ connection.log('encrypting outbound connection using %s', protocol)
455
436
 
456
437
  return {
457
- ...await encrypter.secureOutbound(stream, options),
438
+ ...await encrypter.secureOutbound(connection, options),
458
439
  protocol
459
440
  }
460
441
  } catch (err: any) {
461
- connection.log.error('encrypting outbound connection to %a failed', connection.remoteAddr, err)
462
442
  throw new EncryptionFailedError(err.message)
463
443
  }
464
444
  }
@@ -467,27 +447,23 @@ export class Upgrader implements UpgraderInterface {
467
447
  * Selects one of the given muxers via multistream-select. That
468
448
  * muxer will be used for all future streams on the connection.
469
449
  */
470
- async _multiplexOutbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>, options: AbortOptions): Promise<{ stream: MultiaddrConnection, muxerFactory?: StreamMuxerFactory }> {
450
+ async _multiplexOutbound (maConn: MessageStream, muxers: Map<string, StreamMuxerFactory>, options: AbortOptions): Promise<StreamMuxerFactory> {
471
451
  const protocols = Array.from(muxers.keys())
472
- connection.log('outbound selecting muxer %s', protocols)
473
- try {
474
- connection.log.trace('selecting stream muxer from %s', protocols)
452
+ maConn.log('outbound selecting muxer %s', protocols)
475
453
 
476
- const {
477
- stream,
478
- protocol
479
- } = await mss.select(connection, protocols, {
480
- ...options,
481
- log: connection.log,
482
- yieldBytes: true
483
- })
484
-
485
- connection.log('selected %s as muxer protocol', protocol)
454
+ try {
455
+ maConn.log.trace('selecting stream muxer from %s', protocols)
456
+ const protocol = await mss.select(maConn, protocols, options)
486
457
  const muxerFactory = muxers.get(protocol)
487
458
 
488
- return { stream, muxerFactory }
459
+ if (muxerFactory == null) {
460
+ throw new MuxerUnavailableError(`No muxer configured for protocol "${protocol}"`)
461
+ }
462
+
463
+ maConn.log('selected %s as muxer protocol', protocol)
464
+ return muxerFactory
489
465
  } catch (err: any) {
490
- connection.log.error('error multiplexing outbound connection', err)
466
+ maConn.log.error('error multiplexing outbound connection', err)
491
467
  throw new MuxerUnavailableError(String(err))
492
468
  }
493
469
  }
@@ -496,20 +472,23 @@ export class Upgrader implements UpgraderInterface {
496
472
  * Registers support for one of the given muxers via multistream-select. The
497
473
  * selected muxer will be used for all future streams on the connection.
498
474
  */
499
- async _multiplexInbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>, options: AbortOptions): Promise<{ stream: MultiaddrConnection, muxerFactory?: StreamMuxerFactory }> {
475
+ async _multiplexInbound (maConn: MessageStream, muxers: Map<string, StreamMuxerFactory>, options: AbortOptions): Promise<StreamMuxerFactory> {
500
476
  const protocols = Array.from(muxers.keys())
501
- connection.log('inbound handling muxers %s', protocols)
477
+ maConn.log('inbound handling muxers %s', protocols)
502
478
  try {
503
- const { stream, protocol } = await mss.handle(connection, protocols, {
504
- ...options,
505
- log: connection.log
506
- })
479
+ maConn.log.trace('selecting stream muxer from %s', protocols)
480
+ const protocol = await mss.handle(maConn, protocols, options)
507
481
  const muxerFactory = muxers.get(protocol)
508
482
 
509
- return { stream, muxerFactory }
483
+ if (muxerFactory == null) {
484
+ throw new MuxerUnavailableError(`No muxer configured for protocol "${protocol}"`)
485
+ }
486
+
487
+ maConn.log('selected %s as muxer protocol', protocol)
488
+ return muxerFactory
510
489
  } catch (err: any) {
511
- connection.log.error('error multiplexing inbound connection', err)
512
- throw new MuxerUnavailableError(String(err))
490
+ maConn.log.error('error multiplexing inbound connection', err)
491
+ throw err
513
492
  }
514
493
  }
515
494
 
@@ -521,3 +500,7 @@ export class Upgrader implements UpgraderInterface {
521
500
  return this.streamMuxers
522
501
  }
523
502
  }
503
+
504
+ function isEncryptionSkipped (opts?: any): opts is UpgraderWithoutEncryptionOptions {
505
+ return opts.skipEncryption === true
506
+ }
package/src/utils.ts ADDED
@@ -0,0 +1,31 @@
1
+ import type { MessageStream } from '@libp2p/interface'
2
+
3
+ export function redirect (channelA: MessageStream, channelB: MessageStream): void {
4
+ channelA.addEventListener('message', (evt) => {
5
+ const sendMore = channelB.send(evt.data)
6
+
7
+ if (sendMore === false) {
8
+ channelA.pause()
9
+
10
+ channelA.addEventListener('drain', () => {
11
+ channelA.resume()
12
+ }, {
13
+ once: true
14
+ })
15
+ }
16
+ })
17
+
18
+ channelB.addEventListener('message', (evt) => {
19
+ const sendMore = channelA.send(evt.data)
20
+
21
+ if (sendMore === false) {
22
+ channelB.pause()
23
+
24
+ channelB.addEventListener('drain', () => {
25
+ channelB.resume()
26
+ }, {
27
+ once: true
28
+ })
29
+ }
30
+ })
31
+ }
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '2.10.0'
1
+ export const version = '3.0.0-049bfa0fa'
2
2
  export const name = 'js-libp2p'
@@ -1,24 +0,0 @@
1
- {
2
- "AddressFilter": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.AddressFilter.html",
3
- "AddressManagerInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.AddressManagerInit.html",
4
- "ConnectionManagerInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.ConnectionManagerInit.html",
5
- "ConnectionMonitorInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.ConnectionMonitorInit.html",
6
- "Libp2pInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.Libp2pInit.html",
7
- ".:Libp2pInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.Libp2pInit.html",
8
- "TransportManagerInit": "https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.TransportManagerInit.html",
9
- "Libp2pOptions": "https://libp2p.github.io/js-libp2p/types/libp2p.index.Libp2pOptions.html",
10
- ".:Libp2pOptions": "https://libp2p.github.io/js-libp2p/types/libp2p.index.Libp2pOptions.html",
11
- "ServiceFactoryMap": "https://libp2p.github.io/js-libp2p/types/libp2p.index.ServiceFactoryMap.html",
12
- ".:ServiceFactoryMap": "https://libp2p.github.io/js-libp2p/types/libp2p.index.ServiceFactoryMap.html",
13
- "dnsaddrResolver": "https://libp2p.github.io/js-libp2p/variables/libp2p.index.dnsaddrResolver.html",
14
- "createLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.createLibp2p.html",
15
- ".:createLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.createLibp2p.html",
16
- "isLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.isLibp2p.html",
17
- ".:isLibp2p": "https://libp2p.github.io/js-libp2p/functions/libp2p.index.isLibp2p.html",
18
- "userAgent": "https://libp2p.github.io/js-libp2p/functions/libp2p.user-agent.userAgent.html",
19
- "./user-agent:userAgent": "https://libp2p.github.io/js-libp2p/functions/libp2p.user-agent.userAgent.html",
20
- "name": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.name.html",
21
- "./version:name": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.name.html",
22
- "version": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.version.html",
23
- "./version:version": "https://libp2p.github.io/js-libp2p/variables/libp2p.version.version.html"
24
- }