libp2p 2.10.0-a02cb0461 → 2.10.0-e8398d97e

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 (75) hide show
  1. package/README.md +39 -37
  2. package/dist/index.min.js +13 -12
  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 -42
  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 -12
  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/transport-addresses.js +6 -6
  16. package/dist/src/address-manager/transport-addresses.js.map +1 -1
  17. package/dist/src/config/connection-gater.browser.d.ts.map +1 -1
  18. package/dist/src/config/connection-gater.browser.js +8 -22
  19. package/dist/src/config/connection-gater.browser.js.map +1 -1
  20. package/dist/src/config/connection-gater.d.ts.map +1 -1
  21. package/dist/src/config/connection-gater.js +1 -12
  22. package/dist/src/config/connection-gater.js.map +1 -1
  23. package/dist/src/config.d.ts.map +1 -1
  24. package/dist/src/config.js +3 -22
  25. package/dist/src/config.js.map +1 -1
  26. package/dist/src/connection-manager/connection-pruner.d.ts.map +1 -1
  27. package/dist/src/connection-manager/connection-pruner.js +6 -1
  28. package/dist/src/connection-manager/connection-pruner.js.map +1 -1
  29. package/dist/src/connection-manager/dial-queue.js +2 -2
  30. package/dist/src/connection-manager/dial-queue.js.map +1 -1
  31. package/dist/src/connection-manager/index.d.ts +0 -16
  32. package/dist/src/connection-manager/index.d.ts.map +1 -1
  33. package/dist/src/connection-manager/index.js +18 -10
  34. package/dist/src/connection-manager/index.js.map +1 -1
  35. package/dist/src/connection-manager/utils.d.ts +3 -3
  36. package/dist/src/connection-manager/utils.d.ts.map +1 -1
  37. package/dist/src/connection-manager/utils.js +24 -21
  38. package/dist/src/connection-manager/utils.js.map +1 -1
  39. package/dist/src/connection.d.ts +1 -0
  40. package/dist/src/connection.d.ts.map +1 -1
  41. package/dist/src/connection.js +32 -2
  42. package/dist/src/connection.js.map +1 -1
  43. package/dist/src/get-peer.js +3 -3
  44. package/dist/src/get-peer.js.map +1 -1
  45. package/dist/src/libp2p.d.ts +3 -1
  46. package/dist/src/libp2p.d.ts.map +1 -1
  47. package/dist/src/libp2p.js +11 -5
  48. package/dist/src/libp2p.js.map +1 -1
  49. package/dist/src/registrar.d.ts +5 -1
  50. package/dist/src/registrar.d.ts.map +1 -1
  51. package/dist/src/registrar.js +17 -6
  52. package/dist/src/registrar.js.map +1 -1
  53. package/dist/src/upgrader.d.ts.map +1 -1
  54. package/dist/src/upgrader.js +3 -2
  55. package/dist/src/upgrader.js.map +1 -1
  56. package/dist/src/version.d.ts +1 -1
  57. package/dist/src/version.js +1 -1
  58. package/package.json +13 -13
  59. package/src/address-manager/dns-mappings.ts +50 -49
  60. package/src/address-manager/index.ts +36 -14
  61. package/src/address-manager/ip-mappings.ts +64 -44
  62. package/src/address-manager/transport-addresses.ts +7 -7
  63. package/src/config/connection-gater.browser.ts +8 -24
  64. package/src/config/connection-gater.ts +1 -12
  65. package/src/config.ts +3 -25
  66. package/src/connection-manager/connection-pruner.ts +7 -1
  67. package/src/connection-manager/dial-queue.ts +2 -2
  68. package/src/connection-manager/index.ts +20 -28
  69. package/src/connection-manager/utils.ts +26 -22
  70. package/src/connection.ts +40 -3
  71. package/src/get-peer.ts +3 -3
  72. package/src/libp2p.ts +14 -6
  73. package/src/registrar.ts +21 -8
  74. package/src/upgrader.ts +3 -2
  75. package/src/version.ts +1 -1
