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