libp2p 0.42.2-45fc415b → 0.42.2-593deefe

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 (136) hide show
  1. package/dist/index.min.js +29 -29
  2. package/dist/src/circuit/client.d.ts +81 -0
  3. package/dist/src/circuit/client.d.ts.map +1 -0
  4. package/dist/src/circuit/client.js +285 -0
  5. package/dist/src/circuit/client.js.map +1 -0
  6. package/dist/src/circuit/constants.d.ts +7 -8
  7. package/dist/src/circuit/constants.d.ts.map +1 -1
  8. package/dist/src/circuit/constants.js +11 -8
  9. package/dist/src/circuit/constants.js.map +1 -1
  10. package/dist/src/circuit/hop.d.ts +23 -0
  11. package/dist/src/circuit/hop.d.ts.map +1 -0
  12. package/dist/src/circuit/hop.js +167 -0
  13. package/dist/src/circuit/hop.js.map +1 -0
  14. package/dist/src/circuit/index.d.ts +47 -47
  15. package/dist/src/circuit/index.d.ts.map +1 -1
  16. package/dist/src/circuit/index.js +1 -68
  17. package/dist/src/circuit/index.js.map +1 -1
  18. package/dist/src/circuit/interfaces.d.ts +27 -0
  19. package/dist/src/circuit/interfaces.d.ts.map +1 -0
  20. package/dist/src/circuit/interfaces.js +2 -0
  21. package/dist/src/circuit/interfaces.js.map +1 -0
  22. package/dist/src/circuit/multicodec.d.ts +2 -1
  23. package/dist/src/circuit/multicodec.d.ts.map +1 -1
  24. package/dist/src/circuit/multicodec.js +2 -1
  25. package/dist/src/circuit/multicodec.js.map +1 -1
  26. package/dist/src/circuit/pb/index.d.ts +83 -43
  27. package/dist/src/circuit/pb/index.d.ts.map +1 -1
  28. package/dist/src/circuit/pb/index.js +363 -127
  29. package/dist/src/circuit/pb/index.js.map +1 -1
  30. package/dist/src/circuit/relay.d.ts +34 -0
  31. package/dist/src/circuit/relay.d.ts.map +1 -0
  32. package/dist/src/circuit/relay.js +61 -0
  33. package/dist/src/circuit/relay.js.map +1 -0
  34. package/dist/src/circuit/reservation-store.d.ts +42 -0
  35. package/dist/src/circuit/reservation-store.d.ts.map +1 -0
  36. package/dist/src/circuit/reservation-store.js +59 -0
  37. package/dist/src/circuit/reservation-store.js.map +1 -0
  38. package/dist/src/circuit/reservation-voucher.d.ts +18 -0
  39. package/dist/src/circuit/reservation-voucher.d.ts.map +1 -0
  40. package/dist/src/circuit/reservation-voucher.js +33 -0
  41. package/dist/src/circuit/reservation-voucher.js.map +1 -0
  42. package/dist/src/circuit/stop.d.ts +19 -0
  43. package/dist/src/circuit/stop.d.ts.map +1 -0
  44. package/dist/src/circuit/stop.js +67 -0
  45. package/dist/src/circuit/stop.js.map +1 -0
  46. package/dist/src/circuit/transport.d.ts +24 -9
  47. package/dist/src/circuit/transport.d.ts.map +1 -1
  48. package/dist/src/circuit/transport.js +133 -118
  49. package/dist/src/circuit/transport.js.map +1 -1
  50. package/dist/src/circuit/utils.d.ts +5 -0
  51. package/dist/src/circuit/utils.d.ts.map +1 -1
  52. package/dist/src/circuit/utils.js +114 -0
  53. package/dist/src/circuit/utils.js.map +1 -1
  54. package/dist/src/config.d.ts.map +1 -1
  55. package/dist/src/config.js +2 -3
  56. package/dist/src/config.js.map +1 -1
  57. package/dist/src/connection-manager/dialer/dial-request.d.ts.map +1 -1
  58. package/dist/src/connection-manager/dialer/dial-request.js +7 -0
  59. package/dist/src/connection-manager/dialer/dial-request.js.map +1 -1
  60. package/dist/src/errors.d.ts +2 -1
  61. package/dist/src/errors.d.ts.map +1 -1
  62. package/dist/src/errors.js +1 -0
  63. package/dist/src/errors.js.map +1 -1
  64. package/dist/src/fetch/pb/proto.d.ts +3 -3
  65. package/dist/src/fetch/pb/proto.d.ts.map +1 -1
  66. package/dist/src/fetch/pb/proto.js +4 -3
  67. package/dist/src/fetch/pb/proto.js.map +1 -1
  68. package/dist/src/identify/pb/message.d.ts +2 -2
  69. package/dist/src/identify/pb/message.d.ts.map +1 -1
  70. package/dist/src/identify/pb/message.js +1 -0
  71. package/dist/src/identify/pb/message.js.map +1 -1
  72. package/dist/src/insecure/pb/proto.d.ts +3 -3
  73. package/dist/src/insecure/pb/proto.d.ts.map +1 -1
  74. package/dist/src/insecure/pb/proto.js +4 -5
  75. package/dist/src/insecure/pb/proto.js.map +1 -1
  76. package/dist/src/libp2p.d.ts +2 -0
  77. package/dist/src/libp2p.d.ts.map +1 -1
  78. package/dist/src/libp2p.js +10 -3
  79. package/dist/src/libp2p.js.map +1 -1
  80. package/dist/src/transport-manager.d.ts.map +1 -1
  81. package/dist/src/transport-manager.js +2 -3
  82. package/dist/src/transport-manager.js.map +1 -1
  83. package/dist/src/upgrader.d.ts.map +1 -1
  84. package/dist/src/upgrader.js.map +1 -1
  85. package/package.json +12 -11
  86. package/src/circuit/client.ts +381 -0
  87. package/src/circuit/constants.ts +14 -8
  88. package/src/circuit/hop.ts +210 -0
  89. package/src/circuit/index.ts +49 -111
  90. package/src/circuit/interfaces.ts +28 -0
  91. package/src/circuit/multicodec.ts +2 -1
  92. package/src/circuit/pb/index.proto +57 -32
  93. package/src/circuit/pb/index.ts +448 -138
  94. package/src/circuit/relay.ts +87 -0
  95. package/src/circuit/reservation-store.ts +106 -0
  96. package/src/circuit/reservation-voucher.ts +51 -0
  97. package/src/circuit/stop.ts +92 -0
  98. package/src/circuit/transport.ts +166 -131
  99. package/src/circuit/utils.ts +145 -0
  100. package/src/config.ts +2 -3
  101. package/src/connection-manager/dialer/dial-request.ts +7 -0
  102. package/src/errors.ts +2 -1
  103. package/src/fetch/pb/proto.ts +8 -7
  104. package/src/identify/pb/message.ts +3 -2
  105. package/src/insecure/pb/proto.ts +8 -9
  106. package/src/libp2p.ts +12 -3
  107. package/src/transport-manager.ts +2 -3
  108. package/src/upgrader.ts +4 -4
  109. package/src/version.ts +1 -1
  110. package/dist/src/circuit/auto-relay.d.ts +0 -46
  111. package/dist/src/circuit/auto-relay.d.ts.map +0 -1
  112. package/dist/src/circuit/auto-relay.js +0 -220
  113. package/dist/src/circuit/auto-relay.js.map +0 -1
  114. package/dist/src/circuit/circuit/hop.d.ts +0 -42
  115. package/dist/src/circuit/circuit/hop.d.ts.map +0 -1
  116. package/dist/src/circuit/circuit/hop.js +0 -142
  117. package/dist/src/circuit/circuit/hop.js.map +0 -1
  118. package/dist/src/circuit/circuit/stop.d.ts +0 -24
  119. package/dist/src/circuit/circuit/stop.d.ts.map +0 -1
  120. package/dist/src/circuit/circuit/stop.js +0 -51
  121. package/dist/src/circuit/circuit/stop.js.map +0 -1
  122. package/dist/src/circuit/circuit/stream-handler.d.ts +0 -40
  123. package/dist/src/circuit/circuit/stream-handler.d.ts.map +0 -1
  124. package/dist/src/circuit/circuit/stream-handler.js +0 -59
  125. package/dist/src/circuit/circuit/stream-handler.js.map +0 -1
  126. package/dist/src/circuit/circuit/utils.d.ts +0 -7
  127. package/dist/src/circuit/circuit/utils.d.ts.map +0 -1
  128. package/dist/src/circuit/circuit/utils.js +0 -43
  129. package/dist/src/circuit/circuit/utils.js.map +0 -1
  130. package/src/circuit/IMPLEMENTATION_NOTES.md +0 -128
  131. package/src/circuit/README.md +0 -111
  132. package/src/circuit/auto-relay.ts +0 -292
  133. package/src/circuit/circuit/hop.ts +0 -220
  134. package/src/circuit/circuit/stop.ts +0 -83
  135. package/src/circuit/circuit/stream-handler.ts +0 -87
  136. package/src/circuit/circuit/utils.ts +0 -44
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2p",
3
- "version": "0.42.2-45fc415b",
3
+ "version": "0.42.2-593deefe",
4
4
  "description": "JavaScript implementation of libp2p, a modular peer to peer network stack",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p#readme",
