libp2p 0.42.2-593deefe → 0.42.2-75d5a36f

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 (134) hide show
  1. package/dist/index.min.js +30 -30
  2. package/dist/src/circuit/constants.d.ts +29 -3
  3. package/dist/src/circuit/constants.d.ts.map +1 -1
  4. package/dist/src/circuit/constants.js +32 -5
  5. package/dist/src/circuit/constants.js.map +1 -1
  6. package/dist/src/circuit/index.d.ts +16 -61
  7. package/dist/src/circuit/index.d.ts.map +1 -1
  8. package/dist/src/circuit/index.js +2 -1
  9. package/dist/src/circuit/index.js.map +1 -1
  10. package/dist/src/circuit/server/advert-service.d.ts +43 -0
  11. package/dist/src/circuit/server/advert-service.d.ts.map +1 -0
  12. package/dist/src/circuit/server/advert-service.js +69 -0
  13. package/dist/src/circuit/server/advert-service.js.map +1 -0
  14. package/dist/src/circuit/server/index.d.ts +60 -0
  15. package/dist/src/circuit/server/index.d.ts.map +1 -0
  16. package/dist/src/circuit/server/index.js +287 -0
  17. package/dist/src/circuit/server/index.js.map +1 -0
  18. package/dist/src/circuit/{reservation-store.d.ts → server/reservation-store.d.ts} +17 -10
  19. package/dist/src/circuit/server/reservation-store.d.ts.map +1 -0
  20. package/dist/src/circuit/server/reservation-store.js +57 -0
  21. package/dist/src/circuit/server/reservation-store.js.map +1 -0
  22. package/dist/src/circuit/server/reservation-voucher.d.ts.map +1 -0
  23. package/dist/src/circuit/{reservation-voucher.js → server/reservation-voucher.js} +1 -1
  24. package/dist/src/circuit/server/reservation-voucher.js.map +1 -0
  25. package/dist/src/circuit/transport/discovery.d.ts +45 -0
  26. package/dist/src/circuit/transport/discovery.d.ts.map +1 -0
  27. package/dist/src/circuit/transport/discovery.js +82 -0
  28. package/dist/src/circuit/transport/discovery.js.map +1 -0
  29. package/dist/src/circuit/transport/index.d.ts +33 -0
  30. package/dist/src/circuit/transport/index.d.ts.map +1 -0
  31. package/dist/src/circuit/transport/index.js +225 -0
  32. package/dist/src/circuit/transport/index.js.map +1 -0
  33. package/dist/src/circuit/transport/listener.d.ts +9 -0
  34. package/dist/src/circuit/transport/listener.d.ts.map +1 -0
  35. package/dist/src/circuit/transport/listener.js +76 -0
  36. package/dist/src/circuit/transport/listener.js.map +1 -0
  37. package/dist/src/circuit/transport/reservation-store.d.ts +60 -0
  38. package/dist/src/circuit/transport/reservation-store.d.ts.map +1 -0
  39. package/dist/src/circuit/transport/reservation-store.js +165 -0
  40. package/dist/src/circuit/transport/reservation-store.js.map +1 -0
  41. package/dist/src/circuit/utils.d.ts +4 -2
  42. package/dist/src/circuit/utils.d.ts.map +1 -1
  43. package/dist/src/circuit/utils.js +75 -102
  44. package/dist/src/circuit/utils.js.map +1 -1
  45. package/dist/src/components.d.ts +2 -1
  46. package/dist/src/components.d.ts.map +1 -1
  47. package/dist/src/components.js.map +1 -1
  48. package/dist/src/config.d.ts.map +1 -1
  49. package/dist/src/config.js +7 -18
  50. package/dist/src/config.js.map +1 -1
  51. package/dist/src/connection-manager/dialer/index.d.ts +2 -1
  52. package/dist/src/connection-manager/dialer/index.d.ts.map +1 -1
  53. package/dist/src/connection-manager/dialer/index.js +3 -3
  54. package/dist/src/connection-manager/dialer/index.js.map +1 -1
  55. package/dist/src/index.d.ts +5 -4
  56. package/dist/src/index.d.ts.map +1 -1
  57. package/dist/src/index.js.map +1 -1
  58. package/dist/src/libp2p.d.ts +2 -2
  59. package/dist/src/libp2p.d.ts.map +1 -1
  60. package/dist/src/libp2p.js +7 -19
  61. package/dist/src/libp2p.js.map +1 -1
  62. package/dist/src/transport-manager.js +1 -1
  63. package/dist/src/transport-manager.js.map +1 -1
  64. package/dist/src/upgrader.d.ts +2 -1
  65. package/dist/src/upgrader.d.ts.map +1 -1
  66. package/dist/src/upgrader.js +10 -10
  67. package/dist/src/upgrader.js.map +1 -1
  68. package/package.json +11 -5
  69. package/src/circuit/constants.ts +40 -5
  70. package/src/circuit/index.ts +17 -67
  71. package/src/circuit/server/advert-service.ts +108 -0
  72. package/src/circuit/server/index.ts +420 -0
  73. package/src/circuit/server/reservation-store.ts +111 -0
  74. package/src/circuit/{reservation-voucher.ts → server/reservation-voucher.ts} +3 -3
  75. package/src/circuit/transport/discovery.ts +127 -0
  76. package/src/circuit/transport/index.ts +325 -0
  77. package/src/circuit/transport/listener.ts +99 -0
  78. package/src/circuit/transport/reservation-store.ts +249 -0
  79. package/src/circuit/utils.ts +78 -115
  80. package/src/components.ts +2 -1
  81. package/src/config.ts +7 -18
  82. package/src/connection-manager/dialer/index.ts +5 -4
  83. package/src/index.ts +5 -4
  84. package/src/libp2p.ts +11 -24
  85. package/src/transport-manager.ts +1 -1
  86. package/src/upgrader.ts +12 -11
  87. package/src/version.ts +1 -1
  88. package/dist/src/circuit/client.d.ts +0 -81
  89. package/dist/src/circuit/client.d.ts.map +0 -1
  90. package/dist/src/circuit/client.js +0 -285
  91. package/dist/src/circuit/client.js.map +0 -1
  92. package/dist/src/circuit/hop.d.ts +0 -23
  93. package/dist/src/circuit/hop.d.ts.map +0 -1
  94. package/dist/src/circuit/hop.js +0 -167
  95. package/dist/src/circuit/hop.js.map +0 -1
  96. package/dist/src/circuit/interfaces.d.ts +0 -27
  97. package/dist/src/circuit/interfaces.d.ts.map +0 -1
  98. package/dist/src/circuit/interfaces.js +0 -2
  99. package/dist/src/circuit/interfaces.js.map +0 -1
  100. package/dist/src/circuit/listener.d.ts +0 -9
  101. package/dist/src/circuit/listener.d.ts.map +0 -1
  102. package/dist/src/circuit/listener.js +0 -62
  103. package/dist/src/circuit/listener.js.map +0 -1
  104. package/dist/src/circuit/multicodec.d.ts +0 -3
  105. package/dist/src/circuit/multicodec.d.ts.map +0 -1
  106. package/dist/src/circuit/multicodec.js +0 -3
  107. package/dist/src/circuit/multicodec.js.map +0 -1
  108. package/dist/src/circuit/relay.d.ts +0 -34
  109. package/dist/src/circuit/relay.d.ts.map +0 -1
  110. package/dist/src/circuit/relay.js +0 -61
  111. package/dist/src/circuit/relay.js.map +0 -1
  112. package/dist/src/circuit/reservation-store.d.ts.map +0 -1
  113. package/dist/src/circuit/reservation-store.js +0 -59
  114. package/dist/src/circuit/reservation-store.js.map +0 -1
  115. package/dist/src/circuit/reservation-voucher.d.ts.map +0 -1
  116. package/dist/src/circuit/reservation-voucher.js.map +0 -1
  117. package/dist/src/circuit/stop.d.ts +0 -19
  118. package/dist/src/circuit/stop.d.ts.map +0 -1
  119. package/dist/src/circuit/stop.js +0 -67
  120. package/dist/src/circuit/stop.js.map +0 -1
  121. package/dist/src/circuit/transport.d.ts +0 -66
  122. package/dist/src/circuit/transport.d.ts.map +0 -1
  123. package/dist/src/circuit/transport.js +0 -238
  124. package/dist/src/circuit/transport.js.map +0 -1
  125. package/src/circuit/client.ts +0 -381
  126. package/src/circuit/hop.ts +0 -210
  127. package/src/circuit/interfaces.ts +0 -28
  128. package/src/circuit/listener.ts +0 -83
  129. package/src/circuit/multicodec.ts +0 -3
  130. package/src/circuit/relay.ts +0 -87
  131. package/src/circuit/reservation-store.ts +0 -106
  132. package/src/circuit/stop.ts +0 -92
  133. package/src/circuit/transport.ts +0 -313
  134. /package/dist/src/circuit/{reservation-voucher.d.ts → server/reservation-voucher.d.ts} +0 -0
