libp2p 0.44.0-ba47c957 → 0.44.0-e3deaa40

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 (112) hide show
  1. package/dist/index.min.js +23 -23
  2. package/dist/src/autonat/index.d.ts.map +1 -1
  3. package/dist/src/autonat/index.js +15 -13
  4. package/dist/src/autonat/index.js.map +1 -1
  5. package/dist/src/components.d.ts +2 -66
  6. package/dist/src/components.d.ts.map +1 -1
  7. package/dist/src/components.js +60 -174
  8. package/dist/src/components.js.map +1 -1
  9. package/dist/src/config/connection-gater.browser.d.ts +8 -0
  10. package/dist/src/config/connection-gater.browser.d.ts.map +1 -0
  11. package/dist/src/config/connection-gater.browser.js +27 -0
  12. package/dist/src/config/connection-gater.browser.js.map +1 -0
  13. package/dist/src/config/connection-gater.d.ts +6 -0
  14. package/dist/src/config/connection-gater.d.ts.map +1 -0
  15. package/dist/src/config/connection-gater.js +18 -0
  16. package/dist/src/config/connection-gater.js.map +1 -0
  17. package/dist/src/config.d.ts +2 -1
  18. package/dist/src/config.d.ts.map +1 -1
  19. package/dist/src/config.js +16 -23
  20. package/dist/src/config.js.map +1 -1
  21. package/dist/src/connection-manager/auto-dial.d.ts.map +1 -1
  22. package/dist/src/connection-manager/auto-dial.js +7 -2
  23. package/dist/src/connection-manager/auto-dial.js.map +1 -1
  24. package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
  25. package/dist/src/connection-manager/dial-queue.js +8 -10
  26. package/dist/src/connection-manager/dial-queue.js.map +1 -1
  27. package/dist/src/connection-manager/index.d.ts.map +1 -1
  28. package/dist/src/connection-manager/index.js +3 -0
  29. package/dist/src/connection-manager/index.js.map +1 -1
  30. package/dist/src/content-routing/index.d.ts +0 -10
  31. package/dist/src/content-routing/index.d.ts.map +1 -1
  32. package/dist/src/content-routing/index.js +6 -41
  33. package/dist/src/content-routing/index.js.map +1 -1
  34. package/dist/src/fetch/index.d.ts +13 -35
  35. package/dist/src/fetch/index.d.ts.map +1 -1
  36. package/dist/src/fetch/index.js +7 -9
  37. package/dist/src/fetch/index.js.map +1 -1
  38. package/dist/src/identify/index.d.ts +13 -49
  39. package/dist/src/identify/index.d.ts.map +1 -1
  40. package/dist/src/identify/index.js +122 -96
  41. package/dist/src/identify/index.js.map +1 -1
  42. package/dist/src/index.d.ts +11 -45
  43. package/dist/src/index.d.ts.map +1 -1
  44. package/dist/src/index.js.map +1 -1
  45. package/dist/src/libp2p.d.ts +10 -35
  46. package/dist/src/libp2p.d.ts.map +1 -1
  47. package/dist/src/libp2p.js +110 -171
  48. package/dist/src/libp2p.js.map +1 -1
  49. package/dist/src/peer-routing.d.ts.map +1 -1
  50. package/dist/src/peer-routing.js +7 -6
  51. package/dist/src/peer-routing.js.map +1 -1
  52. package/dist/src/ping/constants.d.ts +4 -0
  53. package/dist/src/ping/constants.d.ts.map +1 -1
  54. package/dist/src/ping/constants.js +10 -0
  55. package/dist/src/ping/constants.js.map +1 -1
  56. package/dist/src/ping/index.d.ts +10 -27
  57. package/dist/src/ping/index.d.ts.map +1 -1
  58. package/dist/src/ping/index.js +18 -21
  59. package/dist/src/ping/index.js.map +1 -1
  60. package/dist/src/registrar.js +2 -2
  61. package/dist/src/registrar.js.map +1 -1
  62. package/dist/src/transport-manager.d.ts +2 -1
  63. package/dist/src/transport-manager.d.ts.map +1 -1
  64. package/dist/src/transport-manager.js +4 -2
  65. package/dist/src/transport-manager.js.map +1 -1
  66. package/dist/src/upgrader.d.ts.map +1 -1
  67. package/dist/src/upgrader.js +7 -14
  68. package/dist/src/upgrader.js.map +1 -1
  69. package/dist/src/upnp-nat/index.d.ts +42 -0
  70. package/dist/src/upnp-nat/index.d.ts.map +1 -0
  71. package/dist/src/{nat-manager.js → upnp-nat/index.js} +11 -7
  72. package/dist/src/upnp-nat/index.js.map +1 -0
  73. package/package.json +32 -17
  74. package/src/autonat/index.ts +14 -13
  75. package/src/components.ts +67 -248
  76. package/src/config/connection-gater.browser.ts +31 -0
  77. package/src/config/connection-gater.ts +19 -0
  78. package/src/config.ts +8 -14
  79. package/src/connection-manager/auto-dial.ts +8 -2
  80. package/src/connection-manager/dial-queue.ts +10 -16
  81. package/src/connection-manager/index.ts +4 -0
  82. package/src/content-routing/index.ts +6 -54
  83. package/src/fetch/index.ts +51 -14
  84. package/src/identify/index.ts +154 -104
  85. package/src/index.ts +12 -52
  86. package/src/libp2p.ts +102 -214
  87. package/src/peer-routing.ts +10 -8
  88. package/src/ping/constants.ts +11 -0
  89. package/src/ping/index.ts +32 -28
  90. package/src/registrar.ts +2 -2
  91. package/src/transport-manager.ts +5 -3
  92. package/src/upgrader.ts +7 -13
  93. package/src/{nat-manager.ts → upnp-nat/index.ts} +15 -16
  94. package/src/version.ts +1 -1
  95. package/dist/src/dht/dht-content-routing.d.ts +0 -17
  96. package/dist/src/dht/dht-content-routing.d.ts.map +0 -1
  97. package/dist/src/dht/dht-content-routing.js +0 -32
  98. package/dist/src/dht/dht-content-routing.js.map +0 -1
  99. package/dist/src/dht/dht-peer-routing.d.ts +0 -15
  100. package/dist/src/dht/dht-peer-routing.d.ts.map +0 -1
  101. package/dist/src/dht/dht-peer-routing.js +0 -26
  102. package/dist/src/dht/dht-peer-routing.js.map +0 -1
  103. package/dist/src/dht/dummy-dht.d.ts +0 -20
  104. package/dist/src/dht/dummy-dht.d.ts.map +0 -1
  105. package/dist/src/dht/dummy-dht.js +0 -46
  106. package/dist/src/dht/dummy-dht.js.map +0 -1
  107. package/dist/src/nat-manager.d.ts +0 -74
  108. package/dist/src/nat-manager.d.ts.map +0 -1
  109. package/dist/src/nat-manager.js.map +0 -1
  110. package/src/dht/dht-content-routing.ts +0 -44
  111. package/src/dht/dht-peer-routing.ts +0 -36
  112. package/src/dht/dummy-dht.ts +0 -60