@@ -106,7 +106,7 @@
106
106
  "@libp2p/interface-libp2p": "^1.0.0",
107
107
  "@libp2p/interface-metrics": "^4.0.0",
108
108
  "@libp2p/interface-peer-discovery": "^1.0.1",
109
- "@libp2p/interface-peer-id": "^2.0.0",
109
+ "@libp2p/interface-peer-id": "^2.0.1",
110
110
  "@libp2p/interface-peer-info": "^1.0.3",
111
111
  "@libp2p/interface-peer-routing": "^1.0.1",
112
112
  "@libp2p/interface-peer-store": "^1.2.2",
@@ -122,7 +122,7 @@
122
122
  "@libp2p/peer-id": "^2.0.0",
123
123
  "@libp2p/peer-id-factory": "^2.0.0",
124
124
  "@libp2p/peer-record": "^5.0.0",
125
- "@libp2p/peer-store": "^6.0.0",
125
+ "@libp2p/peer-store": "^6.0.4",
126
126
  "@libp2p/tracked-map": "^3.0.0",
127
127
  "@libp2p/utils": "^3.0.2",
128
128
  "@multiformats/mafmt": "^11.0.2",
@@ -143,16 +143,17 @@
143
143
  "it-map": "^2.0.0",
144
144
  "it-merge": "^2.0.0",
