libp2p 0.41.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +5 -4
  2. package/dist/index.min.js +58 -0
  3. package/dist/src/address-manager/index.d.ts +8 -0
  4. package/dist/src/address-manager/index.d.ts.map +1 -1
  5. package/dist/src/address-manager/index.js.map +1 -1
  6. package/dist/src/circuit/index.d.ts +11 -1
  7. package/dist/src/circuit/index.d.ts.map +1 -1
  8. package/dist/src/circuit/index.js.map +1 -1
  9. package/dist/src/circuit/transport.d.ts +1 -1
  10. package/dist/src/circuit/transport.d.ts.map +1 -1
  11. package/dist/src/config.js +1 -1
  12. package/dist/src/config.js.map +1 -1
  13. package/dist/src/connection-manager/index.d.ts +9 -28
  14. package/dist/src/connection-manager/index.d.ts.map +1 -1
  15. package/dist/src/connection-manager/index.js +23 -12
  16. package/dist/src/connection-manager/index.js.map +1 -1
  17. package/dist/src/fetch/index.d.ts +14 -0
  18. package/dist/src/fetch/index.d.ts.map +1 -1
  19. package/dist/src/fetch/index.js +14 -0
  20. package/dist/src/fetch/index.js.map +1 -1
  21. package/dist/src/identify/index.d.ts +4 -1
  22. package/dist/src/identify/index.d.ts.map +1 -1
  23. package/dist/src/index.d.ts +123 -137
  24. package/dist/src/index.d.ts.map +1 -1
  25. package/dist/src/index.js +34 -0
  26. package/dist/src/index.js.map +1 -1
  27. package/dist/src/insecure/index.d.ts +23 -0
  28. package/dist/src/insecure/index.d.ts.map +1 -1
  29. package/dist/src/insecure/index.js +23 -0
  30. package/dist/src/insecure/index.js.map +1 -1
  31. package/dist/src/keychain/index.d.ts +2 -2
  32. package/dist/src/keychain/index.d.ts.map +1 -1
  33. package/dist/src/libp2p.d.ts +5 -2
  34. package/dist/src/libp2p.d.ts.map +1 -1
  35. package/dist/src/libp2p.js +16 -0
  36. package/dist/src/libp2p.js.map +1 -1
  37. package/dist/src/nat-manager.d.ts.map +1 -1
  38. package/dist/src/nat-manager.js +5 -1
  39. package/dist/src/nat-manager.js.map +1 -1
  40. package/dist/src/peer-routing.d.ts +1 -1
  41. package/dist/src/peer-routing.d.ts.map +1 -1
  42. package/dist/src/peer-routing.js +1 -1
  43. package/dist/src/peer-routing.js.map +1 -1
  44. package/dist/src/pnet/index.d.ts +23 -0
  45. package/dist/src/pnet/index.d.ts.map +1 -1
  46. package/dist/src/pnet/index.js +23 -0
  47. package/dist/src/pnet/index.js.map +1 -1
  48. package/dist/src/pnet/key-generator.d.ts +3 -2
  49. package/dist/src/pnet/key-generator.d.ts.map +1 -1
  50. package/dist/src/pnet/key-generator.js +7 -10
  51. package/dist/src/pnet/key-generator.js.map +1 -1
  52. package/dist/src/transport-manager.d.ts +1 -13
  53. package/dist/src/transport-manager.d.ts.map +1 -1
  54. package/dist/src/transport-manager.js +1 -14
  55. package/dist/src/transport-manager.js.map +1 -1
  56. package/package.json +30 -32
  57. package/src/address-manager/index.ts +8 -0
  58. package/src/circuit/index.ts +13 -1
  59. package/src/circuit/transport.ts +1 -1
  60. package/src/config.ts +1 -1
  61. package/src/connection-manager/index.ts +49 -56
  62. package/src/fetch/README.md +7 -2
  63. package/src/fetch/index.ts +14 -0
  64. package/src/identify/index.ts +1 -1
  65. package/src/index.ts +130 -149
  66. package/src/insecure/index.ts +24 -0
  67. package/src/keychain/index.ts +2 -2
  68. package/src/libp2p.ts +22 -2
  69. package/src/nat-manager.ts +6 -1
  70. package/src/peer-routing.ts +2 -2
  71. package/src/pnet/README.md +31 -29
  72. package/src/pnet/index.ts +24 -0
  73. package/src/pnet/key-generator.ts +7 -12
  74. package/src/transport-manager.ts +1 -15
  75. package/src/version.ts +1 -1