@@ -8,6 +8,7 @@ import { Multiaddr, multiaddr, protocols } from '@multiformats/multiaddr'
8
8
  import { Identify } from './pb/message.js'
9
9
  import { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'
10
10
  import {
11
+ AGENT_VERSION,
11
12
  MULTICODEC_IDENTIFY,
12
13
  MULTICODEC_IDENTIFY_PUSH,
13
14
  IDENTIFY_PROTOCOL_VERSION,
@@ -21,7 +22,6 @@ import type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'
21
22
  import type { Connection, Stream } from '@libp2p/interface-connection'
22
23
  import type { Startable } from '@libp2p/interfaces/startable'
23
24
  import { peerIdFromKeys } from '@libp2p/peer-id'
24
- import { TimeoutController } from 'timeout-abort-controller'
25
25
  import type { AbortOptions } from '@libp2p/interfaces'
26
26
  import { abortableDuplex } from 'abortable-iterator'
27
27
  import { setMaxListeners } from 'events'
@@ -29,46 +29,44 @@ import type { ConnectionManager } from '@libp2p/interface-connection-manager'
29
29
  import type { PeerId } from '@libp2p/interface-peer-id'
30
30
  import type { Peer, PeerStore } from '@libp2p/interface-peer-store'
31
31
  import type { AddressManager } from '@libp2p/interface-address-manager'
32
+ import { anySignal } from 'any-signal'
32
33
  import type { EventEmitter } from '@libp2p/interfaces/events'
33
34
  import type { Libp2pEvents } from '@libp2p/interface-libp2p'
34
35
  import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
35
36
  import { pbStream } from 'it-pb-stream'
37
+ import { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe'
36
38
 
37
39
  const log = logger('libp2p:identify')
38
40
 
39
41
  // https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L52
40
42
  const MAX_IDENTIFY_MESSAGE_SIZE = 1024 * 8
41
43
 
42
- export interface HostProperties {
43
- agentVersion: string
44
- }
45
-
46
44
  export interface IdentifyServiceInit {
47
45
  /**
48
46
  * The prefix to use for the protocol (default: 'ipfs')
49
47
  */
50
- protocolPrefix: string
48
+ protocolPrefix?: string
51
49
 
52
50
  /**
53
51
  * What details we should send as part of an identify message
54
52
  */
55
- host: HostProperties
53
+ agentVersion?: string
56
54
 
57
55
  /**
58
56
  * How long we should wait for a remote peer to send their identify response
59
57
  */
60
- timeout: number
58
+ timeout?: number
61
59
 
62
60
  /**
63
61
  * Identify responses larger than this in bytes will be rejected (default: 8192)
64
62
  */
65
63
  maxIdentifyMessageSize?: number
66
64
 
67
- maxInboundStreams: number
68
- maxOutboundStreams: number
65
+ maxInboundStreams?: number
66
+ maxOutboundStreams?: number
69
67
 
70
- maxPushIncomingStreams: number
71
- maxPushOutgoingStreams: number
68
+ maxPushIncomingStreams?: number
69
+ maxPushOutgoingStreams?: number
72
70
  maxObservedAddresses?: number
73
71
  }
74
72
 
@@ -81,8 +79,34 @@ export interface IdentifyServiceComponents {
81
79
  events: EventEmitter<Libp2pEvents>
82
80
  }
83
81
 
84
- export class IdentifyService implements Startable {
85
- private readonly components: IdentifyServiceComponents
82
+ export interface IdentifyService {
83
+ /**
84
+ * Requests the `Identify` message from peer associated with the given `connection`.
85
+ * If the identified peer does not match the `PeerId` associated with the connection,
86
+ * an error will be thrown.
87
+ */
88
+ identify: (connection: Connection, options?: AbortOptions) => Promise<void>
89
+
90
+ /**
91
+ * Calls `push` on all peer connections
92
+ */
93
+ push: () => Promise<void>
94
+ }
95
+
96
+ const defaultValues = {
97
+ protocolPrefix: 'ipfs',
98
+ agentVersion: AGENT_VERSION,
99
+ // https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L48
100
+ timeout: 60000,
101
+ maxInboundStreams: 1,
102
+ maxOutboundStreams: 1,
103
+ maxPushIncomingStreams: 1,
104
+ maxPushOutgoingStreams: 1,
105
+ maxObservedAddresses: 10,
106
+ maxIdentifyMessageSize: 8192
107
+ }
108
+
109
+ class DefaultIdentifyService implements Startable, IdentifyService {
86
110
  private readonly identifyProtocolStr: string
87
111
  private readonly identifyPushProtocolStr: string
88
112
  public readonly host: {
@@ -90,33 +114,63 @@ export class IdentifyService implements Startable {
90
114
  agentVersion: string
91
115
  }
92
116
 
93
- private readonly init: IdentifyServiceInit
94
117
  private started: boolean
118
+ private readonly timeout: number
119
+ private readonly peerId: PeerId
120
+ private readonly peerStore: PeerStore
121
+ private readonly registrar: Registrar
122
+ private readonly connectionManager: ConnectionManager
123
+ private readonly addressManager: AddressManager
124
+ private readonly maxInboundStreams: number
125
+ private readonly maxOutboundStreams: number
126
+ private readonly maxPushIncomingStreams: number
127
+ private readonly maxPushOutgoingStreams: number
128
+ private readonly maxIdentifyMessageSize: number
129
+ private readonly maxObservedAddresses: number
95
130
 
96
131
  constructor (components: IdentifyServiceComponents, init: IdentifyServiceInit) {
97
- this.components = components
98
132
  this.started = false
99
- this.init = init
100
-
101
- this.identifyProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`
102
- this.identifyPushProtocolStr = `/${init.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`
133
+ this.peerId = components.peerId
134
+ this.peerStore = components.peerStore
135
+ this.registrar = components.registrar
136
+ this.addressManager = components.addressManager
137
+ this.connectionManager = components.connectionManager
138
+
139
+ this.identifyProtocolStr = `/${init.protocolPrefix ?? defaultValues.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`
140
+ this.identifyPushProtocolStr = `/${init.protocolPrefix ?? defaultValues.protocolPrefix}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`
141
+ this.timeout = init.timeout ?? defaultValues.timeout
142
+ this.maxInboundStreams = init.maxInboundStreams ?? defaultValues.maxInboundStreams
143
+ this.maxOutboundStreams = init.maxOutboundStreams ?? defaultValues.maxOutboundStreams
144
+ this.maxPushIncomingStreams = init.maxPushIncomingStreams ?? defaultValues.maxPushIncomingStreams
145
+ this.maxPushOutgoingStreams = init.maxPushOutgoingStreams ?? defaultValues.maxPushOutgoingStreams
146
+ this.maxIdentifyMessageSize = init.maxIdentifyMessageSize ?? defaultValues.maxIdentifyMessageSize
147
+ this.maxObservedAddresses = init.maxObservedAddresses ?? defaultValues.maxObservedAddresses
103
148
 
104
149
  // Store self host metadata
105
150
  this.host = {
106
- protocolVersion: `${init.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,
107
- ...init.host
151
+ protocolVersion: `${init.protocolPrefix ?? defaultValues.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,
152
+ agentVersion: init.agentVersion ?? defaultValues.agentVersion
108
153
  }
109
154
 
110
155
  // When a new connection happens, trigger identify
111
- this.components.events.addEventListener('connection:open', (evt) => {
156
+ components.events.addEventListener('connection:open', (evt) => {
112
157
  const connection = evt.detail
113
158
  this.identify(connection).catch(err => { log.error('error during identify trigged by connection:open', err) })
114
159
  })
115
160
 
116
161
  // When self peer record changes, trigger identify-push
117
- this.components.events.addEventListener('self:peer:update', (evt) => {
118
- void this.pushToPeerStore().catch(err => { log.error(err) })
162
+ components.events.addEventListener('self:peer:update', (evt) => {
163
+ void this.push().catch(err => { log.error(err) })
119
164
  })
165
+
166
+ // Append user agent version to default AGENT_VERSION depending on the environment
167
+ if (this.host.agentVersion === AGENT_VERSION) {
168
+ if (isNode || isElectronMain) {
169
+ this.host.agentVersion += ` UserAgent=${globalThis.process.version}`
170
+ } else if (isBrowser || isWebWorker || isElectronRenderer || isReactNative) {
171
+ this.host.agentVersion += ` UserAgent=${globalThis.navigator.userAgent}`
172
+ }
173
+ }
120
174
  }
121
175
 
122
176
  isStarted (): boolean {
@@ -128,36 +182,36 @@ export class IdentifyService implements Startable {
128
182
  return
129
183
  }
130
184
 
131
- await this.components.peerStore.merge(this.components.peerId, {
185
+ await this.peerStore.merge(this.peerId, {
132
186
  metadata: {
133
187
  AgentVersion: uint8ArrayFromString(this.host.agentVersion),
134
188
  ProtocolVersion: uint8ArrayFromString(this.host.protocolVersion)
135
189
  }
136
190
  })
137
191
 
138
- await this.components.registrar.handle(this.identifyProtocolStr, (data) => {
192
+ await this.registrar.handle(this.identifyProtocolStr, (data) => {
139
193
  void this._handleIdentify(data).catch(err => {
140
194
  log.error(err)
141
195
  })
142
196
  }, {
143
- maxInboundStreams: this.init.maxInboundStreams,
144
- maxOutboundStreams: this.init.maxOutboundStreams
197
+ maxInboundStreams: this.maxInboundStreams,
198
+ maxOutboundStreams: this.maxOutboundStreams
145
199
  })
146
- await this.components.registrar.handle(this.identifyPushProtocolStr, (data) => {
200
+ await this.registrar.handle(this.identifyPushProtocolStr, (data) => {
147
201
  void this._handlePush(data).catch(err => {
148
202
  log.error(err)
149
203
  })
150
204
  }, {
151
- maxInboundStreams: this.init.maxPushIncomingStreams,
152
- maxOutboundStreams: this.init.maxPushOutgoingStreams
205
+ maxInboundStreams: this.maxPushIncomingStreams,
206
+ maxOutboundStreams: this.maxPushOutgoingStreams
153
207
  })
154
208
 
155
209
  this.started = true
156
210
  }
157
211
 
158
212
  async stop (): Promise<void> {
159
- await this.components.registrar.unhandle(this.identifyProtocolStr)
160
- await this.components.registrar.unhandle(this.identifyPushProtocolStr)
213
+ await this.registrar.unhandle(this.identifyProtocolStr)
214
+ await this.registrar.unhandle(this.identifyPushProtocolStr)
161
215
 
162
216
  this.started = false
163
217
  }
@@ -165,34 +219,35 @@ export class IdentifyService implements Startable {
165
219
  /**
166
220
  * Send an Identify Push update to the list of connections
167
221
  */
168
- async push (connections: Connection[]): Promise<void> {
169
- const listenAddresses = this.components.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))
222
+ async pushToConnections (connections: Connection[]): Promise<void> {
223
+ const listenAddresses = this.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))
170
224
  const peerRecord = new PeerRecord({
171
- peerId: this.components.peerId,
225
+ peerId: this.peerId,
172
226
  multiaddrs: listenAddresses
173
227
  })
174
- const signedPeerRecord = await RecordEnvelope.seal(peerRecord, this.components.peerId)
175
- const supportedProtocols = this.components.registrar.getProtocols()
176
- const peer = await this.components.peerStore.get(this.components.peerId)
228
+ const signedPeerRecord = await RecordEnvelope.seal(peerRecord, this.peerId)
229
+ const supportedProtocols = this.registrar.getProtocols()
230
+ const peer = await this.peerStore.get(this.peerId)
177
231
  const agentVersion = uint8ArrayToString(peer.metadata.get('AgentVersion') ?? uint8ArrayFromString(this.host.agentVersion))
178
232
  const protocolVersion = uint8ArrayToString(peer.metadata.get('ProtocolVersion') ?? uint8ArrayFromString(this.host.protocolVersion))
179
233
 
180
234
  const pushes = connections.map(async connection => {
181
235
  let stream: Stream | undefined
182
- const timeoutController = new TimeoutController(this.init.timeout)
236
+
237
+ const signal = AbortSignal.timeout(this.timeout)
183
238
 
184
239
  try {
185
240
  // fails on node < 15.4
186
- setMaxListeners?.(Infinity, timeoutController.signal)
241
+ setMaxListeners?.(Infinity, signal)
187
242
  } catch {}
188
243
 
189
244
  try {
190
245
  stream = await connection.newStream([this.identifyPushProtocolStr], {
191
- signal: timeoutController.signal
246
+ signal
192
247
  })
193
248
 
194
249
  // make stream abortable
195
- const source = abortableDuplex(stream, timeoutController.signal)
250
+ const source = abortableDuplex(stream, signal)
196
251
 
197
252
  await source.sink(pipe(
198
253
  [Identify.encode({
@@ -211,8 +266,6 @@ export class IdentifyService implements Startable {
211
266
  if (stream != null) {
212
267
  stream.close()
213
268
  }
214
-
215
- timeoutController.clear()
216
269
  }
217
270
  })
218
271
 
@@ -222,7 +275,7 @@ export class IdentifyService implements Startable {
222
275
  /**
223
276
  * Calls `push` on all peer connections
224
277
  */
225
- async pushToPeerStore (): Promise<void> {
278
+ async push (): Promise<void> {
226
279
  // Do not try to push if we are not running
227
280
  if (!this.isStarted()) {
228
281
  return
@@ -230,35 +283,36 @@ export class IdentifyService implements Startable {
230
283
 
231
284
  const connections: Connection[] = []
232
285
 
233
- for (const conn of this.components.connectionManager.getConnections()) {
234
- const peerId = conn.remotePeer
235
- const peer = await this.components.peerStore.get(peerId)
286
+ await Promise.all(
287
+ this.connectionManager.getConnections().map(async conn => {
288
+ try {
289
+ const peer = await this.peerStore.get(conn.remotePeer)
236
290
 
237
- if (!peer.protocols.includes(this.identifyPushProtocolStr)) {
238
- continue
239
- }
291
+ if (!peer.protocols.includes(this.identifyPushProtocolStr)) {
292
+ return
293
+ }
240
294
 
241
- connections.push(conn)
242
- }
295
+ connections.push(conn)
296
+ } catch (err: any) {
297
+ if (err.code !== codes.ERR_NOT_FOUND) {
298
+ throw err
299
+ }
300
+ }
301
+ })
302
+ )
243
303
 
244
- await this.push(connections)
304
+ await this.pushToConnections(connections)
245
305
  }
246
306
 
247
307
  async _identify (connection: Connection, options: AbortOptions = {}): Promise<Identify> {
248
- let timeoutController
249
- let signal = options.signal
250
308
  let stream: Stream | undefined
251
309
 
252
- // create a timeout if no abort signal passed
253
- if (signal == null) {
254
- timeoutController = new TimeoutController(this.init.timeout)
255
- signal = timeoutController.signal
310
+ const signal = anySignal([AbortSignal.timeout(this.timeout), options?.signal])
256
311
 
257
- try {
258
- // fails on node < 15.4
259
- setMaxListeners?.(Infinity, timeoutController.signal)
260
- } catch {}
261
- }
312
+ try {
313
+ // fails on node < 15.4
314
+ setMaxListeners?.(Infinity, signal)
315
+ } catch {}
262
316
 
263
317
  try {
264
318
  stream = await connection.newStream([this.identifyProtocolStr], {
@@ -272,7 +326,7 @@ export class IdentifyService implements Startable {
272
326
  [],
273
327
  source,
274
328
  (source) => lp.decode(source, {
275
- maxDataLength: this.init.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE
329
+ maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE
276
330
  }),
277
331
  async (source) => await first(source)
278
332
  )
@@ -287,21 +341,13 @@ export class IdentifyService implements Startable {
287
341
  throw new CodeError(String(err), codes.ERR_INVALID_MESSAGE)
288
342
  }
289
343
  } finally {
290
- if (timeoutController != null) {
291
- timeoutController.clear()
292
- }
293
-
294
344
  if (stream != null) {
295
345
  stream.close()
296
346
  }
347
+ signal.clear()
297
348
  }
298
349
  }
299
350
 
300
- /**
301
- * Requests the `Identify` message from peer associated with the given `connection`.
302
- * If the identified peer does not match the `PeerId` associated with the connection,
303
- * an error will be thrown.
304
- */
305
351
  async identify (connection: Connection, options: AbortOptions = {}): Promise<void> {
306
352
  const message = await this._identify(connection, options)
307
353
  const {
@@ -320,20 +366,20 @@ export class IdentifyService implements Startable {
320
366
  throw new CodeError('identified peer does not match the expected peer', codes.ERR_INVALID_PEER)
321
367
  }
322
368
 
323
- if (this.components.peerId.equals(id)) {
369
+ if (this.peerId.equals(id)) {
324
370
  throw new CodeError('identified peer is our own peer id?', codes.ERR_INVALID_PEER)
325
371
  }
326
372
 
327
373
  // Get the observedAddr if there is one
328
- const cleanObservedAddr = IdentifyService.getCleanMultiaddr(observedAddr)
374
+ const cleanObservedAddr = getCleanMultiaddr(observedAddr)
329
375
 
330
376
  log('identify completed for peer %p and protocols %o', id, protocols)
331
377
  log('our observed address is %s', cleanObservedAddr)
332
378
 
333
379
  if (cleanObservedAddr != null &&
334
- this.components.addressManager.getObservedAddrs().length < (this.init.maxObservedAddresses ?? Infinity)) {
380
+ this.addressManager.getObservedAddrs().length < (this.maxObservedAddresses ?? Infinity)) {
335
381
  log('storing our observed address %s', cleanObservedAddr?.toString())
336
- this.components.addressManager.addObservedAddr(cleanObservedAddr)
382
+ this.addressManager.addObservedAddr(cleanObservedAddr)
337
383
  }
338
384
 
339
385
  await this.#consumeIdentifyMessage(connection.remotePeer, message)
@@ -345,26 +391,27 @@ export class IdentifyService implements Startable {
345
391
  */
346
392
  async _handleIdentify (data: IncomingStreamData): Promise<void> {
347
393
  const { connection, stream } = data
348
- const timeoutController = new TimeoutController(this.init.timeout)
394
+
395
+ const signal = AbortSignal.timeout(this.timeout)
349
396
 
350
397
  try {
351
398
  // fails on node < 15.4
352
- setMaxListeners?.(Infinity, timeoutController.signal)
399
+ setMaxListeners?.(Infinity, signal)
353
400
  } catch {}
354
401
 
355
402
  try {
356
- const publicKey = this.components.peerId.publicKey ?? new Uint8Array(0)
357
- const peerData = await this.components.peerStore.get(this.components.peerId)
358
- const multiaddrs = this.components.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))
403
+ const publicKey = this.peerId.publicKey ?? new Uint8Array(0)
404
+ const peerData = await this.peerStore.get(this.peerId)
405
+ const multiaddrs = this.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code))
359
406
  let signedPeerRecord = peerData.peerRecordEnvelope
360
407
 
361
408
  if (multiaddrs.length > 0 && signedPeerRecord == null) {
362
409
  const peerRecord = new PeerRecord({
363
- peerId: this.components.peerId,
410
+ peerId: this.peerId,
364
411
  multiaddrs
365
412
  })
366
413
 
367
- const envelope = await RecordEnvelope.seal(peerRecord, this.components.peerId)
414
+ const envelope = await RecordEnvelope.seal(peerRecord, this.peerId)
368
415
  signedPeerRecord = envelope.marshal().subarray()
369
416
  }
370
417
 
@@ -379,7 +426,7 @@ export class IdentifyService implements Startable {
379
426
  })
380
427
 
381
428
  // make stream abortable
382
- const source = abortableDuplex(stream, timeoutController.signal)
429
+ const source = abortableDuplex(stream, signal)
383
430
 
384
431
  const msgWithLenPrefix = pipe([message], (source) => lp.encode(source))
385
432
  await source.sink(msgWithLenPrefix)
@@ -387,7 +434,6 @@ export class IdentifyService implements Startable {
387
434
  log.error('could not respond to identify request', err)
388
435
  } finally {
389
436
  stream.close()
390
- timeoutController.clear()
391
437
  }
392
438
  }
393
439
 
@@ -398,14 +444,14 @@ export class IdentifyService implements Startable {
398
444
  const { connection, stream } = data
399
445
 
400
446
  try {
401
- if (this.components.peerId.equals(connection.remotePeer)) {
447
+ if (this.peerId.equals(connection.remotePeer)) {
402
448
  throw new Error('received push from ourselves?')
403
449
  }
404
450
 
405
451
  // make stream abortable
406
- const source = abortableDuplex(stream, AbortSignal.timeout(this.init.timeout))
452
+ const source = abortableDuplex(stream, AbortSignal.timeout(this.timeout))
407
453
  const pb = pbStream(source, {
408
- maxDataLength: this.init.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE
454
+ maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE
409
455
  })
410
456
  const message = await pb.readPB(Identify)
411
457
 
@@ -447,7 +493,7 @@ export class IdentifyService implements Startable {
447
493
  let peer: Peer | undefined
448
494
 
449
495
  try {
450
- peer = await this.components.peerStore.get(peerRecord.peerId)
496
+ peer = await this.peerStore.get(peerRecord.peerId)
451
497
  } catch (err: any) {
452
498
  if (err.code !== 'ERR_NOT_FOUND') {
453
499
  throw err
@@ -477,7 +523,7 @@ export class IdentifyService implements Startable {
477
523
  metadata.set('ProtocolVersion', uint8ArrayFromString(message.protocolVersion))
478
524
  }
479
525
 
480
- await this.components.peerStore.patch(peerRecord.peerId, {
526
+ await this.peerStore.patch(peerRecord.peerId, {
481
527
  peerRecordEnvelope: message.signedPeerRecord,
482
528
  protocols: message.protocols,
483
529
  addresses: peerRecord.multiaddrs.map(multiaddr => ({
@@ -489,17 +535,17 @@ export class IdentifyService implements Startable {
489
535
 
490
536
  log('consumed signedPeerRecord sent in push from %p', remotePeer)
491
537
  }
538
+ }
492
539
 
493
- /**
494
- * Takes the `addr` and converts it to a Multiaddr if possible
495
- */
496
- static getCleanMultiaddr (addr: Uint8Array | string | null | undefined): Multiaddr | undefined {
497
- if (addr != null && addr.length > 0) {
498
- try {
499
- return multiaddr(addr)
500
- } catch {
540
+ /**
541
+ * Takes the `addr` and converts it to a Multiaddr if possible
542
+ */
543
+ function getCleanMultiaddr (addr: Uint8Array | string | null | undefined): Multiaddr | undefined {
544
+ if (addr != null && addr.length > 0) {
545
+ try {
546
+ return multiaddr(addr)
547
+ } catch {
501
548
 
502
- }
503
549
  }
504
550
  }
505
551
  }
@@ -513,3 +559,7 @@ export const multicodecs = {
513
559
  }
514
560
 
515
561
  export const Message = { Identify }
562
+
563
+ export function identifyService (init: IdentifyServiceInit = {}): (components: IdentifyServiceComponents) => IdentifyService {
564
+ return (components) => new DefaultIdentifyService(components, init)
565
+ }
package/src/index.ts CHANGED
@@ -17,8 +17,6 @@
17
17
  import { createLibp2pNode } from './libp2p.js'
18
18
  import type { RecursivePartial } from '@libp2p/interfaces'
19
19
  import type { TransportManagerInit } from './transport-manager.js'
20
- import type { IdentifyServiceInit } from './identify/index.js'
21
- import type { DualDHT } from '@libp2p/interface-dht'
22
20
  import type { Datastore } from 'interface-datastore'
23
21
  import type { PeerId } from '@libp2p/interface-peer-id'
24
22
  import type { PeerDiscovery } from '@libp2p/interface-peer-discovery'
@@ -29,25 +27,23 @@ import type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'
29
27
  import type { ConnectionEncrypter } from '@libp2p/interface-connection-encrypter'
30
28
  import type { PeerRouting } from '@libp2p/interface-peer-routing'
31
29
  import type { ContentRouting } from '@libp2p/interface-content-routing'
32
- import type { PubSub } from '@libp2p/interface-pubsub'
33
30
  import type { Metrics } from '@libp2p/interface-metrics'
34
- import type { PingServiceInit } from './ping/index.js'
35
- import type { FetchServiceInit } from './fetch/index.js'
36
- import type { AutonatServiceInit } from './autonat/index.js'
37
31
  import type { Components } from './components.js'
38
- import type { Libp2p } from '@libp2p/interface-libp2p'
32
+ import type { Libp2p, ServiceMap } from '@libp2p/interface-libp2p'
39
33
  import type { KeyChainInit } from '@libp2p/keychain'
40
- import type { NatManagerInit } from './nat-manager.js'
41
34
  import type { AddressManagerInit } from './address-manager/index.js'
42
35
  import type { PeerRoutingInit } from './peer-routing.js'
43
36
  import type { ConnectionManagerInit } from './connection-manager/index.js'
44
- import type { CircuitRelayService } from './circuit-relay/index.js'
45
37
  import type { PersistentPeerStoreInit } from '@libp2p/peer-store'
46
38
 
39
+ export type ServiceFactoryMap<T extends Record<string, unknown> = Record<string, unknown>> = {
40
+ [Property in keyof T]: (components: Components) => T[Property]
41
+ }
42
+
47
43
  /**
48
44
  * For Libp2p configurations and modules details read the [Configuration Document](./CONFIGURATION.md).
49
45
  */
50
- export interface Libp2pInit {
46
+ export interface Libp2pInit<T extends ServiceMap = {}> {
51
47
  /**
52
48
  * peerId instance (it will be created if not provided)
53
49
  */
@@ -95,37 +91,6 @@ export interface Libp2pInit {
95
91
  */
96
92
  keychain: KeyChainInit
97
93
 
98
- /**
99
- * The NAT manager controls uPNP hole punching
100
- */
101
- nat: NatManagerInit
102
-
103
- /**
104
- * If configured as a relay this node will relay certain
105
- * types of traffic for other peers
106
- */
107
- relay: (components: Components) => CircuitRelayService
108
-
109
- /**
110
- * identify protocol options
111
- */
112
- identify: IdentifyServiceInit
113
-
114
- /**
115
- * ping protocol options
116
- */
117
- ping: PingServiceInit
118
-
119
- /**
120
- * fetch protocol options
121
- */
122
- fetch: FetchServiceInit
123
-
124
- /**
125
- * autonat protocol options
126
- */
127
- autonat: AutonatServiceInit
128
-
129
94
  /**
130
95
  * An array that must include at least 1 compliant transport
131
96
  */
@@ -136,30 +101,25 @@ export interface Libp2pInit {
136
101
  peerRouters?: Array<(components: Components) => PeerRouting>
137
102
  contentRouters?: Array<(components: Components) => ContentRouting>
138
103
 
139
- /**
140
- * Pass a DHT implementation to enable DHT operations
141
- */
142
- dht?: (components: Components) => DualDHT
143
-
144
104
  /**
145
105
  * A Metrics implementation can be supplied to collect metrics on this node
146
106
  */
147
107
  metrics?: (components: Components) => Metrics
148
108
 
149
109
  /**
150
- * If a PubSub implmentation is supplied, PubSub operations will become available
110
+ * A ConnectionProtector can be used to create a secure overlay on top of the network using pre-shared keys
151
111
  */
152
- pubsub?: (components: Components) => PubSub
112
+ connectionProtector?: (components: Components) => ConnectionProtector
153
113
 
154
114
  /**
155
- * A ConnectionProtector can be used to create a secure overlay on top of the network using pre-shared keys
115
+ * Arbitrary libp2p modules
156
116
  */
157
- connectionProtector?: (components: Components) => ConnectionProtector
117
+ services: ServiceFactoryMap<T>
158
118
  }
159
119
 
160
120
  export type { Libp2p }
161
121
 
162
- export type Libp2pOptions = RecursivePartial<Libp2pInit> & { start?: boolean }
122
+ export type Libp2pOptions<T extends ServiceMap = {}> = RecursivePartial<Libp2pInit<T>> & { start?: boolean }
163
123
 
164
124
  /**
165
125
  * Returns a new instance of the Libp2p interface, generating a new PeerId
@@ -186,7 +146,7 @@ export type Libp2pOptions = RecursivePartial<Libp2pInit> & { start?: boolean }
186
146
  * const libp2p = await createLibp2p(options)
187
147
  * ```
188
148
  */
189
- export async function createLibp2p (options: Libp2pOptions): Promise<Libp2p> {
149
+ export async function createLibp2p <T extends ServiceMap = {}> (options: Libp2pOptions<T>): Promise<Libp2p<T>> {
190
150
  const node = await createLibp2pNode(options)
191
151
 
192
152
  if (options.start !== false) {