-
Notifications
You must be signed in to change notification settings - Fork 43
/
index.ts
2653 lines (2258 loc) · 84.7 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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { pipe } from 'it-pipe'
import type { Connection } from '@libp2p/interfaces/connection'
import { RecordEnvelope } from '@libp2p/peer-record'
import { peerIdFromBytes, peerIdFromString } from '@libp2p/peer-id'
import { Logger, logger } from '@libp2p/logger'
import { createTopology } from '@libp2p/topology'
import { PeerStreams } from '@libp2p/pubsub/peer-streams'
import type { PeerId } from '@libp2p/interfaces/peer-id'
import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
import { MessageCache } from './message-cache.js'
import { RPC } from './message/rpc.js'
import * as constants from './constants.js'
import { createGossipRpc, shuffle, hasGossipProtocol, messageIdToString } from './utils/index.js'
import {
PeerScore,
PeerScoreParams,
PeerScoreThresholds,
createPeerScoreParams,
createPeerScoreThresholds,
PeerScoreStatsDump
} from './score/index.js'
import { IWantTracer } from './tracer.js'
import { SimpleTimeCache } from './utils/time-cache.js'
import {
ACCEPT_FROM_WHITELIST_DURATION_MS,
ACCEPT_FROM_WHITELIST_MAX_MESSAGES,
ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE
} from './constants.js'
import {
ChurnReason,
getMetrics,
IHaveIgnoreReason,
InclusionReason,
Metrics,
MetricsRegister,
ScorePenalty,
TopicStrToLabel,
ToSendGroupCount
} from './metrics.js'
import {
MessageAcceptance,
MsgIdFn,
PublishConfig,
TopicStr,
MsgIdStr,
ValidateError,
PeerIdStr,
MessageStatus,
RejectReason,
RejectReasonObj,
FastMsgIdFn,
AddrInfo,
DataTransform,
TopicValidatorFn,
rejectReasonFromAcceptance
} from './types.js'
import { buildRawMessage, validateToRawMessage } from './utils/buildRawMessage.js'
import { msgIdFnStrictNoSign, msgIdFnStrictSign } from './utils/msgIdFn.js'
import { computeAllPeersScoreWeights } from './score/scoreMetrics.js'
import { getPublishConfigFromPeerId } from './utils/publishConfig.js'
import type { GossipsubOptsSpec } from './config.js'
import { Components, Initializable } from '@libp2p/interfaces/components'
import {
Message,
PublishResult,
PubSub,
PubSubEvents,
PubSubInit,
StrictNoSign,
StrictSign,
SubscriptionChangeData
} from '@libp2p/interfaces/pubsub'
import type { IncomingStreamData } from '@libp2p/interfaces/registrar'
// From 'bl' library
interface BufferList {
slice: () => Buffer
}
type ConnectionDirection = 'inbound' | 'outbound'
type ReceivedMessageResult =
| { code: MessageStatus.duplicate; msgId: MsgIdStr }
| ({ code: MessageStatus.invalid; msgId?: MsgIdStr } & RejectReasonObj)
| { code: MessageStatus.valid; msgIdStr: MsgIdStr; msg: Message }
export const multicodec: string = constants.GossipsubIDv11
export interface GossipsubOpts extends GossipsubOptsSpec, PubSubInit {
/** if incoming messages on a subscribed topic should be automatically gossiped */
gossipIncoming: boolean
/** if dial should fallback to floodsub */
fallbackToFloodsub: boolean
/** if self-published messages should be sent to all peers */
floodPublish: boolean
/** whether PX is enabled; this should be enabled in bootstrappers and other well connected/trusted nodes. */
doPX: boolean
/** peers with which we will maintain direct connections */
directPeers: AddrInfo[]
/**
* If true will not forward messages to mesh peers until reportMessageValidationResult() is called.
* Messages will be cached in mcache for some time after which they are evicted. Calling
* reportMessageValidationResult() after the message is dropped from mcache won't forward the message.
*/
asyncValidation: boolean
/** Do not throw `InsufficientPeers` error if publishing to zero peers */
allowPublishToZeroPeers: boolean
/** For a single stream, await processing each RPC before processing the next */
awaitRpcHandler: boolean
/** For a single RPC, await processing each message before processing the next */
awaitRpcMessageHandler: boolean
// Extra modules, config
msgIdFn: MsgIdFn
/** fast message id function */
fastMsgIdFn: FastMsgIdFn
/** override the default MessageCache */
messageCache: MessageCache
/** peer score parameters */
scoreParams: Partial<PeerScoreParams>
/** peer score thresholds */
scoreThresholds: Partial<PeerScoreThresholds>
/** customize GossipsubIWantFollowupTime in order not to apply IWANT penalties */
gossipsubIWantFollowupMs: number
/** override constants for fine tuning */
prunePeers?: number
pruneBackoff?: number
graftFloodThreshold?: number
opportunisticGraftPeers?: number
opportunisticGraftTicks?: number
directConnectTicks?: number
dataTransform?: DataTransform
metricsRegister?: MetricsRegister | null
metricsTopicStrToLabel?: TopicStrToLabel
// Debug
/** Prefix tag for debug logs */
debugName?: string
}
export interface GossipsubMessage {
propagationSource: PeerId
msgId: MsgIdStr
msg: Message
}
export interface GossipsubEvents extends PubSubEvents {
'gossipsub:heartbeat': CustomEvent
'gossipsub:message': CustomEvent<GossipsubMessage>
}
enum GossipStatusCode {
started,
stopped
}
type GossipStatus =
| {
code: GossipStatusCode.started
registrarTopologyId: string
heartbeatTimeout: ReturnType<typeof setTimeout>
hearbeatStartMs: number
}
| {
code: GossipStatusCode.stopped
}
interface GossipOptions extends GossipsubOpts {
scoreParams: PeerScoreParams
scoreThresholds: PeerScoreThresholds
}
interface AcceptFromWhitelistEntry {
/** number of messages accepted since recomputing the peer's score */
messagesAccepted: number
/** have to recompute score after this time */
acceptUntil: number
}
export class GossipSub extends EventEmitter<GossipsubEvents> implements Initializable, PubSub<GossipsubEvents> {
/**
* The signature policy to follow by default
*/
public readonly globalSignaturePolicy: typeof StrictSign | typeof StrictNoSign
public multicodecs: string[] = [constants.GossipsubIDv11, constants.GossipsubIDv10]
private publishConfig: PublishConfig | undefined
private readonly dataTransform: DataTransform | undefined
// State
public readonly peers = new Map<PeerIdStr, PeerStreams>()
/** Direct peers */
public readonly direct = new Set<PeerIdStr>()
/** Floodsub peers */
private readonly floodsubPeers = new Set<PeerIdStr>()
/** Cache of seen messages */
private readonly seenCache: SimpleTimeCache<void>
/**
* Map of peer id and AcceptRequestWhileListEntry
*/
private readonly acceptFromWhitelist = new Map<PeerIdStr, AcceptFromWhitelistEntry>()
/**
* Map of topics to which peers are subscribed to
*/
private readonly topics = new Map<TopicStr, Set<PeerIdStr>>()
/**
* List of our subscriptions
*/
private readonly subscriptions = new Set<TopicStr>()
/**
* Map of topic meshes
* topic => peer id set
*/
public readonly mesh = new Map<TopicStr, Set<PeerIdStr>>()
/**
* Map of topics to set of peers. These mesh peers are the ones to which we are publishing without a topic membership
* topic => peer id set
*/
public readonly fanout = new Map<TopicStr, Set<PeerIdStr>>()
/**
* Map of last publish time for fanout topics
* topic => last publish time
*/
private readonly fanoutLastpub = new Map<TopicStr, number>()
/**
* Map of pending messages to gossip
* peer id => control messages
*/
public readonly gossip = new Map<PeerIdStr, RPC.ControlIHave[]>()
/**
* Map of control messages
* peer id => control message
*/
public readonly control = new Map<PeerIdStr, RPC.ControlMessage>()
/**
* Number of IHAVEs received from peer in the last heartbeat
*/
private readonly peerhave = new Map<PeerIdStr, number>()
/** Number of messages we have asked from peer in the last heartbeat */
private readonly iasked = new Map<PeerIdStr, number>()
/** Prune backoff map */
private readonly backoff = new Map<TopicStr, Map<PeerIdStr, number>>()
/**
* Connection direction cache, marks peers with outbound connections
* peer id => direction
*/
private readonly outbound = new Map<PeerIdStr, boolean>()
private readonly msgIdFn: MsgIdFn
/**
* A fast message id function used for internal message de-duplication
*/
private readonly fastMsgIdFn: FastMsgIdFn | undefined
/** Maps fast message-id to canonical message-id */
private readonly fastMsgIdCache: SimpleTimeCache<MsgIdStr> | undefined
/**
* Short term cache for published message ids. This is used for penalizing peers sending
* our own messages back if the messages are anonymous or use a random author.
*/
private readonly publishedMessageIds: SimpleTimeCache<void>
/**
* A message cache that contains the messages for last few heartbeat ticks
*/
private readonly mcache: MessageCache
/** Peer score tracking */
public readonly score: PeerScore
public readonly topicValidators = new Map<TopicStr, TopicValidatorFn>()
/**
* Number of heartbeats since the beginning of time
* This allows us to amortize some resource cleanup -- eg: backoff cleanup
*/
private heartbeatTicks = 0
/**
* Tracks IHAVE/IWANT promises broken by peers
*/
readonly gossipTracer: IWantTracer
private components = new Components()
private directPeerInitial: ReturnType<typeof setTimeout> | null = null
private readonly log: Logger
public static multicodec: string = constants.GossipsubIDv11
readonly opts: Required<GossipOptions>
private readonly metrics: Metrics | null
private status: GossipStatus = { code: GossipStatusCode.stopped }
private heartbeatTimer: {
_intervalId: ReturnType<typeof setInterval> | undefined
runPeriodically: (fn: () => void, period: number) => void
cancel: () => void
} | null = null
constructor(options: Partial<GossipsubOpts> = {}) {
super()
const opts = {
gossipIncoming: true,
fallbackToFloodsub: true,
floodPublish: true,
doPX: false,
directPeers: [],
D: constants.GossipsubD,
Dlo: constants.GossipsubDlo,
Dhi: constants.GossipsubDhi,
Dscore: constants.GossipsubDscore,
Dout: constants.GossipsubDout,
Dlazy: constants.GossipsubDlazy,
heartbeatInterval: constants.GossipsubHeartbeatInterval,
fanoutTTL: constants.GossipsubFanoutTTL,
mcacheLength: constants.GossipsubHistoryLength,
mcacheGossip: constants.GossipsubHistoryGossip,
seenTTL: constants.GossipsubSeenTTL,
gossipsubIWantFollowupMs: constants.GossipsubIWantFollowupTime,
prunePeers: constants.GossipsubPrunePeers,
pruneBackoff: constants.GossipsubPruneBackoff,
graftFloodThreshold: constants.GossipsubGraftFloodThreshold,
opportunisticGraftPeers: constants.GossipsubOpportunisticGraftPeers,
opportunisticGraftTicks: constants.GossipsubOpportunisticGraftTicks,
directConnectTicks: constants.GossipsubDirectConnectTicks,
...options,
scoreParams: createPeerScoreParams(options.scoreParams),
scoreThresholds: createPeerScoreThresholds(options.scoreThresholds)
}
this.globalSignaturePolicy = opts.globalSignaturePolicy ?? StrictSign
// Also wants to get notified of peers connected using floodsub
if (opts.fallbackToFloodsub) {
this.multicodecs.push(constants.FloodsubID)
}
// From pubsub
this.log = logger(opts.debugName ?? 'libp2p:gossipsub')
// Gossipsub
this.opts = opts as Required<GossipOptions>
this.direct = new Set(opts.directPeers.map((p) => p.id.toString()))
this.seenCache = new SimpleTimeCache<void>({ validityMs: opts.seenTTL })
this.publishedMessageIds = new SimpleTimeCache<void>({ validityMs: opts.seenTTL })
this.mcache = options.messageCache || new MessageCache(opts.mcacheGossip, opts.mcacheLength)
if (options.msgIdFn) {
// Use custom function
this.msgIdFn = options.msgIdFn
} else {
switch (this.globalSignaturePolicy) {
case StrictSign:
this.msgIdFn = msgIdFnStrictSign
break
case StrictNoSign:
this.msgIdFn = msgIdFnStrictNoSign
break
}
}
if (options.fastMsgIdFn) {
this.fastMsgIdFn = options.fastMsgIdFn
this.fastMsgIdCache = new SimpleTimeCache<string>({ validityMs: opts.seenTTL })
}
if (options.dataTransform) {
this.dataTransform = options.dataTransform
}
if (options.metricsRegister) {
if (!options.metricsTopicStrToLabel) {
throw Error('Must set metricsTopicStrToLabel with metrics')
}
// in theory, each topic has its own meshMessageDeliveriesWindow param
// however in lodestar, we configure it mostly the same so just pick the max of positive ones
// (some topics have meshMessageDeliveriesWindow as 0)
const maxMeshMessageDeliveriesWindowMs = Math.max(
...Object.values(opts.scoreParams.topics).map((topicParam) => topicParam.meshMessageDeliveriesWindow),
constants.DEFAULT_METRIC_MESH_MESSAGE_DELIVERIES_WINDOWS
)
const metrics = getMetrics(options.metricsRegister, options.metricsTopicStrToLabel, {
gossipPromiseExpireSec: this.opts.gossipsubIWantFollowupMs / 1000,
behaviourPenaltyThreshold: opts.scoreParams.behaviourPenaltyThreshold,
maxMeshMessageDeliveriesWindowSec: maxMeshMessageDeliveriesWindowMs / 1000
})
metrics.mcacheSize.addCollect(() => this.onScrapeMetrics(metrics))
for (const protocol of this.multicodecs) {
metrics.protocolsEnabled.set({ protocol }, 1)
}
this.metrics = metrics
} else {
this.metrics = null
}
this.gossipTracer = new IWantTracer(this.opts.gossipsubIWantFollowupMs, this.metrics)
/**
* libp2p
*/
this.score = new PeerScore(this.opts.scoreParams, this.metrics, {
scoreCacheValidityMs: opts.heartbeatInterval
})
}
getPeers(): PeerId[] {
return [...this.peers.keys()].map((str) => peerIdFromString(str))
}
isStarted(): boolean {
return this.status.code === GossipStatusCode.started
}
// LIFECYCLE METHODS
/**
* Pass libp2p components to interested system components
*/
async init(components: Components): Promise<void> {
this.components = components
this.score.init(components)
}
/**
* Mounts the gossipsub protocol onto the libp2p node and sends our
* our subscriptions to every peer connected
*/
async start(): Promise<void> {
// From pubsub
if (this.isStarted()) {
return
}
this.log('starting')
this.publishConfig = await getPublishConfigFromPeerId(this.globalSignaturePolicy, this.components.getPeerId())
// set direct peer addresses in the address book
await Promise.all(
this.opts.directPeers.map(async (p) => {
await this.components.getPeerStore().addressBook.add(p.id, p.addrs)
})
)
// Incoming streams
// Called after a peer dials us
await this.components.getRegistrar().handle(this.multicodecs, this.onIncomingStream.bind(this))
// # How does Gossipsub interact with libp2p? Rough guide from Mar 2022
//
// ## Setup:
// Gossipsub requests libp2p to callback, TBD
//
// `this.libp2p.handle()` registers a handler for `/meshsub/1.1.0` and other Gossipsub protocols
// The handler callback is registered in libp2p Upgrader.protocols map.
//
// Upgrader receives an inbound connection from some transport and (`Upgrader.upgradeInbound`):
// - Adds encryption (NOISE in our case)
// - Multiplex stream
// - Create a muxer and register that for each new stream call Upgrader.protocols handler
//
// ## Topology
// - new instance of Topology (unlinked to libp2p) with handlers
// - registar.register(topology)
// register protocol with topology
// Topology callbacks called on connection manager changes
const topology = createTopology({
onConnect: this.onPeerConnected.bind(this),
onDisconnect: this.onPeerDisconnected.bind(this)
})
const registrarTopologyId = await this.components.getRegistrar().register(this.multicodecs, topology)
// Schedule to start heartbeat after `GossipsubHeartbeatInitialDelay`
const heartbeatTimeout = setTimeout(this.runHeartbeat, constants.GossipsubHeartbeatInitialDelay)
// Then, run heartbeat every `heartbeatInterval` offset by `GossipsubHeartbeatInitialDelay`
this.status = {
code: GossipStatusCode.started,
registrarTopologyId,
heartbeatTimeout: heartbeatTimeout,
hearbeatStartMs: Date.now() + constants.GossipsubHeartbeatInitialDelay
}
this.log('started')
this.score.start()
// connect to direct peers
this.directPeerInitial = setTimeout(() => {
Promise.resolve()
.then(async () => {
await Promise.all(Array.from(this.direct).map(async (id) => await this.connect(id)))
})
.catch((err) => {
this.log(err)
})
}, constants.GossipsubDirectConnectInitialDelay)
}
/**
* Unmounts the gossipsub protocol and shuts down every connection
*/
async stop(): Promise<void> {
this.log('stopping')
// From pubsub
if (this.status.code !== GossipStatusCode.started) {
return
}
const { registrarTopologyId } = this.status
this.status = { code: GossipStatusCode.stopped }
// unregister protocol and handlers
this.components.getRegistrar().unregister(registrarTopologyId)
for (const peerStreams of this.peers.values()) {
peerStreams.close()
}
this.peers.clear()
this.subscriptions.clear()
// Gossipsub
if (this.heartbeatTimer) {
this.heartbeatTimer.cancel()
this.heartbeatTimer = null
}
this.score.stop()
this.mesh.clear()
this.fanout.clear()
this.fanoutLastpub.clear()
this.gossip.clear()
this.control.clear()
this.peerhave.clear()
this.iasked.clear()
this.backoff.clear()
this.outbound.clear()
this.gossipTracer.clear()
this.seenCache.clear()
if (this.fastMsgIdCache) this.fastMsgIdCache.clear()
if (this.directPeerInitial) clearTimeout(this.directPeerInitial)
this.log('stopped')
}
/** FOR DEBUG ONLY - Dump peer stats for all peers. Data is cloned, safe to mutate */
dumpPeerScoreStats(): PeerScoreStatsDump {
return this.score.dumpPeerScoreStats()
}
/**
* On an inbound stream opened
*/
private onIncomingStream({ protocol, stream, connection }: IncomingStreamData) {
if (!this.isStarted()) {
return
}
const peerId = connection.remotePeer
const peer = this.addPeer(peerId, protocol, connection.stat.direction)
const inboundStream = peer.attachInboundStream(stream)
this.pipePeerReadStream(peerId, inboundStream).catch((err) => this.log(err))
}
/**
* Registrar notifies an established connection with pubsub protocol
*/
private onPeerConnected(peerId: PeerId, conn: Connection): void {
if (!this.isStarted()) {
return
}
this.log('topology peer connected %p %s', peerId, conn.stat.direction)
Promise.resolve().then(async () => {
try {
const { stream, protocol } = await conn.newStream(this.multicodecs)
const peer = this.addPeer(peerId, protocol, conn.stat.direction)
await peer.attachOutboundStream(stream)
} catch (err) {
this.log(err)
}
// Immediately send my own subscriptions to the newly established conn
if (this.subscriptions.size > 0) {
this.sendSubscriptions(peerId.toString(), Array.from(this.subscriptions), true)
}
})
}
/**
* Registrar notifies a closing connection with pubsub protocol
*/
private onPeerDisconnected(peerId: PeerId): void {
this.log('connection ended %p', peerId)
this.removePeer(peerId)
}
/**
* Add a peer to the router
*/
private addPeer(peerId: PeerId, protocol: string, direction: ConnectionDirection): PeerStreams {
const peerIdStr = peerId.toString()
let peerStreams = this.peers.get(peerIdStr)
// If peer streams already exists, do nothing
if (peerStreams === undefined) {
// else create a new peer streams
this.log('new peer %p', peerId)
peerStreams = new PeerStreams({
id: peerId,
protocol
})
this.peers.set(peerIdStr, peerStreams)
peerStreams.addEventListener('close', () => this.removePeer(peerId))
}
// Add to peer scoring
this.score.addPeer(peerIdStr)
if (protocol === constants.FloodsubID) {
this.floodsubPeers.add(peerIdStr)
}
this.metrics?.peersPerProtocol.inc({ protocol }, 1)
// track the connection direction. Don't allow to unset outbound
if (!this.outbound.get(peerIdStr)) {
this.outbound.set(peerIdStr, direction === 'outbound')
}
return peerStreams
}
/**
* Removes a peer from the router
*/
private removePeer(peerId: PeerId): PeerStreams | undefined {
const id = peerId.toString()
const peerStreams = this.peers.get(id)
if (peerStreams != null) {
this.metrics?.peersPerProtocol.inc({ protocol: peerStreams.protocol }, -1)
// delete peer streams. Must delete first to prevent re-entracy loop in .close()
this.log('delete peer %p', peerId)
this.peers.delete(id)
// close peer streams
peerStreams.close()
// remove peer from topics map
for (const peers of this.topics.values()) {
peers.delete(id)
}
}
// Remove this peer from the mesh
// eslint-disable-next-line no-unused-vars
for (const [topicStr, peers] of this.mesh) {
if (peers.delete(id) === true) {
this.metrics?.onRemoveFromMesh(topicStr, ChurnReason.Dc, 1)
}
}
// Remove this peer from the fanout
// eslint-disable-next-line no-unused-vars
for (const peers of this.fanout.values()) {
peers.delete(id)
}
// Remove from floodsubPeers
this.floodsubPeers.delete(id)
// Remove from gossip mapping
this.gossip.delete(id)
// Remove from control mapping
this.control.delete(id)
// Remove from backoff mapping
this.outbound.delete(id)
// Remove from peer scoring
this.score.removePeer(id)
this.acceptFromWhitelist.delete(id)
return peerStreams
}
// API METHODS
get started(): boolean {
return this.status.code === GossipStatusCode.started
}
/**
* Get a the peer-ids in a topic mesh
*/
getMeshPeers(topic: TopicStr): PeerIdStr[] {
const peersInTopic = this.mesh.get(topic)
return peersInTopic ? Array.from(peersInTopic) : []
}
/**
* Get a list of the peer-ids that are subscribed to one topic.
*/
getSubscribers(topic: TopicStr): PeerId[] {
const peersInTopic = this.topics.get(topic)
return (peersInTopic ? Array.from(peersInTopic) : []).map((str) => peerIdFromString(str))
}
/**
* Get the list of topics which the peer is subscribed to.
*/
getTopics(): TopicStr[] {
return Array.from(this.subscriptions)
}
// TODO: Reviewing Pubsub API
// MESSAGE METHODS
/**
* Responsible for processing each RPC message received by other peers.
*/
private async pipePeerReadStream(peerId: PeerId, stream: AsyncIterable<Uint8Array | BufferList>): Promise<void> {
try {
await pipe(stream, async (source) => {
for await (const data of source) {
try {
// TODO: Check max gossip message size, before decodeRpc()
// Note: `stream` maybe a BufferList which requires calling .slice to concat all the chunks into
// a single Buffer instance that protobuf js can deal with.
// Otherwise it will throw:
// ```
// Error: illegal buffer
// at create_typed_array (js-libp2p-gossipsub/node_modules/protobufjs/src/reader.js:47:15)
const rpcBytes = data instanceof Uint8Array ? data : data.slice()
// Note: This function may throw, it must be wrapped in a try {} catch {} to prevent closing the stream.
// TODO: What should we do if the entire RPC is invalid?
const rpc = RPC.decode(rpcBytes)
this.metrics?.onRpcRecv(rpc, rpcBytes.length)
// Since processRpc may be overridden entirely in unsafe ways,
// the simplest/safest option here is to wrap in a function and capture all errors
// to prevent a top-level unhandled exception
// This processing of rpc messages should happen without awaiting full validation/execution of prior messages
if (this.opts.awaitRpcHandler) {
await this.handleReceivedRpc(peerId, rpc)
} else {
this.handleReceivedRpc(peerId, rpc).catch((err) => this.log(err))
}
} catch (e) {
this.log(e as Error)
}
}
})
} catch (err) {
this.log.error(err)
this.onPeerDisconnected(peerId)
}
}
/**
* Handles an rpc request from a peer
*/
public async handleReceivedRpc(from: PeerId, rpc: RPC): Promise<void> {
// Check if peer is graylisted in which case we ignore the event
if (!this.acceptFrom(from.toString())) {
this.log('received message from unacceptable peer %p', from)
this.metrics?.rpcRecvNotAccepted.inc()
return
}
this.log('rpc from %p', from)
// Handle received subscriptions
if (rpc.subscriptions.length > 0) {
// update peer subscriptions
rpc.subscriptions.forEach((subOpt) => {
this.handleReceivedSubscription(from, subOpt)
})
this.dispatchEvent(
new CustomEvent<SubscriptionChangeData>('subscription-change', {
detail: {
peerId: from,
subscriptions: rpc.subscriptions
.filter((sub) => sub.topic !== null)
.map((sub) => {
return {
topic: sub.topic ?? '',
subscribe: Boolean(sub.subscribe)
}
})
}
})
)
}
// Handle messages
// TODO: (up to limit)
for (const message of rpc.messages) {
const handleReceivedMessagePromise = this.handleReceivedMessage(from, message)
// Should never throw, but handle just in case
.catch((err) => this.log(err))
if (this.opts.awaitRpcMessageHandler) {
await handleReceivedMessagePromise
}
}
// Handle control messages
if (rpc.control) {
await this.handleControlMessage(from.toString(), rpc.control)
}
}
/**
* Handles a subscription change from a peer
*/
private handleReceivedSubscription(from: PeerId, subOpt: RPC.SubOpts): void {
if (subOpt.topic == null) {
return
}
this.log('subscription update from %p topic %s', from, subOpt.topic)
let topicSet = this.topics.get(subOpt.topic)
if (topicSet == null) {
topicSet = new Set()
this.topics.set(subOpt.topic, topicSet)
}
if (subOpt.subscribe) {
// subscribe peer to new topic
topicSet.add(from.toString())
} else {
// unsubscribe from existing topic
topicSet.delete(from.toString())
}
// TODO: rust-libp2p has A LOT more logic here
}
/**
* Handles a newly received message from an RPC.
* May forward to all peers in the mesh.
*/
private async handleReceivedMessage(from: PeerId, rpcMsg: RPC.Message): Promise<void> {
this.metrics?.onMsgRecvPreValidation(rpcMsg.topic)
const validationResult = await this.validateReceivedMessage(from, rpcMsg)
this.metrics?.onMsgRecvResult(rpcMsg.topic, validationResult.code)
switch (validationResult.code) {
case MessageStatus.duplicate:
// Report the duplicate
this.score.duplicateMessage(from.toString(), validationResult.msgId, rpcMsg.topic)
this.mcache.observeDuplicate(validationResult.msgId, from.toString())
return
case MessageStatus.invalid:
// invalid messages received
// metrics.register_invalid_message(&raw_message.topic)
// Tell peer_score about reject
// Reject the original source, and any duplicates we've seen from other peers.
if (validationResult.msgId) {
this.score.rejectMessage(from.toString(), validationResult.msgId, rpcMsg.topic, validationResult.reason)
this.gossipTracer.rejectMessage(validationResult.msgId, validationResult.reason)
} else {
this.score.rejectInvalidMessage(from.toString(), rpcMsg.topic)
}
this.metrics?.onMsgRecvInvalid(rpcMsg.topic, validationResult)
return
case MessageStatus.valid:
// Tells score that message arrived (but is maybe not fully validated yet).
// Consider the message as delivered for gossip promises.
this.score.validateMessage(validationResult.msgIdStr)
this.gossipTracer.deliverMessage(validationResult.msgIdStr)
// Add the message to our memcache
this.mcache.put(validationResult.msgIdStr, rpcMsg)
// Dispatch the message to the user if we are subscribed to the topic
if (this.subscriptions.has(rpcMsg.topic)) {
const isFromSelf = this.components.getPeerId().equals(from)
if (!isFromSelf || this.opts.emitSelf) {
super.dispatchEvent(
new CustomEvent<GossipsubMessage>('gossipsub:message', {
detail: {
propagationSource: from,
msgId: validationResult.msgIdStr,
msg: validationResult.msg
}
})
)
// TODO: Add option to switch between emit per topic or all messages in one
super.dispatchEvent(new CustomEvent<Message>('message', { detail: validationResult.msg }))
}
}
// Forward the message to mesh peers, if no validation is required
// If asyncValidation is ON, expect the app layer to call reportMessageValidationResult(), then forward
if (!this.opts.asyncValidation) {
// TODO: in rust-libp2p
// .forward_msg(&msg_id, raw_message, Some(propagation_source))
this.forwardMessage(validationResult.msgIdStr, rpcMsg, from.toString())
}
}
}
/**
* Handles a newly received message from an RPC.
* May forward to all peers in the mesh.
*/
private async validateReceivedMessage(
propagationSource: PeerId,
rpcMsg: RPC.Message
): Promise<ReceivedMessageResult> {
// Fast message ID stuff
const fastMsgIdStr = this.fastMsgIdFn?.(rpcMsg)
const msgIdCached = fastMsgIdStr && this.fastMsgIdCache?.get(fastMsgIdStr)
if (msgIdCached) {
// This message has been seen previously. Ignore it
return { code: MessageStatus.duplicate, msgId: msgIdCached }
}
// Perform basic validation on message and convert to RawGossipsubMessage for fastMsgIdFn()
const validationResult = await validateToRawMessage(this.globalSignaturePolicy, rpcMsg)
if (!validationResult.valid) {
return { code: MessageStatus.invalid, reason: RejectReason.Error, error: validationResult.error }
}
// Try and perform the data transform to the message. If it fails, consider it invalid.
let data: Uint8Array
try {
const transformedData = rpcMsg.data ?? new Uint8Array(0)
data = this.dataTransform ? this.dataTransform.inboundTransform(rpcMsg.topic, transformedData) : transformedData
} catch (e) {
this.log('Invalid message, transform failed', e)
return { code: MessageStatus.invalid, reason: RejectReason.Error, error: ValidateError.TransformFailed }
}
if (rpcMsg.from == null) {
this.log('Invalid message, transform failed')
return { code: MessageStatus.invalid, reason: RejectReason.Error, error: ValidateError.TransformFailed }
}
const msg: Message = {
from: peerIdFromBytes(rpcMsg.from),
data: data,
sequenceNumber: rpcMsg.seqno == null ? undefined : BigInt(`0x${uint8ArrayToString(rpcMsg.seqno, 'base16')}`),
topic: rpcMsg.topic
}
// TODO: Check if message is from a blacklisted source or propagation origin