libp2p 0.37.2 → 0.37.3-0bb1b80

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 (161) hide show
  1. package/README.md +1 -0
  2. package/dist/src/address-manager/index.d.ts +2 -2
  3. package/dist/src/address-manager/index.d.ts.map +1 -1
  4. package/dist/src/circuit/auto-relay.d.ts +4 -4
  5. package/dist/src/circuit/auto-relay.d.ts.map +1 -1
  6. package/dist/src/circuit/circuit/hop.d.ts +2 -2
  7. package/dist/src/circuit/circuit/hop.d.ts.map +1 -1
  8. package/dist/src/circuit/circuit/hop.js +2 -2
  9. package/dist/src/circuit/circuit/hop.js.map +1 -1
  10. package/dist/src/circuit/circuit/stop.d.ts +1 -1
  11. package/dist/src/circuit/circuit/stop.d.ts.map +1 -1
  12. package/dist/src/circuit/circuit/stop.js +1 -1
  13. package/dist/src/circuit/circuit/stop.js.map +1 -1
  14. package/dist/src/circuit/circuit/stream-handler.d.ts +1 -1
  15. package/dist/src/circuit/circuit/stream-handler.d.ts.map +1 -1
  16. package/dist/src/circuit/index.d.ts +2 -2
  17. package/dist/src/circuit/index.d.ts.map +1 -1
  18. package/dist/src/circuit/listener.d.ts +3 -3
  19. package/dist/src/circuit/listener.d.ts.map +1 -1
  20. package/dist/src/circuit/transport.d.ts +5 -5
  21. package/dist/src/circuit/transport.d.ts.map +1 -1
  22. package/dist/src/circuit/transport.js +2 -2
  23. package/dist/src/circuit/transport.js.map +1 -1
  24. package/dist/src/config.d.ts.map +1 -1
  25. package/dist/src/config.js +25 -3
  26. package/dist/src/config.js.map +1 -1
  27. package/dist/src/connection-manager/auto-dialler.d.ts +1 -1
  28. package/dist/src/connection-manager/auto-dialler.d.ts.map +1 -1
  29. package/dist/src/connection-manager/dialer/auto-dialer.d.ts +2 -2
  30. package/dist/src/connection-manager/dialer/auto-dialer.d.ts.map +1 -1
  31. package/dist/src/connection-manager/dialer/dial-request.d.ts +1 -1
  32. package/dist/src/connection-manager/dialer/dial-request.d.ts.map +1 -1
  33. package/dist/src/connection-manager/dialer/index.d.ts +9 -9
  34. package/dist/src/connection-manager/dialer/index.d.ts.map +1 -1
  35. package/dist/src/connection-manager/dialer/index.js +11 -11
  36. package/dist/src/connection-manager/dialer/index.js.map +1 -1
  37. package/dist/src/connection-manager/index.d.ts +24 -20
  38. package/dist/src/connection-manager/index.d.ts.map +1 -1
  39. package/dist/src/connection-manager/index.js +199 -82
  40. package/dist/src/connection-manager/index.js.map +1 -1
  41. package/dist/src/constants.d.ts +4 -0
  42. package/dist/src/constants.d.ts.map +1 -1
  43. package/dist/src/constants.js +4 -0
  44. package/dist/src/constants.js.map +1 -1
  45. package/dist/src/content-routing/index.d.ts +4 -4
  46. package/dist/src/content-routing/index.d.ts.map +1 -1
  47. package/dist/src/content-routing/utils.d.ts +2 -2
  48. package/dist/src/content-routing/utils.d.ts.map +1 -1
  49. package/dist/src/dht/dht-content-routing.d.ts +3 -3
  50. package/dist/src/dht/dht-content-routing.d.ts.map +1 -1
  51. package/dist/src/dht/dht-peer-routing.d.ts +5 -5
  52. package/dist/src/dht/dht-peer-routing.d.ts.map +1 -1
  53. package/dist/src/dht/dummy-dht.d.ts +3 -3
  54. package/dist/src/dht/dummy-dht.d.ts.map +1 -1
  55. package/dist/src/dht/dummy-dht.js +1 -1
  56. package/dist/src/dht/dummy-dht.js.map +1 -1
  57. package/dist/src/errors.d.ts +4 -1
  58. package/dist/src/errors.d.ts.map +1 -1
  59. package/dist/src/errors.js +3 -0
  60. package/dist/src/errors.js.map +1 -1
  61. package/dist/src/fetch/index.d.ts +11 -4
  62. package/dist/src/fetch/index.d.ts.map +1 -1
  63. package/dist/src/fetch/index.js +74 -42
  64. package/dist/src/fetch/index.js.map +1 -1
  65. package/dist/src/get-peer.d.ts +2 -2
  66. package/dist/src/get-peer.d.ts.map +1 -1
  67. package/dist/src/get-peer.js +1 -1
  68. package/dist/src/get-peer.js.map +1 -1
  69. package/dist/src/identify/index.d.ts +8 -8
  70. package/dist/src/identify/index.d.ts.map +1 -1
  71. package/dist/src/identify/index.js +23 -32
  72. package/dist/src/identify/index.js.map +1 -1
  73. package/dist/src/index.d.ts +17 -17
  74. package/dist/src/index.d.ts.map +1 -1
  75. package/dist/src/insecure/index.d.ts +2 -2
  76. package/dist/src/insecure/index.d.ts.map +1 -1
  77. package/dist/src/insecure/index.js +1 -1
  78. package/dist/src/insecure/index.js.map +1 -1
  79. package/dist/src/keychain/index.d.ts +2 -2
  80. package/dist/src/keychain/index.d.ts.map +1 -1
  81. package/dist/src/libp2p.d.ts +14 -14
  82. package/dist/src/libp2p.d.ts.map +1 -1
  83. package/dist/src/libp2p.js +16 -16
  84. package/dist/src/libp2p.js.map +1 -1
  85. package/dist/src/metrics/index.d.ts +3 -3
  86. package/dist/src/metrics/index.d.ts.map +1 -1
  87. package/dist/src/metrics/index.js +6 -2
  88. package/dist/src/metrics/index.js.map +1 -1
  89. package/dist/src/metrics/moving-average.d.ts +1 -1
  90. package/dist/src/metrics/moving-average.d.ts.map +1 -1
  91. package/dist/src/metrics/stats.d.ts +1 -1
  92. package/dist/src/metrics/stats.d.ts.map +1 -1
  93. package/dist/src/nat-manager.d.ts +1 -1
  94. package/dist/src/nat-manager.d.ts.map +1 -1
  95. package/dist/src/peer-record-updater.d.ts +1 -1
  96. package/dist/src/peer-record-updater.d.ts.map +1 -1
  97. package/dist/src/peer-routing.d.ts +4 -4
  98. package/dist/src/peer-routing.d.ts.map +1 -1
  99. package/dist/src/ping/index.d.ts +10 -3
  100. package/dist/src/ping/index.d.ts.map +1 -1
  101. package/dist/src/ping/index.js +21 -7
  102. package/dist/src/ping/index.js.map +1 -1
  103. package/dist/src/pnet/index.d.ts +1 -2
  104. package/dist/src/pnet/index.d.ts.map +1 -1
  105. package/dist/src/pnet/index.js.map +1 -1
  106. package/dist/src/pubsub/dummy-pubsub.d.ts +2 -2
  107. package/dist/src/pubsub/dummy-pubsub.d.ts.map +1 -1
  108. package/dist/src/registrar.d.ts +10 -8
  109. package/dist/src/registrar.d.ts.map +1 -1
  110. package/dist/src/registrar.js +63 -44
  111. package/dist/src/registrar.js.map +1 -1
  112. package/dist/src/transport-manager.d.ts +3 -3
  113. package/dist/src/transport-manager.d.ts.map +1 -1
  114. package/dist/src/upgrader.d.ts +12 -6
  115. package/dist/src/upgrader.d.ts.map +1 -1
  116. package/dist/src/upgrader.js +151 -66
  117. package/dist/src/upgrader.js.map +1 -1
  118. package/dist/src/version.d.ts.map +1 -1
  119. package/dist/src/version.js.map +1 -1
  120. package/package.json +56 -32
  121. package/src/address-manager/index.ts +2 -2
  122. package/src/circuit/auto-relay.ts +4 -4
  123. package/src/circuit/circuit/hop.ts +4 -4
  124. package/src/circuit/circuit/stop.ts +2 -2
  125. package/src/circuit/circuit/stream-handler.ts +1 -1
  126. package/src/circuit/index.ts +2 -2
  127. package/src/circuit/listener.ts +3 -3
  128. package/src/circuit/transport.ts +5 -5
  129. package/src/config.ts +25 -3
  130. package/src/connection-manager/auto-dialler.ts +1 -1
  131. package/src/connection-manager/dialer/auto-dialer.ts +2 -2
  132. package/src/connection-manager/dialer/dial-request.ts +1 -1
  133. package/src/connection-manager/dialer/index.ts +15 -15
  134. package/src/connection-manager/index.ts +257 -97
  135. package/src/constants.ts +5 -0
  136. package/src/content-routing/index.ts +2 -2
  137. package/src/content-routing/utils.ts +2 -2
  138. package/src/dht/dht-content-routing.ts +2 -2
  139. package/src/dht/dht-peer-routing.ts +3 -3
  140. package/src/dht/dummy-dht.ts +3 -3
  141. package/src/errors.ts +4 -1
  142. package/src/fetch/index.ts +111 -53
  143. package/src/get-peer.ts +3 -3
  144. package/src/identify/index.ts +34 -40
  145. package/src/index.ts +17 -17
  146. package/src/insecure/index.ts +3 -3
  147. package/src/keychain/index.ts +2 -2
  148. package/src/libp2p.ts +33 -28
  149. package/src/metrics/index.ts +9 -5
  150. package/src/metrics/moving-average.ts +1 -1
  151. package/src/metrics/stats.ts +1 -1
  152. package/src/nat-manager.ts +1 -1
  153. package/src/peer-record-updater.ts +1 -1
  154. package/src/peer-routing.ts +4 -4
  155. package/src/ping/index.ts +35 -12
  156. package/src/pnet/index.ts +1 -2
  157. package/src/pubsub/dummy-pubsub.ts +2 -2
  158. package/src/registrar.ts +79 -55
  159. package/src/transport-manager.ts +3 -3
  160. package/src/upgrader.ts +188 -76
  161. package/src/version.ts +1 -2
