libp2p 0.37.3 → 0.38.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 (189) hide show
  1. package/README.md +1 -2
  2. package/dist/src/address-manager/index.d.ts +2 -2
  3. package/dist/src/address-manager/index.d.ts.map +1 -1
  4. package/dist/src/circuit/auto-relay.d.ts +4 -4
  5. package/dist/src/circuit/auto-relay.d.ts.map +1 -1
  6. package/dist/src/circuit/circuit/hop.d.ts +7 -5
  7. package/dist/src/circuit/circuit/hop.d.ts.map +1 -1
  8. package/dist/src/circuit/circuit/hop.js +8 -4
  9. package/dist/src/circuit/circuit/hop.js.map +1 -1
  10. package/dist/src/circuit/circuit/stop.d.ts +6 -4
  11. package/dist/src/circuit/circuit/stop.d.ts.map +1 -1
  12. package/dist/src/circuit/circuit/stop.js +4 -2
  13. package/dist/src/circuit/circuit/stop.js.map +1 -1
  14. package/dist/src/circuit/circuit/stream-handler.d.ts +3 -2
  15. package/dist/src/circuit/circuit/stream-handler.d.ts.map +1 -1
  16. package/dist/src/circuit/circuit/stream-handler.js +2 -2
  17. package/dist/src/circuit/circuit/stream-handler.js.map +1 -1
  18. package/dist/src/circuit/index.d.ts +4 -12
  19. package/dist/src/circuit/index.d.ts.map +1 -1
  20. package/dist/src/circuit/index.js.map +1 -1
  21. package/dist/src/circuit/listener.d.ts +3 -3
  22. package/dist/src/circuit/listener.d.ts.map +1 -1
  23. package/dist/src/circuit/pb/index.d.ts +5 -4
  24. package/dist/src/circuit/pb/index.d.ts.map +1 -1
  25. package/dist/src/circuit/pb/index.js +107 -11
  26. package/dist/src/circuit/pb/index.js.map +1 -1
  27. package/dist/src/circuit/transport.d.ts +8 -5
  28. package/dist/src/circuit/transport.d.ts.map +1 -1
  29. package/dist/src/circuit/transport.js +81 -59
  30. package/dist/src/circuit/transport.js.map +1 -1
  31. package/dist/src/config.d.ts.map +1 -1
  32. package/dist/src/config.js +27 -4
  33. package/dist/src/config.js.map +1 -1
  34. package/dist/src/connection-manager/auto-dialler.d.ts +1 -1
  35. package/dist/src/connection-manager/auto-dialler.d.ts.map +1 -1
  36. package/dist/src/connection-manager/dialer/auto-dialer.d.ts +2 -2
  37. package/dist/src/connection-manager/dialer/auto-dialer.d.ts.map +1 -1
  38. package/dist/src/connection-manager/dialer/auto-dialer.js +6 -0
  39. package/dist/src/connection-manager/dialer/auto-dialer.js.map +1 -1
  40. package/dist/src/connection-manager/dialer/dial-request.d.ts +1 -1
  41. package/dist/src/connection-manager/dialer/dial-request.d.ts.map +1 -1
  42. package/dist/src/connection-manager/dialer/index.d.ts +9 -9
  43. package/dist/src/connection-manager/dialer/index.d.ts.map +1 -1
  44. package/dist/src/connection-manager/dialer/index.js +11 -11
  45. package/dist/src/connection-manager/dialer/index.js.map +1 -1
  46. package/dist/src/connection-manager/index.d.ts +20 -16
  47. package/dist/src/connection-manager/index.d.ts.map +1 -1
  48. package/dist/src/connection-manager/index.js +185 -65
  49. package/dist/src/connection-manager/index.js.map +1 -1
  50. package/dist/src/constants.d.ts +4 -0
  51. package/dist/src/constants.d.ts.map +1 -1
  52. package/dist/src/constants.js +4 -0
  53. package/dist/src/constants.js.map +1 -1
  54. package/dist/src/content-routing/index.d.ts +4 -4
  55. package/dist/src/content-routing/index.d.ts.map +1 -1
  56. package/dist/src/content-routing/utils.d.ts +2 -2
  57. package/dist/src/content-routing/utils.d.ts.map +1 -1
  58. package/dist/src/dht/dht-content-routing.d.ts +3 -3
  59. package/dist/src/dht/dht-content-routing.d.ts.map +1 -1
  60. package/dist/src/dht/dht-peer-routing.d.ts +5 -5
  61. package/dist/src/dht/dht-peer-routing.d.ts.map +1 -1
  62. package/dist/src/dht/dummy-dht.d.ts +3 -3
  63. package/dist/src/dht/dummy-dht.d.ts.map +1 -1
  64. package/dist/src/dht/dummy-dht.js +1 -1
  65. package/dist/src/dht/dummy-dht.js.map +1 -1
  66. package/dist/src/errors.d.ts +4 -1
  67. package/dist/src/errors.d.ts.map +1 -1
  68. package/dist/src/errors.js +3 -0
  69. package/dist/src/errors.js.map +1 -1
  70. package/dist/src/fetch/index.d.ts +11 -4
  71. package/dist/src/fetch/index.d.ts.map +1 -1
  72. package/dist/src/fetch/index.js +82 -41
  73. package/dist/src/fetch/index.js.map +1 -1
  74. package/dist/src/fetch/pb/proto.d.ts +4 -3
  75. package/dist/src/fetch/pb/proto.d.ts.map +1 -1
  76. package/dist/src/fetch/pb/proto.js +88 -8
  77. package/dist/src/fetch/pb/proto.js.map +1 -1
  78. package/dist/src/get-peer.d.ts +2 -2
  79. package/dist/src/get-peer.d.ts.map +1 -1
  80. package/dist/src/get-peer.js +1 -1
  81. package/dist/src/get-peer.js.map +1 -1
  82. package/dist/src/identify/index.d.ts +8 -8
  83. package/dist/src/identify/index.d.ts.map +1 -1
  84. package/dist/src/identify/index.js +49 -34
  85. package/dist/src/identify/index.js.map +1 -1
  86. package/dist/src/identify/pb/message.d.ts +2 -1
  87. package/dist/src/identify/pb/message.d.ts.map +1 -1
  88. package/dist/src/identify/pb/message.js +94 -10
  89. package/dist/src/identify/pb/message.js.map +1 -1
  90. package/dist/src/index.d.ts +18 -17
  91. package/dist/src/index.d.ts.map +1 -1
  92. package/dist/src/index.js.map +1 -1
  93. package/dist/src/insecure/index.d.ts +2 -2
  94. package/dist/src/insecure/index.d.ts.map +1 -1
  95. package/dist/src/insecure/index.js +8 -4
  96. package/dist/src/insecure/index.js.map +1 -1
  97. package/dist/src/insecure/pb/proto.d.ts +4 -3
  98. package/dist/src/insecure/pb/proto.d.ts.map +1 -1
  99. package/dist/src/insecure/pb/proto.js +89 -9
  100. package/dist/src/insecure/pb/proto.js.map +1 -1
  101. package/dist/src/keychain/index.d.ts +2 -2
  102. package/dist/src/keychain/index.d.ts.map +1 -1
  103. package/dist/src/libp2p.d.ts +14 -14
  104. package/dist/src/libp2p.d.ts.map +1 -1
  105. package/dist/src/libp2p.js +17 -17
  106. package/dist/src/libp2p.js.map +1 -1
  107. package/dist/src/metrics/index.d.ts +4 -5
  108. package/dist/src/metrics/index.d.ts.map +1 -1
  109. package/dist/src/metrics/index.js +9 -6
  110. package/dist/src/metrics/index.js.map +1 -1
  111. package/dist/src/metrics/moving-average.d.ts +1 -1
  112. package/dist/src/metrics/moving-average.d.ts.map +1 -1
  113. package/dist/src/metrics/stats.d.ts +1 -1
  114. package/dist/src/metrics/stats.d.ts.map +1 -1
  115. package/dist/src/nat-manager.d.ts +1 -1
  116. package/dist/src/nat-manager.d.ts.map +1 -1
  117. package/dist/src/peer-record-updater.d.ts +1 -1
  118. package/dist/src/peer-record-updater.d.ts.map +1 -1
  119. package/dist/src/peer-routing.d.ts +4 -4
  120. package/dist/src/peer-routing.d.ts.map +1 -1
  121. package/dist/src/ping/index.d.ts +10 -3
  122. package/dist/src/ping/index.d.ts.map +1 -1
  123. package/dist/src/ping/index.js +32 -9
  124. package/dist/src/ping/index.js.map +1 -1
  125. package/dist/src/pnet/index.d.ts +1 -2
  126. package/dist/src/pnet/index.d.ts.map +1 -1
  127. package/dist/src/pnet/index.js +2 -1
  128. package/dist/src/pnet/index.js.map +1 -1
  129. package/dist/src/pubsub/dummy-pubsub.d.ts +2 -2
  130. package/dist/src/pubsub/dummy-pubsub.d.ts.map +1 -1
  131. package/dist/src/registrar.d.ts +10 -8
  132. package/dist/src/registrar.d.ts.map +1 -1
  133. package/dist/src/registrar.js +63 -44
  134. package/dist/src/registrar.js.map +1 -1
  135. package/dist/src/transport-manager.d.ts +3 -3
  136. package/dist/src/transport-manager.d.ts.map +1 -1
  137. package/dist/src/upgrader.d.ts +12 -6
  138. package/dist/src/upgrader.d.ts.map +1 -1
  139. package/dist/src/upgrader.js +183 -82
  140. package/dist/src/upgrader.js.map +1 -1
  141. package/dist/src/version.d.ts.map +1 -1
  142. package/dist/src/version.js.map +1 -1
  143. package/package.json +66 -42
  144. package/src/address-manager/index.ts +2 -2
  145. package/src/circuit/README.md +2 -2
  146. package/src/circuit/auto-relay.ts +4 -4
  147. package/src/circuit/circuit/hop.ts +20 -11
  148. package/src/circuit/circuit/stop.ts +10 -5
  149. package/src/circuit/circuit/stream-handler.ts +6 -5
  150. package/src/circuit/index.ts +4 -13
  151. package/src/circuit/listener.ts +3 -3
  152. package/src/circuit/pb/index.ts +133 -15
  153. package/src/circuit/transport.ts +92 -63
  154. package/src/config.ts +27 -4
  155. package/src/connection-manager/auto-dialler.ts +1 -1
  156. package/src/connection-manager/dialer/auto-dialer.ts +8 -2
  157. package/src/connection-manager/dialer/dial-request.ts +1 -1
  158. package/src/connection-manager/dialer/index.ts +15 -15
  159. package/src/connection-manager/index.ts +239 -82
  160. package/src/constants.ts +5 -0
  161. package/src/content-routing/index.ts +2 -2
  162. package/src/content-routing/utils.ts +2 -2
  163. package/src/dht/dht-content-routing.ts +2 -2
  164. package/src/dht/dht-peer-routing.ts +3 -3
  165. package/src/dht/dummy-dht.ts +3 -3
  166. package/src/errors.ts +4 -1
  167. package/src/fetch/index.ts +120 -53
  168. package/src/fetch/pb/proto.ts +109 -11
  169. package/src/get-peer.ts +3 -3
  170. package/src/identify/index.ts +64 -47
  171. package/src/identify/pb/message.ts +111 -11
  172. package/src/index.ts +18 -17
  173. package/src/insecure/index.ts +11 -6
  174. package/src/insecure/pb/proto.ts +111 -12
  175. package/src/keychain/index.ts +2 -2
  176. package/src/libp2p.ts +34 -29
  177. package/src/metrics/index.ts +13 -12
  178. package/src/metrics/moving-average.ts +1 -1
  179. package/src/metrics/stats.ts +1 -1
  180. package/src/nat-manager.ts +1 -1
  181. package/src/peer-record-updater.ts +1 -1
  182. package/src/peer-routing.ts +4 -4
  183. package/src/ping/index.ts +48 -15
  184. package/src/pnet/index.ts +3 -2
  185. package/src/pubsub/dummy-pubsub.ts +2 -2
  186. package/src/registrar.ts +79 -55
  187. package/src/transport-manager.ts +3 -3
  188. package/src/upgrader.ts +223 -93
  189. package/src/version.ts +1 -2
