libp2p 1.9.3 → 1.9.4-5214dec4a

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 (98) hide show
  1. package/dist/index.min.js +15 -16
  2. package/dist/src/components.d.ts.map +1 -1
  3. package/dist/src/components.js +4 -3
  4. package/dist/src/components.js.map +1 -1
  5. package/dist/src/config.d.ts +1 -1
  6. package/dist/src/config.d.ts.map +1 -1
  7. package/dist/src/config.js +2 -7
  8. package/dist/src/config.js.map +1 -1
  9. package/dist/src/connection/index.d.ts +3 -3
  10. package/dist/src/connection/index.d.ts.map +1 -1
  11. package/dist/src/connection/index.js +7 -7
  12. package/dist/src/connection/index.js.map +1 -1
  13. package/dist/src/connection-manager/connection-pruner.js +1 -1
  14. package/dist/src/connection-manager/constants.browser.d.ts +0 -8
  15. package/dist/src/connection-manager/constants.browser.d.ts.map +1 -1
  16. package/dist/src/connection-manager/constants.browser.js +0 -8
  17. package/dist/src/connection-manager/constants.browser.js.map +1 -1
  18. package/dist/src/connection-manager/constants.d.ts +0 -8
  19. package/dist/src/connection-manager/constants.d.ts.map +1 -1
  20. package/dist/src/connection-manager/constants.defaults.d.ts +12 -22
  21. package/dist/src/connection-manager/constants.defaults.d.ts.map +1 -1
  22. package/dist/src/connection-manager/constants.defaults.js +12 -22
  23. package/dist/src/connection-manager/constants.defaults.js.map +1 -1
  24. package/dist/src/connection-manager/constants.js +0 -8
  25. package/dist/src/connection-manager/constants.js.map +1 -1
  26. package/dist/src/connection-manager/dial-queue.d.ts.map +1 -1
  27. package/dist/src/connection-manager/dial-queue.js +29 -15
  28. package/dist/src/connection-manager/dial-queue.js.map +1 -1
  29. package/dist/src/connection-manager/index.d.ts +47 -50
  30. package/dist/src/connection-manager/index.d.ts.map +1 -1
  31. package/dist/src/connection-manager/index.js +23 -57
  32. package/dist/src/connection-manager/index.js.map +1 -1
  33. package/dist/src/connection-manager/reconnect-queue.d.ts +35 -0
  34. package/dist/src/connection-manager/reconnect-queue.d.ts.map +1 -0
  35. package/dist/src/connection-manager/reconnect-queue.js +104 -0
  36. package/dist/src/connection-manager/reconnect-queue.js.map +1 -0
  37. package/dist/src/connection-monitor.js +1 -1
  38. package/dist/src/connection-monitor.js.map +1 -1
  39. package/dist/src/content-routing.js +6 -6
  40. package/dist/src/content-routing.js.map +1 -1
  41. package/dist/src/errors.d.ts +41 -61
  42. package/dist/src/errors.d.ts.map +1 -1
  43. package/dist/src/errors.js +84 -63
  44. package/dist/src/errors.js.map +1 -1
  45. package/dist/src/get-peer.d.ts.map +1 -1
  46. package/dist/src/get-peer.js +4 -5
  47. package/dist/src/get-peer.js.map +1 -1
  48. package/dist/src/index.d.ts +25 -7
  49. package/dist/src/index.d.ts.map +1 -1
  50. package/dist/src/index.js +9 -2
  51. package/dist/src/index.js.map +1 -1
  52. package/dist/src/libp2p.d.ts +11 -10
  53. package/dist/src/libp2p.d.ts.map +1 -1
  54. package/dist/src/libp2p.js +11 -29
  55. package/dist/src/libp2p.js.map +1 -1
  56. package/dist/src/peer-routing.js +8 -8
  57. package/dist/src/peer-routing.js.map +1 -1
  58. package/dist/src/registrar.js +7 -7
  59. package/dist/src/registrar.js.map +1 -1
  60. package/dist/src/transport-manager.d.ts.map +1 -1
  61. package/dist/src/transport-manager.js +15 -23
  62. package/dist/src/transport-manager.js.map +1 -1
  63. package/dist/src/upgrader.d.ts +4 -4
  64. package/dist/src/upgrader.d.ts.map +1 -1
  65. package/dist/src/upgrader.js +35 -35
  66. package/dist/src/upgrader.js.map +1 -1
  67. package/dist/src/version.d.ts +1 -1
  68. package/dist/src/version.d.ts.map +1 -1
  69. package/dist/src/version.js +1 -1
  70. package/dist/src/version.js.map +1 -1
  71. package/package.json +20 -20
  72. package/src/components.ts +4 -3
  73. package/src/config.ts +4 -10
  74. package/src/connection/index.ts +9 -9
  75. package/src/connection-manager/connection-pruner.ts +1 -1
  76. package/src/connection-manager/constants.browser.ts +0 -10
  77. package/src/connection-manager/constants.defaults.ts +14 -27
  78. package/src/connection-manager/constants.ts +0 -10
  79. package/src/connection-manager/dial-queue.ts +30 -15
  80. package/src/connection-manager/index.ts +80 -118
  81. package/src/connection-manager/reconnect-queue.ts +134 -0
  82. package/src/connection-monitor.ts +1 -1
  83. package/src/content-routing.ts +6 -6
  84. package/src/errors.ts +96 -61
  85. package/src/get-peer.ts +4 -5
  86. package/src/index.ts +40 -10
  87. package/src/libp2p.ts +20 -34
  88. package/src/peer-routing.ts +8 -8
  89. package/src/registrar.ts +7 -7
  90. package/src/transport-manager.ts +15 -23
  91. package/src/upgrader.ts +37 -38
  92. package/src/version.ts +1 -1
  93. package/dist/src/connection-manager/auto-dial.d.ts +0 -47
  94. package/dist/src/connection-manager/auto-dial.d.ts.map +0 -1
  95. package/dist/src/connection-manager/auto-dial.js +0 -223
  96. package/dist/src/connection-manager/auto-dial.js.map +0 -1
  97. package/dist/typedoc-urls.json +0 -14
  98. package/src/connection-manager/auto-dial.ts +0 -285