@@ -3,21 +3,29 @@ import errCode from 'err-code'
3
3
  import { codes } from '../errors.js'
4
4
  import * as lp from 'it-length-prefixed'
5
5
  import { FetchRequest, FetchResponse } from './pb/proto.js'
6
- import { handshake } from 'it-handshake'
7
6
  import { PROTOCOL_NAME, PROTOCOL_VERSION } from './constants.js'
8
- import type { PeerId } from '@libp2p/interfaces/peer-id'
7
+ import type { PeerId } from '@libp2p/interface-peer-id'
9
8
  import type { Startable } from '@libp2p/interfaces/startable'
10
- import type { Stream } from '@libp2p/interfaces/connection'
11
- import type { IncomingStreamData } from '@libp2p/interfaces/registrar'
12
- import type { Components } from '@libp2p/interfaces/components'
9
+ import type { Stream } from '@libp2p/interface-connection'
10
+ import type { IncomingStreamData } from '@libp2p/interface-registrar'
11
+ import type { Components } from '@libp2p/components'
13
12
  import type { AbortOptions } from '@libp2p/interfaces'
14
- import type { Duplex } from 'it-stream-types'
15
13
  import { abortableDuplex } from 'abortable-iterator'
14
+ import { pipe } from 'it-pipe'
15
+ import first from 'it-first'
16
+ import { TimeoutController } from 'timeout-abort-controller'
16
17
 