@@ -1,6 +1,6 @@
1
1
  import { ConnectionClosedError, InvalidMultiaddrError, InvalidParametersError, InvalidPeerIdError, NotStartedError, start, stop } from '@libp2p/interface'
2
2
  import { PeerMap } from '@libp2p/peer-collections'
3
- import { RateLimiter } from '@libp2p/utils'
3
+ import { getNetConfig, isNetworkAddress, RateLimiter } from '@libp2p/utils'
4
4
  import { multiaddr } from '@multiformats/multiaddr'
5
5
  import { pEvent } from 'p-event'
6
6
  import { CustomProgressEvent } from 'progress-events'
@@ -82,24 +82,6 @@ export interface ConnectionManagerInit {
82
82
  */
83
83
  inboundUpgradeTimeout?: number
84
84
 
85
- /**
86
- * When a new outbound connection is opened, the upgrade process (e.g.
87
- * protect, encrypt, multiplex etc) must complete within this number of ms.
88
- *
89
- * Does not apply if an abort signal is passed to the `.dial` method.
90
- *
91
- * @deprecated This is handled by `dialTimeout`
92
- */
93
- outboundUpgradeTimeout?: number
94
-
95
- /**
96
- * Protocol negotiation must complete within this number of ms
97
- *
98
- * @default 2000
99
- * @deprecated use outboundStreamProtocolNegotiationTimeout or inboundStreamProtocolNegotiationTimeout instead
100
- */
101
- protocolNegotiationTimeout?: number
102
-
103
85
  /**
104
86
  * Outbound protocol negotiation must complete within this number of ms.
105
87
  *
@@ -250,8 +232,8 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
250
232
  this.onDisconnect = this.onDisconnect.bind(this)
251
233
 
252
234
  // allow/deny lists
253
- this.allow = (init.allow ?? []).map(str => multiaddrToIpNet(str))
254
- this.deny = (init.deny ?? []).map(str => multiaddrToIpNet(str))
235
+ this.allow = (init.allow ?? []).map(str => multiaddrToIpNet(multiaddr(str)))
236
+ this.deny = (init.deny ?? []).map(str => multiaddrToIpNet(multiaddr(str)))
255
237
 
256
238
  this.incomingPendingConnections = 0
257
239
  this.maxIncomingPendingConnections = init.maxIncomingPendingConnections ?? defaultOptions.maxIncomingPendingConnections
@@ -639,8 +621,13 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
639
621
 
640
622
  acceptIncomingConnection (maConn: MultiaddrConnection): boolean {
641
623
  // check deny list
642
- const denyConnection = this.deny.some(ma => {
643
- return ma.contains(maConn.remoteAddr.nodeAddress().address)
624
+ const denyConnection = this.deny.some(ipNet => {
625
+ if (isNetworkAddress(maConn.remoteAddr)) {
626
+ const config = getNetConfig(maConn.remoteAddr)
627
+ return ipNet.contains(config.host)
628
+ }
629
+
630
+ return false
644
631
  })
645
632
 
646
633
  if (denyConnection) {
@@ -650,7 +637,12 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
650
637
 
651
638
  // check allow list
652
639
  const allowConnection = this.allow.some(ipNet => {
653
- return ipNet.contains(maConn.remoteAddr.nodeAddress().address)
640
+ if (isNetworkAddress(maConn.remoteAddr)) {
641
+ const config = getNetConfig(maConn.remoteAddr)
642
+ return ipNet.contains(config.host)
643
+ }
644
+
645
+ return true
654
646
  })
655
647
 
656
648
  if (allowConnection) {
@@ -665,13 +657,13 @@ export class DefaultConnectionManager implements ConnectionManager, Startable {
665
657
  return false
666
658
  }
667
659
 
668
- if (maConn.remoteAddr.isThinWaistAddress()) {
669
- const host = maConn.remoteAddr.nodeAddress().address
660
+ if (isNetworkAddress(maConn.remoteAddr)) {
661
+ const config = getNetConfig(maConn.remoteAddr)
670
662
 
671
663
  try {
672
- this.inboundConnectionRateLimiter.consume(host, 1)
664
+ this.inboundConnectionRateLimiter.consume(config.host, 1)
673
665
  } catch {
674
- this.log('connection from %a refused - inboundConnectionThreshold exceeded by host %s', maConn.remoteAddr, host)
666
+ this.log('connection from %a refused - inboundConnectionThreshold exceeded by host %s', maConn.remoteAddr, config.host)
675
667
  return false
676
668
  }
677
669
  }
@@ -1,7 +1,7 @@
1
- import { multiaddr } from '@multiformats/multiaddr'
2
- import { convertToIpNet } from '@multiformats/multiaddr/convert'
1
+ import { IpNet } from '@chainsafe/netmask'
2
+ import { InvalidParametersError } from '@libp2p/interface'
3
+ import { getNetConfig } from '@libp2p/utils'
3
4
  import { Circuit } from '@multiformats/multiaddr-matcher'
4
- import type { IpNet } from '@chainsafe/netmask'
5
5
  import type { Connection, AbortOptions, PeerId } from '@libp2p/interface'
6
6
  import type { Multiaddr } from '@multiformats/multiaddr'
7
7
 
@@ -63,32 +63,36 @@ export async function safelyCloseConnectionIfUnused (connection?: Connection, op
63
63
  * - /ipcidr/32 for IPv4
64
64
  * - /ipcidr/128 for IPv6
65
65
  *
66
- * @param {string | Multiaddr} ma - The multiaddr string or object to convert.
66
+ * @param {string | Multiaddr} ma - The multiaddr object to convert.
67
67
  * @returns {IpNet} The converted IpNet object.
68
68
  * @throws {Error} Throws an error if the multiaddr is not valid.
69
69
  */
70
- export function multiaddrToIpNet (ma: string | Multiaddr): IpNet {
71
- try {
72
- let parsedMa: Multiaddr
73
- if (typeof ma === 'string') {
74
- parsedMa = multiaddr(ma)
75
- } else {
76
- parsedMa = ma
77
- }
70
+ export function multiaddrToIpNet (ma: Multiaddr): IpNet {
71
+ const config = getNetConfig(ma)
72
+ let mask = config.cidr
78
73
 
79
- const protoNames = new Set([...parsedMa.getComponents().map(component => component.name)])
74
+ if (config.type !== 'ip4' && config.type !== 'ip6') {
75
+ throw new InvalidParametersError(`Multiaddr ${ma} was not an IPv4 or IPv6 address`)
76
+ }
80
77
 
81
- // Check if /ipcidr is already present
82
- if (!protoNames.has('ipcidr')) {
83
- const isIPv6 = protoNames.has('ip6')
84
- const cidr = isIPv6 ? '/ipcidr/128' : '/ipcidr/32'
85
- parsedMa = parsedMa.encapsulate(cidr)
78
+ // Check if /ipcidr is already present
79
+ if (mask == null) {
80
+ switch (config.type) {
81
+ case 'ip4': {
82
+ mask = 32
83
+ break
84
+ }
85
+ case 'ip6': {
86
+ mask = 128
87
+ break
88
+ }
89
+ default: {
90
+ throw new InvalidParametersError(`Multiaddr ${ma} was not an IPv4 or IPv6 address`)
91
+ }
86
92
  }
87
-
88
- return convertToIpNet(parsedMa)
89
- } catch (error) {
90
- throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${ma}`)
91
93
  }
94
+
95
+ return new IpNet(config.host, mask)
92
96
  }
93
97
 
94
98
  /**
package/src/connection.ts CHANGED
@@ -6,7 +6,7 @@ import { CONNECTION_CLOSE_TIMEOUT, PROTOCOL_NEGOTIATION_TIMEOUT } from './connec
6
6
  import { isDirect } from './connection-manager/utils.ts'
7
7
  import { MuxerUnavailableError } from './errors.ts'
8
8
  import { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.ts'
9
- import type { AbortOptions, Logger, MessageStreamDirection, Connection as ConnectionInterface, Stream, NewStreamOptions, PeerId, ConnectionLimits, StreamMuxer, Metrics, PeerStore, MultiaddrConnection, MessageStreamEvents, MultiaddrConnectionTimeline, ConnectionStatus, MessageStream } from '@libp2p/interface'
9
+ import type { AbortOptions, Logger, MessageStreamDirection, Connection as ConnectionInterface, Stream, NewStreamOptions, PeerId, ConnectionLimits, StreamMuxer, Metrics, PeerStore, MultiaddrConnection, MessageStreamEvents, MultiaddrConnectionTimeline, ConnectionStatus, MessageStream, StreamMiddleware } from '@libp2p/interface'
10
10
  import type { Registrar } from '@libp2p/interface-internal'
11
11
  import type { Multiaddr } from '@multiformats/multiaddr'
12
12
 
@@ -177,7 +177,9 @@ export class Connection extends TypedEventEmitter<MessageStreamEvents> implement
177
177
 
178
178
  this.components.metrics?.trackProtocolStream(muxedStream)
179
179
 
180
- return muxedStream
180
+ const middleware = this.components.registrar.getMiddleware(muxedStream.protocol)
181
+
182
+ return await this.runMiddlewareChain(muxedStream, this, middleware)
181
183
  } catch (err: any) {
182
184
  if (muxedStream.status === 'open') {
183
185
  muxedStream.abort(err)
@@ -235,12 +237,47 @@ export class Connection extends TypedEventEmitter<MessageStreamEvents> implement
235
237
  throw new LimitedConnectionError('Cannot open protocol stream on limited connection')
236
238
  }
237
239
 
238
- await handler(muxedStream, this)
240
+ const middleware = this.components.registrar.getMiddleware(muxedStream.protocol)
241
+
242
+ middleware.push(async (stream, connection, next) => {
243
+ await handler(stream, connection)
244
+ next(stream, connection)
245
+ })
246
+
247
+ await this.runMiddlewareChain(muxedStream, this, middleware)
239
248
  } catch (err: any) {
240
249
  muxedStream.abort(err)
241
250
  }
242
251
  }
243
252
 
253
+ private async runMiddlewareChain (stream: Stream, connection: ConnectionInterface, middleware: StreamMiddleware[]): Promise<Stream> {
254
+ for (let i = 0; i < middleware.length; i++) {
255
+ const mw = middleware[i]
256
+ stream.log.trace('running middleware', i, mw)
257
+
258
+ // eslint-disable-next-line no-loop-func
259
+ await new Promise<void>((resolve, reject) => {
260
+ try {
261
+ const result = mw(stream, connection, (s, c) => {
262
+ stream = s
263
+ connection = c
264
+ resolve()
265
+ })
266
+
267
+ if (result instanceof Promise) {
268
+ result.catch(reject)
269
+ }
270
+ } catch (err) {
271
+ reject(err)
272
+ }
273
+ })
274
+
275
+ stream.log.trace('ran middleware', i, mw)
276
+ }
277
+
278
+ return stream
279
+ }
280
+
244
281
  /**
245
282
  * Close the connection
246
283
  */
package/src/get-peer.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { InvalidMultiaddrError, InvalidParametersError, isPeerId } from '@libp2p/interface'
2
2
  import { peerIdFromString } from '@libp2p/peer-id'
3
- import { isMultiaddr } from '@multiformats/multiaddr'
3
+ import { CODE_P2P, isMultiaddr } from '@multiformats/multiaddr'
4
4
  import { PEER_ID } from '@multiformats/multiaddr-matcher'
5
5
  import type { PeerId } from '@libp2p/interface'
6
6
  import type { Multiaddr } from '@multiformats/multiaddr'
@@ -24,7 +24,7 @@ export function getPeerAddress (peer: PeerId | Multiaddr | Multiaddr[]): PeerAdd
24
24
  let peerId: PeerId | undefined
25
25
 
26
26
  if (multiaddrs.length > 0) {
27
- const peerIdStr = multiaddrs[0].getPeerId()
27
+ const peerIdStr = multiaddrs[0].getComponents().findLast(c => c.code === CODE_P2P)?.value
28
28
  peerId = peerIdStr == null ? undefined : peerIdFromString(peerIdStr)
29
29
 
30
30
  // ensure PeerId is either not set or is consistent
@@ -33,7 +33,7 @@ export function getPeerAddress (peer: PeerId | Multiaddr | Multiaddr[]): PeerAdd
33
33
  throw new InvalidMultiaddrError('Invalid multiaddr')
34
34
  }
35
35
 
36
- const maPeerIdStr = ma.getPeerId()
36
+ const maPeerIdStr = ma.getComponents().findLast(c => c.code === CODE_P2P)?.value
37
37
 
38
38
  if (maPeerIdStr == null) {
39
39
  if (peerId != null) {
package/src/libp2p.ts CHANGED
@@ -4,7 +4,7 @@ import { defaultLogger } from '@libp2p/logger'
4
4
  import { PeerSet } from '@libp2p/peer-collections'
5
5
  import { peerIdFromString } from '@libp2p/peer-id'
6
6
  import { persistentPeerStore } from '@libp2p/peer-store'
7
- import { isMultiaddr } from '@multiformats/multiaddr'
7
+ import { CODE_P2P, isMultiaddr } from '@multiformats/multiaddr'
8
8
  import { MemoryDatastore } from 'datastore-core/memory'
9
9
  import { TypedEventEmitter, setMaxListeners } from 'main-event'
10
10
  import { concat as uint8ArrayConcat } from 'uint8arrays/concat'
@@ -24,7 +24,7 @@ import { userAgent } from './user-agent.js'
24
24
  import * as pkg from './version.js'
25
25
  import type { Components } from './components.js'
26
26
  import type { Libp2p as Libp2pInterface, Libp2pInit } from './index.js'
27
- import type { PeerRouting, ContentRouting, Libp2pEvents, PendingDial, ServiceMap, AbortOptions, ComponentLogger, Logger, Connection, NewStreamOptions, Stream, Metrics, PeerId, PeerInfo, PeerStore, Topology, Libp2pStatus, IsDialableOptions, DialOptions, PublicKey, Ed25519PeerId, Secp256k1PeerId, RSAPublicKey, RSAPeerId, URLPeerId, Ed25519PublicKey, Secp256k1PublicKey, StreamHandler, StreamHandlerOptions } from '@libp2p/interface'
27
+ import type { PeerRouting, ContentRouting, Libp2pEvents, PendingDial, ServiceMap, AbortOptions, ComponentLogger, Logger, Connection, NewStreamOptions, Stream, Metrics, PeerId, PeerInfo, PeerStore, Topology, Libp2pStatus, IsDialableOptions, DialOptions, PublicKey, Ed25519PeerId, Secp256k1PeerId, RSAPublicKey, RSAPeerId, URLPeerId, Ed25519PublicKey, Secp256k1PublicKey, StreamHandler, StreamHandlerOptions, StreamMiddleware } from '@libp2p/interface'
28
28
  import type { Multiaddr } from '@multiformats/multiaddr'
29
29
 
30
30
  export class Libp2p<T extends ServiceMap = ServiceMap> extends TypedEventEmitter<Libp2pEvents> implements Libp2pInterface<T> {
@@ -119,8 +119,8 @@ export class Libp2p<T extends ServiceMap = ServiceMap> extends TypedEventEmitter
119
119
  connectionEncrypters: (init.connectionEncrypters ?? []).map((fn, index) => this.configureComponent(`connection-encryption-${index}`, fn(this.components))),
120
120
  streamMuxers: (init.streamMuxers ?? []).map((fn, index) => this.configureComponent(`stream-muxers-${index}`, fn(this.components))),
121
121
  inboundUpgradeTimeout: init.connectionManager?.inboundUpgradeTimeout,
122
- inboundStreamProtocolNegotiationTimeout: init.connectionManager?.inboundStreamProtocolNegotiationTimeout ?? init.connectionManager?.protocolNegotiationTimeout,
123
- outboundStreamProtocolNegotiationTimeout: init.connectionManager?.outboundStreamProtocolNegotiationTimeout ?? init.connectionManager?.protocolNegotiationTimeout,
122
+ inboundStreamProtocolNegotiationTimeout: init.connectionManager?.inboundStreamProtocolNegotiationTimeout,
123
+ outboundStreamProtocolNegotiationTimeout: init.connectionManager?.outboundStreamProtocolNegotiationTimeout,
124
124
  connectionCloseTimeout: init.connectionManager?.connectionCloseTimeout
125
125
  })
126
126
 
@@ -237,7 +237,7 @@ export class Libp2p<T extends ServiceMap = ServiceMap> extends TypedEventEmitter
237
237
 
238
238
  this.status = 'started'
239
239
  this.safeDispatchEvent('start', { detail: this })
240
- this.log('libp2p has started')
240
+ this.log('libp2p has started with peer id %p', this.peerId)
241
241
  } catch (err: any) {
242
242
  this.log.error('An error occurred starting libp2p', err)
243
243
  // set status to 'started' so this.stop() will stop any running components
@@ -318,7 +318,7 @@ export class Libp2p<T extends ServiceMap = ServiceMap> extends TypedEventEmitter
318
318
 
319
319
  async hangUp (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise<void> {
320
320
  if (isMultiaddr(peer)) {
321
- peer = peerIdFromString(peer.getPeerId() ?? '')
321
+ peer = peerIdFromString(peer.getComponents().findLast(c => c.code === CODE_P2P)?.value ?? '')
322
322
  }
323
323
 
324
324
  await this.components.connectionManager.closeConnections(peer, options)
@@ -401,6 +401,14 @@ export class Libp2p<T extends ServiceMap = ServiceMap> extends TypedEventEmitter
401
401
  this.components.registrar.unregister(id)
402
402
  }
403
403
 
404
+ use (protocol: string, middleware: StreamMiddleware | StreamMiddleware[]): void {
405
+ this.components.registrar.use(protocol, Array.isArray(middleware) ? middleware : [middleware])
406
+ }
407
+
408
+ unuse (protocol: string): void {
409
+ this.components.registrar.unuse(protocol)
410
+ }
411
+
404
412
  async isDialable (multiaddr: Multiaddr, options: IsDialableOptions = {}): Promise<boolean> {
405
413
  return this.components.connectionManager.isDialable(multiaddr, options)
406
414
  }
package/src/registrar.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { InvalidParametersError } from '@libp2p/interface'
2
- import { mergeOptions, trackedMap } from '@libp2p/utils'
2
+ import { trackedMap } from '@libp2p/utils'
3
3
  import { DuplicateProtocolHandlerError, UnhandledProtocolError } from './errors.js'
4
- import type { IdentifyResult, Libp2pEvents, Logger, PeerUpdate, PeerId, PeerStore, Topology, StreamHandler, StreamHandlerRecord, StreamHandlerOptions, AbortOptions, Metrics } from '@libp2p/interface'
4
+ import type { IdentifyResult, Libp2pEvents, Logger, PeerUpdate, PeerId, PeerStore, Topology, StreamHandler, StreamHandlerRecord, StreamHandlerOptions, AbortOptions, Metrics, StreamMiddleware } from '@libp2p/interface'
5
5
  import type { Registrar as RegistrarInterface } from '@libp2p/interface-internal'
6
6
  import type { ComponentLogger } from '@libp2p/logger'
7
7
  import type { TypedEventTarget } from 'main-event'
@@ -25,10 +25,12 @@ export class Registrar implements RegistrarInterface {
25
25
  private readonly topologies: Map<string, Map<string, Topology>>
26
26
  private readonly handlers: Map<string, StreamHandlerRecord>
27
27
  private readonly components: RegistrarComponents
28
+ private readonly middleware: Map<string, StreamMiddleware[]>
28
29
 
29
30
  constructor (components: RegistrarComponents) {
30
31
  this.components = components
31
32
  this.log = components.logger.forComponent('libp2p:registrar')
33
+ this.middleware = new Map()
32
34
  this.topologies = new Map()
33
35
  components.metrics?.registerMetricGroup('libp2p_registrar_topologies', {
34
36
  calculate: () => {
@@ -93,14 +95,13 @@ export class Registrar implements RegistrarInterface {
93
95
  throw new DuplicateProtocolHandlerError(`Handler already registered for protocol ${protocol}`)
94
96
  }
95
97
 
96
- const options = mergeOptions.bind({ ignoreUndefined: true })({
97
- maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,
98
- maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS
99
- }, opts)
100
-
101
98
  this.handlers.set(protocol, {
102
99
  handler,
103
- options
100
+ options: {
101
+ maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,
102
+ maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS,
103
+ ...opts
104
+ }
104
105
  })
105
106
 
106
107
  // Add new protocol to self protocols in the peer store
@@ -164,6 +165,18 @@ export class Registrar implements RegistrarInterface {
164
165
  }
165
166
  }
166
167
 
168
+ use (protocol: string, middleware: StreamMiddleware[]): void {
169
+ this.middleware.set(protocol, middleware)
170
+ }
171
+
172
+ unuse (protocol: string): void {
173
+ this.middleware.delete(protocol)
174
+ }
175
+
176
+ getMiddleware (protocol: string): StreamMiddleware[] {
177
+ return this.middleware.get(protocol) ?? []
178
+ }
179
+
167
180
  /**
168
181
  * Remove a disconnected peer from the record
169
182
  */
package/src/upgrader.ts CHANGED
@@ -2,6 +2,7 @@ import { InvalidMultiaddrError, InvalidPeerIdError } from '@libp2p/interface'
2
2
  import * as mss from '@libp2p/multistream-select'
3
3
  import { peerIdFromString } from '@libp2p/peer-id'
4
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'
@@ -222,7 +223,7 @@ export class Upgrader implements UpgraderInterface {
222
223
  outbound: true
223
224
  })
224
225
 
225
- const idStr = maConn.remoteAddr.getPeerId()
226
+ const idStr = maConn.remoteAddr.getComponents().findLast(c => c.code === CODE_P2P)?.value
226
227
  let remotePeerId: PeerId | undefined
227
228
 
228
229
  if (idStr != null) {
@@ -284,7 +285,7 @@ export class Upgrader implements UpgraderInterface {
284
285
  cryptoProtocol = 'native'
285
286
  remotePeer = opts.remotePeer
286
287
  } else {
287
- const peerIdString = maConn.remoteAddr.getPeerId()
288
+ const peerIdString = maConn.remoteAddr.getComponents().findLast(c => c.code === CODE_P2P)?.value
288
289
  let remotePeerFromMultiaddr: PeerId | undefined
289
290
 
290
291
  if (peerIdString != null) {
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
- export const version = '2.10.0-a02cb0461'
1
+ export const version = '2.10.0-e8398d97e'
2
2
  export const name = 'js-libp2p'