@@ -9,7 +9,7 @@ import { codes } from '../errors.js'
9
9
  import { isPeerId, PeerId } from '@libp2p/interface-peer-id'
10
10
  import { setMaxListeners } from 'events'
11
11
  import type { Connection, MultiaddrConnection } from '@libp2p/interface-connection'
12
- import type { ConnectionManager, Dialer } from '@libp2p/interface-connection-manager'
12
+ import type { ConnectionManager, ConnectionManagerEvents, Dialer } from '@libp2p/interface-connection-manager'
13
13
  import * as STATUS from '@libp2p/interface-connection/status'
14
14
  import type { AddressSorter, PeerStore } from '@libp2p/interface-peer-store'
15
15
  import { isMultiaddr, multiaddr, Multiaddr, Resolver } from '@multiformats/multiaddr'
@@ -23,63 +23,27 @@ import { getPeer } from '../get-peer.js'
23
23
 
24
24
  const log = logger('libp2p:connection-manager')
25
25
 
26
- const defaultOptions: Partial<ConnectionManagerInit> = {
27
- maxConnections: Infinity,
28
- minConnections: 0,
29
- maxData: Infinity,
30
- maxSentData: Infinity,
31
- maxReceivedData: Infinity,
32
- maxEventLoopDelay: Infinity,
33
- pollInterval: 2000,
34
- autoDialInterval: 10000,
35
- movingAverageInterval: 60000,
36
- inboundConnectionThreshold: 5,
37
- maxIncomingPendingConnections: 10
38
- }
39
-
40
- const STARTUP_RECONNECT_TIMEOUT = 60000
41
-
42
- export interface ConnectionManagerInit {
26
+ export interface ConnectionManagerConfig {
43
27
  /**
44
- * The maximum number of connections to keep open
28
+ * The maximum number of connections libp2p is willing to have before it starts disconnecting. Defaults to `Infinity`
45
29
  */
46
30
  maxConnections: number
47
31
 
48
32
  /**
49
- * The minimum number of connections to keep open
33
+ * The minimum number of connections below which libp2p not activate preemptive disconnections. Defaults to `0`.
50
34
  */
51
35
  minConnections: number
52
36
 
53
37
  /**
54
- * The max data (in and out), per average interval to allow
55
- */
56
- maxData?: number
57
-
58
- /**
59
- * The max outgoing data, per average interval to allow
60
- */
61
- maxSentData?: number
62
-
63
- /**
64
- * The max incoming data, per average interval to allow
65
- */
66
- maxReceivedData?: number
67
-
68
- /**
69
- * The upper limit the event loop can take to run
38
+ * Sets the maximum event loop delay (measured in milliseconds) this node is willing to endure before it starts disconnecting peers. Defaults to `Infinity`.
70
39
  */
71
40
  maxEventLoopDelay?: number
72
41
 
73
42
  /**
74
- * How often, in milliseconds, metrics and latency should be checked
43
+ * 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).
75
44
  */
76
45
  pollInterval?: number
77
46
 
78
- /**
79
- * How often, in milliseconds, to compute averages
80
- */
81
- movingAverageInterval?: number
82
-
83
47
  /**
84
48
  * If true, try to connect to all discovered peers up to the connection manager limit
85
49
  */
@@ -159,11 +123,18 @@ export interface ConnectionManagerInit {
159
123
  maxIncomingPendingConnections?: number
160
124
  }
161
125
 
162
- export interface ConnectionManagerEvents {
163
- 'peer:connect': CustomEvent<PeerId>
164
- 'peer:disconnect': CustomEvent<PeerId>
126
+ const defaultOptions: Partial<ConnectionManagerConfig> = {
127
+ maxConnections: Infinity,
128
+ minConnections: 0,
129
+ maxEventLoopDelay: Infinity,
130
+ pollInterval: 2000,
131
+ autoDialInterval: 10000,
132
+ inboundConnectionThreshold: 5,
133
+ maxIncomingPendingConnections: 10
165
134
  }
166
135
 
136
+ const STARTUP_RECONNECT_TIMEOUT = 60000
137
+
167
138
  export interface DefaultConnectionManagerComponents {
168
139
  peerId: PeerId
169
140
  metrics?: Metrics
@@ -172,15 +143,17 @@ export interface DefaultConnectionManagerComponents {
172
143
  dialer: Dialer
173
144
  }
174
145
 
146
+ export type ConnectionManagerInit = ConnectionManagerConfig
147
+
175
148
  /**
176
149
  * Responsible for managing known connections.
177
150
  */
178
151
  export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEvents> implements ConnectionManager, Startable {
179
152
  private readonly components: DefaultConnectionManagerComponents
180
- private readonly opts: Required<ConnectionManagerInit>
153
+ private readonly opts: ConnectionManagerInit
181
154
  private readonly connections: Map<string, Connection[]>
182
155
  private started: boolean
183
- private readonly latencyMonitor: LatencyMonitor
156
+ private readonly latencyMonitor?: LatencyMonitor
184
157
  private readonly startupReconnectTimeout: number
185
158
  private connectOnStartupController?: TimeoutController
186
159
  private readonly dialTimeout: number
@@ -189,7 +162,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
189
162
  private readonly inboundConnectionRateLimiter: RateLimiterMemory
190
163
  private incomingPendingConnections: number
191
164
 
192
- constructor (components: DefaultConnectionManagerComponents, init: ConnectionManagerInit) {
165
+ constructor (components: DefaultConnectionManagerComponents, init: ConnectionManagerConfig) {
193
166
  super()
194
167
 
195
168
  this.opts = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)
@@ -209,10 +182,12 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
209
182
 
210
183
  this.started = false
211
184
 
212
- this.latencyMonitor = new LatencyMonitor({
213
- latencyCheckIntervalMs: init.pollInterval,
214
- dataEmitIntervalMs: init.pollInterval
215
- })
185
+ if (init.maxEventLoopDelay != null && init.maxEventLoopDelay > 0 && init.maxEventLoopDelay !== Infinity) {
186
+ this.latencyMonitor = new LatencyMonitor({
187
+ latencyCheckIntervalMs: init.pollInterval,
188
+ dataEmitIntervalMs: init.pollInterval
189
+ })
190
+ }
216
191
 
217
192
  try {
218
193
  // This emitter gets listened to a lot
@@ -324,9 +299,9 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
324
299
  })
325
300
 
326
301
  // latency monitor
327
- this.latencyMonitor.start()
302
+ this.latencyMonitor?.start()
328
303
  this._onLatencyMeasure = this._onLatencyMeasure.bind(this)
329
- this.latencyMonitor.addEventListener('data', this._onLatencyMeasure)
304
+ this.latencyMonitor?.addEventListener('data', this._onLatencyMeasure)
330
305
 
331
306
  this.started = true
332
307
  log('started')
@@ -388,8 +363,8 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
388
363
  * Stops the Connection Manager
389
364
  */
390
365
  async stop () {
391
- this.latencyMonitor.removeEventListener('data', this._onLatencyMeasure)
392
- this.latencyMonitor.stop()
366
+ this.latencyMonitor?.removeEventListener('data', this._onLatencyMeasure)
367
+ this.latencyMonitor?.stop()
393
368
 
394
369
  this.started = false
395
370
  await this._close()
@@ -606,6 +581,12 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
606
581
  */
607
582
  async _checkMaxLimit (name: keyof ConnectionManagerInit, value: number, toPrune: number = 1) {
608
583
  const limit = this.opts[name]
584
+
585
+ if (limit == null) {
586
+ log.trace('limit %s was not set so it cannot be applied', name)
587
+ return
588
+ }
589
+
609
590
  log.trace('checking limit of %s. current value: %d of %d', name, value, limit)
610
591
  if (value > limit) {
611
592
  log('%s: limit exceeded: %p, %d/%d, pruning %d connection(s)', this.components.peerId, name, value, limit, toPrune)
@@ -650,6 +631,18 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
650
631
  return -1
651
632
  }
652
633
 
634
+ // if the peers have an equal tag value then we want to close short-lived connections first
635
+ const connectionALifespan = a.stat.timeline.open
636
+ const connectionBLifespan = b.stat.timeline.open
637
+
638
+ if (connectionALifespan < connectionBLifespan) {
639
+ return 1
640
+ }
641
+
642
+ if (connectionALifespan > connectionBLifespan) {
643
+ return -1
644
+ }
645
+
653
646
  return 0
654
647
  })
655
648
 
@@ -1,8 +1,13 @@
1
- libp2p-fetch JavaScript Implementation
1
+ libp2p-fetch JavaScript Implementation <!-- omit in toc -->
2
2
  =====================================
3
3
 
4
4
  > Libp2p fetch protocol JavaScript implementation
5
5
 
6
+ ## Table of contents <!-- omit in toc -->
7
+
8
+ - [Overview](#overview)
9
+ - [Usage](#usage)
10
+
6
11
  ## Overview
7
12
 
8
13
  An implementation of the Fetch protocol as described here: https://github.com/libp2p/specs/tree/master/fetch
@@ -27,7 +32,7 @@ async function my_subsystem_key_lookup(key) {
27
32
  }
28
33
 
29
34
  // Enable this peer to respond to fetch requests for keys that begin with '/my_subsystem_key_prefix/'
30
- const libp2p = Libp2p.create(...)
35
+ const libp2p = createLibp2p()
31
36
  libp2p.fetchService.registerLookupFunction('/my_subsystem_key_prefix/', my_subsystem_key_lookup)
32
37
 
33
38
  const key = '/my_subsystem_key_prefix/{...}'
@@ -235,6 +235,13 @@ export class FetchService implements Startable {
235
235
  /**
236
236
  * Registers a new lookup callback that can map keys to values, for a given set of keys that
237
237
  * share the same prefix
238
+ *
239
+ * @example
240
+ *
241
+ * ```js
242
+ * // ...
243
+ * libp2p.fetchService.registerLookupFunction('/prefix', (key) => { ... })
244
+ * ```
238
245
  */
239
246
  registerLookupFunction (prefix: string, lookup: LookupFunction) {
240
247
  if (this.lookupFunctions.has(prefix)) {
@@ -247,6 +254,13 @@ export class FetchService implements Startable {
247
254
  /**
248
255
  * Registers a new lookup callback that can map keys to values, for a given set of keys that
249
256
  * share the same prefix.
257
+ *
258
+ * @example
259
+ *
260
+ * ```js
261
+ * // ...
262
+ * libp2p.fetchService.unregisterLookupFunction('/prefix')
263
+ * ```
250
264
  */
251
265
  unregisterLookupFunction (prefix: string, lookup?: LookupFunction) {
252
266
  if (lookup != null) {
@@ -79,7 +79,7 @@ export class IdentifyService implements Startable {
79
79
  private readonly components: IdentifyServiceComponents
80
80
  private readonly identifyProtocolStr: string
81
81
  private readonly identifyPushProtocolStr: string
82
- private readonly host: {
82
+ public readonly host: {
83
83
  protocolVersion: string
84
84
  agentVersion: string
85
85
  }
package/src/index.ts CHANGED
@@ -1,213 +1,175 @@
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'
6
- import type { FaultTolerance } from './transport-manager.js'
18
+ import type { RecursivePartial } from '@libp2p/interfaces'
19
+ import type { TransportManagerInit } from './transport-manager.js'
7
20
  import type { IdentifyServiceInit } from './identify/index.js'
8
21
  import type { DualDHT } from '@libp2p/interface-dht'
9
22
  import type { Datastore } from 'interface-datastore'
10
- import type { PeerStore, PeerStoreInit } from '@libp2p/interface-peer-store'
23
+ import type { PeerStoreInit } from '@libp2p/interface-peer-store'
11
24
  import type { PeerId } from '@libp2p/interface-peer-id'
12
- import type { AutoRelayConfig, RelayAdvertiseConfig } from './circuit/index.js'
25
+ import type { RelayConfig } from './circuit/index.js'
13
26
  import type { PeerDiscovery } from '@libp2p/interface-peer-discovery'
14
- import type { Connection, ConnectionGater, ConnectionProtector, Stream } from '@libp2p/interface-connection'
27
+ import type { ConnectionGater, ConnectionProtector } from '@libp2p/interface-connection'
15
28
  import type { Transport } from '@libp2p/interface-transport'
16
29
  import type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'
17
30
  import type { ConnectionEncrypter } from '@libp2p/interface-connection-encrypter'
18
31
  import type { PeerRouting } from '@libp2p/interface-peer-routing'
19
32
  import type { ContentRouting } from '@libp2p/interface-content-routing'
20
33
  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
34
  import type { Metrics } from '@libp2p/interface-metrics'
24
35
  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
36
  import type { PingServiceInit } from './ping/index.js'
28
37
  import type { FetchServiceInit } from './fetch/index.js'
29
38
  import type { Components } from './components.js'
39
+ import type { Libp2p } from '@libp2p/interface-libp2p'
40
+ import type { KeyChainInit } from './keychain/index.js'
41
+ import type { NatManagerInit } from './nat-manager.js'
42
+ import type { AddressManagerInit } from './address-manager/index.js'
43
+ import type { PeerRoutingInit } from './peer-routing.js'
44
+ import type { ConnectionManagerInit } from './connection-manager/index.js'
30
45
 
31
- export interface PersistentPeerStoreOptions {
32
- threshold?: number
33
- }
34
-
35
- export interface DEKConfig {
36
- keyLength: number
37
- iterationCount: number
38
- salt: string
39
- hash: string
40
- }
41
-
42
- export interface KeychainConfig {
43
- pass?: string
44
- dek?: DEKConfig
45
- }
46
-
47
- export interface MetricsConfig {
48
- enabled?: boolean
49
- }
50
-
51
- export interface HopConfig {
52
- enabled?: boolean
53
- active?: boolean
54
- timeout: number
55
- }
56
-
57
- export interface RelayConfig {
58
- enabled: boolean
59
- advertise: RelayAdvertiseConfig
60
- hop: HopConfig
61
- autoRelay: AutoRelayConfig
62
- }
63
-
64
- export interface NatManagerConfig {
65
- enabled: boolean
66
- externalAddress?: string
67
- localAddress?: string
68
- description?: string
69
- ttl?: number
70
- keepAlive: boolean
71
- gateway?: string
72
- }
73
-
74
- export interface AddressesConfig {
75
- listen: string[]
76
- announce: string[]
77
- noAnnounce: string[]
78
- announceFilter: (multiaddrs: Multiaddr[]) => Multiaddr[]
79
- }
46
+ /**
47
+ * For Libp2p configurations and modules details read the [Configuration Document](./CONFIGURATION.md).
48
+ */
49
+ export interface Libp2pInit {
50
+ /**
51
+ * peerId instance (it will be created if not provided)
52
+ */
53
+ peerId: PeerId
80
54
 
81
- export interface TransportManagerConfig {
82
- faultTolerance?: FaultTolerance
83
- }
55
+ /**
56
+ * Addresses for transport listening and to advertise to the network
57
+ */
58
+ addresses: AddressManagerInit
84
59
 
85
- export interface PeerStoreConfig {
86
- persistence?: boolean
87
- threshold?: number
88
- }
60
+ /**
61
+ * libp2p Connection Manager configuration
62
+ */
63
+ connectionManager: ConnectionManagerInit
89
64
 
90
- export interface PeerRoutingConfig {
91
- refreshManager: RefreshManagerConfig
92
- }
65
+ /**
66
+ * A connection gater can deny new connections based on user criteria
67
+ */
68
+ connectionGater: Partial<ConnectionGater>
93
69
 
94
- export interface RefreshManagerConfig {
95
- enabled?: boolean
96
- interval: number
97
- bootDelay: number
98
- }
70
+ /**
71
+ * libp2p transport manager configuration
72
+ */
73
+ transportManager: TransportManagerInit
99
74
 
100
- export interface Libp2pInit {
101
- peerId: PeerId
102
- addresses: AddressesConfig
103
- connectionManager: ConnectionManagerInit
104
- connectionGater: Partial<ConnectionGater>
105
- transportManager: TransportManagerConfig
75
+ /**
76
+ * An optional datastore to persist peer information, DHT records, etc.
77
+ *
78
+ * An in-memory datastore will be used if one is not provided.
79
+ */
106
80
  datastore: Datastore
81
+
82
+ /**
83
+ * libp2p PeerStore configuration
84
+ */
107
85
  peerStore: PeerStoreInit
108
- peerRouting: PeerRoutingConfig
109
- keychain: KeychainConfig
110
- nat: NatManagerConfig
111
- relay: RelayConfig
112
- identify: IdentifyServiceInit
113
- ping: PingServiceInit
114
- fetch: FetchServiceInit
115
86
 
116
- transports: Array<(components: Components) => Transport>
117
- streamMuxers?: Array<(components: Components) => StreamMuxerFactory>
118
- connectionEncryption?: Array<(components: Components) => ConnectionEncrypter>
119
- peerDiscovery?: Array<(components: Components) => PeerDiscovery>
120
- peerRouters?: Array<(components: Components) => PeerRouting>
121
- contentRouters?: Array<(components: Components) => ContentRouting>
122
- dht?: (components: Components) => DualDHT
123
- metrics?: (components: Components) => Metrics
124
- pubsub?: (components: Components) => PubSub
125
- connectionProtector?: (components: Components) => ConnectionProtector
126
- }
87
+ /**
88
+ * libp2p Peer routing service configuration
89
+ */
90
+ peerRouting: PeerRoutingInit
127
91
 
128
- export interface Libp2pEvents {
129
- 'peer:discovery': CustomEvent<PeerInfo>
130
- }
92
+ /**
93
+ * keychain configuration
94
+ */
95
+ keychain: KeyChainInit
131
96
 
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.
97
+ /**
98
+ * The NAT manager controls uPNP hole punching
151
99
  */
152
- getMultiaddrs: () => Multiaddr[]
100
+ nat: NatManagerInit
153
101
 
154
102
  /**
155
- * Return a list of all connections this node has open, optionally filtering
156
- * by a PeerId
103
+ * If configured as a relay this node will relay certain
104
+ * types of traffic for other peers
157
105
  */
158
- getConnections: (peerId?: PeerId) => Connection[]
106
+ relay: RelayConfig
159
107
 
160
108
  /**
161
- * Return a list of all peers we currently have a connection open to
109
+ * libp2p identify protocol options
162
110
  */
163
- getPeers: () => PeerId[]
111
+ identify: IdentifyServiceInit
164
112
 
165
113
  /**
166
- * Dials to the provided peer. If successful, the known metadata of the
167
- * peer will be added to the nodes `peerStore`
114
+ * libp2p ping protocol options
168
115
  */
169
- dial: (peer: PeerId | Multiaddr, options?: AbortOptions) => Promise<Connection>
116
+ ping: PingServiceInit
170
117
 
171
118
  /**
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.
119
+ * libp2p fetch protocol options
175
120
  */
176
- dialProtocol: (peer: PeerId | Multiaddr, protocols: string | string[], options?: AbortOptions) => Promise<Stream>
121
+ fetch: FetchServiceInit
177
122
 
178
123
  /**
179
- * Disconnects all connections to the given `peer`
124
+ * An array that must include at least 1 compliant transport
180
125
  */
181
- hangUp: (peer: PeerId | Multiaddr) => Promise<void>
126
+ transports: Array<(components: Components) => Transport>
127
+ streamMuxers?: Array<(components: Components) => StreamMuxerFactory>
128
+ connectionEncryption?: Array<(components: Components) => ConnectionEncrypter>
129
+ peerDiscovery?: Array<(components: Components) => PeerDiscovery>
130
+ peerRouters?: Array<(components: Components) => PeerRouting>
131
+ contentRouters?: Array<(components: Components) => ContentRouting>
182
132
 
183
133
  /**
184
- * Registers the `handler` for each protocol
134
+ * Pass a DHT implementation to enable DHT operations
185
135
  */
186
- handle: (protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions) => Promise<void>
136
+ dht?: (components: Components) => DualDHT
187
137
 
188
138
  /**
189
- * Removes the handler for each protocol. The protocol
190
- * will no longer be supported on streams.
139
+ * A Metrics implementation can be supplied to collect metrics on this node
191
140
  */
192
- unhandle: (protocols: string[] | string) => Promise<void>
141
+ metrics?: (components: Components) => Metrics
193
142
 
194
143
  /**
195
- * Pings the given peer in order to obtain the operation latency
144
+ * If a PubSub implmentation is supplied, PubSub operations will become available
196
145
  */
197
- ping: (peer: PeerId | Multiaddr, options?: AbortOptions) => Promise<number>
146
+ pubsub?: (components: Components) => PubSub
198
147
 
199
148
  /**
200
- * Sends a request to fetch the value associated with the given key from the given peer.
149
+ * A ConnectionProtector can be used to create a secure overlay on top of the network using pre-shared keys
201
150
  */
202
- fetch: (peer: PeerId | Multiaddr, key: string, options?: AbortOptions) => Promise<Uint8Array | null>
151
+ connectionProtector?: (components: Components) => ConnectionProtector
152
+ }
203
153
 
154
+ /**
155
+ * Once you have a libp2p instance, you can listen to several events it emits, so that you can be notified of relevant network events.
156
+ */
157
+ export interface Libp2pEvents {
204
158
  /**
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.
159
+ * @example
160
+ *
161
+ * ```js
162
+ * libp2p.addEventListener('peer:discovery', (event) => {
163
+ * const peerInfo = event.detail
164
+ * // ...
165
+ * })
166
+ * ```
207
167
  */
208
- getPublicKey: (peer: PeerId, options?: AbortOptions) => Promise<Uint8Array>
168
+ 'peer:discovery': CustomEvent<PeerInfo>
209
169
  }
210
170
 
171
+ export type { Libp2p }
172
+
211
173
  export type Libp2pOptions = RecursivePartial<Libp2pInit> & { start?: boolean }
212
174
 
213
175
  /**
@@ -215,6 +177,25 @@ export type Libp2pOptions = RecursivePartial<Libp2pInit> & { start?: boolean }
215
177
  * if one is not passed as part of the options.
216
178
  *
217
179
  * The node will be started unless `start: false` is passed as an option.
180
+ *
181
+ * @example
182
+ *
183
+ * ```js
184
+ * import { createLibp2p } from 'libp2p'
185
+ * import { tcp } from '@libp2p/tcp'
186
+ * import { mplex } from '@libp2p/mplex'
187
+ * import { noise } from '@chainsafe/libp2p-noise'
188
+ *
189
+ * // specify options
190
+ * const options = {
191
+ * transports: [tcp()],
192
+ * streamMuxers: [mplex()],
193
+ * connectionEncryption: [noise()]
194
+ * }
195
+ *
196
+ * // create libp2p
197
+ * const libp2p = await createLibp2p(options)
198
+ * ```
218
199
  */
219
200
  export async function createLibp2p (options: Libp2pOptions): Promise<Libp2p> {
220
201
  const node = await createLibp2pNode(options)
@@ -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'
@@ -17,7 +17,7 @@ import type { Datastore } from 'interface-datastore'
17
17
 
18
18
  const log = logger('libp2p:keychain')
19
19
 
20
- export interface DekOptions {
20
+ export interface DEKConfig {
21
21
  hash: string
22
22
  salt: string
23
23
  iterationCount: number
@@ -26,7 +26,7 @@ export interface DekOptions {
26
26
 
27
27
  export interface KeyChainInit {
28
28
  pass?: string
29
- dek?: DekOptions
29
+ dek?: DEKConfig
30
30
  }
31
31
 
32
32
  /**