145
145
  "it-pair": "^2.0.2",
146
+ "it-pb-stream": "^3.0.0",
146
147
  "it-pipe": "^2.0.3",
147
148
  "it-sort": "^2.0.0",
148
149
  "it-stream-types": "^1.0.4",
149
150
  "merge-options": "^3.0.4",
150
151
  "multiformats": "^11.0.0",
152
+ "p-defer": "^4.0.0",
151
153
  "p-fifo": "^1.0.0",
152
154
  "p-retry": "^5.0.0",
153
- "p-settle": "^5.0.0",
154
155
  "private-ip": "^3.0.0",
155
- "protons-runtime": "^4.0.1",
156
+ "protons-runtime": "^5.0.0",
156
157
  "rate-limiter-flexible": "^2.3.11",
157
158
  "retimer": "^3.0.0",
158
159
  "set-delayed-interval": "^1.0.0",
@@ -163,17 +164,18 @@
163
164
  "xsalsa20": "^1.1.0"
164
165
  },
165
166
  "devDependencies": {
167
+ "@chainsafe/libp2p-gossipsub": "^6.2.0",
166
168
  "@chainsafe/libp2p-noise": "^11.0.0",
167
169
  "@chainsafe/libp2p-yamux": "^3.0.3",
168
170
  "@libp2p/bootstrap": "^6.0.0",
169
- "@libp2p/daemon-client": "^4.0.1",
170
- "@libp2p/daemon-server": "^4.0.1",
171
+ "@libp2p/daemon-client": "^5.0.0",
172
+ "@libp2p/daemon-server": "^4.1.0",
171
173
  "@libp2p/floodsub": "^6.0.0",
172
174
  "@libp2p/interface-compliance-tests": "^3.0.2",
173
175
  "@libp2p/interface-connection-compliance-tests": "^2.0.3",
174
176
  "@libp2p/interface-connection-encrypter-compliance-tests": "^4.0.0",
175
177
  "@libp2p/interface-mocks": "^9.0.0",
176
- "@libp2p/interop": "^4.0.0",
178
+ "@libp2p/interop": "^7.0.0",
177
179
  "@libp2p/kad-dht": "^7.0.0",
178
180
  "@libp2p/mdns": "^6.0.0",
179
181
  "@libp2p/mplex": "^7.0.0",
@@ -189,15 +191,14 @@
189
191
  "cborg": "^1.8.1",
190
192
  "delay": "^5.0.0",
191
193
  "execa": "^7.0.0",
192
- "go-libp2p": "^0.0.6",
194
+ "go-libp2p": "^1.0.1",
193
195
  "it-pushable": "^3.0.0",
194
196
  "it-to-buffer": "^3.0.0",
195
197
  "npm-run-all": "^4.1.5",
196
- "p-defer": "^4.0.0",
197
198
  "p-event": "^5.0.1",
198
199
  "p-times": "^4.0.0",
199
200
  "p-wait-for": "^5.0.0",
200
- "protons": "^6.0.0",
201
+ "protons": "^7.0.2",
201
202
  "sinon": "^15.0.1",
202
203
  "sinon-ts": "^1.0.0"
203
204
  },