@@ -1,7 +1,8 @@
1
1
  /* eslint-disable import/export */
2
2
  /* eslint-disable @typescript-eslint/no-namespace */
3
3
 
4
- import { encodeMessage, decodeMessage, message, string, bytes } from 'protons-runtime'
4
+ import { encodeMessage, decodeMessage, message } from 'protons-runtime'
5
+ import type { Uint8ArrayList } from 'uint8arraylist'
5
6
  import type { Codec } from 'protons-runtime'
6
7
 
7
8
  export interface Identify {
@@ -15,23 +16,122 @@ export interface Identify {
15
16
  }
16
17
 
17
18
  export namespace Identify {
19
+ let _codec: Codec<Identify>
20
+
18
21
  export const codec = (): Codec<Identify> => {
19
- return message<Identify>({
20
- 5: { name: 'protocolVersion', codec: string, optional: true },
21
- 6: { name: 'agentVersion', codec: string, optional: true },
22
- 1: { name: 'publicKey', codec: bytes, optional: true },
23
- 2: { name: 'listenAddrs', codec: bytes, repeats: true },
24
- 4: { name: 'observedAddr', codec: bytes, optional: true },
25
- 3: { name: 'protocols', codec: string, repeats: true },
26
- 8: { name: 'signedPeerRecord', codec: bytes, optional: true }
27
- })
22
+ if (_codec == null) {
23
+ _codec = message<Identify>((obj, writer, opts = {}) => {
24
+ if (opts.lengthDelimited !== false) {
25
+ writer.fork()
26
+ }
27
+
28
+ if (obj.protocolVersion != null) {
29
+ writer.uint32(42)
30
+ writer.string(obj.protocolVersion)
31
+ }
32
+
33
+ if (obj.agentVersion != null) {
34
+ writer.uint32(50)
35
+ writer.string(obj.agentVersion)
36
+ }
37
+
38
+ if (obj.publicKey != null) {
39
+ writer.uint32(10)
40
+ writer.bytes(obj.publicKey)
41
+ }
42
+
43
+ if (obj.listenAddrs != null) {
44
+ for (const value of obj.listenAddrs) {
45
+ writer.uint32(18)
46
+ writer.bytes(value)
47
+ }
48
+ } else {
49
+ throw new Error('Protocol error: required field "listenAddrs" was not found in object')
50
+ }
51
+
52
+ if (obj.observedAddr != null) {
53
+ writer.uint32(34)
54
+ writer.bytes(obj.observedAddr)
55
+ }
56
+
57
+ if (obj.protocols != null) {
58
+ for (const value of obj.protocols) {
59
+ writer.uint32(26)
60
+ writer.string(value)
61
+ }
62
+ } else {
63
+ throw new Error('Protocol error: required field "protocols" was not found in object')
64
+ }
65
+
66
+ if (obj.signedPeerRecord != null) {
67
+ writer.uint32(66)
68
+ writer.bytes(obj.signedPeerRecord)
69
+ }
70
+
71
+ if (opts.lengthDelimited !== false) {
72
+ writer.ldelim()
73
+ }
74
+ }, (reader, length) => {
75
+ const obj: any = {}
76
+
77
+ const end = length == null ? reader.len : reader.pos + length
78
+
79
+ while (reader.pos < end) {
80
+ const tag = reader.uint32()
81
+
82
+ switch (tag >>> 3) {
83
+ case 5:
84
+ obj.protocolVersion = reader.string()
85
+ break
86
+ case 6:
87
+ obj.agentVersion = reader.string()
88
+ break
89
+ case 1:
90
+ obj.publicKey = reader.bytes()
91
+ break
92
+ case 2:
93
+ obj.listenAddrs = obj.listenAddrs ?? []
94
+ obj.listenAddrs.push(reader.bytes())
95
+ break
96
+ case 4:
97
+ obj.observedAddr = reader.bytes()
98
+ break
99
+ case 3:
100
+ obj.protocols = obj.protocols ?? []
101
+ obj.protocols.push(reader.string())
102
+ break
103
+ case 8:
104
+ obj.signedPeerRecord = reader.bytes()
105
+ break
106
+ default:
107
+ reader.skipType(tag & 7)
108
+ break
109
+ }
110
+ }
111
+
112
+ obj.listenAddrs = obj.listenAddrs ?? []
113
+ obj.protocols = obj.protocols ?? []
114
+
115
+ if (obj.listenAddrs == null) {
116
+ throw new Error('Protocol error: value for required field "listenAddrs" was not found in protobuf')
117
+ }
118
+
119
+ if (obj.protocols == null) {
120
+ throw new Error('Protocol error: value for required field "protocols" was not found in protobuf')
121
+ }
122
+
123
+ return obj
124
+ })
125
+ }
126
+
127
+ return _codec
28
128
  }
29
129
 
30
130
  export const encode = (obj: Identify): Uint8Array => {
31
131
  return encodeMessage(obj, Identify.codec())
32
132
  }
33
133
 
34
- export const decode = (buf: Uint8Array): Identify => {
134
+ export const decode = (buf: Uint8Array | Uint8ArrayList): Identify => {
35
135
  return decodeMessage(buf, Identify.codec())
36
136
  }
37
137
  }
package/src/index.ts CHANGED
@@ -5,23 +5,23 @@ import type { Startable } from '@libp2p/interfaces/startable'
5
5
  import type { Multiaddr } from '@multiformats/multiaddr'
6
6
  import type { FaultTolerance } from './transport-manager.js'
7
7
  import type { IdentifyServiceInit } from './identify/index.js'
8
- import type { DualDHT } from '@libp2p/interfaces/dht'
8
+ import type { DualDHT } from '@libp2p/interface-dht'
9
9
  import type { Datastore } from 'interface-datastore'
10
- import type { PeerStore, PeerStoreInit } from '@libp2p/interfaces/peer-store'
11
- import type { PeerId } from '@libp2p/interfaces/peer-id'
10
+ import type { PeerStore, PeerStoreInit } from '@libp2p/interface-peer-store'
11
+ import type { PeerId } from '@libp2p/interface-peer-id'
12
12
  import type { AutoRelayConfig, RelayAdvertiseConfig } from './circuit/index.js'
13
- import type { PeerDiscovery } from '@libp2p/interfaces/peer-discovery'
14
- import type { Connection, ConnectionGater, ConnectionProtector, ProtocolStream } from '@libp2p/interfaces/connection'
15
- import type { Transport } from '@libp2p/interfaces/transport'
16
- import type { StreamMuxerFactory } from '@libp2p/interfaces/stream-muxer'
17
- import type { ConnectionEncrypter } from '@libp2p/interfaces/connection-encrypter'
18
- import type { PeerRouting } from '@libp2p/interfaces/peer-routing'
19
- import type { ContentRouting } from '@libp2p/interfaces/content-routing'
20
- import type { PubSub } from '@libp2p/interfaces/pubsub'
21
- import type { Registrar, StreamHandler } from '@libp2p/interfaces/registrar'
22
- import type { ConnectionManager } from '@libp2p/interfaces/connection-manager'
23
- import type { Metrics, MetricsInit } from '@libp2p/interfaces/metrics'
24
- import type { PeerInfo } from '@libp2p/interfaces/peer-info'
13
+ import type { PeerDiscovery } from '@libp2p/interface-peer-discovery'
14
+ import type { Connection, ConnectionGater, ConnectionProtector, Stream } from '@libp2p/interface-connection'
15
+ import type { Transport } from '@libp2p/interface-transport'
16
+ import type { StreamMuxerFactory } from '@libp2p/interface-stream-muxer'
17
+ import type { ConnectionEncrypter } from '@libp2p/interface-connection-encrypter'
18
+ import type { PeerRouting } from '@libp2p/interface-peer-routing'
19
+ import type { ContentRouting } from '@libp2p/interface-content-routing'
20
+ import type { PubSub } from '@libp2p/interface-pubsub'
21
+ import type { Registrar, StreamHandler, StreamHandlerOptions } from '@libp2p/interface-registrar'
22
+ import type { ConnectionManager } from '@libp2p/interface-connection-manager'
23
+ import type { Metrics, MetricsInit } from '@libp2p/interface-metrics'
24
+ import type { PeerInfo } from '@libp2p/interface-peer-info'
25
25
  import type { KeyChain } from './keychain/index.js'
26
26
  import type { ConnectionManagerInit } from './connection-manager/index.js'
27
27
  import type { PingServiceInit } from './ping/index.js'
@@ -50,6 +50,7 @@ export interface MetricsConfig {
50
50
  export interface HopConfig {
51
51
  enabled?: boolean
52
52
  active?: boolean
53
+ timeout: number
53
54
  }
54
55
 
55
56
  export interface RelayConfig {
@@ -177,7 +178,7 @@ export interface Libp2p extends Startable, EventEmitter<Libp2pEvents> {
177
178
  * If successful, the known metadata of the peer will be added to the nodes `peerStore`,
178
179
  * and the `MuxedStream` will be returned together with the successful negotiated protocol.
179
180
  */
180
- dialProtocol: (peer: PeerId | Multiaddr, protocols: string | string[], options?: AbortOptions) => Promise<ProtocolStream>
181
+ dialProtocol: (peer: PeerId | Multiaddr, protocols: string | string[], options?: AbortOptions) => Promise<Stream>
181
182
 
182
183
  /**
183
184
  * Disconnects all connections to the given `peer`
@@ -187,7 +188,7 @@ export interface Libp2p extends Startable, EventEmitter<Libp2pEvents> {
187
188
  /**
188
189
  * Registers the `handler` for each protocol
189
190
  */
190
- handle: (protocol: string | string[], handler: StreamHandler) => Promise<void>
191
+ handle: (protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions) => Promise<void>
191
192
 
192
193
  /**
193
194
  * Removes the handler for each protocol. The protocol
@@ -1,12 +1,13 @@
1
1
  import { logger } from '@libp2p/logger'
2
2
  import { handshake } from 'it-handshake'
3
3
  import * as lp from 'it-length-prefixed'
4
- import { UnexpectedPeerError, InvalidCryptoExchangeError } from '@libp2p/interfaces/connection-encrypter/errors'
4
+ import { UnexpectedPeerError, InvalidCryptoExchangeError } from '@libp2p/interface-connection-encrypter/errors'
5
5
  import { Exchange, KeyType } from './pb/proto.js'
6
- import type { PeerId } from '@libp2p/interfaces/peer-id'
6
+ import type { PeerId } from '@libp2p/interface-peer-id'
7
7
  import { peerIdFromBytes, peerIdFromKeys } from '@libp2p/peer-id'
8
- import type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interfaces/connection-encrypter'
8
+ import type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interface-connection-encrypter'
9
9
  import type { Duplex } from 'it-stream-types'
10
+ import map from 'it-map'
10
11
 
11
12
  const log = logger('libp2p:plaintext')
12
13
  const PROTOCOL = '/plaintext/2.0.0'
@@ -39,7 +40,7 @@ async function encrypt (localId: PeerId, conn: Duplex<Uint8Array>, remoteId?: Pe
39
40
  Type: type,
40
41
  Data: localId.publicKey ?? new Uint8Array(0)
41
42
  }
42
- }).slice()
43
+ }).subarray()
43
44
  )
44
45
 
45
46
  log('write pubkey exchange to peer %p', remoteId)
@@ -47,7 +48,7 @@ async function encrypt (localId: PeerId, conn: Duplex<Uint8Array>, remoteId?: Pe
47
48
  // Get the Exchange message
48
49
  // @ts-expect-error needs to be generator
49
50
  const response = (await lp.decode.fromReader(shake.reader).next()).value
50
- const id = Exchange.decode(response.slice())
51
+ const id = Exchange.decode(response)
51
52
  log('read pubkey exchange from peer %p', remoteId)
52
53
 
53
54
  let peerId
@@ -81,8 +82,12 @@ async function encrypt (localId: PeerId, conn: Duplex<Uint8Array>, remoteId?: Pe
81
82
  log('plaintext key exchange completed successfully with peer %p', peerId)
82
83
 
83
84
  shake.rest()
85
+
84
86
  return {
85
- conn: shake.stream,
87
+ conn: {
88
+ sink: shake.stream.sink,
89
+ source: map(shake.stream.source, (buf) => buf.subarray())
90
+ },
86
91
  remotePeer: peerId,
87
92
  remoteEarlyData: new Uint8Array()
88
93
  }
@@ -1,7 +1,8 @@
1
1
  /* eslint-disable import/export */
2
2
  /* eslint-disable @typescript-eslint/no-namespace */
3
3
 
4
- import { encodeMessage, decodeMessage, message, bytes, enumeration } from 'protons-runtime'
4
+ import { encodeMessage, decodeMessage, message, enumeration } from 'protons-runtime'
5
+ import type { Uint8ArrayList } from 'uint8arraylist'
5
6
  import type { Codec } from 'protons-runtime'
6
7
 
7
8
  export interface Exchange {
@@ -10,18 +11,61 @@ export interface Exchange {
10
11
  }
11
12
 
12
13
  export namespace Exchange {
14
+ let _codec: Codec<Exchange>
15
+
13
16
  export const codec = (): Codec<Exchange> => {
14
- return message<Exchange>({
15
- 1: { name: 'id', codec: bytes, optional: true },
16
- 2: { name: 'pubkey', codec: PublicKey.codec(), optional: true }
17
- })
17
+ if (_codec == null) {
18
+ _codec = message<Exchange>((obj, writer, opts = {}) => {
19
+ if (opts.lengthDelimited !== false) {
20
+ writer.fork()
21
+ }
22
+
23
+ if (obj.id != null) {
24
+ writer.uint32(10)
25
+ writer.bytes(obj.id)
26
+ }
27
+
28
+ if (obj.pubkey != null) {
29
+ writer.uint32(18)
30
+ PublicKey.codec().encode(obj.pubkey, writer)
31
+ }
32
+
33
+ if (opts.lengthDelimited !== false) {
34
+ writer.ldelim()
35
+ }
36
+ }, (reader, length) => {
37
+ const obj: any = {}
38
+
39
+ const end = length == null ? reader.len : reader.pos + length
40
+
41
+ while (reader.pos < end) {
42
+ const tag = reader.uint32()
43
+
44
+ switch (tag >>> 3) {
45
+ case 1:
46
+ obj.id = reader.bytes()
47
+ break
48
+ case 2:
49
+ obj.pubkey = PublicKey.codec().decode(reader, reader.uint32())
50
+ break
51
+ default:
52
+ reader.skipType(tag & 7)
53
+ break
54
+ }
55
+ }
56
+
57
+ return obj
58
+ })
59
+ }
60
+
61
+ return _codec
18
62
  }
19
63
 
20
64
  export const encode = (obj: Exchange): Uint8Array => {
21
65
  return encodeMessage(obj, Exchange.codec())
22
66
  }
23
67
 
24
- export const decode = (buf: Uint8Array): Exchange => {
68
+ export const decode = (buf: Uint8Array | Uint8ArrayList): Exchange => {
25
69
  return decodeMessage(buf, Exchange.codec())
26
70
  }
27
71
  }
@@ -42,7 +86,7 @@ enum __KeyTypeValues {
42
86
 
43
87
  export namespace KeyType {
44
88
  export const codec = () => {
45
- return enumeration<typeof KeyType>(__KeyTypeValues)
89
+ return enumeration<KeyType>(__KeyTypeValues)
46
90
  }
47
91
  }
48
92
  export interface PublicKey {
@@ -51,18 +95,73 @@ export interface PublicKey {
51
95
  }
52
96
 
53
97
  export namespace PublicKey {
98
+ let _codec: Codec<PublicKey>
99
+
54
100
  export const codec = (): Codec<PublicKey> => {
55
- return message<PublicKey>({
56
- 1: { name: 'Type', codec: KeyType.codec() },
57
- 2: { name: 'Data', codec: bytes }
58
- })
101
+ if (_codec == null) {
102
+ _codec = message<PublicKey>((obj, writer, opts = {}) => {
103
+ if (opts.lengthDelimited !== false) {
104
+ writer.fork()
105
+ }
106
+
107
+ if (obj.Type != null) {
108
+ writer.uint32(8)
109
+ KeyType.codec().encode(obj.Type, writer)
110
+ } else {
111
+ throw new Error('Protocol error: required field "Type" was not found in object')
112
+ }
113
+
114
+ if (obj.Data != null) {
115
+ writer.uint32(18)
116
+ writer.bytes(obj.Data)
117
+ } else {
118
+ throw new Error('Protocol error: required field "Data" was not found in object')
119
+ }
120
+
121
+ if (opts.lengthDelimited !== false) {
122
+ writer.ldelim()
123
+ }
124
+ }, (reader, length) => {
125
+ const obj: any = {}
126
+
127
+ const end = length == null ? reader.len : reader.pos + length
128
+
129
+ while (reader.pos < end) {
130
+ const tag = reader.uint32()
131
+
132
+ switch (tag >>> 3) {
133
+ case 1:
134
+ obj.Type = KeyType.codec().decode(reader)
135
+ break
136
+ case 2:
137
+ obj.Data = reader.bytes()
138
+ break
139
+ default:
140
+ reader.skipType(tag & 7)
141
+ break
142
+ }
143
+ }
144
+
145
+ if (obj.Type == null) {
146
+ throw new Error('Protocol error: value for required field "Type" was not found in protobuf')
147
+ }
148
+
149
+ if (obj.Data == null) {
150
+ throw new Error('Protocol error: value for required field "Data" was not found in protobuf')
151
+ }
152
+
153
+ return obj
154
+ })
155
+ }
156
+
157
+ return _codec
59
158
  }
60
159
 
61
160
  export const encode = (obj: PublicKey): Uint8Array => {
62
161
  return encodeMessage(obj, PublicKey.codec())
63
162
  }
64
163
 
65
- export const decode = (buf: Uint8Array): PublicKey => {
164
+ export const decode = (buf: Uint8Array | Uint8ArrayList): PublicKey => {
66
165
  return decodeMessage(buf, PublicKey.codec())
67
166
  }
68
167
  }
@@ -10,8 +10,8 @@ import { codes } from '../errors.js'
10
10
  import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
11
11
  import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
12
12
  import { generateKeyPair, importKey, unmarshalPrivateKey } from '@libp2p/crypto/keys'
13
- import type { PeerId } from '@libp2p/interfaces/peer-id'
14
- import type { Components } from '@libp2p/interfaces/components'
13
+ import type { PeerId } from '@libp2p/interface-peer-id'
14
+ import type { Components } from '@libp2p/components'
15
15
  import { pbkdf2, randomBytes } from '@libp2p/crypto'
16
16
 
17
17
  const log = logger('libp2p:keychain')
package/src/libp2p.ts CHANGED
@@ -27,25 +27,25 @@ import { DHTPeerRouting } from './dht/dht-peer-routing.js'
27
27
  import { PersistentPeerStore } from '@libp2p/peer-store'
28
28
  import { DHTContentRouting } from './dht/dht-content-routing.js'
29
29
  import { AutoDialer } from './connection-manager/dialer/auto-dialer.js'
30
- import { Initializable, Components, isInitializable } from '@libp2p/interfaces/components'
31
- import type { PeerId } from '@libp2p/interfaces/peer-id'
32
- import type { Connection } from '@libp2p/interfaces/connection'
33
- import type { PeerRouting } from '@libp2p/interfaces/peer-routing'
34
- import type { ContentRouting } from '@libp2p/interfaces/content-routing'
35
- import type { PubSub } from '@libp2p/interfaces/pubsub'
36
- import type { Registrar, StreamHandler } from '@libp2p/interfaces/registrar'
37
- import type { ConnectionManager } from '@libp2p/interfaces/connection-manager'
38
- import type { PeerInfo } from '@libp2p/interfaces/peer-info'
30
+ import { Initializable, Components, isInitializable } from '@libp2p/components'
31
+ import type { PeerId } from '@libp2p/interface-peer-id'
32
+ import type { Connection } from '@libp2p/interface-connection'
33
+ import type { PeerRouting } from '@libp2p/interface-peer-routing'
34
+ import type { ContentRouting } from '@libp2p/interface-content-routing'
35
+ import type { PubSub } from '@libp2p/interface-pubsub'
36
+ import type { Registrar, StreamHandler, StreamHandlerOptions } from '@libp2p/interface-registrar'
37
+ import type { ConnectionManager } from '@libp2p/interface-connection-manager'
38
+ import type { PeerInfo } from '@libp2p/interface-peer-info'
39
39
  import type { Libp2p, Libp2pEvents, Libp2pInit, Libp2pOptions } from './index.js'
40
40
  import { validateConfig } from './config.js'
41
41
  import { createEd25519PeerId } from '@libp2p/peer-id-factory'
42
- import type { PeerStore } from '@libp2p/interfaces/peer-store'
43
- import type { DualDHT } from '@libp2p/interfaces/dht'
42
+ import type { PeerStore } from '@libp2p/interface-peer-store'
43
+ import type { DualDHT } from '@libp2p/interface-dht'
44
44
  import { concat as uint8ArrayConcat } from 'uint8arrays/concat'
45
45
  import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
46
46
  import errCode from 'err-code'
47
47
  import { unmarshalPublicKey } from '@libp2p/crypto/keys'
48
- import type { Metrics } from '@libp2p/interfaces/metrics'
48
+ import type { Metrics } from '@libp2p/interface-metrics'
49
49
  import { DummyDHT } from './dht/dummy-dht.js'
50
50
  import { DummyPubSub } from './pubsub/dummy-pubsub.js'
51
51
  import { PeerSet } from '@libp2p/peer-collections'
@@ -124,7 +124,8 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
124
124
  // Set up the Upgrader
125
125
  this.components.setUpgrader(new DefaultUpgrader(this.components, {
126
126
  connectionEncryption: (init.connectionEncryption ?? []).map(component => this.configureComponent(component)),
127
- muxers: (init.streamMuxers ?? []).map(component => this.configureComponent(component))
127
+ muxers: (init.streamMuxers ?? []).map(component => this.configureComponent(component)),
128
+ inboundUpgradeTimeout: init.connectionManager.inboundUpgradeTimeout
128
129
  }))
129
130
 
130
131
  // Create the Connection Manager
@@ -217,7 +218,7 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
217
218
  })))
218
219
 
219
220
  if (init.relay.enabled) {
220
- this.components.getTransportManager().add(this.configureComponent(new Circuit()))
221
+ this.components.getTransportManager().add(this.configureComponent(new Circuit(init.relay)))
221
222
 
222
223
  this.configureComponent(new Relay(this.components, {
223
224
  addressSorter: init.connectionManager.addressSorter,
@@ -309,18 +310,6 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
309
310
  )
310
311
 
311
312
  log('libp2p has started')
312
-
313
- // Once we start, emit any peers we may have already discovered
314
- // TODO: this should be removed, as we already discovered these peers in the past
315
- await this.components.getPeerStore().forEach(peer => {
316
- this.dispatchEvent(new CustomEvent<PeerInfo>('peer:discovery', {
317
- detail: {
318
- id: peer.id,
319
- multiaddrs: peer.addresses.map(addr => addr.multiaddr),
320
- protocols: peer.protocols
321
- }
322
- }))
323
- })
324
313
  } catch (err: any) {
325
314
  log.error('An error occurred starting libp2p', err)
326
315
  await this.stop()
@@ -490,12 +479,28 @@ export class Libp2pNode extends EventEmitter<Libp2pEvents> implements Libp2p {
490
479
  return await this.pingService.ping(id, options)
491
480
  }
492
481
 
493
- async handle (protocols: string | string[], handler: StreamHandler): Promise<void> {
494
- return await this.components.getRegistrar().handle(protocols, handler)
482
+ async handle (protocols: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void> {
483
+ if (!Array.isArray(protocols)) {
484
+ protocols = [protocols]
485
+ }
486
+
487
+ await Promise.all(
488
+ protocols.map(async protocol => {
489
+ await this.components.getRegistrar().handle(protocol, handler, options)
490
+ })
491
+ )
495
492
  }
496
493
 
497
494
  async unhandle (protocols: string[] | string): Promise<void> {
498
- return await this.components.getRegistrar().unhandle(protocols)
495
+ if (!Array.isArray(protocols)) {
496
+ protocols = [protocols]
497
+ }
498
+
499
+ await Promise.all(
500
+ protocols.map(async protocol => {
501
+ await this.components.getRegistrar().unhandle(protocol)
502
+ })
503
+ )
499
504
  }
500
505
 
501
506
  /**
@@ -3,10 +3,9 @@ import each from 'it-foreach'
3
3
  import LRU from 'hashlru'
4
4
  import { METRICS as defaultOptions } from '../constants.js'
5
5
  import { DefaultStats, StatsInit } from './stats.js'
6
- import type { ComponentMetricsUpdate, Metrics, Stats, TrackStreamOptions } from '@libp2p/interfaces/metrics'
7
- import type { PeerId } from '@libp2p/interfaces/peer-id'
6
+ import type { ComponentMetricsUpdate, Metrics, Stats, TrackedMetric, TrackStreamOptions } from '@libp2p/interface-metrics'
7
+ import type { PeerId } from '@libp2p/interface-peer-id'
8
8
  import type { Startable } from '@libp2p/interfaces/startable'
9
- import type { Duplex } from 'it-stream-types'
10
9
 
11
10
  const initialCounters: ['dataReceived', 'dataSent'] = [
12
11
  'dataReceived',
@@ -41,7 +40,7 @@ export class DefaultMetrics implements Metrics, Startable {
41
40
  private readonly protocolStats: Map<string, DefaultStats>
42
41
  private readonly oldPeers: ReturnType<typeof LRU>
43
42
  private running: boolean
44
- private readonly systems: Map<string, Map<string, Map<string, number>>>
43
+ private readonly systems: Map<string, Map<string, Map<string, TrackedMetric>>>
45
44
  private readonly statsInit: StatsInit
46
45
 
47
46
  constructor (init: MetricsInit) {
@@ -115,7 +114,7 @@ export class DefaultMetrics implements Metrics, Startable {
115
114
  }
116
115
 
117
116
  updateComponentMetric (update: ComponentMetricsUpdate) {
118
- const { system = 'libp2p', component, metric, value } = update
117
+ const { system = 'libp2p', component, metric, value, label, help } = update
119
118
 
120
119
  if (!this.systems.has(system)) {
121
120
  this.systems.set(system, new Map())
@@ -137,7 +136,11 @@ export class DefaultMetrics implements Metrics, Startable {
137
136
  throw new Error('Unknown metric component')
138
137
  }
139
138
 
140
- componentMetrics.set(metric, value)
139
+ componentMetrics.set(metric, {
140
+ label,
141
+ help,
142
+ calculate: typeof value !== 'function' ? () => value : value
143
+ })
141
144
  }
142
145
 
143
146
  /**
@@ -259,11 +262,11 @@ export class DefaultMetrics implements Metrics, Startable {
259
262
  * When the `PeerId` is known, `Metrics.updatePlaceholder` should be called
260
263
  * with the placeholder string returned from here, and the known `PeerId`.
261
264
  */
262
- trackStream <T extends Duplex<Uint8Array>> (opts: TrackStreamOptions<T>): T {
265
+ trackStream (opts: TrackStreamOptions): void {
263
266
  const { stream, remotePeer, protocol } = opts
264
267
 
265
268
  if (!this.running) {
266
- return stream
269
+ return
267
270
  }
268
271
 
269
272
  const source = stream.source
@@ -271,7 +274,7 @@ export class DefaultMetrics implements Metrics, Startable {
271
274
  remotePeer,
272
275
  protocol,
273
276
  direction: 'in',
274
- dataLength: chunk.length
277
+ dataLength: chunk.byteLength
275
278
  }))
276
279
 
277
280
  const sink = stream.sink
@@ -283,14 +286,12 @@ export class DefaultMetrics implements Metrics, Startable {
283
286
  remotePeer,
284
287
  protocol,
285
288
  direction: 'out',
286
- dataLength: chunk.length
289
+ dataLength: chunk.byteLength
287
290
  })
288
291
  }),
289
292
  sink
290
293
  )
291
294
  }
292
-
293
- return stream
294
295
  }
295
296
  }
296
297
 
@@ -1,4 +1,4 @@
1
- import type { MovingAverage } from '@libp2p/interfaces/metrics'
1
+ import type { MovingAverage } from '@libp2p/interface-metrics'
2
2
 
3
3
  export class DefaultMovingAverage {
4
4
  public movingAverage: number
@@ -2,7 +2,7 @@ import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'
2
2
  import { createMovingAverage } from './moving-average.js'
3
3
  // @ts-expect-error no types
4
4
  import retimer from 'retimer'
5
- import type { MovingAverages, Stats, TransferStats } from '@libp2p/interfaces/metrics'
5
+ import type { MovingAverages, Stats, TransferStats } from '@libp2p/interface-metrics'
6
6
 
7
7
  export interface StatsEvents {
8
8
  'update': CustomEvent<TransferStats>
@@ -8,7 +8,7 @@ import errCode from 'err-code'
8
8
  import { codes } from './errors.js'
9
9
  import { isLoopback } from '@libp2p/utils/multiaddr/is-loopback'
10
10
  import type { Startable } from '@libp2p/interfaces/startable'
11
- import type { Components } from '@libp2p/interfaces/components'
11
+ import type { Components } from '@libp2p/components'
12
12
 
13
13
  const log = logger('libp2p:nat')
14
14
  const DEFAULT_TTL = 7200
@@ -1,5 +1,5 @@
1
1
  import { RecordEnvelope, PeerRecord } from '@libp2p/peer-record'
2
- import type { Components } from '@libp2p/interfaces/components'
2
+ import type { Components } from '@libp2p/components'
3
3
  import type { Startable } from '@libp2p/interfaces/startable'
4
4
  import { logger } from '@libp2p/logger'
5
5
  import { protocols } from '@multiformats/multiaddr'