17
18
  const log = logger('libp2p:fetch')
18
19
 
19
20
  export interface FetchServiceInit {
20
21
  protocolPrefix: string
22
+ maxInboundStreams: number
23
+ maxOutboundStreams: number
24
+
25
+ /**
26
+ * How long we should wait for a remote peer to send any data
27
+ */
28
+ timeout: number
21
29
  }
22
30
 
23
31
  export interface HandleMessageOptions {
@@ -40,6 +48,7 @@ export class FetchService implements Startable {
40
48
  private readonly components: Components
41
49
  private readonly lookupFunctions: Map<string, LookupFunction>
42
50
  private started: boolean
51
+ private readonly init: FetchServiceInit
43
52
 
44
53
  constructor (components: Components, init: FetchServiceInit) {
45
54
  this.started = false
@@ -47,13 +56,21 @@ export class FetchService implements Startable {
47
56
  this.protocol = `/${init.protocolPrefix ?? 'libp2p'}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`
48
57
  this.lookupFunctions = new Map() // Maps key prefix to value lookup function
49
58
  this.handleMessage = this.handleMessage.bind(this)
59
+ this.init = init
50
60
  }
51
61
 
52
62
  async start () {
53
63
  await this.components.getRegistrar().handle(this.protocol, (data) => {
54
- void this.handleMessage(data).catch(err => {
55
- log.error(err)
56
- })
64
+ void this.handleMessage(data)
65
+ .catch(err => {
66
+ log.error(err)
67
+ })
68
+ .finally(() => {
69
+ data.stream.close()
70
+ })
71
+ }, {
72
+ maxInboundStreams: this.init.maxInboundStreams,
73
+ maxOutboundStreams: this.init.maxOutboundStreams
57
74
  })
58
75
  this.started = true
59
76
  }
@@ -74,36 +91,62 @@ export class FetchService implements Startable {
74
91
  log('dialing %s to %p', this.protocol, peer)
75
92
 
76
93
  const connection = await this.components.getConnectionManager().openConnection(peer, options)
77
- const { stream } = await connection.newStream([this.protocol], options)
78
- let source: Duplex<Uint8Array> = stream
94
+ let timeoutController
95
+ let signal = options.signal
79
96
 
80
- // make stream abortable if AbortSignal passed
81
- if (options.signal != null) {
82
- source = abortableDuplex(stream, options.signal)
97
+ // create a timeout if no abort signal passed
98
+ if (signal == null) {
99
+ timeoutController = new TimeoutController(this.init.timeout)
100
+ signal = timeoutController.signal
83
101
  }
84
102
 
85
- const shake = handshake(source)
86
-
87
- // send message
88
- shake.write(lp.encode.single(FetchRequest.encode({ identifier: key })).slice())
103
+ const stream = await connection.newStream([this.protocol], {
104
+ signal
105
+ })
89
106
 
90
- // read response
91
- // @ts-expect-error fromReader returns a Source which has no .next method
92
- const response = FetchResponse.decode((await lp.decode.fromReader(shake.reader).next()).value.slice())
93
- switch (response.status) {
94
- case (FetchResponse.StatusCode.OK): {
95
- return response.data
96
- }
97
- case (FetchResponse.StatusCode.NOT_FOUND): {
98
- return null
99
- }
100
- case (FetchResponse.StatusCode.ERROR): {
101
- const errmsg = (new TextDecoder()).decode(response.data)
102
- throw errCode(new Error('Error in fetch protocol response: ' + errmsg), codes.ERR_INVALID_PARAMETERS)
103
- }
104
- default: {
105
- throw errCode(new Error('Unknown response status'), codes.ERR_INVALID_MESSAGE)
107
+ // make stream abortable
108
+ const source = abortableDuplex(stream, signal)
109
+
110
+ try {
111
+ const result = await pipe(
112
+ [FetchRequest.encode({ identifier: key })],
113
+ lp.encode(),
114
+ source,
115
+ lp.decode(),
116
+ async function (source) {
117
+ const buf = await first(source)
118
+
119
+ if (buf == null) {
120
+ throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE)
121
+ }
122
+
123
+ const response = FetchResponse.decode(buf)
124
+
125
+ switch (response.status) {
126
+ case (FetchResponse.StatusCode.OK): {
127
+ return response.data
128
+ }
129
+ case (FetchResponse.StatusCode.NOT_FOUND): {
130
+ return null
131
+ }
132
+ case (FetchResponse.StatusCode.ERROR): {
133
+ const errmsg = (new TextDecoder()).decode(response.data)
134
+ throw errCode(new Error('Error in fetch protocol response: ' + errmsg), codes.ERR_INVALID_PARAMETERS)
135
+ }
136
+ default: {
137
+ throw errCode(new Error('Unknown response status'), codes.ERR_INVALID_MESSAGE)
138
+ }
139
+ }
140
+ }
141
+ )
142
+
143
+ return result ?? null
144
+ } finally {
145
+ if (timeoutController != null) {
146
+ timeoutController.clear()
106
147
  }
148
+
149
+ stream.close()
107
150
  }
108
151
  }
109
152
 
@@ -114,25 +157,40 @@ export class FetchService implements Startable {
114
157
  */
115
158
  async handleMessage (data: IncomingStreamData) {
116
159
  const { stream } = data
117
- const shake = handshake(stream)
118
- // @ts-expect-error fromReader returns a Source which has no .next method
119
- const request = FetchRequest.decode((await lp.decode.fromReader(shake.reader).next()).value.slice())
120
-
121
- let response: FetchResponse
122
- const lookup = this._getLookupFunction(request.identifier)
123
- if (lookup != null) {
124
- const data = await lookup(request.identifier)
125
- if (data != null) {
126
- response = { status: FetchResponse.StatusCode.OK, data }
127
- } else {
128
- response = { status: FetchResponse.StatusCode.NOT_FOUND, data: new Uint8Array(0) }
129
- }
130
- } else {
131
- const errmsg = (new TextEncoder()).encode('No lookup function registered for key: ' + request.identifier)
132
- response = { status: FetchResponse.StatusCode.ERROR, data: errmsg }
133
- }
134
-
135
- shake.write(lp.encode.single(FetchResponse.encode(response)).slice())
160
+ const self = this
161
+
162
+ await pipe(
163
+ stream,
164
+ lp.decode(),
165
+ async function * (source) {
166
+ const buf = await first(source)
167
+
168
+ if (buf == null) {
169
+ throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE)
170
+ }
171
+
172
+ // for await (const buf of source) {
173
+ const request = FetchRequest.decode(buf)
174
+
175
+ let response: FetchResponse
176
+ const lookup = self._getLookupFunction(request.identifier)
177
+ if (lookup != null) {
178
+ const data = await lookup(request.identifier)
179
+ if (data != null) {
180
+ response = { status: FetchResponse.StatusCode.OK, data }
181
+ } else {
182
+ response = { status: FetchResponse.StatusCode.NOT_FOUND, data: new Uint8Array(0) }
183
+ }
184
+ } else {
185
+ const errmsg = (new TextEncoder()).encode('No lookup function registered for key: ' + request.identifier)
186
+ response = { status: FetchResponse.StatusCode.ERROR, data: errmsg }
187
+ }
188
+
189
+ yield FetchResponse.encode(response)
190
+ },
191
+ lp.encode(),
192
+ stream
193
+ )
136
194
  }
137
195
 
138
196
  /**
package/src/get-peer.ts CHANGED
@@ -2,9 +2,9 @@ import { peerIdFromString } from '@libp2p/peer-id'
2
2
  import { Multiaddr } from '@multiformats/multiaddr'
3
3
  import errCode from 'err-code'
4
4
  import { codes } from './errors.js'
5
- import { isPeerId } from '@libp2p/interfaces/peer-id'
6
- import type { PeerId } from '@libp2p/interfaces/peer-id'
7
- import type { PeerInfo } from '@libp2p/interfaces/peer-info'
5
+ import { isPeerId } from '@libp2p/interface-peer-id'
6
+ import type { PeerId } from '@libp2p/interface-peer-id'
7
+ import type { PeerInfo } from '@libp2p/interface-peer-info'
8
8
 
9
9
  function peerIdFromMultiaddr (ma: Multiaddr) {
10
10
  const idStr = ma.getPeerId()
@@ -18,11 +18,11 @@ import {
18
18
  MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION
19
19
  } from './consts.js'
20
20
  import { codes } from '../errors.js'
21
- import type { IncomingStreamData } from '@libp2p/interfaces/registrar'
22
- import type { Connection, Stream } from '@libp2p/interfaces/connection'
21
+ import type { IncomingStreamData } from '@libp2p/interface-registrar'
22
+ import type { Connection, Stream } from '@libp2p/interface-connection'
23
23
  import type { Startable } from '@libp2p/interfaces/startable'
24
24
  import { peerIdFromKeys } from '@libp2p/peer-id'
25
- import type { Components } from '@libp2p/interfaces/components'
25
+ import type { Components } from '@libp2p/components'
26
26
  import { TimeoutController } from 'timeout-abort-controller'
27
27
  import type { AbortOptions } from '@libp2p/interfaces'
28
28
  import { abortableDuplex } from 'abortable-iterator'
@@ -30,9 +30,6 @@ import type { Duplex } from 'it-stream-types'
30
30
 
31
31
  const log = logger('libp2p:identify')
32
32
 
33
- // https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L48
34
- const IDENTIFY_TIMEOUT = 60000
35
-
36
33
  // https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L52
37
34
  const MAX_IDENTIFY_MESSAGE_SIZE = 1024 * 8
38
35
 
@@ -54,12 +51,18 @@ export interface IdentifyServiceInit {
54
51
  /**
55
52
  * How long we should wait for a remote peer to send their identify response
56
53
  */
57
- timeout?: number
54
+ timeout: number
58
55
 
59
56
  /**
60
57
  * Identify responses larger than this in bytes will be rejected (default: 8192)
61
58
  */
62
59
  maxIdentifyMessageSize?: number
60
+
61
+ maxInboundStreams: number
62
+ maxOutboundStreams: number
63
+
64
+ maxPushIncomingStreams: number
65
+ maxPushOutgoingStreams: number
63
66
  }
64
67
 
65
68
  export class IdentifyService implements Startable {
@@ -79,8 +82,6 @@ export class IdentifyService implements Startable {
79
82
  this.started = false
80
83
  this.init = init
81
84
 
82
- this.handleMessage = this.handleMessage.bind(this)
83
-
84
85
  this.identifyProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`
85
86
  this.identifyPushProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`
86
87
 
@@ -127,13 +128,21 @@ export class IdentifyService implements Startable {
127
128
  await this.components.getPeerStore().metadataBook.setValue(this.components.getPeerId(), 'AgentVersion', uint8ArrayFromString(this.host.agentVersion))
128
129
  await this.components.getPeerStore().metadataBook.setValue(this.components.getPeerId(), 'ProtocolVersion', uint8ArrayFromString(this.host.protocolVersion))
129
130
 
130
- await this.components.getRegistrar().handle([
131
- this.identifyProtocolStr,
132
- this.identifyPushProtocolStr
133
- ], (data) => {
134
- void this.handleMessage(data)?.catch(err => {
131
+ await this.components.getRegistrar().handle(this.identifyProtocolStr, (data) => {
132
+ void this._handleIdentify(data).catch(err => {
133
+ log.error(err)
134
+ })
135
+ }, {
136
+ maxInboundStreams: this.init.maxInboundStreams,
137
+ maxOutboundStreams: this.init.maxOutboundStreams
138
+ })
139
+ await this.components.getRegistrar().handle(this.identifyPushProtocolStr, (data) => {
140
+ void this._handlePush(data).catch(err => {
135
141
  log.error(err)
136
142
  })
143
+ }, {
144
+ maxInboundStreams: this.init.maxPushIncomingStreams,
145
+ maxOutboundStreams: this.init.maxPushOutgoingStreams
137
146
  })
138
147
 
139
148
  this.started = true
@@ -155,14 +164,13 @@ export class IdentifyService implements Startable {
155
164
  const protocols = await this.components.getPeerStore().protoBook.get(this.components.getPeerId())
156
165
 
157
166
  const pushes = connections.map(async connection => {
158
- const timeoutController = new TimeoutController(this.init.timeout ?? IDENTIFY_TIMEOUT)
167
+ const timeoutController = new TimeoutController(this.init.timeout)
159
168
  let stream: Stream | undefined
160
169
 
161
170
  try {
162
- const data = await connection.newStream([this.identifyPushProtocolStr], {
171
+ stream = await connection.newStream([this.identifyPushProtocolStr], {
163
172
  signal: timeoutController.signal
164
173
  })
165
- stream = data.stream
166
174
 
167
175
  // make stream abortable
168
176
  const source: Duplex<Uint8Array> = abortableDuplex(stream, timeoutController.signal)
@@ -218,19 +226,21 @@ export class IdentifyService implements Startable {
218
226
  }
219
227
 
220
228
  async _identify (connection: Connection, options: AbortOptions = {}): Promise<Identify> {
221
- const { stream } = await connection.newStream([this.identifyProtocolStr], options)
222
- let source: Duplex<Uint8Array> = stream
223
229
  let timeoutController
224
230
  let signal = options.signal
225
231
 
226
232
  // create a timeout if no abort signal passed
227
233
  if (signal == null) {
228
- timeoutController = new TimeoutController(this.init.timeout ?? IDENTIFY_TIMEOUT)
234
+ timeoutController = new TimeoutController(this.init.timeout)
229
235
  signal = timeoutController.signal
230
236
  }
231
237
 
232
- // make stream abortable if AbortSignal passed
233
- source = abortableDuplex(stream, signal)
238
+ const stream = await connection.newStream([this.identifyProtocolStr], {
239
+ signal
240
+ })
241
+
242
+ // make stream abortable
243
+ const source = abortableDuplex(stream, signal)
234
244
 
235
245
  try {
236
246
  const data = await pipe(
@@ -353,29 +363,13 @@ export class IdentifyService implements Startable {
353
363
  // this.components.getAddressManager().addObservedAddr(observedAddr)
354
364
  }
355
365
 
356
- /**
357
- * A handler to register with Libp2p to process identify messages
358
- */
359
- handleMessage (data: IncomingStreamData) {
360
- const { protocol } = data
361
-
362
- switch (protocol) {
363
- case this.identifyProtocolStr:
364
- return this._handleIdentify(data)
365
- case this.identifyPushProtocolStr:
366
- return this._handlePush(data)
367
- default:
368
- log.error('cannot handle unknown protocol %s', protocol)
369
- }
370
- }
371
-
372
366
  /**
373
367
  * Sends the `Identify` response with the Signed Peer Record
374
368
  * to the requesting peer over the given `connection`
375
369
  */
376
370
  async _handleIdentify (data: IncomingStreamData) {
377
371
  const { connection, stream } = data
378
- const timeoutController = new TimeoutController(this.init.timeout ?? IDENTIFY_TIMEOUT)
372
+ const timeoutController = new TimeoutController(this.init.timeout)
379
373
 
380
374
  try {
381
375
  const publicKey = this.components.getPeerId().publicKey ?? new Uint8Array(0)
@@ -426,7 +420,7 @@ export class IdentifyService implements Startable {
426
420
  */
427
421
  async _handlePush (data: IncomingStreamData) {
428
422
  const { connection, stream } = data
429
- const timeoutController = new TimeoutController(this.init.timeout ?? IDENTIFY_TIMEOUT)
423
+ const timeoutController = new TimeoutController(this.init.timeout)
430
424
 
431
425
  let message: Identify | undefined
432
426
  try {
package/src/index.ts CHANGED
@@ -5,23 +5,23 @@ import type { Startable } from '@libp2p/interfaces/startable'
5
5
  import type { Multiaddr } from '@multiformats/multiaddr'
6
6
  import type { FaultTolerance } from './transport-manager.js'
7
7
  import type { IdentifyServiceInit } from './identify/index.js'
8
- import type { DualDHT } from '@libp2p/interfaces/dht'
8
+ import type { DualDHT } from '@libp2p/interface-dht'
9
9
  import type { Datastore } from 'interface-datastore'
10
- import type { PeerStore, PeerStoreInit } from '@libp2p/interfaces/peer-store'
11
- import type { PeerId } from '@libp2p/interfaces/peer-id'
10
+ import type { PeerStore, PeerStoreInit } from '@libp2p/interface-peer-store'
11
+ import type { PeerId } from '@libp2p/interface-peer-id'
12
12
  import type { AutoRelayConfig, RelayAdvertiseConfig } from './circuit/index.js'
13
- import type { PeerDiscovery } from '@libp2p/interfaces/peer-discovery'
14
- import type { Connection, ConnectionGater, ConnectionProtector, ProtocolStream } from '@libp2p/interfaces/connection'
15
- import type { Transport } from '@libp2p/interfaces/transport'
16
- import type { StreamMuxerFactory } from '@libp2p/interfaces/stream-muxer'
17
- import type { ConnectionEncrypter } from '@libp2p/interfaces/connection-encrypter'
18
- import type { PeerRouting } from '@libp2p/interfaces/peer-routing'
19
- import type { ContentRouting } from '@libp2p/interfaces/content-routing'
20
- import type { PubSub } from '@libp2p/interfaces/pubsub'
21
- import type { Registrar, StreamHandler } from '@libp2p/interfaces/registrar'
22
- import type { ConnectionManager } from '@libp2p/interfaces/connection-manager'
23
- import type { Metrics, MetricsInit } from '@libp2p/interfaces/metrics'
24
- import type { PeerInfo } from '@libp2p/interfaces/peer-info'
13
+ import type { PeerDiscovery } from '@libp2p/interface-peer-discovery'
14
+ import type { Connection, ConnectionGater, ConnectionProtector, Stream } from '@libp2p/interface-connection'
15
+ import type { Transport } from '@libp2p/interface-transport'
16
+ import type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'
17
+ import type { ConnectionEncrypter } from '@libp2p/interface-connection-encrypter'
18
+ import type { PeerRouting } from '@libp2p/interface-peer-routing'
19
+ import type { ContentRouting } from '@libp2p/interface-content-routing'
20
+ import type { PubSub } from '@libp2p/interface-pubsub'
21
+ import type { Registrar, StreamHandler, StreamHandlerOptions } from '@libp2p/interface-registrar'
22
+ import type { ConnectionManager } from '@libp2p/interface-connection-manager'
23
+ import type { Metrics, MetricsInit } from '@libp2p/interface-metrics'
24
+ import type { PeerInfo } from '@libp2p/interface-peer-info'
25
25
  import type { KeyChain } from './keychain/index.js'
26
26
  import type { ConnectionManagerInit } from './connection-manager/index.js'
27
27
  import type { PingServiceInit } from './ping/index.js'
@@ -177,7 +177,7 @@ export interface Libp2p extends Startable, EventEmitter<Libp2pEvents> {
177
177
  * If successful, the known metadata of the peer will be added to the nodes `peerStore`,
178
178
  * and the `MuxedStream` will be returned together with the successful negotiated protocol.
179
179
  */
180
- dialProtocol: (peer: PeerId | Multiaddr, protocols: string | string[], options?: AbortOptions) => Promise<ProtocolStream>
180
+ dialProtocol: (peer: PeerId | Multiaddr, protocols: string | string[], options?: AbortOptions) => Promise<Stream>
181
181
 
182
182
  /**
183
183
  * Disconnects all connections to the given `peer`
@@ -187,7 +187,7 @@ export interface Libp2p extends Startable, EventEmitter<Libp2pEvents> {
187
187
  /**
188
188
  * Registers the `handler` for each protocol
189
189
  */
190
- handle: (protocol: string | string[], handler: StreamHandler) => Promise<void>
190
+ handle: (protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions) => Promise<void>
191
191
 
192
192
  /**
193
193
  * Removes the handler for each protocol. The protocol
@@ -1,11 +1,11 @@
1
1
  import { logger } from '@libp2p/logger'
2
2
  import { handshake } from 'it-handshake'
3
3
  import * as lp from 'it-length-prefixed'
4
- import { UnexpectedPeerError, InvalidCryptoExchangeError } from '@libp2p/interfaces/connection-encrypter/errors'
4
+ import { UnexpectedPeerError, InvalidCryptoExchangeError } from '@libp2p/interface-connection-encrypter/errors'
5
5
  import { Exchange, KeyType } from './pb/proto.js'
6
- import type { PeerId } from '@libp2p/interfaces/peer-id'
6
+ import type { PeerId } from '@libp2p/interface-peer-id'
7
7
  import { peerIdFromBytes, peerIdFromKeys } from '@libp2p/peer-id'
8
- import type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interfaces/connection-encrypter'
8
+ import type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interface-connection-encrypter'
9
9
  import type { Duplex } from 'it-stream-types'
10
10
 
11
11
  const log = logger('libp2p:plaintext')
@@ -10,8 +10,8 @@ import { codes } from '../errors.js'
10
10
  import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
11
11
  import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
12
12
  import { generateKeyPair, importKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'
13
- import type { PeerId } from '@libp2p/interfaces/peer-id'
14
- import type { Components } from '@libp2p/interfaces/components'
13
+ import type { PeerId } from '@libp2p/interface-peer-id'
14
+ import type { Components } from '@libp2p/components'
15
15
  import { pbkdf2, randomBytes } from '@libp2p/crypto'
16
16
 
17
17
  const log = logger('libp2p:keychain')
package/src/libp2p.ts CHANGED
@@ -27,25 +27,25 @@ import { DHTPeerRouting } from './dht/dht-peer-routing.js'
27
27
  import { PersistentPeerStore } from '@libp2p/peer-store'
28
28
  import { DHTContentRouting } from './dht/dht-content-routing.js'
29
29
  import { AutoDialer } from './connection-manager/dialer/auto-dialer.js'
30
- import { Initializable, Components, isInitializable } from '@libp2p/interfaces/components'
31
- import type { PeerId } from '@libp2p/interfaces/peer-id'
32
- import type { Connection } from '@libp2p/interfaces/connection'
33
- import type { PeerRouting } from '@libp2p/interfaces/peer-routing'
34
- import type { ContentRouting } from '@libp2p/interfaces/content-routing'
35
- import type { PubSub } from '@libp2p/interfaces/pubsub'
36
- import type { Registrar, StreamHandler } from '@libp2p/interfaces/registrar'
37
- import type { ConnectionManager } from '@libp2p/interfaces/connection-manager'
38
- import type { PeerInfo } from '@libp2p/interfaces/peer-info'
30
+ import { Initializable, Components, isInitializable } from '@libp2p/components'
31
+ import type { PeerId } from '@libp2p/interface-peer-id'
32
+ import type { Connection } from '@libp2p/interface-connection'
33
+ import type { PeerRouting } from '@libp2p/interface-peer-routing'
34
+ import type { ContentRouting } from '@libp2p/interface-content-routing'
35
+ import type { PubSub } from '@libp2p/interface-pubsub'
36
+ import type { Registrar, StreamHandler, StreamHandlerOptions } from '@libp2p/interface-registrar'
37
+ import type { ConnectionManager } from '@libp2p/interface-connection-manager'
38
+ import type { PeerInfo } from '@libp2p/interface-peer-info'
39
39
  import type { Libp2p, Libp2pEvents, Libp2pInit, Libp2pOptions } from './index.js'
40
40
  import { validateConfig } from './config.js'
41
41
  import { createEd25519PeerId } from '@libp2p/peer-id-factory'
42
- import type { PeerStore } from '@libp2p/interfaces/peer-store'
43
- import type { DualDHT } from '@libp2p/interfaces/dht'
42
+ import type { PeerStore } from '@libp2p/interface-peer-store'
43
+ import type { DualDHT } from '@libp2p/interface-dht'
44
44
  import { concat as uint8ArrayConcat } from 'uint8arrays/concat'
45
45
  import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
46
46
  import errCode from 'err-code'
47
47
  import { unmarshalPublicKey } from '@libp2p/crypto/keys'
48
- import type { Metrics } from '@libp2p/interfaces/metrics'
48
+ import type { Metrics } from '@libp2p/interface-metrics'
49
49
  import { DummyDHT } from './dht/dummy-dht.js'
50
50
  import { DummyPubSub } from './pubsub/dummy-pubsub.js'
51
51
  import { PeerSet } from '@libp2p/peer-collections'
@@ -124,7 +124,8 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
124
124
  // Set up the Upgrader
125
125
  this.components.setUpgrader(new DefaultUpgrader(this.components, {
126
126
  connectionEncryption: (init.connectionEncryption ?? []).map(component => this.configureComponent(component)),
127
- muxers: (init.streamMuxers ?? []).map(component => this.configureComponent(component))
127
+ muxers: (init.streamMuxers ?? []).map(component => this.configureComponent(component)),
128
+ inboundUpgradeTimeout: init.connectionManager.inboundUpgradeTimeout
128
129
  }))
129
130
 
130
131
  // Create the Connection Manager
@@ -309,18 +310,6 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
309
310
  )
310
311
 
311
312
  log('libp2p has started')
312
-
313
- // Once we start, emit any peers we may have already discovered
314
- // TODO: this should be removed, as we already discovered these peers in the past
315
- await this.components.getPeerStore().forEach(peer => {
316
- this.dispatchEvent(new CustomEvent<PeerInfo>('peer:discovery', {
317
- detail: {
318
- id: peer.id,
319
- multiaddrs: peer.addresses.map(addr => addr.multiaddr),
320
- protocols: peer.protocols
321
- }
322
- }))
323
- })
324
313
  } catch (err: any) {
325
314
  log.error('An error occurred starting libp2p', err)
326
315
  await this.stop()
@@ -490,12 +479,28 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
490
479
  return await this.pingService.ping(id, options)
491
480
  }
492
481
 
493
- async handle (protocols: string | string[], handler: StreamHandler): Promise<void> {
494
- return await this.components.getRegistrar().handle(protocols, handler)
482
+ async handle (protocols: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void> {
483
+ if (!Array.isArray(protocols)) {
484
+ protocols = [protocols]
485
+ }
486
+
487
+ await Promise.all(
488
+ protocols.map(async protocol => {
489
+ await this.components.getRegistrar().handle(protocol, handler, options)
490
+ })
491
+ )
495
492
  }
496
493
 
497
494
  async unhandle (protocols: string[] | string): Promise<void> {
498
- return await this.components.getRegistrar().unhandle(protocols)
495
+ if (!Array.isArray(protocols)) {
496
+ protocols = [protocols]
497
+ }
498
+
499
+ await Promise.all(
500
+ protocols.map(async protocol => {
501
+ await this.components.getRegistrar().unhandle(protocol)
502
+ })
503
+ )
499
504
  }
500
505
 
501
506
  /**
@@ -3,8 +3,8 @@ import each from 'it-foreach'
3
3
  import LRU from 'hashlru'
4
4
  import { METRICS as defaultOptions } from '../constants.js'
5
5
  import { DefaultStats, StatsInit } from './stats.js'
6
- import type { ComponentMetricsUpdate, Metrics, Stats, TrackStreamOptions } from '@libp2p/interfaces/metrics'
7
- import type { PeerId } from '@libp2p/interfaces/peer-id'
6
+ import type { ComponentMetricsUpdate, Metrics, Stats, TrackedMetric, TrackStreamOptions } from '@libp2p/interface-metrics'
7
+ import type { PeerId } from '@libp2p/interface-peer-id'
8
8
  import type { Startable } from '@libp2p/interfaces/startable'
9
9
  import type { Duplex } from 'it-stream-types'
10
10
 
@@ -41,7 +41,7 @@ export class DefaultMetrics implements Metrics, Startable {
41
41
  private readonly protocolStats: Map<string, DefaultStats>
42
42
  private readonly oldPeers: ReturnType<typeof LRU>
43
43
  private running: boolean
44
- private readonly systems: Map<string, Map<string, Map<string, number>>>
44
+ private readonly systems: Map<string, Map<string, Map<string, TrackedMetric>>>
45
45
  private readonly statsInit: StatsInit
46
46
 
47
47
  constructor (init: MetricsInit) {
@@ -115,7 +115,7 @@ export class DefaultMetrics implements Metrics, Startable {
115
115
  }
116
116
 
117
117
  updateComponentMetric (update: ComponentMetricsUpdate) {
118
- const { system = 'libp2p', component, metric, value } = update
118
+ const { system = 'libp2p', component, metric, value, label, help } = update
119
119
 
120
120
  if (!this.systems.has(system)) {
121
121
  this.systems.set(system, new Map())
@@ -137,7 +137,11 @@ export class DefaultMetrics implements Metrics, Startable {
137
137
  throw new Error('Unknown metric component')
138
138
  }
139
139
 
140
- componentMetrics.set(metric, value)
140
+ componentMetrics.set(metric, {
141
+ label,
142
+ help,
143
+ calculate: typeof value !== 'function' ? () => value : value
144
+ })
141
145
  }
142
146
 
143
147
  /**
@@ -1,4 +1,4 @@
1
- import type { MovingAverage } from '@libp2p/interfaces/metrics'
1
+ import type { MovingAverage } from '@libp2p/interface-metrics'
2
2
 
3
3
  export class DefaultMovingAverage {
4
4
  public movingAverage: number
@@ -2,7 +2,7 @@ import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'
2
2
  import { createMovingAverage } from './moving-average.js'
3
3
  // @ts-expect-error no types
4
4
  import retimer from 'retimer'
5
- import type { MovingAverages, Stats, TransferStats } from '@libp2p/interfaces/metrics'
5
+ import type { MovingAverages, Stats, TransferStats } from '@libp2p/interface-metrics'
6
6
 
7
7
  export interface StatsEvents {
8
8
  'update': CustomEvent<TransferStats>
@@ -8,7 +8,7 @@ import errCode from 'err-code'
8
8
  import { codes } from './errors.js'
9
9
  import { isLoopback } from '@libp2p/utils/multiaddr/is-loopback'
10
10
  import type { Startable } from '@libp2p/interfaces/startable'
11
- import type { Components } from '@libp2p/interfaces/components'
11
+ import type { Components } from '@libp2p/components'
12
12
 
13
13
  const log = logger('libp2p:nat')
14
14
  const DEFAULT_TTL = 7200
@@ -1,5 +1,5 @@
1
1
  import { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'
2
- import type { Components } from '@libp2p/interfaces/components'
2
+ import type { Components } from '@libp2p/components'
3
3
  import type { Startable } from '@libp2p/interfaces/startable'
4
4
  import { logger } from '@libp2p/logger'
5
5
  import { protocols } from '@multiformats/multiaddr'