libp2p 2.1.0 → 2.1.1-c258b35af

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.
@@ -57,17 +57,34 @@ export interface ConnectionManagerInit {
57
57
  /**
58
58
  * How long a dial attempt is allowed to take, including DNS resolution
59
59
  * of the multiaddr, opening a socket and upgrading it to a Connection.
60
+ *
61
+ * @default 5000
60
62
  */
61
63
  dialTimeout?: number
62
64
 
63
65
  /**
64
- * When a new inbound connection is opened, the upgrade process (e.g. protect,
65
- * encrypt, multiplex etc) must complete within this number of ms.
66
+ * When a new incoming connection is opened, the upgrade process (e.g.
67
+ * protect, encrypt, multiplex etc) must complete within this number of ms.
66
68
  *
67
- * @default 30000
69
+ * @default 3000
68
70
  */
69
71
  inboundUpgradeTimeout?: number
70
72
 
73
+ /**
74
+ * When a new outbound connection is opened, the upgrade process (e.g.
75
+ * protect, encrypt, multiplex etc) must complete within this number of ms.
76
+ *
77
+ * @default 3000
78
+ */
79
+ outboundUpgradeTimeout?: number
80
+
81
+ /**
82
+ * Protocol negotiation must complete within this number of ms
83
+ *
84
+ * @default 2000
85
+ */
86
+ protocolNegotiationTimeout?: number
87
+
71
88
  /**
72
89
  * Multiaddr resolvers to use when dialling
73
90
  */
@@ -88,7 +105,9 @@ export interface ConnectionManagerInit {
88
105
 
89
106
  /**
90
107
  * If more than this many connections are opened per second by a single
91
- * host, reject subsequent connections. (default: 5)
108
+ * host, reject subsequent connections.
109
+ *
110
+ * @default 5
92
111
  */
93
112
  inboundConnectionThreshold?: number
94
113
 
@@ -162,7 +181,6 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
162
181
  private readonly deny: Multiaddr[]
163
182
  private readonly maxIncomingPendingConnections: number
164
183
  private incomingPendingConnections: number
165
- private outboundPendingConnections: number
166
184
  private readonly maxConnections: number
167
185
 
168
186
  public readonly dialQueue: DialQueue
@@ -201,7 +219,6 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
201
219
  this.allow = (init.allow ?? []).map(ma => multiaddr(ma))
202
220
  this.deny = (init.deny ?? []).map(ma => multiaddr(ma))
203
221
 
204
- this.outboundPendingConnections = 0
205
222
  this.incomingPendingConnections = 0
206
223
  this.maxIncomingPendingConnections = init.maxIncomingPendingConnections ?? defaultOptions.maxIncomingPendingConnections
207
224
 
@@ -264,8 +281,7 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
264
281
  const metric = {
265
282
  inbound: 0,
266
283
  'inbound pending': this.incomingPendingConnections,
267
- outbound: 0,
268
- 'outbound pending': this.outboundPendingConnections
284
+ outbound: 0
269
285
  }
270
286
 
271
287
  for (const conns of this.connections.values()) {
@@ -466,54 +482,48 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
466
482
 
467
483
  options.signal?.throwIfAborted()
468
484
 
469
- try {
470
- this.outboundPendingConnections++
471
-
472
- const { peerId } = getPeerAddress(peerIdOrMultiaddr)
485
+ const { peerId } = getPeerAddress(peerIdOrMultiaddr)
473
486
 
474
- if (peerId != null && options.force !== true) {
475
- this.log('dial %p', peerId)
476
- const existingConnection = this.getConnections(peerId)
477
- .find(conn => conn.limits == null)
487
+ if (peerId != null && options.force !== true) {
488
+ this.log('dial %p', peerId)
489
+ const existingConnection = this.getConnections(peerId)
490
+ .find(conn => conn.limits == null)
478
491
 
479
- if (existingConnection != null) {
480
- this.log('had an existing non-limited connection to %p', peerId)
492
+ if (existingConnection != null) {
493
+ this.log('had an existing non-limited connection to %p', peerId)
481
494
 
482
- options.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'))
483
- return existingConnection
484
- }
495
+ options.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'))
496
+ return existingConnection
485
497
  }
498
+ }
486
499
 
487
- const connection = await this.dialQueue.dial(peerIdOrMultiaddr, {
488
- ...options,
489
- priority: options.priority ?? DEFAULT_DIAL_PRIORITY
490
- })
491
- let peerConnections = this.connections.get(connection.remotePeer)
492
-
493
- if (peerConnections == null) {
494
- peerConnections = []
495
- this.connections.set(connection.remotePeer, peerConnections)
496
- }
500
+ const connection = await this.dialQueue.dial(peerIdOrMultiaddr, {
501
+ ...options,
502
+ priority: options.priority ?? DEFAULT_DIAL_PRIORITY
503
+ })
504
+ let peerConnections = this.connections.get(connection.remotePeer)
497
505
 
498
- // we get notified of connections via the Upgrader emitting "connection"
499
- // events, double check we aren't already tracking this connection before
500
- // storing it
501
- let trackedConnection = false
506
+ if (peerConnections == null) {
507
+ peerConnections = []
508
+ this.connections.set(connection.remotePeer, peerConnections)
509
+ }
502
510
 
503
- for (const conn of peerConnections) {
504
- if (conn.id === connection.id) {
505
- trackedConnection = true
506
- }
507
- }
511
+ // we get notified of connections via the Upgrader emitting "connection"
512
+ // events, double check we aren't already tracking this connection before
513
+ // storing it
514
+ let trackedConnection = false
508
515
 
509
- if (!trackedConnection) {
510
- peerConnections.push(connection)
516
+ for (const conn of peerConnections) {
517
+ if (conn.id === connection.id) {
518
+ trackedConnection = true
511
519
  }
520
+ }
512
521
 
513
- return connection
514
- } finally {
515
- this.outboundPendingConnections--
522
+ if (!trackedConnection) {
523
+ peerConnections.push(connection)
516
524
  }
525
+
526
+ return connection
517
527
  }
518
528
 
519
529
  async closeConnections (peerId: PeerId, options: AbortOptions = {}): Promise<void> {
package/src/index.ts CHANGED
@@ -18,7 +18,7 @@ import { generateKeyPair } from '@libp2p/crypto/keys'
18
18
  import { peerIdFromPrivateKey } from '@libp2p/peer-id'
19
19
  import { validateConfig } from './config.js'
20
20
  import { Libp2p as Libp2pClass } from './libp2p.js'
21
- import type { AddressManagerInit } from './address-manager/index.js'
21
+ import type { AddressManagerInit, AddressFilter } from './address-manager/index.js'
22
22
  import type { Components } from './components.js'
23
23
  import type { ConnectionManagerInit } from './connection-manager/index.js'
24
24
  import type { ConnectionMonitorInit } from './connection-monitor.js'
@@ -32,6 +32,8 @@ export type ServiceFactoryMap<T extends ServiceMap = ServiceMap> = {
32
32
  [Property in keyof T]: (components: Components & T) => T[Property]
33
33
  }
34
34
 
35
+ export type { AddressManagerInit, AddressFilter }
36
+
35
37
  /**
36
38
  * For Libp2p configurations and modules details read the [Configuration Document](https://github.com/libp2p/js-libp2p/tree/main/doc/CONFIGURATION.md).
37
39
  */
@@ -164,7 +166,7 @@ export interface Libp2pInit<T extends ServiceMap = ServiceMap> {
164
166
  dns?: DNS
165
167
  }
166
168
 
167
- export type { Libp2p }
169
+ export type { Libp2p, ConnectionManagerInit, ConnectionMonitorInit, TransportManagerInit }
168
170
 
169
171
  export type Libp2pOptions<T extends ServiceMap = ServiceMap> = Libp2pInit<T> & { start?: boolean }
170
172
 
package/src/libp2p.ts CHANGED
@@ -3,7 +3,7 @@ import { contentRoutingSymbol, TypedEventEmitter, setMaxListeners, peerDiscovery
3
3
  import { defaultLogger } from '@libp2p/logger'
4
4
  import { PeerSet } from '@libp2p/peer-collections'
5
5
  import { peerIdFromString } from '@libp2p/peer-id'
6
- import { PersistentPeerStore } from '@libp2p/peer-store'
6
+ import { persistentPeerStore } from '@libp2p/peer-store'
7
7
  import { isMultiaddr, type Multiaddr } from '@multiformats/multiaddr'
8
8
  import { MemoryDatastore } from 'datastore-core/memory'
9
9
  import { concat as uint8ArrayConcat } from 'uint8arrays/concat'
@@ -79,7 +79,7 @@ export class Libp2p<T extends ServiceMap = ServiceMap> extends TypedEventEmitter
79
79
  dns: init.dns
80
80
  })
81
81
 
82
- this.peerStore = this.configureComponent('peerStore', new PersistentPeerStore(components, {
82
+ this.peerStore = this.configureComponent('peerStore', persistentPeerStore(components, {
83
83
  addressFilter: this.components.connectionGater.filterMultiaddrForPeer,
84
84
  ...init.peerStore
85
85
  }))
@@ -110,7 +110,8 @@ export class Libp2p<T extends ServiceMap = ServiceMap> extends TypedEventEmitter
110
110
  this.components.upgrader = new DefaultUpgrader(this.components, {
111
111
  connectionEncrypters: (init.connectionEncrypters ?? []).map((fn, index) => this.configureComponent(`connection-encryption-${index}`, fn(this.components))),
112
112
  streamMuxers: (init.streamMuxers ?? []).map((fn, index) => this.configureComponent(`stream-muxers-${index}`, fn(this.components))),
113
- inboundUpgradeTimeout: init.connectionManager?.inboundUpgradeTimeout
113
+ inboundUpgradeTimeout: init.connectionManager?.inboundUpgradeTimeout,
114
+ outboundUpgradeTimeout: init.connectionManager?.outboundUpgradeTimeout
114
115
  })
115
116
 
116
117
  // Setup the transport manager
package/src/upgrader.ts CHANGED
@@ -1,16 +1,15 @@
1
- import { InvalidMultiaddrError, InvalidPeerIdError, TooManyInboundProtocolStreamsError, TooManyOutboundProtocolStreamsError, LimitedConnectionError, TimeoutError, setMaxListeners } from '@libp2p/interface'
1
+ import { InvalidMultiaddrError, TooManyInboundProtocolStreamsError, TooManyOutboundProtocolStreamsError, LimitedConnectionError, setMaxListeners } from '@libp2p/interface'
2
2
  import * as mss from '@libp2p/multistream-select'
3
3
  import { peerIdFromString } from '@libp2p/peer-id'
4
+ import { anySignal } from 'any-signal'
4
5
  import { CustomProgressEvent } from 'progress-events'
5
6
  import { createConnection } from './connection/index.js'
6
- import { INBOUND_UPGRADE_TIMEOUT } from './connection-manager/constants.js'
7
+ import { PROTOCOL_NEGOTIATION_TIMEOUT, UPGRADE_TIMEOUT } from './connection-manager/constants.js'
7
8
  import { ConnectionDeniedError, ConnectionInterceptedError, EncryptionFailedError, MuxerUnavailableError } from './errors.js'
8
9
  import { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js'
9
10
  import type { Libp2pEvents, AbortOptions, ComponentLogger, MultiaddrConnection, Connection, Stream, ConnectionProtector, NewStreamOptions, ConnectionEncrypter, SecuredConnection, ConnectionGater, TypedEventTarget, Metrics, PeerId, PeerStore, StreamMuxer, StreamMuxerFactory, Upgrader, UpgraderOptions, ConnectionLimits, SecureConnectionOptions } from '@libp2p/interface'
10
11
  import type { ConnectionManager, Registrar } from '@libp2p/interface-internal'
11
12
 
12
- const DEFAULT_PROTOCOL_SELECT_TIMEOUT = 30000
13
-
14
13
  interface CreateConnectionOptions {
15
14
  cryptoProtocol: string
16
15
  direction: 'inbound' | 'outbound'
@@ -36,10 +35,34 @@ export interface UpgraderInit {
36
35
  streamMuxers: StreamMuxerFactory[]
37
36
 
38
37
  /**
39
- * An amount of ms by which an inbound connection upgrade
40
- * must complete
38
+ * An amount of ms by which an inbound connection upgrade must complete
39
+ *
40
+ * @default 3000
41
41
  */
42
42
  inboundUpgradeTimeout?: number
43
+
44
+ /**
45
+ * An amount of ms by which an outbound connection upgrade must complete
46
+ *
47
+ * @default 3000
48
+ */
49
+ outboundUpgradeTimeout?: number
50
+
51
+ /**
52
+ * When a new incoming stream is opened on a multiplexed connection, protocol
53
+ * negotiation on that stream must complete within this many ms
54
+ *
55
+ * @default 2000
56
+ */
57
+ inboundStreamProtocolNegotiationTimeout?: number
58
+
59
+ /**
60
+ * When a new incoming stream is opened on a multiplexed connection, protocol
61
+ * negotiation on that stream must complete within this many ms
62
+ *
63
+ * @default 2000
64
+ */
65
+ outboundStreamProtocolNegotiationTimeout?: number
43
66
  }
44
67
 
45
68
  function findIncomingStreamLimit (protocol: string, registrar: Registrar): number | undefined {
@@ -103,6 +126,9 @@ export class DefaultUpgrader implements Upgrader {
103
126
  private readonly connectionEncrypters: Map<string, ConnectionEncrypter>
104
127
  private readonly streamMuxers: Map<string, StreamMuxerFactory>
105
128
  private readonly inboundUpgradeTimeout: number
129
+ private readonly outboundUpgradeTimeout: number
130
+ private readonly inboundStreamProtocolNegotiationTimeout: number
131
+ private readonly outboundStreamProtocolNegotiationTimeout: number
106
132
  private readonly events: TypedEventTarget<Libp2pEvents>
107
133
 
108
134
  constructor (components: DefaultUpgraderComponents, init: UpgraderInit) {
@@ -119,135 +145,46 @@ export class DefaultUpgrader implements Upgrader {
119
145
  this.streamMuxers.set(muxer.protocol, muxer)
120
146
  })
121
147
 
122
- this.inboundUpgradeTimeout = init.inboundUpgradeTimeout ?? INBOUND_UPGRADE_TIMEOUT
148
+ this.inboundUpgradeTimeout = init.inboundUpgradeTimeout ?? UPGRADE_TIMEOUT
149
+ this.outboundUpgradeTimeout = init.outboundUpgradeTimeout ?? UPGRADE_TIMEOUT
150
+ this.inboundStreamProtocolNegotiationTimeout = init.inboundStreamProtocolNegotiationTimeout ?? PROTOCOL_NEGOTIATION_TIMEOUT
151
+ this.outboundStreamProtocolNegotiationTimeout = init.outboundStreamProtocolNegotiationTimeout ?? PROTOCOL_NEGOTIATION_TIMEOUT
123
152
  this.events = components.events
124
153
  }
125
154
 
126
155
  readonly [Symbol.toStringTag] = '@libp2p/upgrader'
127
156
 
128
- async shouldBlockConnection (remotePeer: PeerId, maConn: MultiaddrConnection, connectionType: ConnectionDeniedType): Promise<void> {
129
- const connectionGater = this.components.connectionGater[connectionType]
157
+ async shouldBlockConnection (connectionType: 'denyInboundConnection', maConn: MultiaddrConnection): Promise<void>
158
+ async shouldBlockConnection (connectionType: ConnectionDeniedType, remotePeer: PeerId, maConn: MultiaddrConnection): Promise<void>
159
+ async shouldBlockConnection (method: ConnectionDeniedType | 'denyInboundConnection', ...args: any[]): Promise<void> {
160
+ const denyOperation: any = this.components.connectionGater[method]
130
161
 
131
- if (connectionGater !== undefined) {
132
- if (await connectionGater(remotePeer, maConn)) {
133
- throw new ConnectionInterceptedError(`The multiaddr connection is blocked by gater.${connectionType}`)
134
- }
162
+ if (denyOperation == null) {
163
+ return
164
+ }
165
+
166
+ const result = await denyOperation.apply(this.components.connectionGater, args)
167
+
168
+ if (result === true) {
169
+ throw new ConnectionInterceptedError(`The multiaddr connection is blocked by gater.${method}`)
135
170
  }
136
171
  }
137
172
 
138
173
  /**
139
174
  * Upgrades an inbound connection
140
175
  */
141
- async upgradeInbound (maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise<Connection> {
142
- const accept = await this.components.connectionManager.acceptIncomingConnection(maConn)
143
-
144
- if (!accept) {
145
- throw new ConnectionDeniedError('connection denied')
146
- }
147
-
148
- let encryptedConn: MultiaddrConnection
149
- let remotePeer
150
- let upgradedConn: MultiaddrConnection
151
- let muxerFactory: StreamMuxerFactory | undefined
152
- let cryptoProtocol
153
-
154
- const signal = AbortSignal.timeout(this.inboundUpgradeTimeout)
155
-
156
- const onAbort = (): void => {
157
- maConn.abort(new TimeoutError('inbound upgrade timeout'))
158
- }
159
-
160
- signal.addEventListener('abort', onAbort, { once: true })
161
-
162
- setMaxListeners(Infinity, signal)
163
-
176
+ async upgradeInbound (maConn: MultiaddrConnection, opts: UpgraderOptions = {}): Promise<Connection> {
164
177
  try {
165
- if ((await this.components.connectionGater.denyInboundConnection?.(maConn)) === true) {
166
- throw new ConnectionInterceptedError('The multiaddr connection is blocked by gater.acceptConnection')
167
- }
168
-
169
- this.components.metrics?.trackMultiaddrConnection(maConn)
178
+ const accept = await this.components.connectionManager.acceptIncomingConnection(maConn)
170
179
 
171
- maConn.log('starting the inbound connection upgrade')
172
-
173
- // Protect
174
- let protectedConn = maConn
175
-
176
- if (opts?.skipProtection !== true) {
177
- const protector = this.components.connectionProtector
178
-
179
- if (protector != null) {
180
- maConn.log('protecting the inbound connection')
181
- protectedConn = await protector.protect(maConn)
182
- }
180
+ if (!accept) {
181
+ throw new ConnectionDeniedError('connection denied')
183
182
  }
184
183
 
185
- try {
186
- // Encrypt the connection
187
- encryptedConn = protectedConn
188
- if (opts?.skipEncryption !== true) {
189
- opts?.onProgress?.(new CustomProgressEvent('upgrader:encrypt-inbound-connection'));
190
-
191
- ({
192
- conn: encryptedConn,
193
- remotePeer,
194
- protocol: cryptoProtocol
195
- } = await this._encryptInbound(protectedConn))
196
-
197
- const maConn: MultiaddrConnection = {
198
- ...protectedConn,
199
- ...encryptedConn
200
- }
184
+ await this.shouldBlockConnection('denyInboundConnection', maConn)
201
185
 
202
- await this.shouldBlockConnection(remotePeer, maConn, 'denyInboundEncryptedConnection')
203
- } else {
204
- const idStr = maConn.remoteAddr.getPeerId()
205
-
206
- if (idStr == null) {
207
- throw new InvalidMultiaddrError('inbound connection that skipped encryption must have a peer id')
208
- }
209
-
210
- const remotePeerId = peerIdFromString(idStr)
211
-
212
- cryptoProtocol = 'native'
213
- remotePeer = remotePeerId
214
- }
215
-
216
- upgradedConn = encryptedConn
217
- if (opts?.muxerFactory != null) {
218
- muxerFactory = opts.muxerFactory
219
- } else if (this.streamMuxers.size > 0) {
220
- opts?.onProgress?.(new CustomProgressEvent('upgrader:multiplex-inbound-connection'))
221
-
222
- // Multiplex the connection
223
- const multiplexed = await this._multiplexInbound({
224
- ...protectedConn,
225
- ...encryptedConn
226
- }, this.streamMuxers)
227
- muxerFactory = multiplexed.muxerFactory
228
- upgradedConn = multiplexed.stream
229
- }
230
- } catch (err: any) {
231
- maConn.log.error('failed to upgrade inbound connection', err)
232
- throw err
233
- }
234
-
235
- await this.shouldBlockConnection(remotePeer, maConn, 'denyInboundUpgradedConnection')
236
-
237
- maConn.log('successfully upgraded inbound connection')
238
-
239
- return this._createConnection({
240
- cryptoProtocol,
241
- direction: 'inbound',
242
- maConn,
243
- upgradedConn,
244
- muxerFactory,
245
- remotePeer,
246
- limits: opts?.limits
247
- })
186
+ return await this._performUpgrade(maConn, 'inbound', opts)
248
187
  } finally {
249
- signal.removeEventListener('abort', onAbort)
250
-
251
188
  this.components.connectionManager.afterUpgradeInbound()
252
189
  }
253
190
  }
@@ -255,36 +192,43 @@ export class DefaultUpgrader implements Upgrader {
255
192
  /**
256
193
  * Upgrades an outbound connection
257
194
  */
258
- async upgradeOutbound (maConn: MultiaddrConnection, opts?: UpgraderOptions): Promise<Connection> {
195
+ async upgradeOutbound (maConn: MultiaddrConnection, opts: UpgraderOptions = {}): Promise<Connection> {
259
196
  const idStr = maConn.remoteAddr.getPeerId()
260
197
  let remotePeerId: PeerId | undefined
261
198
 
262
199
  if (idStr != null) {
263
200
  remotePeerId = peerIdFromString(idStr)
264
-
265
- await this.shouldBlockConnection(remotePeerId, maConn, 'denyOutboundConnection')
201
+ await this.shouldBlockConnection('denyOutboundConnection', remotePeerId, maConn)
266
202
  }
267
203
 
204
+ return this._performUpgrade(maConn, 'outbound', opts)
205
+ }
206
+
207
+ private async _performUpgrade (maConn: MultiaddrConnection, direction: 'inbound' | 'outbound', opts: UpgraderOptions): Promise<Connection> {
268
208
  let encryptedConn: MultiaddrConnection
269
209
  let remotePeer: PeerId
270
210
  let upgradedConn: MultiaddrConnection
211
+ let muxerFactory: StreamMuxerFactory | undefined
271
212
  let cryptoProtocol
272
- let muxerFactory
273
213
 
274
- this.components.metrics?.trackMultiaddrConnection(maConn)
214
+ const upgradeTimeoutSignal = AbortSignal.timeout(direction === 'inbound' ? this.inboundUpgradeTimeout : this.outboundUpgradeTimeout)
215
+ const signal = anySignal([upgradeTimeoutSignal, opts.signal])
216
+ setMaxListeners(Infinity, upgradeTimeoutSignal, signal)
217
+ opts.signal = signal
275
218
 
276
- maConn.log('starting the outbound connection upgrade')
219
+ this.components.metrics?.trackMultiaddrConnection(maConn)
277
220
 
278
- // If the transport natively supports encryption, skip connection
279
- // protector and encryption
221
+ maConn.log('starting the %s connection upgrade', direction)
280
222
 
281
223
  // Protect
282
224
  let protectedConn = maConn
225
+
283
226
  if (opts?.skipProtection !== true) {
284
227
  const protector = this.components.connectionProtector
285
228
 
286
229
  if (protector != null) {
287
- protectedConn = await protector.protect(maConn)
230
+ maConn.log('protecting the %s connection', direction)
231
+ protectedConn = await protector.protect(maConn, opts)
288
232
  }
289
233
  }
290
234
 
@@ -292,26 +236,38 @@ export class DefaultUpgrader implements Upgrader {
292
236
  // Encrypt the connection
293
237
  encryptedConn = protectedConn
294
238
  if (opts?.skipEncryption !== true) {
239
+ opts?.onProgress?.(new CustomProgressEvent(`upgrader:encrypt-${direction}-connection`));
240
+
295
241
  ({
296
242
  conn: encryptedConn,
297
243
  remotePeer,
298
244
  protocol: cryptoProtocol
299
- } = await this._encryptOutbound(protectedConn, {
300
- ...opts,
301
- remotePeer: remotePeerId
302
- }))
245
+ } = await (direction === 'inbound'
246
+ ? this._encryptInbound(protectedConn, {
247
+ ...opts,
248
+ signal
249
+ })
250
+ : this._encryptOutbound(protectedConn, {
251
+ ...opts,
252
+ signal
253
+ })
254
+ ))
303
255
 
304
256
  const maConn: MultiaddrConnection = {
305
257
  ...protectedConn,
306
258
  ...encryptedConn
307
259
  }
308
260
 
309
- await this.shouldBlockConnection(remotePeer, maConn, 'denyOutboundEncryptedConnection')
261
+ await this.shouldBlockConnection(direction === 'inbound' ? 'denyInboundEncryptedConnection' : 'denyOutboundEncryptedConnection', remotePeer, maConn)
310
262
  } else {
311
- if (remotePeerId == null) {
312
- throw new InvalidPeerIdError('Encryption was skipped but no peer id was passed')
263
+ const idStr = maConn.remoteAddr.getPeerId()
264
+
265
+ if (idStr == null) {
266
+ throw new InvalidMultiaddrError(`${direction} connection that skipped encryption must have a peer id`)
313
267
  }
314
268
 
269
+ const remotePeerId = peerIdFromString(idStr)
270
+
315
271
  cryptoProtocol = 'native'
316
272
  remotePeer = remotePeerId
317
273
  }
@@ -320,27 +276,33 @@ export class DefaultUpgrader implements Upgrader {
320
276
  if (opts?.muxerFactory != null) {
321
277
  muxerFactory = opts.muxerFactory
322
278
  } else if (this.streamMuxers.size > 0) {
279
+ opts?.onProgress?.(new CustomProgressEvent(`upgrader:multiplex-${direction}-connection`))
280
+
323
281
  // Multiplex the connection
324
- const multiplexed = await this._multiplexOutbound({
325
- ...protectedConn,
326
- ...encryptedConn
327
- }, this.streamMuxers)
282
+ const multiplexed = await (direction === 'inbound'
283
+ ? this._multiplexInbound({
284
+ ...protectedConn,
285
+ ...encryptedConn
286
+ }, this.streamMuxers, opts)
287
+ : this._multiplexOutbound({
288
+ ...protectedConn,
289
+ ...encryptedConn
290
+ }, this.streamMuxers, opts))
328
291
  muxerFactory = multiplexed.muxerFactory
329
292
  upgradedConn = multiplexed.stream
330
293
  }
331
294
  } catch (err: any) {
332
- maConn.log.error('failed to upgrade outbound connection', err)
333
- await maConn.close(err)
295
+ maConn.log.error('failed to upgrade inbound connection', err)
334
296
  throw err
335
297
  }
336
298
 
337
- await this.shouldBlockConnection(remotePeer, maConn, 'denyOutboundUpgradedConnection')
299
+ await this.shouldBlockConnection(direction === 'inbound' ? 'denyInboundUpgradedConnection' : 'denyOutboundUpgradedConnection', remotePeer, maConn)
338
300
 
339
- maConn.log('successfully upgraded outbound connection')
301
+ maConn.log('successfully %s inbound connection', direction)
340
302
 
341
303
  return this._createConnection({
342
304
  cryptoProtocol,
343
- direction: 'outbound',
305
+ direction,
344
306
  maConn,
345
307
  upgradedConn,
346
308
  muxerFactory,
@@ -380,7 +342,11 @@ export class DefaultUpgrader implements Upgrader {
380
342
  void Promise.resolve()
381
343
  .then(async () => {
382
344
  const protocols = this.components.registrar.getProtocols()
345
+ const signal = AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout)
346
+ setMaxListeners(Infinity, signal)
347
+
383
348
  const { stream, protocol } = await mss.handle(muxedStream, protocols, {
349
+ signal,
384
350
  log: muxedStream.log,
385
351
  yieldBytes: false
386
352
  })
@@ -455,7 +421,7 @@ export class DefaultUpgrader implements Upgrader {
455
421
  if (options.signal == null) {
456
422
  muxedStream.log('no abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols)
457
423
 
458
- const signal = AbortSignal.timeout(DEFAULT_PROTOCOL_SELECT_TIMEOUT)
424
+ const signal = AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout)
459
425
  setMaxListeners(Infinity, signal)
460
426
 
461
427
  options = {
@@ -632,6 +598,7 @@ export class DefaultUpgrader implements Upgrader {
632
598
 
633
599
  try {
634
600
  const { stream, protocol } = await mss.handle(connection, protocols, {
601
+ ...options,
635
602
  log: connection.log
636
603
  })
637
604
  const encrypter = this.connectionEncrypters.get(protocol)
@@ -656,7 +623,7 @@ export class DefaultUpgrader implements Upgrader {
656
623
  * Attempts to encrypt the given `connection` with the provided connection encrypters.
657
624
  * The first `ConnectionEncrypter` module to succeed will be used
658
625
  */
659
- async _encryptOutbound (connection: MultiaddrConnection, options?: SecureConnectionOptions): Promise<CryptoResult> {
626
+ async _encryptOutbound (connection: MultiaddrConnection, options: SecureConnectionOptions): Promise<CryptoResult> {
660
627
  const protocols = Array.from(this.connectionEncrypters.keys())
661
628
  connection.log('selecting outbound crypto protocol', protocols)
662
629
 
@@ -667,6 +634,7 @@ export class DefaultUpgrader implements Upgrader {
667
634
  stream,
668
635
  protocol
669
636
  } = await mss.select(connection, protocols, {
637
+ ...options,
670
638
  log: connection.log,
671
639
  yieldBytes: true
672
640
  })
@@ -693,7 +661,7 @@ export class DefaultUpgrader implements Upgrader {
693
661
  * Selects one of the given muxers via multistream-select. That
694
662
  * muxer will be used for all future streams on the connection.
695
663
  */
696
- async _multiplexOutbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>): Promise<{ stream: MultiaddrConnection, muxerFactory?: StreamMuxerFactory }> {
664
+ async _multiplexOutbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>, options: AbortOptions): Promise<{ stream: MultiaddrConnection, muxerFactory?: StreamMuxerFactory }> {
697
665
  const protocols = Array.from(muxers.keys())
698
666
  connection.log('outbound selecting muxer %s', protocols)
699
667
  try {
@@ -703,6 +671,7 @@ export class DefaultUpgrader implements Upgrader {
703
671
  stream,
704
672
  protocol
705
673
  } = await mss.select(connection, protocols, {
674
+ ...options,
706
675
  log: connection.log,
707
676
  yieldBytes: true
708
677
  })
@@ -721,11 +690,12 @@ export class DefaultUpgrader implements Upgrader {
721
690
  * Registers support for one of the given muxers via multistream-select. The
722
691
  * selected muxer will be used for all future streams on the connection.
723
692
  */
724
- async _multiplexInbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>): Promise<{ stream: MultiaddrConnection, muxerFactory?: StreamMuxerFactory }> {
693
+ async _multiplexInbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>, options: AbortOptions): Promise<{ stream: MultiaddrConnection, muxerFactory?: StreamMuxerFactory }> {
725
694
  const protocols = Array.from(muxers.keys())
726
695
  connection.log('inbound handling muxers %s', protocols)
727
696
  try {
728
697
  const { stream, protocol } = await mss.handle(connection, protocols, {
698
+ ...options,
729
699
  log: connection.log
730
700
  })
731
701
  const muxerFactory = muxers.get(protocol)
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '2.1.0'
1
+ export const version = '2.1.1-c258b35af'
2
2
  export const name = 'libp2p'