@@ -0,0 +1,381 @@
1
+ import { logger } from '@libp2p/logger'
2
+ import { RELAY_V2_HOP_CODEC } from './multicodec.js'
3
+ import { getExpiration, namespaceToCid } from './utils.js'
4
+ import {
5
+ CIRCUIT_PROTO_CODE,
6
+ DEFAULT_MAX_RESERVATIONS,
7
+ RELAY_RENDEZVOUS_NS
8
+ } from './constants.js'
9
+ import type { PeerId } from '@libp2p/interface-peer-id'
10
+ import type { AddressSorter } from '@libp2p/interface-peer-store'
11
+ import type { Connection } from '@libp2p/interface-connection'
12
+ import sort from 'it-sort'
13
+ import all from 'it-all'
14
+ import { pipe } from 'it-pipe'
15
+ import { publicAddressesFirst } from '@libp2p/utils/address-sort'
16
+ import { reserve } from './hop.js'
17
+ import { EventEmitter, CustomEvent } from '@libp2p/interfaces/events'
18
+ import type { Startable } from '@libp2p/interfaces/startable'
19
+ import type { Components } from '../components.js'
20
+ import type { RelayReservationManagerConfig } from './index.js'
21
+ import { PeerSet, PeerMap, PeerList } from '@libp2p/peer-collections'
22
+
23
+ const log = logger('libp2p:circuit:client')
24
+
25
+ const noop = () => {}
26
+
27
+ /**
28
+ * CircuitServiceInit initializes the circuit service using values
29
+ * from the provided config and an @type{AddressSorter}.
30
+ */
31
+ export interface CircuitServiceInit extends RelayReservationManagerConfig {
32
+ /**
33
+ * Allows prioritizing addresses from the peerstore for dialing. The
34
+ * default behavior is to prioritise public addresses.
35
+ */
36
+ addressSorter?: AddressSorter
37
+ /**
38
+ * A callback to invoke when an error occurs in the circuit service.
39
+ */
40
+ onError?: (error: Error) => void
41
+ }
42
+
43
+ export interface RelayReservationManagerEvents {
44
+ 'relay:reservation': CustomEvent
45
+ }
46
+
47
+ /**
48
+ * ReservationManager automatically makes a circuit v2 reservation on any connected
49
+ * peers that support the circuit v2 HOP protocol.
50
+ */
51
+ export class RelayReservationManager extends EventEmitter<RelayReservationManagerEvents> implements Startable {
52
+ private readonly components: Components
53
+ private readonly addressSorter: AddressSorter
54
+ private readonly maxReservations: number
55
+ private readonly relays: PeerSet
56
+ private readonly reservationMap: PeerMap<ReturnType<typeof setTimeout>>
57
+ private readonly onError: (error: Error) => void
58
+ private started: boolean
59
+
60
+ constructor (components: Components, init: CircuitServiceInit) {
61
+ super()
62
+ this.started = false
63
+ this.components = components
64
+ this.addressSorter = init.addressSorter ?? publicAddressesFirst
65
+ this.maxReservations = init.maxReservations ?? DEFAULT_MAX_RESERVATIONS
66
+ this.relays = new PeerSet()
67
+ this.reservationMap = new PeerMap()
68
+ this.onError = init.onError ?? noop
69
+
70
+ this._onProtocolChange = this._onProtocolChange.bind(this)
71
+ this._onPeerDisconnected = this._onPeerDisconnected.bind(this)
72
+ this._onPeerConnect = this._onPeerConnect.bind(this)
73
+
74
+ this.components.peerStore.addEventListener('change:protocols', (evt) => {
75
+ void this._onProtocolChange(evt.detail).catch(err => {
76
+ log.error('handling protocol change failed', err)
77
+ })
78
+ })
79
+
80
+ this.components.connectionManager.addEventListener('peer:disconnect', this._onPeerDisconnected)
81
+ this.components.connectionManager.addEventListener('peer:connect', this._onPeerConnect)
82
+ }
83
+
84
+ isStarted () {
85
+ return this.started
86
+ }
87
+
88
+ start () {
89
+ void this._listenOnAvailableHopRelays().catch(err => { log.error('error listening on relays', err) })
90
+ this.started = true
91
+ }
92
+
93
+ async stop () {
94
+ this.reservationMap.forEach((timer) => clearTimeout(timer))
95
+ this.reservationMap.clear()
96
+ this.relays.clear()
97
+ }
98
+
99
+ /**
100
+ * Check if a peer supports the relay protocol.
101
+ * If the protocol is not supported, check if it was supported before and remove it as a listen relay.
102
+ * If the protocol is supported, check if the peer supports **HOP** and add it as a listener if
103
+ * inside the threshold.
104
+ */
105
+ async _onProtocolChange ({ peerId, protocols }: {peerId: PeerId, protocols: string[]}) {
106
+ if (peerId.equals(this.components.peerId)) {
107
+ return
108
+ }
109
+
110
+ // Check if it has the protocol
111
+ const hasProtocol = protocols.includes(RELAY_V2_HOP_CODEC)
112
+ log.trace('Peer %p protocol change %p', peerId, this.components.peerId)
113
+
114
+ // If no protocol, check if we were keeping the peer before as a listenRelay
115
+ if (!hasProtocol) {
116
+ if (this.relays.has(peerId)) {
117
+ await this._removeListenRelay(peerId)
118
+ }
119
+ return
120
+ }
121
+
122
+ if (this.relays.has(peerId)) {
123
+ return
124
+ }
125
+
126
+ // If protocol, check if can hop, store info in the metadataBook and listen on it
127
+ try {
128
+ const connections = this.components.connectionManager.getConnections(peerId)
129
+
130
+ // if no connections, try to listen on relay
131
+ if (connections.length === 0) {
132
+ void this._tryToListenOnRelay(peerId)
133
+ return
134
+ }
135
+ const connection = connections[0]
136
+
137
+ // Do not hop on a relayed connection
138
+ if (connection.remoteAddr.protoCodes().includes(CIRCUIT_PROTO_CODE)) {
139
+ log('relayed connection to %p will not be used to hop on', peerId)
140
+ return
141
+ }
142
+
143
+ await this._addListenRelay(connection, peerId)
144
+ } catch (err: any) {
145
+ log.error('could not add %p as relay', peerId)
146
+ this.onError(err)
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Handle case when peer connects. If we already have the peer in the protobook,
152
+ * we treat this event as an `onProtocolChange`.
153
+ */
154
+ _onPeerConnect ({ detail: connection }: CustomEvent<Connection>) {
155
+ void this.components.peerStore.protoBook.get(connection.remotePeer)
156
+ .then((protocols) => {
157
+ void this._onProtocolChange({ peerId: connection.remotePeer, protocols })
158
+ .catch((err) => log.error('handling reconnect failed', err))
159
+ },
160
+ (err) => {
161
+ // this is not necessarily an error as we will only have the protocols stored
162
+ // in case of a reconnect
163
+ log.trace('could not fetch protocols for peer: %p', connection.remotePeer, err)
164
+ })
165
+ }
166
+
167
+ /**
168
+ * Peer disconnects
169
+ */
170
+ _onPeerDisconnected (evt: CustomEvent<Connection>) {
171
+ const connection = evt.detail
172
+ const peerId = connection.remotePeer
173
+ clearTimeout(this.reservationMap.get(peerId))
174
+ this.reservationMap.delete(peerId)
175
+
176
+ // Not listening on this relay
177
+ if (!this.relays.has(peerId)) {
178
+ return
179
+ }
180
+
181
+ this._removeListenRelay(peerId).catch(err => {
182
+ log.error(err)
183
+ })
184
+ }
185
+
186
+ /**
187
+ * Attempt to listen on the given relay connection
188
+ */
189
+ async _addListenRelay (connection: Connection, peerId: PeerId): Promise<void> {
190
+ log.trace('peerId %p is being added as relay', peerId)
191
+ try {
192
+ // Check if already enough relay reservations
193
+ if (this.relays.size >= this.maxReservations) {
194
+ return
195
+ }
196
+
197
+ await this.createOrRefreshReservation(peerId)
198
+
199
+ // Get peer known addresses and sort them with public addresses first
200
+ const remoteAddrs = await pipe(
201
+ await this.components.peerStore.addressBook.get(connection.remotePeer),
202
+ (source) => sort(source, this.addressSorter),
203
+ async (source) => await all(source)
204
+ )
205
+
206
+ // Attempt to listen on relay
207
+ const result = await Promise.all(
208
+ remoteAddrs.map(async addr => {
209
+ let multiaddr = addr.multiaddr
210
+
211
+ if (multiaddr.getPeerId() == null) {
212
+ multiaddr = multiaddr.encapsulate(`/p2p/${connection.remotePeer.toString()}`)
213
+ }
214
+ multiaddr = multiaddr.encapsulate('/p2p-circuit')
215
+ try {
216
+ // Announce multiaddrs will update on listen success by TransportManager event being triggered
217
+ await this.components.transportManager.listen([multiaddr])
218
+ return true
219
+ } catch (err: any) {
220
+ log.error('error listening on circuit address', multiaddr, err)
221
+ this.onError(err)
222
+ }
223
+
224
+ return false
225
+ })
226
+ )
227
+
228
+ if (result.includes(true)) {
229
+ this.relays.add(peerId)
230
+ }
231
+ } catch (err: any) {
232
+ this.relays.delete(peerId)
233
+ log.error('error adding relay for %p %s', peerId, err)
234
+ this.onError(err)
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Remove listen relay
240
+ */
241
+ async _removeListenRelay (PeerId: PeerId) {
242
+ const recheck = this.relays.has(PeerId)
243
+ this.relays.delete(PeerId)
244
+ if (recheck) {
245
+ // TODO: this should be responsibility of the connMgr
246
+ await this._listenOnAvailableHopRelays(new PeerList([PeerId]))
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Try to listen on available hop relay connections.
252
+ * The following order will happen while we do not have enough relays.
253
+ * 1. Check the metadata store for known relays, try to listen on the ones we are already connected.
254
+ * 2. Dial and try to listen on the peers we know that support hop but are not connected.
255
+ * 3. Search the network.
256
+ */
257
+ async _listenOnAvailableHopRelays (peersToIgnore: PeerList = new PeerList([])) {
258
+ // Check if already listening on enough relays
259
+ if (this.relays.size >= this.maxReservations) {
260
+ return
261
+ }
262
+
263
+ const knownHopsToDial: PeerId[] = []
264
+ const peers = (await this.components.peerStore.all())
265
+ // filter by a list of peers supporting RELAY_V2_HOP and ones we are not listening on
266
+ .filter(({ id, protocols }) =>
267
+ protocols.includes(RELAY_V2_HOP_CODEC) && !this.relays.has(id) && !peersToIgnore.includes(id)
268
+ )
269
+ .map(({ id }) => {
270
+ const connections = this.components.connectionManager.getConnections(id)
271
+ if (connections.length === 0) {
272
+ knownHopsToDial.push(id)
273
+ return [id, null]
274
+ }
275
+ return [id, connections[0]]
276
+ })
277
+ .sort(() => Math.random() - 0.5)
278
+
279
+ // Check if we have known hop peers to use and attempt to listen on the already connected
280
+ for (const [id, conn] of peers) {
281
+ await this._addListenRelay(conn as Connection, id as PeerId)
282
+
283
+ // Check if already listening on enough relays
284
+ if (this.relays.size >= this.maxReservations) {
285
+ return
286
+ }
287
+ }
288
+
289
+ // Try to listen on known peers that are not connected
290
+ for (const peerId of knownHopsToDial) {
291
+ // Check if already listening on enough relays
292
+ if (this.relays.size >= this.maxReservations) {
293
+ return
294
+ }
295
+
296
+ await this._tryToListenOnRelay(peerId)
297
+ }
298
+
299
+ // Try to find relays to hop on the network
300
+ try {
301
+ const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)
302
+ for await (const provider of this.components.contentRouting.findProviders(cid)) {
303
+ if (
304
+ provider.multiaddrs.length > 0 &&
305
+ !provider.id.equals(this.components.peerId)
306
+ ) {
307
+ const peerId = provider.id
308
+
309
+ await this.components.peerStore.addressBook.add(peerId, provider.multiaddrs)
310
+ await this._tryToListenOnRelay(peerId)
311
+
312
+ // Check if already listening on enough relays
313
+ if (this.relays.size >= this.maxReservations) {
314
+ return
315
+ }
316
+ }
317
+ }
318
+ } catch (err: any) {
319
+ log.error('failed when finding relays on the network', err)
320
+ this.onError(err)
321
+ }
322
+ }
323
+
324
+ async _tryToListenOnRelay (peerId: PeerId) {
325
+ try {
326
+ if (peerId.equals(this.components.peerId)) {
327
+ log.trace('Skipping dialling self %p', peerId.toString())
328
+ return
329
+ }
330
+ const connection = await this.components.connectionManager.openConnection(peerId)
331
+ await this._addListenRelay(connection, peerId)
332
+ } catch (err: any) {
333
+ log.error('Could not connect and listen on relay %p', peerId, err)
334
+ this.onError(err)
335
+ }
336
+ }
337
+
338
+ private readonly createOrRefreshReservation = async (peerId: PeerId) => {
339
+ try {
340
+ const connections = this.components.connectionManager.getConnections(peerId)
341
+
342
+ if (connections.length === 0) {
343
+ throw new Error('No connections to peer')
344
+ }
345
+
346
+ const connection = connections[0]
347
+
348
+ const reservation = await reserve(connection)
349
+
350
+ const refreshReservation = this.createOrRefreshReservation
351
+
352
+ if (reservation != null) {
353
+ log('new reservation on %p', peerId)
354
+
355
+ // clear any previous timeouts
356
+ const previous = this.reservationMap.get(peerId)
357
+ if (previous != null) {
358
+ clearTimeout(previous)
359
+ }
360
+
361
+ const timeout = setTimeout(
362
+ (peerId: PeerId) => {
363
+ void refreshReservation(peerId).catch(err => {
364
+ log.error('error refreshing reservation for %p', peerId, err)
365
+ })
366
+ },
367
+ Math.max(getExpiration(reservation.expire) - 100, 0),
368
+ peerId
369
+ )
370
+ this.reservationMap.set(
371
+ peerId,
372
+ timeout
373
+ )
374
+ this.dispatchEvent(new CustomEvent<unknown>('relay:reservation'))
375
+ }
376
+ } catch (err: any) {
377
+ log.error(err)
378
+ await this._removeListenRelay(peerId)
379
+ }
380
+ }
381
+ }
@@ -16,16 +16,22 @@ export const ADVERTISE_TTL = 30 * minute
16
16
  export const CIRCUIT_PROTO_CODE = 290
17
17
 
18
18
  /**
19
- * PeerStore metadaBook key for HOP relay service
19
+ * Relay HOP relay service namespace for discovery
20
20
  */
21
- export const HOP_METADATA_KEY = 'hop_relay'
21
+ export const RELAY_RENDEZVOUS_NS = '/libp2p/relay'
22
22
 
23
23
  /**
24
- * PeerStore metadaBook value for HOP relay service
24
+ * Maximum reservations for auto relay
25
25
  */
26
- export const HOP_METADATA_VALUE = 'true'
26
+ export const DEFAULT_MAX_RESERVATIONS = 1
27
27
 
28
- /**
29
- * Relay HOP relay service namespace for discovery
30
- */
31
- export const RELAY_RENDEZVOUS_NS = '/libp2p/relay'
28
+ export const RELAY_DESTINATION_TAG = 'relay-destination'
29
+
30
+ // circuit v2 connection limits
31
+ // https://github.com/libp2p/go-libp2p/blob/master/p2p/protocol/circuitv2/relay/resources.go#L61-L66
32
+
33
+ // 2 min is the default connection duration
34
+ export const DEFAULT_DURATION_LIMIT = 2 * 60 * 1000
35
+
36
+ // 128k is the default data limit
37
+ export const DEFAULT_DATA_LIMIT = BigInt(1 << 17)