@@ -0,0 +1,108 @@
1
+ import { logger } from '@libp2p/logger'
2
+ import { codes } from '../../errors.js'
3
+ import { namespaceToCid } from '../utils.js'
4
+ import {
5
+ DEFAULT_ADVERT_BOOT_DELAY,
6
+ RELAY_RENDEZVOUS_NS
7
+ } from '../constants.js'
8
+ import type { Startable } from '@libp2p/interfaces/startable'
9
+ import type { ContentRouting } from '@libp2p/interface-content-routing'
10
+ import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'
11
+ import pRetry from 'p-retry'
12
+
13
+ const log = logger('libp2p:circuit-relay:advert-service')
14
+
15
+ export interface AdvertServiceInit {
16
+ /**
17
+ * How long to wait after startup to begin advertising the service
18
+ * - if some configured content routers take a while to warm up (for
19
+ * example, the DHT needs some peers to be able to publish) this
20
+ * value should be high enough that they will have warmed up
21
+ */
22
+ bootDelay?: number
23
+ }
24
+
25
+ export interface AdvertServiceComponents {
26
+ contentRouting: ContentRouting
27
+ }
28
+
29
+ export interface AdvertServiceEvents {
30
+ 'advert:success': CustomEvent<unknown>
31
+ 'advert:error': CustomEvent<Error>
32
+ }
33
+
34
+ export class AdvertService extends EventEmitter<AdvertServiceEvents> implements Startable {
35
+ private readonly contentRouting: ContentRouting
36
+ private timeout?: any
37
+ private started: boolean
38
+ private readonly bootDelay: number
39
+
40
+ /**
41
+ * Creates an instance of Relay
42
+ */
43
+ constructor (components: AdvertServiceComponents, init?: AdvertServiceInit) {
44
+ super()
45
+
46
+ this.contentRouting = components.contentRouting
47
+ this.bootDelay = init?.bootDelay ?? DEFAULT_ADVERT_BOOT_DELAY
48
+ this.started = false
49
+ }
50
+
51
+ isStarted (): boolean {
52
+ return this.started
53
+ }
54
+
55
+ /**
56
+ * Start Relay service
57
+ */
58
+ start (): void {
59
+ if (this.started) {
60
+ return
61
+ }
62
+
63
+ // Advertise service if HOP enabled and advertising enabled
64
+ this.timeout = setTimeout(() => {
65
+ this._advertiseService().catch(err => {
66
+ log.error('could not advertise service', err)
67
+ })
68
+ }, this.bootDelay)
69
+
70
+ this.started = true
71
+ }
72
+
73
+ /**
74
+ * Stop Relay service
75
+ */
76
+ stop (): void {
77
+ try {
78
+ clearTimeout(this.timeout)
79
+ } catch (err) { }
80
+
81
+ this.started = false
82
+ }
83
+
84
+ /**
85
+ * Advertise hop relay service in the network.
86
+ */
87
+ async _advertiseService (): Promise<void> {
88
+ await pRetry(async () => {
89
+ try {
90
+ const cid = await namespaceToCid(RELAY_RENDEZVOUS_NS)
91
+ await this.contentRouting.provide(cid)
92
+
93
+ this.dispatchEvent(new CustomEvent('advert:success'))
94
+ } catch (err: any) {
95
+ this.safeDispatchEvent('advert:error', { detail: err })
96
+
97
+ if (err.code === codes.ERR_NO_ROUTERS_AVAILABLE) {
98
+ log.error('a content router, such as a DHT, must be provided in order to advertise the relay service', err)
99
+ await this.stop()
100
+ return
101
+ }
102
+
103
+ log.error('could not advertise service', err)
104
+ throw err
105
+ }
106
+ })
107
+ }
108
+ }
@@ -0,0 +1,420 @@
1
+ import { logger } from '@libp2p/logger'
2
+ import { createLimitedRelay } from '../utils.js'
3
+ import {
4
+ CIRCUIT_PROTO_CODE,
5
+ DEFAULT_HOP_TIMEOUT,
6
+ RELAY_SOURCE_TAG
7
+ , RELAY_V2_HOP_CODEC, RELAY_V2_STOP_CODEC
8
+ } from '../constants.js'
9
+ import type { PeerStore } from '@libp2p/interface-peer-store'
10
+ import type { Startable } from '@libp2p/interfaces/startable'
11
+ import { ReservationStore, ReservationStoreInit } from './reservation-store.js'
12
+ import type { IncomingStreamData, Registrar } from '@libp2p/interface-registrar'
13
+ import { AdvertService, AdvertServiceComponents, AdvertServiceInit } from './advert-service.js'
14
+ import pDefer from 'p-defer'
15
+ import { pbStream, ProtobufStream } from 'it-pb-stream'
16
+ import { HopMessage, Reservation, Status, StopMessage } from '../pb/index.js'
17
+ import { Multiaddr, multiaddr } from '@multiformats/multiaddr'
18
+ import type { Connection, Stream } from '@libp2p/interface-connection'
19
+ import type { ConnectionGater } from '@libp2p/interface-connection-gater'
20
+ import { peerIdFromBytes } from '@libp2p/peer-id'
21
+ import type { PeerId } from '@libp2p/interface-peer-id'
22
+ import { RecordEnvelope } from '@libp2p/peer-record'
23
+ import { ReservationVoucherRecord } from './reservation-voucher.js'
24
+ import type { AddressManager } from '@libp2p/interface-address-manager'
25
+ import type { ConnectionManager } from '@libp2p/interface-connection-manager'
26
+ import type { CircuitRelayService, RelayReservation } from '../index.js'
27
+ import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'
28
+ import { setMaxListeners } from 'events'
29
+
30
+ const log = logger('libp2p:circuit-relay:server')
31
+
32
+ const isRelayAddr = (ma: Multiaddr): boolean => ma.protoCodes().includes(CIRCUIT_PROTO_CODE)
33
+
34
+ export interface CircuitRelayServerInit {
35
+ /**
36
+ * Incoming hop requests must complete within this time in ms otherwise
37
+ * the stream will be reset (default: 30s)
38
+ */
39
+ hopTimeout?: number
40
+
41
+ /**
42
+ * If true, advertise this service via libp2p content routing to allow
43
+ * peers to locate us on the network (default: false)
44
+ */
45
+ advertise?: boolean | AdvertServiceInit
46
+
47
+ /**
48
+ * Configuration of reservations
49
+ */
50
+ reservations?: ReservationStoreInit
51
+
52
+ /**
53
+ * The maximum number of simultaneous HOP inbound streams that can be open at once
54
+ */
55
+ maxInboundHopStreams?: number
56
+
57
+ /**
58
+ * The maximum number of simultaneous HOP outbound streams that can be open at once
59
+ */
60
+ maxOutboundHopStreams?: number
61
+ }
62
+
63
+ export interface HopProtocolOptions {
64
+ connection: Connection
65
+ request: HopMessage
66
+ stream: ProtobufStream<Stream>
67
+ }
68
+
69
+ export interface StopOptions {
70
+ connection: Connection
71
+ request: StopMessage
72
+ }
73
+
74
+ export interface CircuitRelayServerComponents extends AdvertServiceComponents {
75
+ registrar: Registrar
76
+ peerStore: PeerStore
77
+ addressManager: AddressManager
78
+ peerId: PeerId
79
+ connectionManager: ConnectionManager
80
+ connectionGater: ConnectionGater
81
+ }
82
+
83
+ export interface RelayServerEvents {
84
+ 'relay:reservation': CustomEvent<RelayReservation>
85
+ 'relay:advert:success': CustomEvent<unknown>
86
+ 'relay:advert:error': CustomEvent<Error>
87
+ }
88
+
89
+ class CircuitRelayServer extends EventEmitter<RelayServerEvents> implements Startable, CircuitRelayService {
90
+ private readonly registrar: Registrar
91
+ private readonly peerStore: PeerStore
92
+ private readonly addressManager: AddressManager
93
+ private readonly peerId: PeerId
94
+ private readonly connectionManager: ConnectionManager
95
+ private readonly connectionGater: ConnectionGater
96
+ private readonly reservationStore: ReservationStore
97
+ private readonly advertService: AdvertService | undefined
98
+ private started: boolean
99
+ private readonly hopTimeout: number
100
+ private readonly shutdownController: AbortController
101
+ private readonly maxInboundHopStreams?: number
102
+ private readonly maxOutboundHopStreams?: number
103
+
104
+ /**
105
+ * Creates an instance of Relay
106
+ */
107
+ constructor (components: CircuitRelayServerComponents, init: CircuitRelayServerInit = {}) {
108
+ super()
109
+
110
+ this.registrar = components.registrar
111
+ this.peerStore = components.peerStore
112
+ this.addressManager = components.addressManager
113
+ this.peerId = components.peerId
114
+ this.connectionManager = components.connectionManager
115
+ this.connectionGater = components.connectionGater
116
+ this.started = false
117
+ this.hopTimeout = init?.hopTimeout ?? DEFAULT_HOP_TIMEOUT
118
+ this.shutdownController = new AbortController()
119
+ this.maxInboundHopStreams = init.maxInboundHopStreams
120
+ this.maxOutboundHopStreams = init.maxOutboundHopStreams
121
+
122
+ try {
123
+ // fails on node < 15.4
124
+ setMaxListeners?.(Infinity, this.shutdownController.signal)
125
+ } catch { }
126
+
127
+ if (init.advertise != null && init.advertise !== false) {
128
+ this.advertService = new AdvertService(components, init.advertise === true ? undefined : init.advertise)
129
+ this.advertService.addEventListener('advert:success', () => {
130
+ this.dispatchEvent(new CustomEvent('relay:advert:success'))
131
+ })
132
+ this.advertService.addEventListener('advert:error', (evt) => {
133
+ this.safeDispatchEvent('relay:advert:error', { detail: evt.detail })
134
+ })
135
+ }
136
+
137
+ this.reservationStore = new ReservationStore(init.reservations)
138
+ }
139
+
140
+ isStarted (): boolean {
141
+ return this.started
142
+ }
143
+
144
+ /**
145
+ * Start Relay service
146
+ */
147
+ async start (): Promise<void> {
148
+ if (this.started) {
149
+ return
150
+ }
151
+
152
+ // Advertise service if HOP enabled and advertising enabled
153
+ this.advertService?.start()
154
+
155
+ await this.registrar.handle(RELAY_V2_HOP_CODEC, (data) => {
156
+ void this.onHop(data).catch(err => {
157
+ log.error(err)
158
+ })
159
+ }, {
160
+ maxInboundStreams: this.maxInboundHopStreams,
161
+ maxOutboundStreams: this.maxOutboundHopStreams
162
+ })
163
+
164
+ this.reservationStore.start()
165
+
166
+ this.started = true
167
+ }
168
+
169
+ /**
170
+ * Stop Relay service
171
+ */
172
+ async stop (): Promise<void> {
173
+ this.advertService?.stop()
174
+ this.reservationStore.stop()
175
+ this.shutdownController.abort()
176
+ await this.registrar.unhandle(RELAY_V2_HOP_CODEC)
177
+
178
+ this.started = false
179
+ }
180
+
181
+ async onHop ({ connection, stream }: IncomingStreamData): Promise<void> {
182
+ log('received circuit v2 hop protocol stream from %s', connection.remotePeer)
183
+
184
+ const hopTimeoutPromise = pDefer<HopMessage>()
185
+ const timeout = setTimeout(() => {
186
+ hopTimeoutPromise.reject('timed out')
187
+ }, this.hopTimeout)
188
+ const pbstr = pbStream(stream)
189
+
190
+ try {
191
+ const request: HopMessage = await Promise.race([
192
+ pbstr.pb(HopMessage).read(),
193
+ hopTimeoutPromise.promise
194
+ ])
195
+
196
+ if (request?.type == null) {
197
+ throw new Error('request was invalid, could not read from stream')
198
+ }
199
+
200
+ log('received', request.type)
201
+
202
+ await Promise.race([
203
+ this.handleHopProtocol({
204
+ connection,
205
+ stream: pbstr,
206
+ request
207
+ }),
208
+ hopTimeoutPromise.promise
209
+ ])
210
+ } catch (err: any) {
211
+ log.error('error while handling hop', err)
212
+ pbstr.pb(HopMessage).write({
213
+ type: HopMessage.Type.STATUS,
214
+ status: Status.MALFORMED_MESSAGE
215
+ })
216
+ stream.abort(err)
217
+ } finally {
218
+ clearTimeout(timeout)
219
+ }
220
+ }
221
+
222
+ async handleHopProtocol ({ stream, request, connection }: HopProtocolOptions): Promise<void> {
223
+ log('received hop message')
224
+ switch (request.type) {
225
+ case HopMessage.Type.RESERVE: await this.handleReserve({ stream, request, connection }); break
226
+ case HopMessage.Type.CONNECT: await this.handleConnect({ stream, request, connection }); break
227
+ default: {
228
+ log.error('invalid hop request type %s via peer %s', request.type, connection.remotePeer)
229
+ stream.pb(HopMessage).write({ type: HopMessage.Type.STATUS, status: Status.UNEXPECTED_MESSAGE })
230
+ }
231
+ }
232
+ }
233
+
234
+ async handleReserve ({ stream, request, connection }: HopProtocolOptions): Promise<void> {
235
+ const hopstr = stream.pb(HopMessage)
236
+ log('hop reserve request from %s', connection.remotePeer)
237
+
238
+ if (isRelayAddr(connection.remoteAddr)) {
239
+ log.error('relay reservation over circuit connection denied for peer: %p', connection.remotePeer)
240
+ hopstr.write({ type: HopMessage.Type.STATUS, status: Status.PERMISSION_DENIED })
241
+ return
242
+ }
243
+
244
+ if ((await this.connectionGater.denyInboundRelayReservation?.(connection.remotePeer)) === true) {
245
+ log.error('reservation for %p denied by connection gater', connection.remotePeer)
246
+ hopstr.write({ type: HopMessage.Type.STATUS, status: Status.PERMISSION_DENIED })
247
+ return
248
+ }
249
+
250
+ const result = await this.reservationStore.reserve(connection.remotePeer, connection.remoteAddr)
251
+
252
+ if (result.status !== Status.OK) {
253
+ hopstr.write({ type: HopMessage.Type.STATUS, status: result.status })
254
+ return
255
+ }
256
+
257
+ try {
258
+ // tag relay target peer
259
+ // result.expire is non-null if `ReservationStore.reserve` returns with status == OK
260
+ if (result.expire != null) {
261
+ const ttl = new Date().getTime() - result.expire
262
+ await this.peerStore.tagPeer(connection.remotePeer, RELAY_SOURCE_TAG, { value: 1, ttl })
263
+ }
264
+
265
+ hopstr.write({
266
+ type: HopMessage.Type.STATUS,
267
+ status: Status.OK,
268
+ reservation: await this.makeReservation(connection.remotePeer, BigInt(result.expire ?? 0)),
269
+ limit: (await this.reservationStore.get(connection.remotePeer))?.limit
270
+ })
271
+ log('sent confirmation response to %s', connection.remotePeer)
272
+ } catch (err) {
273
+ log.error('failed to send confirmation response to %p', connection.remotePeer, err)
274
+ await this.reservationStore.removeReservation(connection.remotePeer)
275
+ }
276
+ }
277
+
278
+ async makeReservation (
279
+ remotePeer: PeerId,
280
+ expire: bigint
281
+ ): Promise<Reservation> {
282
+ const addrs = []
283
+
284
+ for (const relayAddr of this.addressManager.getAddresses()) {
285
+ addrs.push(relayAddr.bytes)
286
+ }
287
+
288
+ const voucher = await RecordEnvelope.seal(new ReservationVoucherRecord({
289
+ peer: remotePeer,
290
+ relay: this.peerId,
291
+ expiration: Number(expire)
292
+ }), this.peerId)
293
+
294
+ return {
295
+ addrs,
296
+ expire,
297
+ voucher: voucher.marshal()
298
+ }
299
+ }
300
+
301
+ async handleConnect ({ stream, request, connection }: HopProtocolOptions): Promise<void> {
302
+ const hopstr = stream.pb(HopMessage)
303
+
304
+ if (isRelayAddr(connection.remoteAddr)) {
305
+ log.error('relay reservation over circuit connection denied for peer: %p', connection.remotePeer)
306
+ hopstr.write({ type: HopMessage.Type.STATUS, status: Status.PERMISSION_DENIED })
307
+ return
308
+ }
309
+
310
+ log('hop connect request from %s', connection.remotePeer)
311
+
312
+ let dstPeer: PeerId
313
+
314
+ try {
315
+ if (request.peer == null) {
316
+ log.error('no peer info in hop connect request')
317
+ throw new Error('no peer info in request')
318
+ }
319
+
320
+ request.peer.addrs.forEach(multiaddr)
321
+ dstPeer = peerIdFromBytes(request.peer.id)
322
+ } catch (err) {
323
+ log.error('invalid hop connect request via peer %p %s', connection.remotePeer, err)
324
+ hopstr.write({ type: HopMessage.Type.STATUS, status: Status.MALFORMED_MESSAGE })
325
+ return
326
+ }
327
+
328
+ if (!await this.reservationStore.hasReservation(dstPeer)) {
329
+ log.error('hop connect denied for destination peer %p not having a reservation for %p with status %s', dstPeer, connection.remotePeer, Status.NO_RESERVATION)
330
+ hopstr.write({ type: HopMessage.Type.STATUS, status: Status.NO_RESERVATION })
331
+ return
332
+ }
333
+
334
+ if ((await this.connectionGater.denyOutboundRelayedConnection?.(connection.remotePeer, dstPeer)) === true) {
335
+ log.error('hop connect for %p to %p denied by connection gater', connection.remotePeer, dstPeer)
336
+ hopstr.write({ type: HopMessage.Type.STATUS, status: Status.PERMISSION_DENIED })
337
+ return
338
+ }
339
+
340
+ const connections = this.connectionManager.getConnections(dstPeer)
341
+
342
+ if (connections.length === 0) {
343
+ log('hop connect denied for destination peer %p not having a connection for %p as there is no destination connection', dstPeer, connection.remotePeer)
344
+ hopstr.write({ type: HopMessage.Type.STATUS, status: Status.NO_RESERVATION })
345
+ return
346
+ }
347
+
348
+ const destinationConnection = connections[0]
349
+
350
+ const destinationStream = await this.stopHop({
351
+ connection: destinationConnection,
352
+ request: {
353
+ type: StopMessage.Type.CONNECT,
354
+ peer: {
355
+ id: connection.remotePeer.toBytes(),
356
+ addrs: []
357
+ }
358
+ }
359
+ })
360
+
361
+ if (destinationStream == null) {
362
+ log.error('failed to open stream to destination peer %s', destinationConnection?.remotePeer)
363
+ hopstr.write({ type: HopMessage.Type.STATUS, status: Status.CONNECTION_FAILED })
364
+ return
365
+ }
366
+
367
+ hopstr.write({ type: HopMessage.Type.STATUS, status: Status.OK })
368
+ const sourceStream = stream.unwrap()
369
+
370
+ log('connection from %p to %p established - merging streans', connection.remotePeer, dstPeer)
371
+ const limit = (await this.reservationStore.get(dstPeer))?.limit
372
+ // Short circuit the two streams to create the relayed connection
373
+ createLimitedRelay(sourceStream, destinationStream, this.shutdownController.signal, limit)
374
+ }
375
+
376
+ /**
377
+ * Send a STOP request to the target peer that the dialing peer wants to contact
378
+ */
379
+ async stopHop ({
380
+ connection,
381
+ request
382
+ }: StopOptions): Promise<Stream | undefined> {
383
+ log('starting circuit relay v2 stop request to %s', connection.remotePeer)
384
+ const stream = await connection.newStream([RELAY_V2_STOP_CODEC])
385
+ const pbstr = pbStream(stream)
386
+ const stopstr = pbstr.pb(StopMessage)
387
+ stopstr.write(request)
388
+ let response
389
+
390
+ try {
391
+ response = await stopstr.read()
392
+ } catch (err) {
393
+ log.error('error parsing stop message response from %s', connection.remotePeer)
394
+ }
395
+
396
+ if (response == null) {
397
+ log.error('could not read response from %s', connection.remotePeer)
398
+ stream.close()
399
+ return
400
+ }
401
+
402
+ if (response.status === Status.OK) {
403
+ log('stop request to %s was successful', connection.remotePeer)
404
+ return pbstr.unwrap()
405
+ }
406
+
407
+ log('stop request failed with code %d', response.status)
408
+ stream.close()
409
+ }
410
+
411
+ get reservations () {
412
+ return this.reservationStore.reservations
413
+ }
414
+ }
415
+
416
+ export function circuitRelayServer (init: CircuitRelayServerInit = {}): (components: CircuitRelayServerComponents) => CircuitRelayService {
417
+ return (components) => {
418
+ return new CircuitRelayServer(components, init)
419
+ }
420
+ }
@@ -0,0 +1,111 @@
1
+ import { Limit, Status } from '../pb/index.js'
2
+ import type { Multiaddr } from '@multiformats/multiaddr'
3
+ import type { PeerId } from '@libp2p/interface-peer-id'
4
+ import type { Startable } from '@libp2p/interfaces/startable'
5
+ import { PeerMap } from '@libp2p/peer-collections'
6
+ import type { RecursivePartial } from '@libp2p/interfaces'
7
+ import { DEFAULT_DATA_LIMIT, DEFAULT_DURATION_LIMIT, DEFAULT_MAX_RESERVATION_CLEAR_INTERVAL, DEFAULT_MAX_RESERVATION_STORE_SIZE, DEFAULT_MAX_RESERVATION_TTL } from '../constants.js'
8
+ import type { RelayReservation } from '../index.js'
9
+
10
+ export type ReservationStatus = Status.OK | Status.PERMISSION_DENIED | Status.RESERVATION_REFUSED
11
+
12
+ export interface ReservationStoreInit {
13
+ /*
14
+ * maximum number of reservations allowed, default: 15
15
+ */
16
+ maxReservations?: number
17
+ /*
18
+ * interval after which stale reservations are cleared, default: 300s
19
+ */
20
+ reservationClearInterval?: number
21
+ /*
22
+ * apply default relay limits to a new reservation, default: true
23
+ */
24
+ applyDefaultLimit?: boolean
25
+ /**
26
+ * reservation ttl, default: 2 hours
27
+ */
28
+ reservationTtl?: number
29
+ /**
30
+ * The maximum time a relayed connection can be open for
31
+ */
32
+ defaultDurationLimit?: number
33
+ /**
34
+ * The maximum amount of data allowed to be transferred over a relayed connection
35
+ */
36
+ defaultDataLimit?: bigint
37
+ }
38
+
39
+ export type ReservationStoreOptions = RecursivePartial<ReservationStoreInit>
40
+
41
+ export class ReservationStore implements Startable {
42
+ public readonly reservations = new PeerMap<RelayReservation>()
43
+ private _started = false
44
+ private interval: any
45
+ private readonly maxReservations: number
46
+ private readonly reservationClearInterval: number
47
+ private readonly applyDefaultLimit: boolean
48
+ private readonly reservationTtl: number
49
+ private readonly defaultDurationLimit: number
50
+ private readonly defaultDataLimit: bigint
51
+
52
+ constructor (options: ReservationStoreOptions = {}) {
53
+ this.maxReservations = options.maxReservations ?? DEFAULT_MAX_RESERVATION_STORE_SIZE
54
+ this.reservationClearInterval = options.reservationClearInterval ?? DEFAULT_MAX_RESERVATION_CLEAR_INTERVAL
55
+ this.applyDefaultLimit = options.applyDefaultLimit !== false
56
+ this.reservationTtl = options.reservationTtl ?? DEFAULT_MAX_RESERVATION_TTL
57
+ this.defaultDurationLimit = options.defaultDurationLimit ?? DEFAULT_DURATION_LIMIT
58
+ this.defaultDataLimit = options.defaultDataLimit ?? DEFAULT_DATA_LIMIT
59
+ }
60
+
61
+ isStarted (): boolean {
62
+ return this._started
63
+ }
64
+
65
+ start (): void {
66
+ if (this._started) {
67
+ return
68
+ }
69
+ this._started = true
70
+ this.interval = setInterval(
71
+ () => {
72
+ const now = (new Date()).getTime()
73
+ this.reservations.forEach((r, k) => {
74
+ if (r.expire.getTime() < now) {
75
+ this.reservations.delete(k)
76
+ }
77
+ })
78
+ },
79
+ this.reservationClearInterval
80
+ )
81
+ }
82
+
83
+ stop (): void {
84
+ clearInterval(this.interval)
85
+ }
86
+
87
+ reserve (peer: PeerId, addr: Multiaddr, limit?: Limit): { status: ReservationStatus, expire?: number } {
88
+ if (this.reservations.size >= this.maxReservations && !this.reservations.has(peer)) {
89
+ return { status: Status.RESERVATION_REFUSED }
90
+ }
91
+ const expire = new Date(Date.now() + this.reservationTtl)
92
+ let checkedLimit: Limit | undefined
93
+ if (this.applyDefaultLimit) {
94
+ checkedLimit = limit ?? { data: this.defaultDataLimit, duration: this.defaultDurationLimit }
95
+ }
96
+ this.reservations.set(peer, { addr, expire, limit: checkedLimit })
97
+ return { status: Status.OK, expire: expire.getTime() }
98
+ }
99
+
100
+ removeReservation (peer: PeerId): void {
101
+ this.reservations.delete(peer)
102
+ }
103
+
104
+ hasReservation (dst: PeerId): boolean {
105
+ return this.reservations.has(dst)
106
+ }
107
+
108
+ get (peer: PeerId): RelayReservation | undefined {
109
+ return this.reservations.get(peer)
110
+ }
111
+ }
@@ -1,6 +1,6 @@
1
1
  import type { PeerId } from '@libp2p/interface-peer-id'
2
2
  import type { Record } from '@libp2p/interface-record'
3
- import { ReservationVoucher } from './pb/index.js'
3
+ import { ReservationVoucher } from '../pb/index.js'
4
4
 
5
5
  export interface ReservationVoucherOptions {
6
6
  relay: PeerId
@@ -22,7 +22,7 @@ export class ReservationVoucherRecord implements Record {
22
22
  this.expiration = expiration
23
23
  }
24
24
 
25
- marshal () {
25
+ marshal (): Uint8Array {
26
26
  return ReservationVoucher.encode({
27
27
  relay: this.relay.toBytes(),
28
28
  peer: this.peer.toBytes(),
@@ -30,7 +30,7 @@ export class ReservationVoucherRecord implements Record {
30
30
  })
31
31
  }
32
32
 
33
- equals (other: Record) {
33
+ equals (other: Record): boolean {
34
34
  if (!(other instanceof ReservationVoucherRecord)) {
35
35
  return false
36
36
  }