libp2p 0.40.0 → 0.41.0-19e96cc

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 (101) hide show
  1. package/README.md +26 -6
  2. package/dist/index.min.js +50 -0
  3. package/dist/src/address-manager/index.d.ts.map +1 -1
  4. package/dist/src/address-manager/index.js +1 -1
  5. package/dist/src/address-manager/index.js.map +1 -1
  6. package/dist/src/config.d.ts.map +1 -1
  7. package/dist/src/config.js +0 -11
  8. package/dist/src/config.js.map +1 -1
  9. package/dist/src/connection/index.d.ts +83 -0
  10. package/dist/src/connection/index.d.ts.map +1 -0
  11. package/dist/src/connection/index.js +96 -0
  12. package/dist/src/connection/index.js.map +1 -0
  13. package/dist/src/connection-manager/dialer/index.d.ts +13 -14
  14. package/dist/src/connection-manager/dialer/index.d.ts.map +1 -1
  15. package/dist/src/connection-manager/dialer/index.js +82 -62
  16. package/dist/src/connection-manager/dialer/index.js.map +1 -1
  17. package/dist/src/connection-manager/index.d.ts +7 -115
  18. package/dist/src/connection-manager/index.d.ts.map +1 -1
  19. package/dist/src/connection-manager/index.js +21 -57
  20. package/dist/src/connection-manager/index.js.map +1 -1
  21. package/dist/src/fetch/index.d.ts +14 -0
  22. package/dist/src/fetch/index.d.ts.map +1 -1
  23. package/dist/src/fetch/index.js +29 -3
  24. package/dist/src/fetch/index.js.map +1 -1
  25. package/dist/src/get-peer.d.ts +2 -2
  26. package/dist/src/get-peer.d.ts.map +1 -1
  27. package/dist/src/get-peer.js +2 -5
  28. package/dist/src/get-peer.js.map +1 -1
  29. package/dist/src/index.d.ts +192 -77
  30. package/dist/src/index.d.ts.map +1 -1
  31. package/dist/src/index.js +41 -1
  32. package/dist/src/index.js.map +1 -1
  33. package/dist/src/insecure/index.d.ts +23 -0
  34. package/dist/src/insecure/index.d.ts.map +1 -1
  35. package/dist/src/insecure/index.js +23 -0
  36. package/dist/src/insecure/index.js.map +1 -1
  37. package/dist/src/keychain/index.d.ts +1 -1
  38. package/dist/src/keychain/index.d.ts.map +1 -1
  39. package/dist/src/libp2p.d.ts +3 -3
  40. package/dist/src/libp2p.d.ts.map +1 -1
  41. package/dist/src/libp2p.js +2 -3
  42. package/dist/src/libp2p.js.map +1 -1
  43. package/dist/src/nat-manager.d.ts.map +1 -1
  44. package/dist/src/nat-manager.js +5 -1
  45. package/dist/src/nat-manager.js.map +1 -1
  46. package/dist/src/pnet/index.d.ts +23 -0
  47. package/dist/src/pnet/index.d.ts.map +1 -1
  48. package/dist/src/pnet/index.js +23 -0
  49. package/dist/src/pnet/index.js.map +1 -1
  50. package/dist/src/pnet/key-generator.d.ts +3 -2
  51. package/dist/src/pnet/key-generator.d.ts.map +1 -1
  52. package/dist/src/pnet/key-generator.js +7 -10
  53. package/dist/src/pnet/key-generator.js.map +1 -1
  54. package/dist/src/registrar.d.ts +5 -0
  55. package/dist/src/registrar.d.ts.map +1 -1
  56. package/dist/src/registrar.js +25 -0
  57. package/dist/src/registrar.js.map +1 -1
  58. package/dist/src/transport-manager.d.ts.map +1 -1
  59. package/dist/src/transport-manager.js +1 -2
  60. package/dist/src/transport-manager.js.map +1 -1
  61. package/dist/src/upgrader.d.ts +1 -1
  62. package/dist/src/upgrader.d.ts.map +1 -1
  63. package/dist/src/upgrader.js +46 -59
  64. package/dist/src/upgrader.js.map +1 -1
  65. package/package.json +15 -14
  66. package/src/address-manager/index.ts +3 -2
  67. package/src/circuit/README.md +6 -6
  68. package/src/config.ts +0 -11
  69. package/src/connection/index.ts +171 -0
  70. package/src/connection-manager/dialer/index.ts +100 -75
  71. package/src/connection-manager/index.ts +29 -192
  72. package/src/fetch/README.md +7 -2
  73. package/src/fetch/index.ts +30 -3
  74. package/src/get-peer.ts +3 -7
  75. package/src/index.ts +224 -83
  76. package/src/insecure/index.ts +24 -0
  77. package/src/keychain/index.ts +1 -1
  78. package/src/libp2p.ts +5 -6
  79. package/src/nat-manager.ts +6 -1
  80. package/src/pnet/README.md +31 -29
  81. package/src/pnet/index.ts +24 -0
  82. package/src/pnet/key-generator.ts +7 -12
  83. package/src/registrar.ts +29 -2
  84. package/src/transport-manager.ts +1 -2
  85. package/src/upgrader.ts +51 -64
  86. package/src/version.ts +1 -1
  87. package/dist/src/metrics/index.d.ts +0 -93
  88. package/dist/src/metrics/index.d.ts.map +0 -1
  89. package/dist/src/metrics/index.js +0 -234
  90. package/dist/src/metrics/index.js.map +0 -1
  91. package/dist/src/metrics/moving-average.d.ts +0 -14
  92. package/dist/src/metrics/moving-average.d.ts.map +0 -1
  93. package/dist/src/metrics/moving-average.js +0 -40
  94. package/dist/src/metrics/moving-average.js.map +0 -1
  95. package/dist/src/metrics/stats.d.ts +0 -87
  96. package/dist/src/metrics/stats.d.ts.map +0 -1
  97. package/dist/src/metrics/stats.js +0 -183
  98. package/dist/src/metrics/stats.js.map +0 -1
  99. package/src/metrics/index.ts +0 -311
  100. package/src/metrics/moving-average.ts +0 -53
  101. package/src/metrics/stats.ts +0 -238