@@ -1,7 +1,7 @@
1
- import { CodeError } from '@libp2p/interface'
1
+ import { NotStartedError } from '@libp2p/interface'
2
2
  import { PeerSet } from '@libp2p/peer-collections'
3
3
  import merge from 'it-merge'
4
- import { codes, messages } from './errors.js'
4
+ import { NoContentRoutersError } from './errors.js'
5
5
  import type { AbortOptions, ComponentLogger, ContentRouting, PeerInfo, PeerRouting, PeerStore, RoutingOptions, Startable } from '@libp2p/interface'
6
6
  import type { CID } from 'multiformats/cid'
7
7
 
@@ -45,7 +45,7 @@ export class CompoundContentRouting implements ContentRouting, Startable {
45
45
  */
46
46
  async * findProviders (key: CID, options: RoutingOptions = {}): AsyncIterable<PeerInfo> {
47
47
  if (this.routers.length === 0) {
48
- throw new CodeError('No content routers available', codes.ERR_NO_ROUTERS_AVAILABLE)
48
+ throw new NoContentRoutersError('No content routers available')
49
49
  }
50
50
 
51
51
  const self = this
@@ -84,7 +84,7 @@ export class CompoundContentRouting implements ContentRouting, Startable {
84
84
  */
85
85
  async provide (key: CID, options: AbortOptions = {}): Promise<void> {
86
86
  if (this.routers.length === 0) {
87
- throw new CodeError('No content routers available', codes.ERR_NO_ROUTERS_AVAILABLE)
87
+ throw new NoContentRoutersError('No content routers available')
88
88
  }
89
89
 
90
90
  await Promise.all(this.routers.map(async (router) => {
@@ -97,7 +97,7 @@ export class CompoundContentRouting implements ContentRouting, Startable {
97
97
  */
98
98
  async put (key: Uint8Array, value: Uint8Array, options?: AbortOptions): Promise<void> {
99
99
  if (!this.isStarted()) {
100
- throw new CodeError(messages.NOT_STARTED_YET, codes.ERR_NODE_NOT_STARTED)
100
+ throw new NotStartedError()
101
101
  }
102
102
 
103
103
  await Promise.all(this.routers.map(async (router) => {
@@ -111,7 +111,7 @@ export class CompoundContentRouting implements ContentRouting, Startable {
111
111
  */
112
112
  async get (key: Uint8Array, options?: AbortOptions): Promise<Uint8Array> {
113
113
  if (!this.isStarted()) {
114
- throw new CodeError(messages.NOT_STARTED_YET, codes.ERR_NODE_NOT_STARTED)
114
+ throw new NotStartedError()
115
115
  }
116
116
 
117
117
  return Promise.any(this.routers.map(async (router) => {
package/src/errors.ts CHANGED
@@ -1,67 +1,102 @@
1
1
  export enum messages {
2
2
  NOT_STARTED_YET = 'The libp2p node is not started yet',
3
- ERR_PROTECTOR_REQUIRED = 'Private network is enforced, but no protector was provided',
4
3
  NOT_FOUND = 'Not found'
5
4
  }
6
5
 
7
- export enum codes {
8
- ERR_PROTECTOR_REQUIRED = 'ERR_PROTECTOR_REQUIRED',
9
- ERR_PEER_DIAL_INTERCEPTED = 'ERR_PEER_DIAL_INTERCEPTED',
10
- ERR_CONNECTION_INTERCEPTED = 'ERR_CONNECTION_INTERCEPTED',
11
- ERR_INVALID_PROTOCOLS_FOR_STREAM = 'ERR_INVALID_PROTOCOLS_FOR_STREAM',
12
- ERR_CONNECTION_ENDED = 'ERR_CONNECTION_ENDED',
13
- ERR_CONNECTION_FAILED = 'ERR_CONNECTION_FAILED',
14
- ERR_NODE_NOT_STARTED = 'ERR_NODE_NOT_STARTED',
15
- ERR_ALREADY_ABORTED = 'ERR_ALREADY_ABORTED',
16
- ERR_TOO_MANY_ADDRESSES = 'ERR_TOO_MANY_ADDRESSES',
17
- ERR_NO_VALID_ADDRESSES = 'ERR_NO_VALID_ADDRESSES',
18
- ERR_RELAYED_DIAL = 'ERR_RELAYED_DIAL',
19
- ERR_DIALED_SELF = 'ERR_DIALED_SELF',
20
- ERR_DISCOVERED_SELF = 'ERR_DISCOVERED_SELF',
21
- ERR_DUPLICATE_TRANSPORT = 'ERR_DUPLICATE_TRANSPORT',
22
- ERR_ENCRYPTION_FAILED = 'ERR_ENCRYPTION_FAILED',
23
- ERR_HOP_REQUEST_FAILED = 'ERR_HOP_REQUEST_FAILED',
24
- ERR_INVALID_KEY = 'ERR_INVALID_KEY',
25
- ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE',
26
- ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS',
27
- ERR_INVALID_PEER = 'ERR_INVALID_PEER',
28
- ERR_MUXER_UNAVAILABLE = 'ERR_MUXER_UNAVAILABLE',
29
- ERR_NOT_FOUND = 'ERR_NOT_FOUND',
30
- ERR_TRANSPORT_UNAVAILABLE = 'ERR_TRANSPORT_UNAVAILABLE',
31
- ERR_TRANSPORT_DIAL_FAILED = 'ERR_TRANSPORT_DIAL_FAILED',
32
- ERR_UNSUPPORTED_PROTOCOL = 'ERR_UNSUPPORTED_PROTOCOL',
33
- ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED = 'ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED',
34
- ERR_INVALID_MULTIADDR = 'ERR_INVALID_MULTIADDR',
35
- ERR_SIGNATURE_NOT_VALID = 'ERR_SIGNATURE_NOT_VALID',
36
- ERR_FIND_SELF = 'ERR_FIND_SELF',
37
- ERR_NO_ROUTERS_AVAILABLE = 'ERR_NO_ROUTERS_AVAILABLE',
38
- ERR_CONNECTION_NOT_MULTIPLEXED = 'ERR_CONNECTION_NOT_MULTIPLEXED',
39
- ERR_NO_DIAL_TOKENS = 'ERR_NO_DIAL_TOKENS',
40
- ERR_INVALID_CMS = 'ERR_INVALID_CMS',
41
- ERR_MISSING_KEYS = 'ERR_MISSING_KEYS',
42
- ERR_NO_KEY = 'ERR_NO_KEY',
43
- ERR_INVALID_KEY_NAME = 'ERR_INVALID_KEY_NAME',
44
- ERR_INVALID_KEY_TYPE = 'ERR_INVALID_KEY_TYPE',
45
- ERR_KEY_ALREADY_EXISTS = 'ERR_KEY_ALREADY_EXISTS',
46
- ERR_INVALID_KEY_SIZE = 'ERR_INVALID_KEY_SIZE',
47
- ERR_KEY_NOT_FOUND = 'ERR_KEY_NOT_FOUND',
48
- ERR_OLD_KEY_NAME_INVALID = 'ERR_OLD_KEY_NAME_INVALID',
49
- ERR_NEW_KEY_NAME_INVALID = 'ERR_NEW_KEY_NAME_INVALID',
50
- ERR_PASSWORD_REQUIRED = 'ERR_PASSWORD_REQUIRED',
51
- ERR_PEM_REQUIRED = 'ERR_PEM_REQUIRED',
52
- ERR_CANNOT_READ_KEY = 'ERR_CANNOT_READ_KEY',
53
- ERR_MISSING_PRIVATE_KEY = 'ERR_MISSING_PRIVATE_KEY',
54
- ERR_MISSING_PUBLIC_KEY = 'ERR_MISSING_PUBLIC_KEY',
55
- ERR_INVALID_OLD_PASS_TYPE = 'ERR_INVALID_OLD_PASS_TYPE',
56
- ERR_INVALID_NEW_PASS_TYPE = 'ERR_INVALID_NEW_PASS_TYPE',
57
- ERR_INVALID_PASS_LENGTH = 'ERR_INVALID_PASS_LENGTH',
58
- ERR_NOT_IMPLEMENTED = 'ERR_NOT_IMPLEMENTED',
59
- ERR_WRONG_PING_ACK = 'ERR_WRONG_PING_ACK',
60
- ERR_INVALID_RECORD = 'ERR_INVALID_RECORD',
61
- ERR_ALREADY_SUCCEEDED = 'ERR_ALREADY_SUCCEEDED',
62
- ERR_NO_HANDLER_FOR_PROTOCOL = 'ERR_NO_HANDLER_FOR_PROTOCOL',
63
- ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS',
64
- ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS = 'ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS',
65
- ERR_CONNECTION_DENIED = 'ERR_CONNECTION_DENIED',
66
- ERR_TRANSFER_LIMIT_EXCEEDED = 'ERR_TRANSFER_LIMIT_EXCEEDED'
6
+ export class MissingServiceError extends Error {
7
+ constructor (message = 'Missing service') {
8
+ super(message)
9
+ this.name = 'MissingServiceError'
10
+ }
11
+ }
12
+
13
+ export class UnmetServiceDependenciesError extends Error {
14
+ constructor (message = 'Unmet service dependencies') {
15
+ super(message)
16
+ this.name = 'UnmetServiceDependenciesError'
17
+ }
18
+ }
19
+
20
+ export class NoContentRoutersError extends Error {
21
+ constructor (message = 'No content routers available') {
22
+ super(message)
23
+ this.name = 'NoContentRoutersError'
24
+ }
25
+ }
26
+
27
+ export class NoPeerRoutersError extends Error {
28
+ constructor (message = 'No peer routers available') {
29
+ super(message)
30
+ this.name = 'NoPeerRoutersError'
31
+ }
32
+ }
33
+
34
+ export class QueriedForSelfError extends Error {
35
+ constructor (message = 'Should not try to find self') {
36
+ super(message)
37
+ this.name = 'QueriedForSelfError'
38
+ }
39
+ }
40
+
41
+ export class UnhandledProtocolError extends Error {
42
+ constructor (message = 'Unhandled protocol error') {
43
+ super(message)
44
+ this.name = 'UnhandledProtocolError'
45
+ }
46
+ }
47
+
48
+ export class DuplicateProtocolHandlerError extends Error {
49
+ constructor (message = 'Duplicate protocol handler error') {
50
+ super(message)
51
+ this.name = 'DuplicateProtocolHandlerError'
52
+ }
53
+ }
54
+
55
+ export class DialDeniedError extends Error {
56
+ constructor (message = 'Dial denied error') {
57
+ super(message)
58
+ this.name = 'DialDeniedError'
59
+ }
60
+ }
61
+
62
+ export class NoValidAddressesError extends Error {
63
+ constructor (message = 'No valid addresses') {
64
+ super(message)
65
+ this.name = 'NoValidAddressesError'
66
+ }
67
+ }
68
+
69
+ export class ConnectionInterceptedError extends Error {
70
+ constructor (message = 'Connection intercepted') {
71
+ super(message)
72
+ this.name = 'ConnectionInterceptedError'
73
+ }
74
+ }
75
+
76
+ export class ConnectionDeniedError extends Error {
77
+ constructor (message = 'Connection denied') {
78
+ super(message)
79
+ this.name = 'ConnectionDeniedError'
80
+ }
81
+ }
82
+
83
+ export class MuxerUnavailableError extends Error {
84
+ constructor (message = 'Stream is not multiplexed') {
85
+ super(message)
86
+ this.name = 'MuxerUnavailableError'
87
+ }
88
+ }
89
+
90
+ export class EncryptionFailedError extends Error {
91
+ constructor (message = 'Encryption failed') {
92
+ super(message)
93
+ this.name = 'EncryptionFailedError'
94
+ }
95
+ }
96
+
97
+ export class TransportUnavailableError extends Error {
98
+ constructor (message = 'Transport unavailable') {
99
+ super(message)
100
+ this.name = 'TransportUnavailableError'
101
+ }
67
102
  }
package/src/get-peer.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { CodeError, isPeerId } from '@libp2p/interface'
1
+ import { InvalidMultiaddrError, InvalidParametersError, isPeerId } from '@libp2p/interface'
2
2
  import { peerIdFromString } from '@libp2p/peer-id'
3
3
  import { isMultiaddr } from '@multiformats/multiaddr'
4
- import { codes } from './errors.js'
5
4
  import type { PeerId } from '@libp2p/interface'
6
5
  import type { Multiaddr } from '@multiformats/multiaddr'
7
6
 
@@ -31,20 +30,20 @@ export function getPeerAddress (peer: PeerId | Multiaddr | Multiaddr[]): PeerAdd
31
30
  // ensure PeerId is either not set or is consistent
32
31
  peer.forEach(ma => {
33
32
  if (!isMultiaddr(ma)) {
34
- throw new CodeError('Invalid Multiaddr', codes.ERR_INVALID_MULTIADDR)
33
+ throw new InvalidMultiaddrError('Invalid multiaddr')
35
34
  }
36
35
 
37
36
  const maPeerIdStr = ma.getPeerId()
38
37
 
39
38
  if (maPeerIdStr == null) {
40
39
  if (peerId != null) {
41
- throw new CodeError('Multiaddrs must all have the same peer id or have no peer id', codes.ERR_INVALID_PARAMETERS)
40
+ throw new InvalidParametersError('Multiaddrs must all have the same peer id or have no peer id')
42
41
  }
43
42
  } else {
44
43
  const maPeerId = peerIdFromString(maPeerIdStr)
45
44
 
46
45
  if (peerId?.equals(maPeerId) !== true) {
47
- throw new CodeError('Multiaddrs must all have the same peer id or have no peer id', codes.ERR_INVALID_PARAMETERS)
46
+ throw new InvalidParametersError('Multiaddrs must all have the same peer id or have no peer id')
48
47
  }
49
48
  }
50
49
  })
package/src/index.ts CHANGED
@@ -14,13 +14,16 @@
14
14
  * ```
15
15
  */
16
16
 
17
- import { createLibp2pNode } from './libp2p.js'
17
+ import { generateKeyPair } from '@libp2p/crypto/keys'
18
+ import { peerIdFromPrivateKey } from '@libp2p/peer-id'
19
+ import { validateConfig } from './config.js'
20
+ import { Libp2p as Libp2pClass } from './libp2p.js'
18
21
  import type { AddressManagerInit } from './address-manager/index.js'
19
22
  import type { Components } from './components.js'
20
23
  import type { ConnectionManagerInit } from './connection-manager/index.js'
21
24
  import type { ConnectionMonitorInit } from './connection-monitor.js'
22
25
  import type { TransportManagerInit } from './transport-manager.js'
23
- import type { Libp2p, ServiceMap, ComponentLogger, NodeInfo, ConnectionProtector, ConnectionEncrypter, ConnectionGater, ContentRouting, Metrics, PeerDiscovery, PeerId, PeerRouting, StreamMuxerFactory, Transport, PrivateKey } from '@libp2p/interface'
26
+ import type { Libp2p, ServiceMap, ComponentLogger, NodeInfo, ConnectionProtector, ConnectionEncrypter, ConnectionGater, ContentRouting, Metrics, PeerDiscovery, PeerRouting, StreamMuxerFactory, Transport, PrivateKey } from '@libp2p/interface'
24
27
  import type { PersistentPeerStoreInit } from '@libp2p/peer-store'
25
28
  import type { DNS } from '@multiformats/dns'
26
29
  import type { Datastore } from 'interface-datastore'
@@ -34,12 +37,11 @@ export type ServiceFactoryMap<T extends ServiceMap = ServiceMap> = {
34
37
  */
35
38
  export interface Libp2pInit<T extends ServiceMap = ServiceMap> {
36
39
  /**
37
- * peerId instance (it will be created if not provided)
38
- */
39
- peerId?: PeerId
40
-
41
- /**
42
- * Private key associated with the peerId
40
+ * The private key is used in cryptographic operations and the Peer ID derived
41
+ * from it's corresponding public key is used to identify the node to other
42
+ * peers on the network.
43
+ *
44
+ * If this is not passed a new Ed25519 private key will be generated.
43
45
  */
44
46
  privateKey?: PrivateKey
45
47
 
@@ -86,13 +88,36 @@ export interface Libp2pInit<T extends ServiceMap = ServiceMap> {
86
88
  peerStore?: PersistentPeerStoreInit
87
89
 
88
90
  /**
89
- * An array that must include at least 1 compliant transport
91
+ * Transports are low-level communication channels
90
92
  */
91
93
  transports?: Array<(components: Components) => Transport>
94
+
95
+ /**
96
+ * Stream muxers allow the creation of many data streams over a single
97
+ * connection.
98
+ */
92
99
  streamMuxers?: Array<(components: Components) => StreamMuxerFactory>
100
+
101
+ /**
102
+ * Connection encrypters ensure that data sent over connections cannot be
103
+ * eavesdropped on, and that the remote peer posesses the private key that
104
+ * corresponds to the public key that it's Peer ID is derived from.
105
+ */
93
106
  connectionEncryption?: Array<(components: Components) => ConnectionEncrypter>
107
+
108
+ /**
109
+ * Peer discovery mechanisms allow finding peers on the network
110
+ */
94
111
  peerDiscovery?: Array<(components: Components) => PeerDiscovery>
112
+
113
+ /**
114
+ * Peer routers provide implementations for peer routing queries
115
+ */
95
116
  peerRouters?: Array<(components: Components) => PeerRouting>
117
+
118
+ /**
119
+ * Content routers provide implementations for content routing queries
120
+ */
96
121
  contentRouters?: Array<(components: Components) => ContentRouting>
97
122
 
98
123
  /**
@@ -170,7 +195,12 @@ export type Libp2pOptions<T extends ServiceMap = ServiceMap> = Libp2pInit<T> & {
170
195
  * ```
171
196
  */
172
197
  export async function createLibp2p <T extends ServiceMap = ServiceMap> (options: Libp2pOptions<T> = {}): Promise<Libp2p<T>> {
173
- const node = await createLibp2pNode(options)
198
+ options.privateKey ??= await generateKeyPair('Ed25519')
199
+
200
+ const node = new Libp2pClass({
201
+ ...await validateConfig(options),
202
+ peerId: peerIdFromPrivateKey(options.privateKey)
203
+ })
174
204
 
175
205
  if (options.start !== false) {
176
206
  await node.start()
package/src/libp2p.ts CHANGED
@@ -1,9 +1,8 @@
1
- import { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys'
2
- import { contentRoutingSymbol, CodeError, TypedEventEmitter, CustomEvent, setMaxListeners, peerDiscoverySymbol, peerRoutingSymbol } from '@libp2p/interface'
1
+ import { publicKeyFromProtobuf } from '@libp2p/crypto/keys'
2
+ import { contentRoutingSymbol, TypedEventEmitter, setMaxListeners, peerDiscoverySymbol, peerRoutingSymbol, InvalidParametersError } from '@libp2p/interface'
3
3
  import { defaultLogger } from '@libp2p/logger'
4
4
  import { PeerSet } from '@libp2p/peer-collections'
5
5
  import { peerIdFromString } from '@libp2p/peer-id'
6
- import { createEd25519PeerId } from '@libp2p/peer-id-factory'
7
6
  import { PersistentPeerStore } from '@libp2p/peer-store'
8
7
  import { isMultiaddr, type Multiaddr } from '@multiformats/multiaddr'
9
8
  import { MemoryDatastore } from 'datastore-core/memory'
@@ -12,11 +11,9 @@ import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
12
11
  import { DefaultAddressManager } from './address-manager/index.js'
13
12
  import { checkServiceDependencies, defaultComponents } from './components.js'
14
13
  import { connectionGater } from './config/connection-gater.js'
15
- import { validateConfig } from './config.js'
16
14
  import { DefaultConnectionManager } from './connection-manager/index.js'
17
15
  import { ConnectionMonitor } from './connection-monitor.js'
18
16
  import { CompoundContentRouting } from './content-routing.js'
19
- import { codes } from './errors.js'
20
17
  import { DefaultPeerRouting } from './peer-routing.js'
21
18
  import { RandomWalk } from './random-walk.js'
22
19
  import { DefaultRegistrar } from './registrar.js'
@@ -24,11 +21,11 @@ import { DefaultTransportManager } from './transport-manager.js'
24
21
  import { DefaultUpgrader } from './upgrader.js'
25
22
  import * as pkg from './version.js'
26
23
  import type { Components } from './components.js'
27
- import type { Libp2p, Libp2pInit, Libp2pOptions } from './index.js'
28
- import type { PeerRouting, ContentRouting, Libp2pEvents, PendingDial, ServiceMap, AbortOptions, ComponentLogger, Logger, Connection, NewStreamOptions, Stream, Metrics, PeerId, PeerInfo, PeerStore, Topology, Libp2pStatus, IsDialableOptions, DialOptions } from '@libp2p/interface'
24
+ import type { Libp2p as Libp2pInterface, Libp2pInit } from './index.js'
25
+ import type { PeerRouting, ContentRouting, Libp2pEvents, PendingDial, ServiceMap, AbortOptions, ComponentLogger, Logger, Connection, NewStreamOptions, Stream, Metrics, PeerId, PeerInfo, PeerStore, Topology, Libp2pStatus, IsDialableOptions, DialOptions, PublicKey, Ed25519PeerId, Secp256k1PeerId, RSAPublicKey, RSAPeerId, URLPeerId, Ed25519PublicKey, Secp256k1PublicKey } from '@libp2p/interface'
29
26
  import type { StreamHandler, StreamHandlerOptions } from '@libp2p/interface-internal'
30
27
 
31
- export class Libp2pNode<T extends ServiceMap = ServiceMap> extends TypedEventEmitter<Libp2pEvents> implements Libp2p<T> {
28
+ export class Libp2p<T extends ServiceMap = ServiceMap> extends TypedEventEmitter<Libp2pEvents> implements Libp2pInterface<T> {
32
29
  public peerId: PeerId
33
30
  public peerStore: PeerStore
34
31
  public contentRouting: ContentRouting
@@ -41,7 +38,7 @@ export class Libp2pNode<T extends ServiceMap = ServiceMap> extends TypedEventEmi
41
38
  public components: Components & T
42
39
  private readonly log: Logger
43
40
 
44
- constructor (init: Libp2pInit<T> & Required<Pick<Libp2pInit<T>, 'peerId'>>) {
41
+ constructor (init: Libp2pInit<T> & { peerId: PeerId }) {
45
42
  super()
46
43
 
47
44
  this.status = 'stopped'
@@ -288,13 +285,13 @@ export class Libp2pNode<T extends ServiceMap = ServiceMap> extends TypedEventEmi
288
285
 
289
286
  async dialProtocol (peer: PeerId | Multiaddr | Multiaddr[], protocols: string | string[], options: NewStreamOptions = {}): Promise<Stream> {
290
287
  if (protocols == null) {
291
- throw new CodeError('no protocols were provided to open a stream', codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)
288
+ throw new InvalidParametersError('no protocols were provided to open a stream')
292
289
  }
293
290
 
294
291
  protocols = Array.isArray(protocols) ? protocols : [protocols]
295
292
 
296
293
  if (protocols.length === 0) {
297
- throw new CodeError('no protocols were provided to open a stream', codes.ERR_INVALID_PROTOCOLS_FOR_STREAM)
294
+ throw new InvalidParametersError('no protocols were provided to open a stream')
298
295
  }
299
296
 
300
297
  const connection = await this.dial(peer, options)
@@ -321,7 +318,12 @@ export class Libp2pNode<T extends ServiceMap = ServiceMap> extends TypedEventEmi
321
318
  /**
322
319
  * Get the public key for the given peer id
323
320
  */
324
- async getPublicKey (peer: PeerId, options: AbortOptions = {}): Promise<Uint8Array> {
321
+ async getPublicKey (peer: Ed25519PeerId, options?: AbortOptions): Promise<Ed25519PublicKey>
322
+ async getPublicKey (peer: Secp256k1PeerId, options?: AbortOptions): Promise<Secp256k1PublicKey>
323
+ async getPublicKey (peer: RSAPeerId, options?: AbortOptions): Promise<RSAPublicKey>
324
+ async getPublicKey (peer: URLPeerId, options?: AbortOptions): Promise<never>
325
+ async getPublicKey (peer: PeerId, options?: AbortOptions): Promise<PublicKey>
326
+ async getPublicKey (peer: PeerId, options: AbortOptions = {}): Promise<PublicKey> {
325
327
  this.log('getPublicKey %p', peer)
326
328
 
327
329
  if (peer.publicKey != null) {
@@ -335,27 +337,27 @@ export class Libp2pNode<T extends ServiceMap = ServiceMap> extends TypedEventEmi
335
337
  return peerInfo.id.publicKey
336
338
  }
337
339
  } catch (err: any) {
338
- if (err.code !== codes.ERR_NOT_FOUND) {
340
+ if (err.name !== 'NotFoundError') {
339
341
  throw err
340
342
  }
341
343
  }
342
344
 
343
345
  const peerKey = uint8ArrayConcat([
344
346
  uint8ArrayFromString('/pk/'),
345
- peer.multihash.digest
347
+ peer.toMultihash().bytes
346
348
  ])
347
349
 
348
350
  // search any available content routing methods
349
351
  const bytes = await this.contentRouting.get(peerKey, options)
350
352
 
351
353
  // ensure the returned key is valid
352
- unmarshalPublicKey(bytes)
354
+ const publicKey = publicKeyFromProtobuf(bytes)
353
355
 
354
356
  await this.peerStore.patch(peer, {
355
- publicKey: bytes
357
+ publicKey
356
358
  })
357
359
 
358
- return bytes
360
+ return publicKey
359
361
  }
360
362
 
361
363
  async handle (protocols: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void> {
@@ -402,7 +404,7 @@ export class Libp2pNode<T extends ServiceMap = ServiceMap> extends TypedEventEmi
402
404
  const { detail: peer } = evt
403
405
 
404
406
  if (peer.id.toString() === this.peerId.toString()) {
405
- this.log.error(new Error(codes.ERR_DISCOVERED_SELF))
407
+ this.log.error('peer discovery mechanism discovered self')
406
408
  return
407
409
  }
408
410
 
@@ -412,19 +414,3 @@ export class Libp2pNode<T extends ServiceMap = ServiceMap> extends TypedEventEmi
412
414
  .catch(err => { this.log.error(err) })
413
415
  }
414
416
  }
415
-
416
- /**
417
- * Returns a new Libp2pNode instance - this exposes more of the internals than the
418
- * libp2p interface and is useful for testing and debugging.
419
- */
420
- export async function createLibp2pNode <T extends ServiceMap = ServiceMap> (options: Libp2pOptions<T> = {}): Promise<Libp2pNode<T>> {
421
- const peerId = options.peerId ??= await createEd25519PeerId()
422
-
423
- if (peerId.privateKey == null) {
424
- throw new CodeError('peer id was missing private key', 'ERR_MISSING_PRIVATE_KEY')
425
- }
426
-
427
- options.privateKey ??= await unmarshalPrivateKey(peerId.privateKey)
428
-
429
- return new Libp2pNode(await validateConfig(options))
430
- }
@@ -1,8 +1,8 @@
1
- import { CodeError } from '@libp2p/interface'
1
+ import { NotFoundError } from '@libp2p/interface'
2
2
  import { createScalableCuckooFilter } from '@libp2p/utils/filters'
3
3
  import merge from 'it-merge'
4
4
  import parallel from 'it-parallel'
5
- import { codes, messages } from './errors.js'
5
+ import { NoPeerRoutersError, QueriedForSelfError } from './errors.js'
6
6
  import type { Logger, PeerId, PeerInfo, PeerRouting, PeerStore, RoutingOptions } from '@libp2p/interface'
7
7
  import type { ComponentLogger } from '@libp2p/logger'
8
8
 
@@ -36,11 +36,11 @@ export class DefaultPeerRouting implements PeerRouting {
36
36
  */
37
37
  async findPeer (id: PeerId, options?: RoutingOptions): Promise<PeerInfo> {
38
38
  if (this.routers.length === 0) {
39
- throw new CodeError('No peer routers available', codes.ERR_NO_ROUTERS_AVAILABLE)
39
+ throw new NoPeerRoutersError('No peer routers available')
40
40
  }
41
41
 
42
42
  if (id.toString() === this.peerId.toString()) {
43
- throw new CodeError('Should not try to find self', codes.ERR_FIND_SELF)
43
+ throw new QueriedForSelfError('Should not try to find self')
44
44
  }
45
45
 
46
46
  const self = this
@@ -69,7 +69,7 @@ export class DefaultPeerRouting implements PeerRouting {
69
69
  return peer
70
70
  }
71
71
 
72
- throw new CodeError(messages.NOT_FOUND, codes.ERR_NOT_FOUND)
72
+ throw new NotFoundError()
73
73
  }
74
74
 
75
75
  /**
@@ -77,7 +77,7 @@ export class DefaultPeerRouting implements PeerRouting {
77
77
  */
78
78
  async * getClosestPeers (key: Uint8Array, options: RoutingOptions = {}): AsyncIterable<PeerInfo> {
79
79
  if (this.routers.length === 0) {
80
- throw new CodeError('No peer routers available', codes.ERR_NO_ROUTERS_AVAILABLE)
80
+ throw new NoPeerRoutersError('No peer routers available')
81
81
  }
82
82
 
83
83
  const self = this
@@ -121,11 +121,11 @@ export class DefaultPeerRouting implements PeerRouting {
121
121
  }
122
122
 
123
123
  // deduplicate peers
124
- if (seen.has(peer.id.toBytes())) {
124
+ if (seen.has(peer.id.toMultihash().bytes)) {
125
125
  continue
126
126
  }
127
127
 
128
- seen.add(peer.id.toBytes())
128
+ seen.add(peer.id.toMultihash().bytes)
129
129
 
130
130
  yield peer
131
131
  }
package/src/registrar.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { CodeError } from '@libp2p/interface'
1
+ import { InvalidParametersError } from '@libp2p/interface'
2
2
  import merge from 'merge-options'
3
- import { codes } from './errors.js'
3
+ import * as errorsJs from './errors.js'
4
4
  import type { IdentifyResult, Libp2pEvents, Logger, PeerUpdate, TypedEventTarget, PeerId, PeerStore, Topology } from '@libp2p/interface'
5
5
  import type { ConnectionManager, StreamHandlerOptions, StreamHandlerRecord, Registrar, StreamHandler } from '@libp2p/interface-internal'
6
6
  import type { ComponentLogger } from '@libp2p/logger'
@@ -52,7 +52,7 @@ export class DefaultRegistrar implements Registrar {
52
52
  const handler = this.handlers.get(protocol)
53
53
 
54
54
  if (handler == null) {
55
- throw new CodeError(`No handler registered for protocol ${protocol}`, codes.ERR_NO_HANDLER_FOR_PROTOCOL)
55
+ throw new errorsJs.UnhandledProtocolError(`No handler registered for protocol ${protocol}`)
56
56
  }
57
57
 
58
58
  return handler
@@ -75,7 +75,7 @@ export class DefaultRegistrar implements Registrar {
75
75
  */
76
76
  async handle (protocol: string, handler: StreamHandler, opts?: StreamHandlerOptions): Promise<void> {
77
77
  if (this.handlers.has(protocol)) {
78
- throw new CodeError(`Handler already registered for protocol ${protocol}`, codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED)
78
+ throw new errorsJs.DuplicateProtocolHandlerError(`Handler already registered for protocol ${protocol}`)
79
79
  }
80
80
 
81
81
  const options = merge.bind({ ignoreUndefined: true })({
@@ -116,7 +116,7 @@ export class DefaultRegistrar implements Registrar {
116
116
  */
117
117
  async register (protocol: string, topology: Topology): Promise<string> {
118
118
  if (topology == null) {
119
- throw new CodeError('invalid topology', codes.ERR_INVALID_PARAMETERS)
119
+ throw new InvalidParametersError('invalid topology')
120
120
  }
121
121
 
122
122
  // Create topology
@@ -176,7 +176,7 @@ export class DefaultRegistrar implements Registrar {
176
176
  }
177
177
  })
178
178
  .catch(err => {
179
- if (err.code === codes.ERR_NOT_FOUND) {
179
+ if (err.name === 'NotFoundError') {
180
180
  // peer has not completed identify so they are not in the peer store
181
181
  return
182
182
  }
@@ -230,7 +230,7 @@ export class DefaultRegistrar implements Registrar {
230
230
  }
231
231
 
232
232
  for (const topology of topologies.values()) {
233
- if (connection.transient && topology.notifyOnTransient !== true) {
233
+ if (connection.limits != null && topology.notifyOnLimitedConnection !== true) {
234
234
  continue
235
235
  }
236
236