libp2p 0.37.3 → 0.38.0-57ef754

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 (193) hide show
  1. package/README.md +2 -1
  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/auto-relay.js +4 -0
  7. package/dist/src/circuit/auto-relay.js.map +1 -1
  8. package/dist/src/circuit/circuit/hop.d.ts +7 -5
  9. package/dist/src/circuit/circuit/hop.d.ts.map +1 -1
  10. package/dist/src/circuit/circuit/hop.js +8 -4
  11. package/dist/src/circuit/circuit/hop.js.map +1 -1
  12. package/dist/src/circuit/circuit/stop.d.ts +6 -4
  13. package/dist/src/circuit/circuit/stop.d.ts.map +1 -1
  14. package/dist/src/circuit/circuit/stop.js +4 -2
  15. package/dist/src/circuit/circuit/stop.js.map +1 -1
  16. package/dist/src/circuit/circuit/stream-handler.d.ts +3 -2
  17. package/dist/src/circuit/circuit/stream-handler.d.ts.map +1 -1
  18. package/dist/src/circuit/circuit/stream-handler.js +2 -2
  19. package/dist/src/circuit/circuit/stream-handler.js.map +1 -1
  20. package/dist/src/circuit/index.d.ts +4 -12
  21. package/dist/src/circuit/index.d.ts.map +1 -1
  22. package/dist/src/circuit/index.js.map +1 -1
  23. package/dist/src/circuit/listener.d.ts +3 -3
  24. package/dist/src/circuit/listener.d.ts.map +1 -1
  25. package/dist/src/circuit/pb/index.d.ts +5 -4
  26. package/dist/src/circuit/pb/index.d.ts.map +1 -1
  27. package/dist/src/circuit/pb/index.js +107 -11
  28. package/dist/src/circuit/pb/index.js.map +1 -1
  29. package/dist/src/circuit/transport.d.ts +8 -5
  30. package/dist/src/circuit/transport.d.ts.map +1 -1
  31. package/dist/src/circuit/transport.js +81 -59
  32. package/dist/src/circuit/transport.js.map +1 -1
  33. package/dist/src/config.d.ts.map +1 -1
  34. package/dist/src/config.js +27 -4
  35. package/dist/src/config.js.map +1 -1
  36. package/dist/src/connection-manager/auto-dialler.d.ts +1 -1
  37. package/dist/src/connection-manager/auto-dialler.d.ts.map +1 -1
  38. package/dist/src/connection-manager/dialer/auto-dialer.d.ts +2 -2
  39. package/dist/src/connection-manager/dialer/auto-dialer.d.ts.map +1 -1
  40. package/dist/src/connection-manager/dialer/auto-dialer.js +6 -0
  41. package/dist/src/connection-manager/dialer/auto-dialer.js.map +1 -1
  42. package/dist/src/connection-manager/dialer/dial-request.d.ts +1 -1
  43. package/dist/src/connection-manager/dialer/dial-request.d.ts.map +1 -1
  44. package/dist/src/connection-manager/dialer/index.d.ts +9 -9
  45. package/dist/src/connection-manager/dialer/index.d.ts.map +1 -1
  46. package/dist/src/connection-manager/dialer/index.js +15 -12
  47. package/dist/src/connection-manager/dialer/index.js.map +1 -1
  48. package/dist/src/connection-manager/index.d.ts +20 -16
  49. package/dist/src/connection-manager/index.d.ts.map +1 -1
  50. package/dist/src/connection-manager/index.js +185 -65
  51. package/dist/src/connection-manager/index.js.map +1 -1
  52. package/dist/src/constants.d.ts +4 -0
  53. package/dist/src/constants.d.ts.map +1 -1
  54. package/dist/src/constants.js +4 -0
  55. package/dist/src/constants.js.map +1 -1
  56. package/dist/src/content-routing/index.d.ts +4 -4
  57. package/dist/src/content-routing/index.d.ts.map +1 -1
  58. package/dist/src/content-routing/utils.d.ts +2 -2
  59. package/dist/src/content-routing/utils.d.ts.map +1 -1
  60. package/dist/src/dht/dht-content-routing.d.ts +3 -3
  61. package/dist/src/dht/dht-content-routing.d.ts.map +1 -1
  62. package/dist/src/dht/dht-peer-routing.d.ts +5 -5
  63. package/dist/src/dht/dht-peer-routing.d.ts.map +1 -1
  64. package/dist/src/dht/dummy-dht.d.ts +3 -3
  65. package/dist/src/dht/dummy-dht.d.ts.map +1 -1
  66. package/dist/src/dht/dummy-dht.js +1 -1
  67. package/dist/src/dht/dummy-dht.js.map +1 -1
  68. package/dist/src/errors.d.ts +4 -1
  69. package/dist/src/errors.d.ts.map +1 -1
  70. package/dist/src/errors.js +3 -0
  71. package/dist/src/errors.js.map +1 -1
  72. package/dist/src/fetch/index.d.ts +11 -4
  73. package/dist/src/fetch/index.d.ts.map +1 -1
  74. package/dist/src/fetch/index.js +82 -41
  75. package/dist/src/fetch/index.js.map +1 -1
  76. package/dist/src/fetch/pb/proto.d.ts +4 -3
  77. package/dist/src/fetch/pb/proto.d.ts.map +1 -1
  78. package/dist/src/fetch/pb/proto.js +88 -8
  79. package/dist/src/fetch/pb/proto.js.map +1 -1
  80. package/dist/src/get-peer.d.ts +2 -2
  81. package/dist/src/get-peer.d.ts.map +1 -1
  82. package/dist/src/get-peer.js +1 -1
  83. package/dist/src/get-peer.js.map +1 -1
  84. package/dist/src/identify/index.d.ts +8 -8
  85. package/dist/src/identify/index.d.ts.map +1 -1
  86. package/dist/src/identify/index.js +49 -34
  87. package/dist/src/identify/index.js.map +1 -1
  88. package/dist/src/identify/pb/message.d.ts +2 -1
  89. package/dist/src/identify/pb/message.d.ts.map +1 -1
  90. package/dist/src/identify/pb/message.js +94 -10
  91. package/dist/src/identify/pb/message.js.map +1 -1
  92. package/dist/src/index.d.ts +18 -22
  93. package/dist/src/index.d.ts.map +1 -1
  94. package/dist/src/index.js.map +1 -1
  95. package/dist/src/insecure/index.d.ts +2 -2
  96. package/dist/src/insecure/index.d.ts.map +1 -1
  97. package/dist/src/insecure/index.js +8 -4
  98. package/dist/src/insecure/index.js.map +1 -1
  99. package/dist/src/insecure/pb/proto.d.ts +4 -3
  100. package/dist/src/insecure/pb/proto.d.ts.map +1 -1
  101. package/dist/src/insecure/pb/proto.js +89 -9
  102. package/dist/src/insecure/pb/proto.js.map +1 -1
  103. package/dist/src/keychain/index.d.ts +8 -3
  104. package/dist/src/keychain/index.d.ts.map +1 -1
  105. package/dist/src/keychain/index.js +19 -2
  106. package/dist/src/keychain/index.js.map +1 -1
  107. package/dist/src/libp2p.d.ts +14 -19
  108. package/dist/src/libp2p.d.ts.map +1 -1
  109. package/dist/src/libp2p.js +17 -32
  110. package/dist/src/libp2p.js.map +1 -1
  111. package/dist/src/metrics/index.d.ts +4 -5
  112. package/dist/src/metrics/index.d.ts.map +1 -1
  113. package/dist/src/metrics/index.js +9 -6
  114. package/dist/src/metrics/index.js.map +1 -1
  115. package/dist/src/metrics/moving-average.d.ts +1 -1
  116. package/dist/src/metrics/moving-average.d.ts.map +1 -1
  117. package/dist/src/metrics/stats.d.ts +1 -1
  118. package/dist/src/metrics/stats.d.ts.map +1 -1
  119. package/dist/src/nat-manager.d.ts +1 -1
  120. package/dist/src/nat-manager.d.ts.map +1 -1
  121. package/dist/src/peer-record-updater.d.ts +1 -1
  122. package/dist/src/peer-record-updater.d.ts.map +1 -1
  123. package/dist/src/peer-routing.d.ts +4 -4
  124. package/dist/src/peer-routing.d.ts.map +1 -1
  125. package/dist/src/ping/index.d.ts +10 -3
  126. package/dist/src/ping/index.d.ts.map +1 -1
  127. package/dist/src/ping/index.js +32 -9
  128. package/dist/src/ping/index.js.map +1 -1
  129. package/dist/src/pnet/index.d.ts +1 -2
  130. package/dist/src/pnet/index.d.ts.map +1 -1
  131. package/dist/src/pnet/index.js +2 -1
  132. package/dist/src/pnet/index.js.map +1 -1
  133. package/dist/src/pubsub/dummy-pubsub.d.ts +2 -2
  134. package/dist/src/pubsub/dummy-pubsub.d.ts.map +1 -1
  135. package/dist/src/registrar.d.ts +10 -8
  136. package/dist/src/registrar.d.ts.map +1 -1
  137. package/dist/src/registrar.js +63 -44
  138. package/dist/src/registrar.js.map +1 -1
  139. package/dist/src/transport-manager.d.ts +3 -3
  140. package/dist/src/transport-manager.d.ts.map +1 -1
  141. package/dist/src/upgrader.d.ts +12 -6
  142. package/dist/src/upgrader.d.ts.map +1 -1
  143. package/dist/src/upgrader.js +183 -82
  144. package/dist/src/upgrader.js.map +1 -1
  145. package/dist/src/version.d.ts.map +1 -1
  146. package/dist/src/version.js.map +1 -1
  147. package/package.json +66 -42
  148. package/src/address-manager/index.ts +2 -2
  149. package/src/circuit/README.md +2 -2
  150. package/src/circuit/auto-relay.ts +10 -4
  151. package/src/circuit/circuit/hop.ts +20 -11
  152. package/src/circuit/circuit/stop.ts +10 -5
  153. package/src/circuit/circuit/stream-handler.ts +6 -5
  154. package/src/circuit/index.ts +4 -13
  155. package/src/circuit/listener.ts +3 -3
  156. package/src/circuit/pb/index.ts +133 -15
  157. package/src/circuit/transport.ts +92 -63
  158. package/src/config.ts +27 -4
  159. package/src/connection-manager/auto-dialler.ts +1 -1
  160. package/src/connection-manager/dialer/auto-dialer.ts +8 -2
  161. package/src/connection-manager/dialer/dial-request.ts +1 -1
  162. package/src/connection-manager/dialer/index.ts +19 -16
  163. package/src/connection-manager/index.ts +239 -82
  164. package/src/constants.ts +5 -0
  165. package/src/content-routing/index.ts +2 -2
  166. package/src/content-routing/utils.ts +2 -2
  167. package/src/dht/dht-content-routing.ts +2 -2
  168. package/src/dht/dht-peer-routing.ts +3 -3
  169. package/src/dht/dummy-dht.ts +3 -3
  170. package/src/errors.ts +4 -1
  171. package/src/fetch/index.ts +120 -53
  172. package/src/fetch/pb/proto.ts +109 -11
  173. package/src/get-peer.ts +3 -3
  174. package/src/identify/index.ts +64 -47
  175. package/src/identify/pb/message.ts +111 -11
  176. package/src/index.ts +18 -23
  177. package/src/insecure/index.ts +11 -6
  178. package/src/insecure/pb/proto.ts +111 -12
  179. package/src/keychain/index.ts +29 -5
  180. package/src/libp2p.ts +34 -45
  181. package/src/metrics/index.ts +13 -12
  182. package/src/metrics/moving-average.ts +1 -1
  183. package/src/metrics/stats.ts +1 -1
  184. package/src/nat-manager.ts +1 -1
  185. package/src/peer-record-updater.ts +1 -1
  186. package/src/peer-routing.ts +4 -4
  187. package/src/ping/index.ts +48 -15
  188. package/src/pnet/index.ts +3 -2
  189. package/src/pubsub/dummy-pubsub.ts +2 -2
  190. package/src/registrar.ts +79 -55
  191. package/src/transport-manager.ts +3 -3
  192. package/src/upgrader.ts +223 -93
  193. 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 { enumeration, encodeMessage, decodeMessage, message, bytes } from 'protons-runtime'