@@ -14,6 +14,8 @@ import { pipe } from 'it-pipe'
14
14
  import first from 'it-first'
15
15
  import { TimeoutController } from 'timeout-abort-controller'
16
16
  import { setMaxListeners } from 'events'
17
+ import { fromString as uint8arrayFromString } from 'uint8arrays/from-string'
18
+ import { toString as uint8arrayToString } from 'uint8arrays/to-string'
17
19
  import type { ConnectionManager } from '@libp2p/interface-connection-manager'
18
20
 
19
21
  const log = logger('libp2p:fetch')
@@ -103,6 +105,7 @@ export class FetchService implements Startable {
103
105
 
104
106
  // create a timeout if no abort signal passed
105
107
  if (signal == null) {
108
+ log('using default timeout of %d ms', this.init.timeout)
106
109
  timeoutController = new TimeoutController(this.init.timeout)
107
110
  signal = timeoutController.signal
108
111
 
@@ -113,13 +116,15 @@ export class FetchService implements Startable {
113
116
  }
114
117
 
115
118
  try {
116
- stream = await connection.newStream([this.protocol], {
119
+ stream = await connection.newStream(this.protocol, {
117
120
  signal
118
121
  })
119
122
 
120
123
  // make stream abortable
121
124
  const source = abortableDuplex(stream, signal)
122
125
 
126
+ log('fetch %s', key)
127
+
123
128
  const result = await pipe(
124
129
  [FetchRequest.encode({ identifier: key })],
125
130
  lp.encode(),
@@ -136,16 +141,20 @@ export class FetchService implements Startable {
136
141
 
137
142
  switch (response.status) {
138
143
  case (FetchResponse.StatusCode.OK): {
144
+ log('received status for %s ok', key)
139
145
  return response.data
140
146
  }
141
147
  case (FetchResponse.StatusCode.NOT_FOUND): {
148
+ log('received status for %s not found', key)
142
149
  return null
143
150
  }
144
151
  case (FetchResponse.StatusCode.ERROR): {
145
- const errmsg = (new TextDecoder()).decode(response.data)
152
+ log('received status for %s error', key)
153
+ const errmsg = uint8arrayToString(response.data)
146
154
  throw errCode(new Error('Error in fetch protocol response: ' + errmsg), codes.ERR_INVALID_PARAMETERS)
147
155
  }
148
156
  default: {
157
+ log('received status for %s unknown', key)
149
158
  throw errCode(new Error('Unknown response status'), codes.ERR_INVALID_MESSAGE)
150
159
  }
151
160
  }
@@ -189,14 +198,18 @@ export class FetchService implements Startable {
189
198
  let response: FetchResponse
190
199
  const lookup = self._getLookupFunction(request.identifier)
191
200
  if (lookup != null) {
201
+ log('look up data with identifier %s', request.identifier)
192
202
  const data = await lookup(request.identifier)
193
203
  if (data != null) {
204
+ log('sending status for %s ok', request.identifier)
194
205
  response = { status: FetchResponse.StatusCode.OK, data }
195
206
  } else {
207
+ log('sending status for %s not found', request.identifier)
196
208
  response = { status: FetchResponse.StatusCode.NOT_FOUND, data: new Uint8Array(0) }
197
209
  }
198
210
  } else {
199
- const errmsg = (new TextEncoder()).encode('No lookup function registered for key: ' + request.identifier)
211
+ log('sending status for %s error', request.identifier)
212
+ const errmsg = uint8arrayFromString(`No lookup function registered for key: ${request.identifier}`)
200
213
  response = { status: FetchResponse.StatusCode.ERROR, data: errmsg }
201
214
  }
202
215
 
@@ -222,6 +235,13 @@ export class FetchService implements Startable {
222
235
  /**
223
236
  * Registers a new lookup callback that can map keys to values, for a given set of keys that
224
237
  * share the same prefix
238
+ *
239
+ * @example
240
+ *
241
+ * ```js
242
+ * // ...
243
+ * libp2p.fetchService.registerLookupFunction('/prefix', (key) => { ... })
244
+ * ```
225
245
  */
226
246
  registerLookupFunction (prefix: string, lookup: LookupFunction) {
227
247
  if (this.lookupFunctions.has(prefix)) {
@@ -234,6 +254,13 @@ export class FetchService implements Startable {
234
254
  /**
235
255
  * Registers a new lookup callback that can map keys to values, for a given set of keys that
236
256
  * share the same prefix.
257
+ *
258
+ * @example
259
+ *
260
+ * ```js
261
+ * // ...
262
+ * libp2p.fetchService.unregisterLookupFunction('/prefix')
263
+ * ```
237
264
  */
238
265
  unregisterLookupFunction (prefix: string, lookup?: LookupFunction) {
239
266
  if (lookup != null) {
package/src/get-peer.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { peerIdFromString } from '@libp2p/peer-id'
2
2
  import type { Multiaddr } from '@multiformats/multiaddr'
3
- import { multiaddr, isMultiaddr } from '@multiformats/multiaddr'
3
+ import { isMultiaddr } from '@multiformats/multiaddr'
4
4
  import errCode from 'err-code'
5
5
  import { codes } from './errors.js'
6
6
  import { isPeerId } from '@libp2p/interface-peer-id'
@@ -28,9 +28,9 @@ function peerIdFromMultiaddr (ma: Multiaddr) {
28
28
  }
29
29
 
30
30
  /**
31
- * Converts the given `peer` to a `Peer` object.
31
+ * Converts the given `peer` to a `PeerInfo` object.
32
32
  */
33
- export function getPeer (peer: PeerId | Multiaddr | string): PeerInfo {
33
+ export function getPeer (peer: PeerId | Multiaddr): PeerInfo {
34
34
  if (isPeerId(peer)) {
35
35
  return {
36
36
  id: peer,
@@ -39,10 +39,6 @@ export function getPeer (peer: PeerId | Multiaddr | string): PeerInfo {
39
39
  }
40
40
  }
41
41
 
42
- if (typeof peer === 'string') {
43
- peer = multiaddr(peer)
44
- }
45
-
46
42
  let addr
47
43
 
48
44
  if (isMultiaddr(peer)) {
package/src/index.ts CHANGED
@@ -1,32 +1,43 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * Use the `createLibp2p` function to create a libp2p node.
5
+ *
6
+ * @example
7
+ *
8
+ * ```typescript
9
+ * import { createLibp2p } from 'libp2p'
10
+ *
11
+ * const node = await createLibp2p({
12
+ * // ...other options
13
+ * })
14
+ * ```
15
+ */
16
+
1
17
  import { createLibp2pNode } from './libp2p.js'
2
- import type { AbortOptions, RecursivePartial } from '@libp2p/interfaces'
3
- import type { EventEmitter } from '@libp2p/interfaces/events'
4
- import type { Startable } from '@libp2p/interfaces/startable'
5
- import type { Multiaddr } from '@multiformats/multiaddr'
18
+ import type { RecursivePartial } from '@libp2p/interfaces'
19
+ import type { Multiaddr, Resolver } from '@multiformats/multiaddr'
6
20
  import type { FaultTolerance } from './transport-manager.js'
7
21
  import type { IdentifyServiceInit } from './identify/index.js'
8
22
  import type { DualDHT } from '@libp2p/interface-dht'
9
23
  import type { Datastore } from 'interface-datastore'
10
- import type { PeerStore, PeerStoreInit } from '@libp2p/interface-peer-store'
24
+ import type { AddressSorter, PeerStoreInit } from '@libp2p/interface-peer-store'
11
25
  import type { PeerId } from '@libp2p/interface-peer-id'
12
26
  import type { AutoRelayConfig, RelayAdvertiseConfig } from './circuit/index.js'
13
27
  import type { PeerDiscovery } from '@libp2p/interface-peer-discovery'
14
- import type { Connection, ConnectionGater, ConnectionProtector, Stream } from '@libp2p/interface-connection'
28
+ import type { ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'
15
29
  import type { Transport } from '@libp2p/interface-transport'
16
30
  import type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'
17
31
  import type { ConnectionEncrypter } from '@libp2p/interface-connection-encrypter'
18
32
  import type { PeerRouting } from '@libp2p/interface-peer-routing'
19
33
  import type { ContentRouting } from '@libp2p/interface-content-routing'
20
34
  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'
35
+ import type { Metrics } from '@libp2p/interface-metrics'
24
36
  import type { PeerInfo } from '@libp2p/interface-peer-info'
25
- import type { KeyChain } from './keychain/index.js'
26
- import type { ConnectionManagerInit } from './connection-manager/index.js'
27
37
  import type { PingServiceInit } from './ping/index.js'
28
38
  import type { FetchServiceInit } from './fetch/index.js'
29
39
  import type { Components } from './components.js'
40
+ import type { Libp2p } from '@libp2p/interface-libp2p'
30
41
 
31
42
  export interface PersistentPeerStoreOptions {
32
43
  threshold?: number
@@ -97,123 +108,253 @@ export interface RefreshManagerConfig {
97
108
  bootDelay: number
98
109
  }
99
110
 
111
+ export interface ConnectionManagerConfig {
112
+ /**
113
+ * The maximum number of connections libp2p is willing to have before it starts disconnecting. Defaults to `Infinity`
114
+ */
115
+ maxConnections: number
116
+
117
+ /**
118
+ * The minimum number of connections below which libp2p not activate preemptive disconnections. Defaults to `0`.
119
+ */
120
+ minConnections: number
121
+
122
+ /**
123
+ * Sets the maximum event loop delay (measured in milliseconds) this node is willing to endure before it starts disconnecting peers. Defaults to `Infinity`.
124
+ */
125
+ maxEventLoopDelay?: number
126
+
127
+ /**
128
+ * Sets the poll interval (in milliseconds) for assessing the current state and determining if this peer needs to force a disconnect. Defaults to `2000` (2 seconds).
129
+ */
130
+ pollInterval?: number
131
+
132
+ /**
133
+ * If true, try to connect to all discovered peers up to the connection manager limit
134
+ */
135
+ autoDial?: boolean
136
+
137
+ /**
138
+ * How long to wait between attempting to keep our number of concurrent connections
139
+ * above minConnections
140
+ */
141
+ autoDialInterval: number
142
+
143
+ /**
144
+ * Sort the known addresses of a peer before trying to dial
145
+ */
146
+ addressSorter?: AddressSorter
147
+
148
+ /**
149
+ * Number of max concurrent dials
150
+ */
151
+ maxParallelDials?: number
152
+
153
+ /**
154
+ * Number of max addresses to dial for a given peer
155
+ */
156
+ maxAddrsToDial?: number
157
+
158
+ /**
159
+ * How long a dial attempt is allowed to take, including DNS resolution
160
+ * of the multiaddr, opening a socket and upgrading it to a Connection.
161
+ */
162
+ dialTimeout?: number
163
+
164
+ /**
165
+ * When a new inbound connection is opened, the upgrade process (e.g. protect,
166
+ * encrypt, multiplex etc) must complete within this number of ms.
167
+ */
168
+ inboundUpgradeTimeout: number
169
+
170
+ /**
171
+ * Number of max concurrent dials per peer
172
+ */
173
+ maxDialsPerPeer?: number
174
+
175
+ /**
176
+ * Multiaddr resolvers to use when dialing
177
+ */
178
+ resolvers?: Record<string, Resolver>
179
+
180
+ /**
181
+ * On startup we try to dial any peer that has previously been
182
+ * tagged with KEEP_ALIVE up to this timeout in ms. (default: 60000)
183
+ */
184
+ startupReconnectTimeout?: number
185
+
186
+ /**
187
+ * A list of multiaddrs that will always be allowed (except if they are in the
188
+ * deny list) to open connections to this node even if we've reached maxConnections
189
+ */
190
+ allow?: string[]
191
+
192
+ /**
193
+ * A list of multiaddrs that will never be allowed to open connections to
194
+ * this node under any circumstances
195
+ */
196
+ deny?: string[]
197
+
198
+ /**
199
+ * If more than this many connections are opened per second by a single
200
+ * host, reject subsequent connections
201
+ */
202
+ inboundConnectionThreshold?: number
203
+
204
+ /**
205
+ * The maximum number of parallel incoming connections allowed that have yet to
206
+ * complete the connection upgrade - e.g. choosing connection encryption, muxer, etc
207
+ */
208
+ maxIncomingPendingConnections?: number
209
+ }
210
+
211
+ /**
212
+ * For Libp2p configurations and modules details read the [Configuration Document](./CONFIGURATION.md).
213
+ */
100
214
  export interface Libp2pInit {
215
+ /**
216
+ * peerId instance (it will be created if not provided)
217
+ */
101
218
  peerId: PeerId
219
+
220
+ /**
221
+ * Addresses for transport listening and to advertise to the network
222
+ */
102
223
  addresses: AddressesConfig
103
- connectionManager: ConnectionManagerInit
224
+
225
+ /**
226
+ * libp2p Connection Manager configuration
227
+ */
228
+ connectionManager: ConnectionManagerConfig
104
229
  connectionGater: Partial<ConnectionGater>
230
+
231
+ /**
232
+ * libp2p transport manager configuration
233
+ */
105
234
  transportManager: TransportManagerConfig
106
- datastore: Datastore
107
- metrics: MetricsInit
108
- peerStore: PeerStoreInit
109
- peerRouting: PeerRoutingConfig
110
- keychain: KeychainConfig
111
- nat: NatManagerConfig
112
- relay: RelayConfig
113
- identify: IdentifyServiceInit
114
- ping: PingServiceInit
115
- fetch: FetchServiceInit
116
235
 
117
- transports: Array<(components: Components) => Transport>
118
- streamMuxers?: Array<(components: Components) => StreamMuxerFactory>
119
- connectionEncryption?: Array<(components: Components) => ConnectionEncrypter>
120
- peerDiscovery?: Array<(components: Components) => PeerDiscovery>
121
- peerRouters?: Array<(components: Components) => PeerRouting>
122
- contentRouters?: Array<(components: Components) => ContentRouting>
123
- dht?: (components: Components) => DualDHT
124
- pubsub?: (components: Components) => PubSub
125
- connectionProtector?: (components: Components) => ConnectionProtector
126
- }
236
+ /**
237
+ * An optional datastore to persist peer information, DHT records, etc.
238
+ *
239
+ * An in-memory datastore will be used if one is not provided.
240
+ */
241
+ datastore: Datastore
127
242
 
128
- export interface Libp2pEvents {
129
- 'peer:discovery': CustomEvent<PeerInfo>
130
- }
243
+ /**
244
+ * libp2p PeerStore configuration
245
+ */
246
+ peerStore: PeerStoreInit
131
247
 
132
- export interface Libp2p extends Startable, EventEmitter<Libp2pEvents> {
133
- peerId: PeerId
134
- peerStore: PeerStore
135
- peerRouting: PeerRouting
136
- contentRouting: ContentRouting
137
- keychain: KeyChain
138
- connectionManager: ConnectionManager
139
- registrar: Registrar
140
- metrics?: Metrics
141
- pubsub: PubSub
142
- dht: DualDHT
143
-
144
- /**
145
- * Get a deduplicated list of peer advertising multiaddrs by concatenating
146
- * the listen addresses used by transports with any configured
147
- * announce addresses as well as observed addresses reported by peers.
148
- *
149
- * If Announce addrs are specified, configured listen addresses will be
150
- * ignored though observed addresses will still be included.
248
+ /**
249
+ * libp2p Peer routing service configuration
151
250
  */
152
- getMultiaddrs: () => Multiaddr[]
251
+ peerRouting: PeerRoutingConfig
153
252
 
154
253
  /**
155
- * Return a list of all connections this node has open, optionally filtering
156
- * by a PeerId
254
+ * keychain configuration
157
255
  */
158
- getConnections: (peerId?: PeerId) => Connection[]
256
+ keychain: KeychainConfig
257
+ nat: NatManagerConfig
258
+ relay: RelayConfig
159
259
 
160
260
  /**
161
- * Return a list of all peers we currently have a connection open to
261
+ * libp2p identify protocol options
162
262
  */
163
- getPeers: () => PeerId[]
263
+ identify: IdentifyServiceInit
164
264
 
165
265
  /**
166
- * Dials to the provided peer. If successful, the known metadata of the
167
- * peer will be added to the nodes `peerStore`
266
+ * libp2p ping protocol options
168
267
  */
169
- dial: (peer: PeerId | Multiaddr, options?: AbortOptions) => Promise<Connection>
268
+ ping: PingServiceInit
170
269
 
171
270
  /**
172
- * Dials to the provided peer and tries to handshake with the given protocols in order.
173
- * If successful, the known metadata of the peer will be added to the nodes `peerStore`,
174
- * and the `MuxedStream` will be returned together with the successful negotiated protocol.
271
+ * libp2p fetch protocol options
175
272
  */
176
- dialProtocol: (peer: PeerId | Multiaddr, protocols: string | string[], options?: AbortOptions) => Promise<Stream>
273
+ fetch: FetchServiceInit
177
274
 
178
275
  /**
179
- * Disconnects all connections to the given `peer`
276
+ * An array that must include at least 1 compliant transport
180
277
  */
181
- hangUp: (peer: PeerId | Multiaddr | string) => Promise<void>
278
+ transports: Array<(components: Components) => Transport>
279
+ streamMuxers?: Array<(components: Components) => StreamMuxerFactory>
280
+ connectionEncryption?: Array<(components: Components) => ConnectionEncrypter>
281
+ peerDiscovery?: Array<(components: Components) => PeerDiscovery>
282
+ peerRouters?: Array<(components: Components) => PeerRouting>
283
+ contentRouters?: Array<(components: Components) => ContentRouting>
182
284
 
183
285
  /**
184
- * Registers the `handler` for each protocol
286
+ * Pass a DHT implementation to enable DHT operations
185
287
  */
186
- handle: (protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions) => Promise<void>
288
+ dht?: (components: Components) => DualDHT
187
289
 
188
290
  /**
189
- * Removes the handler for each protocol. The protocol
190
- * will no longer be supported on streams.
291
+ * A Metrics implementation can be supplied to collect metrics on this node
191
292
  */
192
- unhandle: (protocols: string[] | string) => Promise<void>
293
+ metrics?: (components: Components) => Metrics
193
294
 
194
295
  /**
195
- * Pings the given peer in order to obtain the operation latency
296
+ * If a PubSub implmentation is supplied, PubSub operations will become available
196
297
  */
197
- ping: (peer: Multiaddr | PeerId, options?: AbortOptions) => Promise<number>
298
+ pubsub?: (components: Components) => PubSub
198
299
 
199
300
  /**
200
- * Sends a request to fetch the value associated with the given key from the given peer.
301
+ * A ConnectionProtector can be used to create a secure overlay on top of the network using pre-shared keys
201
302
  */
202
- fetch: (peer: PeerId | Multiaddr | string, key: string, options?: AbortOptions) => Promise<Uint8Array | null>
303
+ connectionProtector?: (components: Components) => ConnectionProtector
304
+ }
203
305
 
306
+ /**
307
+ * Once you have a libp2p instance, you can listen to several events it emits, so that you can be notified of relevant network events.
308
+ */
309
+ export interface Libp2pEvents {
204
310
  /**
205
- * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA' type
206
- * this may mean searching the DHT if the key is not present in the KeyStore.
311
+ * @example
312
+ *
313
+ * ```js
314
+ * libp2p.addEventListener('peer:discovery', (event) => {
315
+ * const peerInfo = event.detail
316
+ * // ...
317
+ * })
318
+ * ```
207
319
  */
208
- getPublicKey: (peer: PeerId, options?: AbortOptions) => Promise<Uint8Array>
320
+ 'peer:discovery': CustomEvent<PeerInfo>
209
321
  }
210
322
 
211
- export type Libp2pOptions = RecursivePartial<Libp2pInit>
323
+ export type { Libp2p }
324
+
325
+ export type Libp2pOptions = RecursivePartial<Libp2pInit> & { start?: boolean }
212
326
 
213
327
  /**
214
328
  * Returns a new instance of the Libp2p interface, generating a new PeerId
215
329
  * if one is not passed as part of the options.
330
+ *
331
+ * The node will be started unless `start: false` is passed as an option.
332
+ *
333
+ * @example
334
+ *
335
+ * ```js
336
+ * import { createLibp2p } from 'libp2p'
337
+ * import { tcp } from '@libp2p/tcp'
338
+ * import { mplex } from '@libp2p/mplex'
339
+ * import { noise } from '@chainsafe/libp2p-noise'
340
+ *
341
+ * // specify options
342
+ * const options = {
343
+ * transports: [tcp()],
344
+ * streamMuxers: [mplex()],
345
+ * connectionEncryption: [noise()]
346
+ * }
347
+ *
348
+ * // create libp2p
349
+ * const libp2p = await createLibp2p(options)
350
+ * ```
216
351
  */
217
352
  export async function createLibp2p (options: Libp2pOptions): Promise<Libp2p> {
218
- return await createLibp2pNode(options)
353
+ const node = await createLibp2pNode(options)
354
+
355
+ if (options.start !== false) {
356
+ await node.start()
357
+ }
358
+
359
+ return node
219
360
  }
@@ -1,3 +1,27 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * A connection encrypter that does no connection encryption.
5
+ *
6
+ * This should not be used in production should be used for research purposes only.
7
+ *
8
+ * @example
9
+ *
10
+ * ```typescript
11
+ * import { createLibp2p } from 'libp2p'
12
+ * import { plaintext } from 'libp2p/insecure'
13
+ *
14
+ * // Create a Uint8Array and write the swarm key to it
15
+ * const swarmKey = new Uint8Array(95)
16
+ * generateKey(swarmKey)
17
+ *
18
+ * const node = await createLibp2p({
19
+ * // ...other options
20
+ * connectionEncryption: [plaintext()]
21
+ * })
22
+ * ```
23
+ */
24
+
1
25
  import { logger } from '@libp2p/logger'
2
26
  import { handshake } from 'it-handshake'
3
27
  import * as lp from 'it-length-prefixed'
@@ -118,7 +118,7 @@ export interface KeyChainComponents {
118
118
  */
119
119
  export class KeyChain implements Startable {
120
120
  private readonly components: KeyChainComponents
121
- private init: KeyChainInit
121
+ private readonly init: KeyChainInit
122
122
  private started: boolean
123
123
 
124
124
  /**
package/src/libp2p.ts CHANGED
@@ -14,7 +14,6 @@ import { AutoDialler } from './connection-manager/auto-dialler.js'
14
14
  import { Circuit } from './circuit/transport.js'
15
15
  import { Relay } from './circuit/index.js'
16
16
  import { KeyChain } from './keychain/index.js'
17
- import { DefaultMetrics } from './metrics/index.js'
18
17
  import { DefaultTransportManager } from './transport-manager.js'
19
18
  import { DefaultUpgrader } from './upgrader.js'
20
19
  import { DefaultRegistrar } from './registrar.js'
@@ -103,8 +102,8 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
103
102
  ]
104
103
 
105
104
  // Create Metrics
106
- if (init.metrics.enabled) {
107
- this.metrics = this.components.metrics = new DefaultMetrics(init.metrics)
105
+ if (init.metrics != null) {
106
+ this.metrics = this.components.metrics = this.configureComponent(init.metrics(this.components))
108
107
  }
109
108
 
110
109
  this.peerStore = this.components.peerStore
@@ -374,7 +373,7 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
374
373
  return this.components.addressManager.getAddresses()
375
374
  }
376
375
 
377
- async hangUp (peer: PeerId | Multiaddr | string): Promise<void> {
376
+ async hangUp (peer: PeerId | Multiaddr): Promise<void> {
378
377
  const { id } = getPeer(peer)
379
378
 
380
379
  await this.components.connectionManager.closeConnections(id)
@@ -419,7 +418,7 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
419
418
  throw errCode(new Error(`Node not responding with its public key: ${peer.toString()}`), codes.ERR_INVALID_RECORD)
420
419
  }
421
420
 
422
- async fetch (peer: PeerId | Multiaddr | string, key: string, options: AbortOptions = {}): Promise<Uint8Array | null> {
421
+ async fetch (peer: PeerId | Multiaddr, key: string, options: AbortOptions = {}): Promise<Uint8Array | null> {
423
422
  const { id, multiaddrs } = getPeer(peer)
424
423
 
425
424
  if (multiaddrs != null) {
@@ -429,7 +428,7 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
429
428
  return await this.fetchService.fetch(id, key, options)
430
429
  }
431
430
 
432
- async ping (peer: PeerId | Multiaddr | string, options: AbortOptions = {}): Promise<number> {
431
+ async ping (peer: PeerId | Multiaddr, options: AbortOptions = {}): Promise<number> {
433
432
  const { id, multiaddrs } = getPeer(peer)
434
433
 
435
434
  if (multiaddrs.length > 0) {
@@ -149,11 +149,16 @@ export class NatManager implements Startable {
149
149
 
150
150
  const client = await this._getClient()
151
151
  const publicIp = this.externalAddress ?? await client.externalIp()
152
+ const isPrivate = isPrivateIp(publicIp)
152
153
 
153
- if (isPrivateIp(publicIp)) {
154
+ if (isPrivate === true) {
154
155
  throw new Error(`${publicIp} is private - please set config.nat.externalIp to an externally routable IP or ensure you are not behind a double NAT`)
155
156
  }
156
157
 
158
+ if (isPrivate == null) {
159
+ throw new Error(`${publicIp} is not an IP address`)
160
+ }
161
+
157
162
  const publicPort = highPort()
158
163
 
159
164
  log(`opening uPnP connection from ${publicIp}:${publicPort} to ${host}:${port}`)