4
+ import { enumeration, 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 CircuitRelay {
@@ -52,7 +53,7 @@ export namespace CircuitRelay {
52
53
 
53
54
  export namespace Status {
54
55
  export const codec = () => {
55
- return enumeration<typeof Status>(__StatusValues)
56
+ return enumeration<Status>(__StatusValues)
56
57
  }
57
58
  }
58
59
 
@@ -72,7 +73,7 @@ export namespace CircuitRelay {
72
73
 
73
74
  export namespace Type {
74
75
  export const codec = () => {
75
- return enumeration<typeof Type>(__TypeValues)
76
+ return enumeration<Type>(__TypeValues)
76
77
  }
77
78
  }
78
79
 
@@ -82,36 +83,153 @@ export namespace CircuitRelay {
82
83
  }
83
84
 
84
85
  export namespace Peer {
86
+ let _codec: Codec<Peer>
87
+
85
88
  export const codec = (): Codec<Peer> => {
86
- return message<Peer>({
87
- 1: { name: 'id', codec: bytes },
88
- 2: { name: 'addrs', codec: bytes, repeats: true }
89
- })
89
+ if (_codec == null) {
90
+ _codec = message<Peer>((obj, writer, opts = {}) => {
91
+ if (opts.lengthDelimited !== false) {
92
+ writer.fork()
93
+ }
94
+
95
+ if (obj.id != null) {
96
+ writer.uint32(10)
97
+ writer.bytes(obj.id)
98
+ } else {
99
+ throw new Error('Protocol error: required field "id" was not found in object')
100
+ }
101
+
102
+ if (obj.addrs != null) {
103
+ for (const value of obj.addrs) {
104
+ writer.uint32(18)
105
+ writer.bytes(value)
106
+ }
107
+ } else {
108
+ throw new Error('Protocol error: required field "addrs" was not found in object')
109
+ }
110
+
111
+ if (opts.lengthDelimited !== false) {
112
+ writer.ldelim()
113
+ }
114
+ }, (reader, length) => {
115
+ const obj: any = {}
116
+
117
+ const end = length == null ? reader.len : reader.pos + length
118
+
119
+ while (reader.pos < end) {
120
+ const tag = reader.uint32()
121
+
122
+ switch (tag >>> 3) {
123
+ case 1:
124
+ obj.id = reader.bytes()
125
+ break
126
+ case 2:
127
+ obj.addrs = obj.addrs ?? []
128
+ obj.addrs.push(reader.bytes())
129
+ break
130
+ default:
131
+ reader.skipType(tag & 7)
132
+ break
133
+ }
134
+ }
135
+
136
+ obj.addrs = obj.addrs ?? []
137
+
138
+ if (obj.id == null) {
139
+ throw new Error('Protocol error: value for required field "id" was not found in protobuf')
140
+ }
141
+
142
+ if (obj.addrs == null) {
143
+ throw new Error('Protocol error: value for required field "addrs" was not found in protobuf')
144
+ }
145
+
146
+ return obj
147
+ })
148
+ }
149
+
150
+ return _codec
90
151
  }
91
152
 
92
153
  export const encode = (obj: Peer): Uint8Array => {
93
154
  return encodeMessage(obj, Peer.codec())
94
155
  }
95
156
 
96
- export const decode = (buf: Uint8Array): Peer => {
157
+ export const decode = (buf: Uint8Array | Uint8ArrayList): Peer => {
97
158
  return decodeMessage(buf, Peer.codec())
98
159
  }
99
160
  }
100
161
 
162
+ let _codec: Codec<CircuitRelay>
163
+
101
164
  export const codec = (): Codec<CircuitRelay> => {
102
- return message<CircuitRelay>({
103
- 1: { name: 'type', codec: CircuitRelay.Type.codec(), optional: true },
104
- 2: { name: 'srcPeer', codec: CircuitRelay.Peer.codec(), optional: true },
105
- 3: { name: 'dstPeer', codec: CircuitRelay.Peer.codec(), optional: true },
106
- 4: { name: 'code', codec: CircuitRelay.Status.codec(), optional: true }
107
- })
165
+ if (_codec == null) {
166
+ _codec = message<CircuitRelay>((obj, writer, opts = {}) => {
167
+ if (opts.lengthDelimited !== false) {
168
+ writer.fork()
169
+ }
170
+
171
+ if (obj.type != null) {
172
+ writer.uint32(8)
173
+ CircuitRelay.Type.codec().encode(obj.type, writer)
174
+ }
175
+
176
+ if (obj.srcPeer != null) {
177
+ writer.uint32(18)
178
+ CircuitRelay.Peer.codec().encode(obj.srcPeer, writer)
179
+ }
180
+
181
+ if (obj.dstPeer != null) {
182
+ writer.uint32(26)
183
+ CircuitRelay.Peer.codec().encode(obj.dstPeer, writer)
184
+ }
185
+
186
+ if (obj.code != null) {
187
+ writer.uint32(32)
188
+ CircuitRelay.Status.codec().encode(obj.code, writer)
189
+ }
190
+
191
+ if (opts.lengthDelimited !== false) {
192
+ writer.ldelim()
193
+ }
194
+ }, (reader, length) => {
195
+ const obj: any = {}
196
+
197
+ const end = length == null ? reader.len : reader.pos + length
198
+
199
+ while (reader.pos < end) {
200
+ const tag = reader.uint32()
201
+
202
+ switch (tag >>> 3) {
203
+ case 1:
204
+ obj.type = CircuitRelay.Type.codec().decode(reader)
205
+ break
206
+ case 2:
207
+ obj.srcPeer = CircuitRelay.Peer.codec().decode(reader, reader.uint32())
208
+ break
209
+ case 3:
210
+ obj.dstPeer = CircuitRelay.Peer.codec().decode(reader, reader.uint32())
211
+ break
212
+ case 4:
213
+ obj.code = CircuitRelay.Status.codec().decode(reader)
214
+ break
215
+ default:
216
+ reader.skipType(tag & 7)
217
+ break
218
+ }
219
+ }
220
+
221
+ return obj
222
+ })
223
+ }
224
+
225
+ return _codec
108
226
  }
109
227
 
110
228
  export const encode = (obj: CircuitRelay): Uint8Array => {
111
229
  return encodeMessage(obj, CircuitRelay.codec())
112
230
  }
113
231
 
114
- export const decode = (buf: Uint8Array): CircuitRelay => {
232
+ export const decode = (buf: Uint8Array | Uint8ArrayList): CircuitRelay => {
115
233
  return decodeMessage(buf, CircuitRelay.codec())
116
234
  }
117
235
  }
@@ -10,19 +10,30 @@ import { createListener } from './listener.js'
10
10
  import { handleCanHop, handleHop, hop } from './circuit/hop.js'
11
11
  import { handleStop } from './circuit/stop.js'
12
12
  import { StreamHandler } from './circuit/stream-handler.js'
13
- import { symbol } from '@libp2p/interfaces/transport'
13
+ import { symbol } from '@libp2p/interface-transport'
14
14
  import { peerIdFromString } from '@libp2p/peer-id'
15
- import { Components, Initializable } from '@libp2p/interfaces/components'
15
+ import { Components, Initializable } from '@libp2p/components'
16
16
  import type { AbortOptions } from '@libp2p/interfaces'
17
- import type { IncomingStreamData } from '@libp2p/interfaces/registrar'
18
- import type { Listener, Transport, CreateListenerOptions, ConnectionHandler } from '@libp2p/interfaces/transport'
19
- import type { Connection } from '@libp2p/interfaces/connection'
17
+ import type { IncomingStreamData } from '@libp2p/interface-registrar'
18
+ import type { Listener, Transport, CreateListenerOptions, ConnectionHandler } from '@libp2p/interface-transport'
19
+ import type { Connection } from '@libp2p/interface-connection'
20
+ import type { RelayConfig } from '../index.js'
21
+ import { abortableDuplex } from 'abortable-iterator'
22
+ import { TimeoutController } from 'timeout-abort-controller'
23
+ import { setMaxListeners } from 'events'
24
+ import type { Uint8ArrayList } from 'uint8arraylist'
25
+ import type { Duplex } from 'it-stream-types'
20
26
 
21
27
  const log = logger('libp2p:circuit')
22
28
 
23
29
  export class Circuit implements Transport, Initializable {
24
30
  private handler?: ConnectionHandler
25
31
  private components: Components = new Components()
32
+ private readonly _init: RelayConfig
33
+
34
+ constructor (init: RelayConfig) {
35
+ this._init = init
36
+ }
26
37
 
27
38
  init (components: Components): void {
28
39
  this.components = components
@@ -54,49 +65,25 @@ export class Circuit implements Transport, Initializable {
54
65
 
55
66
  async _onProtocol (data: IncomingStreamData) {
56
67
  const { connection, stream } = data
57
- const streamHandler = new StreamHandler({ stream })
58
- const request = await streamHandler.read()
59
-
60
- if (request == null) {
61
- log('request was invalid, could not read from stream')
62
- streamHandler.write({
63
- type: CircuitPB.Type.STATUS,
64
- code: CircuitPB.Status.MALFORMED_MESSAGE
65
- })
66
- streamHandler.close()
67
- return
68
- }
68
+ const controller = new TimeoutController(this._init.hop.timeout)
69
69
 
70
- let virtualConnection
70
+ try {
71
+ // fails on node < 15.4
72
+ setMaxListeners?.(Infinity, controller.signal)
73
+ } catch {}
71
74
 
72
- switch (request.type) {
73
- case CircuitPB.Type.CAN_HOP: {
74
- log('received CAN_HOP request from %p', connection.remotePeer)
75
- await handleCanHop({ circuit: this, connection, streamHandler })
76
- break
77
- }
78
- case CircuitPB.Type.HOP: {
79
- log('received HOP request from %p', connection.remotePeer)
80
- virtualConnection = await handleHop({
81
- connection,
82
- request,
83
- streamHandler,
84
- circuit: this,
85
- connectionManager: this.components.getConnectionManager()
86
- })
87
- break
88
- }
89
- case CircuitPB.Type.STOP: {
90
- log('received STOP request from %p', connection.remotePeer)
91
- virtualConnection = await handleStop({
92
- connection,
93
- request,
94
- streamHandler
95
- })
96
- break
97
- }
98
- default: {
99
- log('Request of type %s not supported', request.type)
75
+ try {
76
+ const source = abortableDuplex(stream, controller.signal)
77
+ const streamHandler = new StreamHandler({
78
+ stream: {
79
+ ...stream,
80
+ ...source
81
+ }
82
+ })
83
+ const request = await streamHandler.read()
84
+
85
+ if (request == null) {
86
+ log('request was invalid, could not read from stream')
100
87
  streamHandler.write({
101
88
  type: CircuitPB.Type.STATUS,
102
89
  code: CircuitPB.Status.MALFORMED_MESSAGE
@@ -104,27 +91,68 @@ export class Circuit implements Transport, Initializable {
104
91
  streamHandler.close()
105
92
  return
106
93
  }
107
- }
108
94
 
109
- if (virtualConnection != null) {
110
- // @ts-expect-error dst peer will not be undefined
111
- const remoteAddr = new Multiaddr(request.dstPeer.addrs[0])
112
- // @ts-expect-error dst peer will not be undefined
113
- const localAddr = new Multiaddr(request.srcPeer.addrs[0])
114
- const maConn = streamToMaConnection({
115
- stream: virtualConnection,
116
- remoteAddr,
117
- localAddr
118
- })
119
- const type = request.type === CircuitPB.Type.HOP ? 'relay' : 'inbound'
120
- log('new %s connection %s', type, maConn.remoteAddr)
95
+ let virtualConnection: Duplex<Uint8ArrayList, Uint8ArrayList | Uint8Array> | undefined
96
+
97
+ switch (request.type) {
98
+ case CircuitPB.Type.CAN_HOP: {
99
+ log('received CAN_HOP request from %p', connection.remotePeer)
100
+ await handleCanHop({ circuit: this, connection, streamHandler })
101
+ break
102
+ }
103
+ case CircuitPB.Type.HOP: {
104
+ log('received HOP request from %p', connection.remotePeer)
105
+ await handleHop({
106
+ connection,
107
+ request,
108
+ streamHandler,
109
+ circuit: this,
110
+ connectionManager: this.components.getConnectionManager()
111
+ })
112
+ break
113
+ }
114
+ case CircuitPB.Type.STOP: {
115
+ log('received STOP request from %p', connection.remotePeer)
116
+ virtualConnection = await handleStop({
117
+ connection,
118
+ request,
119
+ streamHandler
120
+ })
121
+ break
122
+ }
123
+ default: {
124
+ log('Request of type %s not supported', request.type)
125
+ streamHandler.write({
126
+ type: CircuitPB.Type.STATUS,
127
+ code: CircuitPB.Status.MALFORMED_MESSAGE
128
+ })
129
+ streamHandler.close()
130
+ return
131
+ }
132
+ }
121
133
 
122
- const conn = await this.components.getUpgrader().upgradeInbound(maConn)
123
- log('%s connection %s upgraded', type, maConn.remoteAddr)
134
+ if (virtualConnection != null) {
135
+ const remoteAddr = connection.remoteAddr
136
+ .encapsulate('/p2p-circuit')
137
+ .encapsulate(new Multiaddr(request.dstPeer?.addrs[0]))
138
+ const localAddr = new Multiaddr(request.srcPeer?.addrs[0])
139
+ const maConn = streamToMaConnection({
140
+ stream: virtualConnection,
141
+ remoteAddr,
142
+ localAddr
143
+ })
144
+ const type = request.type === CircuitPB.Type.HOP ? 'relay' : 'inbound'
145
+ log('new %s connection %s', type, maConn.remoteAddr)
146
+
147
+ const conn = await this.components.getUpgrader().upgradeInbound(maConn)
148
+ log('%s connection %s upgraded', type, maConn.remoteAddr)
124
149
 
125
- if (this.handler != null) {
126
- this.handler(conn)
150
+ if (this.handler != null) {
151
+ this.handler(conn)
152
+ }
127
153
  }
154
+ } finally {
155
+ controller.clear()
128
156
  }
129
157
  }
130
158
 
@@ -160,6 +188,7 @@ export class Circuit implements Transport, Initializable {
160
188
 
161
189
  try {
162
190
  const virtualConnection = await hop({
191
+ ...options,
163
192
  connection: relayConnection,
164
193
  request: {
165
194
  type: CircuitPB.Type.HOP,
package/src/config.ts CHANGED
@@ -10,6 +10,7 @@ import type { Libp2pInit } from './index.js'
10
10
  import { codes, messages } from './errors.js'
11
11
  import errCode from 'err-code'
12
12
  import type { RecursivePartial } from '@libp2p/interfaces'
13
+ import { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe'
13
14
 
14
15
  const DefaultConfig: Partial<Libp2pInit> = {
15
16
  addresses: {
@@ -26,6 +27,7 @@ const DefaultConfig: Partial<Libp2pInit> = {
26
27
  maxParallelDials: Constants.MAX_PARALLEL_DIALS,
27
28
  maxDialsPerPeer: Constants.MAX_PER_PEER_DIALS,
28
29
  dialTimeout: Constants.DIAL_TIMEOUT,
30
+ inboundUpgradeTimeout: Constants.INBOUND_UPGRADE_TIMEOUT,
29
31
  resolvers: {
30
32
  dnsaddr: dnsaddrResolver
31
33
  },
@@ -67,7 +69,8 @@ const DefaultConfig: Partial<Libp2pInit> = {
67
69
  },
68
70
  hop: {
69
71
  enabled: false,
70
- active: false
72
+ active: false,
73
+ timeout: 30000
71
74
  },
72
75
  autoRelay: {
73
76
  enabled: false,
@@ -79,13 +82,24 @@ const DefaultConfig: Partial<Libp2pInit> = {
79
82
  host: {
80
83
  agentVersion: AGENT_VERSION
81
84
  },
82
- timeout: 30000
85
+ // https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L48
86
+ timeout: 60000,
87
+ maxInboundStreams: 1,
88
+ maxOutboundStreams: 1,
89
+ maxPushIncomingStreams: 1,
90
+ maxPushOutgoingStreams: 1
83
91
  },
84
92
  ping: {
85
- protocolPrefix: 'ipfs'
93
+ protocolPrefix: 'ipfs',
94
+ maxInboundStreams: 1,
95
+ maxOutboundStreams: 1,
96
+ timeout: 10000
86
97
  },
87
98
  fetch: {
88
- protocolPrefix: 'libp2p'
99
+ protocolPrefix: 'libp2p',
100
+ maxInboundStreams: 1,
101
+ maxOutboundStreams: 1,
102
+ timeout: 10000
89
103
  }
90
104
  }
91
105
 
@@ -104,5 +118,14 @@ export function validateConfig (opts: RecursivePartial<Libp2pInit>): Libp2pInit
104
118
  throw errCode(new Error(messages.ERR_PROTECTOR_REQUIRED), codes.ERR_PROTECTOR_REQUIRED)
105
119
  }
106
120
 
121
+ // Append user agent version to default AGENT_VERSION depending on the environment
122
+ if (resultingOptions.identify.host.agentVersion === AGENT_VERSION) {
123
+ if (isNode || isElectronMain) {
124
+ resultingOptions.identify.host.agentVersion += ` UserAgent=${globalThis.process.version}`
125
+ } else if (isBrowser || isWebWorker || isElectronRenderer || isReactNative) {
126
+ resultingOptions.identify.host.agentVersion += ` UserAgent=${globalThis.navigator.userAgent}`
127
+ }
128
+ }
129
+
107
130
  return resultingOptions
108
131
  }
@@ -7,7 +7,7 @@ import { pipe } from 'it-pipe'
7
7
  import filter from 'it-filter'
8
8
  import sort from 'it-sort'
9
9
  import type { Startable } from '@libp2p/interfaces/startable'
10
- import type { Components } from '@libp2p/interfaces/components'
10
+ import type { Components } from '@libp2p/components'
11
11
 
12
12
  const log = logger('libp2p:connection-manager:auto-dialler')
13
13
 
@@ -1,7 +1,8 @@
1
- import type { PeerInfo } from '@libp2p/interfaces/peer-info'
1
+ import type { PeerInfo } from '@libp2p/interface-peer-info'
2
2
  import { logger } from '@libp2p/logger'
3
- import type { Components } from '@libp2p/interfaces/components'
3
+ import type { Components } from '@libp2p/components'
4
4
  import { TimeoutController } from 'timeout-abort-controller'
5
+ import { setMaxListeners } from 'events'
5
6
 
6
7
  const log = logger('libp2p:dialer:auto-dialer')
7
8
 
@@ -44,6 +45,11 @@ export class AutoDialer {
44
45
 
45
46
  const controller = new TimeoutController(this.dialTimeout)
46
47
 
48
+ try {
49
+ // fails on node < 15.4
50
+ setMaxListeners?.(Infinity, controller.signal)
51
+ } catch {}
52
+
47
53
  void this.components.getConnectionManager().openConnection(peer.id, {
48
54
  signal: controller.signal
49
55
  })
@@ -5,7 +5,7 @@ import { setMaxListeners } from 'events'
5
5
  import { codes } from '../../errors.js'
6
6
  import { logger } from '@libp2p/logger'
7
7
  import type { Multiaddr } from '@multiformats/multiaddr'
8
- import type { Connection } from '@libp2p/interfaces/connection'
8
+ import type { Connection } from '@libp2p/interface-connection'
9
9
  import type { AbortOptions } from '@libp2p/interfaces'
10
10
  import type { Dialer } from './index.js'
11
11
 
@@ -18,16 +18,16 @@ import {
18
18
  MAX_PER_PEER_DIALS,
19
19
  MAX_ADDRS_TO_DIAL
20
20
  } from '../../constants.js'
21
- import type { Connection } from '@libp2p/interfaces/connection'
21
+ import type { Connection } from '@libp2p/interface-connection'
22
22
  import type { AbortOptions } from '@libp2p/interfaces'
23
23
  import type { Startable } from '@libp2p/interfaces/startable'
24
- import type { PeerId } from '@libp2p/interfaces/peer-id'
24
+ import type { PeerId } from '@libp2p/interface-peer-id'
25
25
  import { getPeer } from '../../get-peer.js'
26
26
  import sort from 'it-sort'
27
- import { Components, Initializable } from '@libp2p/interfaces/components'
27
+ import { Components, Initializable } from '@libp2p/components'
28
28
  import map from 'it-map'
29
- import type { AddressSorter } from '@libp2p/interfaces/peer-store'
30
- import type { ComponentMetricsTracker } from '@libp2p/interfaces/metrics'
29
+ import type { AddressSorter } from '@libp2p/interface-peer-store'
30
+ import type { ComponentMetricsTracker } from '@libp2p/interface-metrics'
31
31
 
32
32
  const log = logger('libp2p:dialer')
33
33
 
@@ -177,7 +177,7 @@ export class Dialer implements Startable, Initializable {
177
177
 
178
178
  log('creating dial target for %p', id)
179
179
 
180
- const dialTarget = await this._createCancellableDialTarget(id)
180
+ const dialTarget = await this._createCancellableDialTarget(id, options)
181
181
 
182
182
  if (dialTarget.addrs.length === 0) {
183
183
  throw errCode(new Error('The dial request has no valid addresses'), codes.ERR_NO_VALID_ADDRESSES)
@@ -207,7 +207,7 @@ export class Dialer implements Startable, Initializable {
207
207
  * The dial to the first address that is successfully able to upgrade a connection
208
208
  * will be used.
209
209
  */
210
- async _createCancellableDialTarget (peer: PeerId): Promise<DialTarget> {
210
+ async _createCancellableDialTarget (peer: PeerId, options: AbortOptions): Promise<DialTarget> {
211
211
  // Make dial target promise cancellable
212
212
  const id = `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`
213
213
  const cancellablePromise = new Promise<DialTarget>((resolve, reject) => {
@@ -216,7 +216,7 @@ export class Dialer implements Startable, Initializable {
216
216
 
217
217
  try {
218
218
  const dialTarget = await Promise.race([
219
- this._createDialTarget(peer),
219
+ this._createDialTarget(peer, options),
220
220
  cancellablePromise
221
221
  ])
222
222
 
@@ -232,7 +232,7 @@ export class Dialer implements Startable, Initializable {
232
232
  * If a multiaddr is received it should be the first address attempted.
233
233
  * Multiaddrs not supported by the available transports will be filtered out.
234
234
  */
235
- async _createDialTarget (peer: PeerId): Promise<DialTarget> {
235
+ async _createDialTarget (peer: PeerId, options: AbortOptions): Promise<DialTarget> {
236
236
  const knownAddrs = await pipe(
237
237
  await this.components.getPeerStore().addressBook.get(peer),
238
238
  (source) => filter(source, async (address) => {
@@ -253,7 +253,7 @@ export class Dialer implements Startable, Initializable {
253
253
 
254
254
  const addrs: Multiaddr[] = []
255
255
  for (const a of knownAddrs) {
256
- const resolvedAddrs = await this._resolve(a)
256
+ const resolvedAddrs = await this._resolve(a, options)
257
257
  resolvedAddrs.forEach(ra => addrs.push(ra))
258
258
  }
259
259
 
@@ -284,7 +284,10 @@ export class Dialer implements Startable, Initializable {
284
284
  throw errCode(new Error('already aborted'), codes.ERR_ALREADY_ABORTED)
285
285
  }
286
286
 
287
- return await this.components.getTransportManager().dial(addr, options)
287
+ return await this.components.getTransportManager().dial(addr, options).catch(err => {
288
+ log.error('dial to %s failed', addr, err)
289
+ throw err
290
+ })
288
291
  }
289
292
 
290
293
  const dialRequest = new DialRequest({
@@ -341,7 +344,7 @@ export class Dialer implements Startable, Initializable {
341
344
  /**
342
345
  * Resolve multiaddr recursively
343
346
  */
344
- async _resolve (ma: Multiaddr): Promise<Multiaddr[]> {
347
+ async _resolve (ma: Multiaddr, options: AbortOptions): Promise<Multiaddr[]> {
345
348
  // TODO: recursive logic should live in multiaddr once dns4/dns6 support is in place
346
349
  // Now only supporting resolve for dnsaddr
347
350
  const resolvableProto = ma.protoNames().includes('dnsaddr')
@@ -351,9 +354,9 @@ export class Dialer implements Startable, Initializable {
351
354
  return [ma]
352
355
  }
353
356
 
354
- const resolvedMultiaddrs = await this._resolveRecord(ma)
357
+ const resolvedMultiaddrs = await this._resolveRecord(ma, options)
355
358
  const recursiveMultiaddrs = await Promise.all(resolvedMultiaddrs.map(async (nm) => {
356
- return await this._resolve(nm)
359
+ return await this._resolve(nm, options)
357
360
  }))
358
361
 
359
362
  const addrs = recursiveMultiaddrs.flat()
@@ -368,10 +371,10 @@ export class Dialer implements Startable, Initializable {
368
371
  /**
369
372
  * Resolve a given multiaddr. If this fails, an empty array will be returned
370
373
  */
371
- async _resolveRecord (ma: Multiaddr): Promise<Multiaddr[]> {
374
+ async _resolveRecord (ma: Multiaddr, options: AbortOptions): Promise<Multiaddr[]> {
372
375
  try {
373
376
  ma = new Multiaddr(ma.toString()) // Use current multiaddr module
374
- const multiaddrs = await ma.resolve()
377
+ const multiaddrs = await ma.resolve(options)
375
378
  return multiaddrs
376
379
  } catch (err) {
377
380
  log.error(`multiaddr ${ma.toString()} could not be resolved`, err)