-
Notifications
You must be signed in to change notification settings - Fork 44
/
index.ts
3126 lines (2668 loc) · 103 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 { CustomEvent, TypedEventEmitter, StrictSign, StrictNoSign, TopicValidatorResult, serviceCapabilities, serviceDependencies } from '@libp2p/interface'
import { peerIdFromBytes, peerIdFromString } from '@libp2p/peer-id'
import { encode } from 'it-length-prefixed'
import { pipe } from 'it-pipe'
import { pushable } from 'it-pushable'
import * as constants from './constants.js'
import {
ACCEPT_FROM_WHITELIST_DURATION_MS,
ACCEPT_FROM_WHITELIST_MAX_MESSAGES,
ACCEPT_FROM_WHITELIST_THRESHOLD_SCORE,
BACKOFF_SLACK
} from './constants.js'
import { type DecodeRPCLimits, defaultDecodeRpcLimits } from './message/decodeRpc.js'
import { RPC } from './message/rpc.js'
import { MessageCache, type MessageCacheRecord } from './message-cache.js'
import {
ChurnReason,
getMetrics,
IHaveIgnoreReason,
InclusionReason,
type Metrics,
type MetricsRegister,
ScorePenalty,
type TopicStrToLabel,
type ToSendGroupCount
} from './metrics.js'
import {
PeerScore,
type PeerScoreParams,
type PeerScoreThresholds,
createPeerScoreParams,
createPeerScoreThresholds,
type PeerScoreStatsDump
} from './score/index.js'
import { computeAllPeersScoreWeights } from './score/scoreMetrics.js'
import { InboundStream, OutboundStream } from './stream.js'
import { IWantTracer } from './tracer.js'
import {
type MsgIdFn,
type PublishConfig,
type TopicStr,
type MsgIdStr,
ValidateError,
type PeerIdStr,
MessageStatus,
RejectReason,
type RejectReasonObj,
type FastMsgIdFn,
type AddrInfo,
type DataTransform,
rejectReasonFromAcceptance,
type MsgIdToStrFn,
type MessageId,
type PublishOpts
} from './types.js'
import { buildRawMessage, validateToRawMessage } from './utils/buildRawMessage.js'
import { createGossipRpc, ensureControl } from './utils/create-gossip-rpc.js'
import { shuffle, messageIdToString } from './utils/index.js'
import { msgIdFnStrictNoSign, msgIdFnStrictSign } from './utils/msgIdFn.js'
import { multiaddrToIPStr } from './utils/multiaddr.js'
import { getPublishConfigFromPeerId } from './utils/publishConfig.js'
import { removeFirstNItemsFromSet, removeItemsFromSet } from './utils/set.js'
import { SimpleTimeCache } from './utils/time-cache.js'
import type { GossipsubOptsSpec } from './config.js'
import type {
Connection, Direction, Stream, PeerId, Peer, PeerStore,
Message,
PublishResult,
PubSub,
PubSubEvents,
PubSubInit,
SubscriptionChangeData,
TopicValidatorFn,
Logger,
ComponentLogger,
Topology
} from '@libp2p/interface'
import type { ConnectionManager, IncomingStreamData, Registrar } from '@libp2p/interface-internal'
import type { Multiaddr } from '@multiformats/multiaddr'
import type { Uint8ArrayList } from 'uint8arraylist'
type ConnectionDirection = 'inbound' | 'outbound'
type ReceivedMessageResult =
| { code: MessageStatus.duplicate, msgIdStr: MsgIdStr }
| ({ code: MessageStatus.invalid, msgIdStr?: MsgIdStr } & RejectReasonObj)
| { code: MessageStatus.valid, messageId: MessageId, msg: Message }
export const multicodec: string = constants.GossipsubIDv11
export interface GossipsubOpts extends GossipsubOptsSpec, PubSubInit {
/** if dial should fallback to floodsub */
fallbackToFloodsub: boolean
/** if self-published messages should be sent to all peers */
floodPublish: boolean
/** serialize message once and send to all peers without control messages */
batchPublish: 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 `PublishError.NoPeersSubscribedToTopic` error if there are no
* peers listening on the topic.
*
* N.B. if you sent this option to true, and you publish a message on a topic
* with no peers listening on that topic, no other network node will ever
* receive the message.
*/
allowPublishToZeroTopicPeers: boolean
/** Do not throw `PublishError.Duplicate` if publishing duplicate messages */
ignoreDuplicatePublishError: 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
/** message id function */
msgIdFn: MsgIdFn
/** fast message id function */
fastMsgIdFn: FastMsgIdFn
/** Uint8Array message id to string function */
msgIdToStrFn: MsgIdToStrFn
/** 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
unsubcribeBackoff?: number
graftFloodThreshold?: number
opportunisticGraftPeers?: number
opportunisticGraftTicks?: number
directConnectTicks?: number
dataTransform?: DataTransform
metricsRegister?: MetricsRegister | null
metricsTopicStrToLabel?: TopicStrToLabel
// Debug
/** Prefix tag for debug logs */
debugName?: string
/**
* Specify the maximum number of inbound gossipsub protocol
* streams that are allowed to be open concurrently
*/
maxInboundStreams?: number
/**
* Specify the maximum number of outbound gossipsub protocol
* streams that are allowed to be open concurrently
*/
maxOutboundStreams?: number
/**
* Pass true to run on transient connections - data or time-limited
* connections that may be closed at any time such as circuit relay
* connections.
*
* @default false
*/
runOnTransientConnection?: boolean
/**
* Specify max buffer size in bytes for OutboundStream.
* If full it will throw and reject sending any more data.
*/
maxOutboundBufferSize?: number
/**
* Specify max size to skip decoding messages whose data
* section exceeds this size.
*
*/
maxInboundDataLength?: number
/**
* If provided, only allow topics in this list
*/
allowedTopics?: string[] | Set<string>
/**
* Limits to bound protobuf decoding
*/
decodeRpcLimits?: DecodeRPCLimits
/**
* If true, will utilize the libp2p connection manager tagging system to prune/graft connections to peers, defaults to true
*/
tagMeshPeers: boolean
}
export interface GossipsubMessage {
propagationSource: PeerId
msgId: MsgIdStr
msg: Message
}
export interface MeshPeer {
peerId: string
topic: string
direction: Direction
}
export interface GossipsubEvents extends PubSubEvents {
'gossipsub:heartbeat': CustomEvent
'gossipsub:message': CustomEvent<GossipsubMessage>
'gossipsub:graft': CustomEvent<MeshPeer>
'gossipsub:prune': CustomEvent<MeshPeer>
}
enum GossipStatusCode {
started,
stopped
}
type GossipStatus =
| {
code: GossipStatusCode.started
registrarTopologyIds: 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 interface GossipSubComponents {
peerId: PeerId
peerStore: PeerStore
registrar: Registrar
connectionManager: ConnectionManager
logger: ComponentLogger
}
export class GossipSub extends TypedEventEmitter<GossipsubEvents> implements 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 Set<PeerIdStr>()
public readonly streamsInbound = new Map<PeerIdStr, InboundStream>()
public readonly streamsOutbound = new Map<PeerIdStr, OutboundStream>()
/** Ensures outbound streams are created sequentially */
private outboundInflightQueue = pushable<{ peerId: PeerId, connection: Connection }>({ objectMode: true })
/** 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
private readonly msgIdToStrFn: MsgIdToStrFn
/** 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
/**
* Custom validator function per topic.
* Must return or resolve quickly (< 100ms) to prevent causing penalties for late messages.
* If you need to apply validation that may require longer times use `asyncValidation` option and callback the
* validation result through `Gossipsub.reportValidationResult`
*/
public readonly topicValidators = new Map<TopicStr, TopicValidatorFn>()
/**
* Make this protected so child class may want to redirect to its own log.
*/
protected readonly log: Logger
/**
* 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 readonly components: GossipSubComponents
private directPeerInitial: ReturnType<typeof setTimeout> | null = null
public static multicodec: string = constants.GossipsubIDv11
// Options
readonly opts: Required<GossipOptions>
private readonly decodeRpcLimits: DecodeRPCLimits
private readonly metrics: Metrics | null
private status: GossipStatus = { code: GossipStatusCode.stopped }
private readonly maxInboundStreams?: number
private readonly maxOutboundStreams?: number
private readonly runOnTransientConnection?: boolean
private readonly allowedTopics: Set<TopicStr> | null
private heartbeatTimer: {
_intervalId: ReturnType<typeof setInterval> | undefined
runPeriodically(fn: () => void, period: number): void
cancel(): void
} | null = null
constructor (components: GossipSubComponents, options: Partial<GossipsubOpts> = {}) {
super()
const opts = {
fallbackToFloodsub: true,
floodPublish: true,
batchPublish: false,
tagMeshPeers: 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,
unsubcribeBackoff: constants.GossipsubUnsubscribeBackoff,
graftFloodThreshold: constants.GossipsubGraftFloodThreshold,
opportunisticGraftPeers: constants.GossipsubOpportunisticGraftPeers,
opportunisticGraftTicks: constants.GossipsubOpportunisticGraftTicks,
directConnectTicks: constants.GossipsubDirectConnectTicks,
...options,
scoreParams: createPeerScoreParams(options.scoreParams),
scoreThresholds: createPeerScoreThresholds(options.scoreThresholds)
}
this.components = components
this.decodeRpcLimits = opts.decodeRpcLimits ?? defaultDecodeRpcLimits
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 = components.logger.forComponent(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 })
if (options.msgIdFn != null) {
// Use custom function
this.msgIdFn = options.msgIdFn
} else {
switch (this.globalSignaturePolicy) {
case StrictSign:
this.msgIdFn = msgIdFnStrictSign
break
case StrictNoSign:
this.msgIdFn = msgIdFnStrictNoSign
break
default:
throw new Error(`Invalid globalSignaturePolicy: ${this.globalSignaturePolicy}`)
}
}
if (options.fastMsgIdFn != null) {
this.fastMsgIdFn = options.fastMsgIdFn
this.fastMsgIdCache = new SimpleTimeCache<MsgIdStr>({ validityMs: opts.seenTTL })
}
// By default, gossipsub only provide a browser friendly function to convert Uint8Array message id to string.
this.msgIdToStrFn = options.msgIdToStrFn ?? messageIdToString
this.mcache = options.messageCache ?? new MessageCache(opts.mcacheGossip, opts.mcacheLength, this.msgIdToStrFn)
if (options.dataTransform != null) {
this.dataTransform = options.dataTransform
}
if (options.metricsRegister != null) {
if (options.metricsTopicStrToLabel == null) {
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.msgIdToStrFn, this.metrics)
/**
* libp2p
*/
this.score = new PeerScore(this.opts.scoreParams, this.metrics, this.components.logger, {
scoreCacheValidityMs: opts.heartbeatInterval
})
this.maxInboundStreams = options.maxInboundStreams
this.maxOutboundStreams = options.maxOutboundStreams
this.runOnTransientConnection = options.runOnTransientConnection
this.allowedTopics = (opts.allowedTopics != null) ? new Set(opts.allowedTopics) : null
}
readonly [Symbol.toStringTag] = '@chainsafe/libp2p-gossipsub'
readonly [serviceCapabilities]: string[] = [
'@libp2p/pubsub'
]
readonly [serviceDependencies]: string[] = [
'@libp2p/identify'
]
getPeers (): PeerId[] {
return [...this.peers.keys()].map((str) => peerIdFromString(str))
}
isStarted (): boolean {
return this.status.code === GossipStatusCode.started
}
// LIFECYCLE METHODS
/**
* 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.peerId)
// Create the outbound inflight queue
// This ensures that outbound stream creation happens sequentially
this.outboundInflightQueue = pushable({ objectMode: true })
pipe(this.outboundInflightQueue, async (source) => {
for await (const { peerId, connection } of source) {
await this.createOutboundStream(peerId, connection)
}
}).catch((e) => { this.log.error('outbound inflight queue error', e) })
// set direct peer addresses in the address book
await Promise.all(
this.opts.directPeers.map(async (p) => {
await this.components.peerStore.merge(p.id, {
multiaddrs: p.addrs
})
})
)
const registrar = this.components.registrar
// Incoming streams
// Called after a peer dials us
await Promise.all(
this.multicodecs.map(async (multicodec) =>
registrar.handle(multicodec, this.onIncomingStream.bind(this), {
maxInboundStreams: this.maxInboundStreams,
maxOutboundStreams: this.maxOutboundStreams,
runOnTransientConnection: this.runOnTransientConnection
})
)
)
// # 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: Topology = {
onConnect: this.onPeerConnected.bind(this),
onDisconnect: this.onPeerDisconnected.bind(this),
notifyOnTransient: this.runOnTransientConnection
}
const registrarTopologyIds = await Promise.all(
this.multicodecs.map(async (multicodec) => registrar.register(multicodec, 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,
registrarTopologyIds,
heartbeatTimeout,
hearbeatStartMs: Date.now() + constants.GossipsubHeartbeatInitialDelay
}
this.score.start()
// connect to direct peers
this.directPeerInitial = setTimeout(() => {
Promise.resolve()
.then(async () => {
await Promise.all(Array.from(this.direct).map(async (id) => this.connect(id)))
})
.catch((err) => {
this.log(err)
})
}, constants.GossipsubDirectConnectInitialDelay)
if (this.opts.tagMeshPeers) {
this.addEventListener('gossipsub:graft', this.tagMeshPeer)
this.addEventListener('gossipsub:prune', this.untagMeshPeer)
}
this.log('started')
}
/**
* 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 { registrarTopologyIds } = this.status
this.status = { code: GossipStatusCode.stopped }
if (this.opts.tagMeshPeers) {
this.removeEventListener('gossipsub:graft', this.tagMeshPeer)
this.removeEventListener('gossipsub:prune', this.untagMeshPeer)
}
// unregister protocol and handlers
const registrar = this.components.registrar
await Promise.all(this.multicodecs.map(async (multicodec) => registrar.unhandle(multicodec)))
registrarTopologyIds.forEach((id) => { registrar.unregister(id) })
this.outboundInflightQueue.end()
const closePromises = []
for (const outboundStream of this.streamsOutbound.values()) {
closePromises.push(outboundStream.close())
}
this.streamsOutbound.clear()
for (const inboundStream of this.streamsInbound.values()) {
closePromises.push(inboundStream.close())
}
this.streamsInbound.clear()
await Promise.all(closePromises)
this.peers.clear()
this.subscriptions.clear()
// Gossipsub
if (this.heartbeatTimer != null) {
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 != null) this.fastMsgIdCache.clear()
if (this.directPeerInitial != null) 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 ({ stream, connection }: IncomingStreamData): void {
if (!this.isStarted()) {
return
}
const peerId = connection.remotePeer
// add peer to router
this.addPeer(peerId, connection.direction, connection.remoteAddr)
// create inbound stream
this.createInboundStream(peerId, stream)
// attempt to create outbound stream
this.outboundInflightQueue.push({ peerId, connection })
}
/**
* Registrar notifies an established connection with pubsub protocol
*/
private onPeerConnected (peerId: PeerId, connection: Connection): void {
this.metrics?.newConnectionCount.inc({ status: connection.status })
// libp2p may emit a closed connection and never issue peer:disconnect event
// see https://github.com/ChainSafe/js-libp2p-gossipsub/issues/398
if (!this.isStarted() || connection.status !== 'open') {
return
}
this.addPeer(peerId, connection.direction, connection.remoteAddr)
this.outboundInflightQueue.push({ peerId, connection })
}
/**
* Registrar notifies a closing connection with pubsub protocol
*/
private onPeerDisconnected (peerId: PeerId): void {
this.log('connection ended %p', peerId)
this.removePeer(peerId)
}
private async createOutboundStream (peerId: PeerId, connection: Connection): Promise<void> {
if (!this.isStarted()) {
return
}
const id = peerId.toString()
if (!this.peers.has(id)) {
return
}
// TODO make this behavior more robust
// This behavior is different than for inbound streams
// If an outbound stream already exists, don't create a new stream
if (this.streamsOutbound.has(id)) {
return
}
try {
const stream = new OutboundStream(
await connection.newStream(this.multicodecs, {
runOnTransientConnection: this.runOnTransientConnection
}),
(e) => { this.log.error('outbound pipe error', e) },
{ maxBufferSize: this.opts.maxOutboundBufferSize }
)
this.log('create outbound stream %p', peerId)
this.streamsOutbound.set(id, stream)
const protocol = stream.protocol
if (protocol === constants.FloodsubID) {
this.floodsubPeers.add(id)
}
this.metrics?.peersPerProtocol.inc({ protocol }, 1)
// Immediately send own subscriptions via the newly attached stream
if (this.subscriptions.size > 0) {
this.log('send subscriptions to', id)
this.sendSubscriptions(id, Array.from(this.subscriptions), true)
}
} catch (e) {
this.log.error('createOutboundStream error', e)
}
}
private createInboundStream (peerId: PeerId, stream: Stream): void {
if (!this.isStarted()) {
return
}
const id = peerId.toString()
if (!this.peers.has(id)) {
return
}
// TODO make this behavior more robust
// This behavior is different than for outbound streams
// If a peer initiates a new inbound connection
// we assume that one is the new canonical inbound stream
const priorInboundStream = this.streamsInbound.get(id)
if (priorInboundStream !== undefined) {
this.log('replacing existing inbound steam %s', id)
priorInboundStream.close().catch((err) => { this.log.error(err) })
}
this.log('create inbound stream %s', id)
const inboundStream = new InboundStream(stream, { maxDataLength: this.opts.maxInboundDataLength })
this.streamsInbound.set(id, inboundStream)
this.pipePeerReadStream(peerId, inboundStream.source).catch((err) => { this.log(err) })
}
/**
* Add a peer to the router
*/
private addPeer (peerId: PeerId, direction: ConnectionDirection, addr: Multiaddr): void {
const id = peerId.toString()
if (!this.peers.has(id)) {
this.log('new peer %p', peerId)
this.peers.add(id)
// Add to peer scoring
this.score.addPeer(id)
const currentIP = multiaddrToIPStr(addr)
if (currentIP !== null) {
this.score.addIP(id, currentIP)
} else {
this.log('Added peer has no IP in current address %s %s', id, addr.toString())
}
// track the connection direction. Don't allow to unset outbound
if (!this.outbound.has(id)) {
this.outbound.set(id, direction === 'outbound')
}
}
}
/**
* Removes a peer from the router
*/
private removePeer (peerId: PeerId): void {
const id = peerId.toString()
if (!this.peers.has(id)) {
return
}
// delete peer
this.log('delete peer %p', peerId)
this.peers.delete(id)
const outboundStream = this.streamsOutbound.get(id)
const inboundStream = this.streamsInbound.get(id)
if (outboundStream != null) {
this.metrics?.peersPerProtocol.inc({ protocol: outboundStream.protocol }, -1)
}
// close streams
outboundStream?.close().catch((err) => { this.log.error(err) })
inboundStream?.close().catch((err) => { this.log.error(err) })
// remove streams
this.streamsOutbound.delete(id)
this.streamsInbound.delete(id)
// remove peer from topics map
for (const peers of this.topics.values()) {
peers.delete(id)
}
// Remove this peer from the mesh
for (const [topicStr, peers] of this.mesh) {
if (peers.delete(id)) {
this.metrics?.onRemoveFromMesh(topicStr, ChurnReason.Dc, 1)
}
}
// Remove this peer from the fanout
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)
}
// 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 != null) ? 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 != null) ? 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<Uint8ArrayList>): Promise<void> {
try {
await pipe(stream, async (source) => {
for await (const data of source) {
try {
// TODO: Check max gossip message size, before decodeRpc()
const rpcBytes = data.subarray()
// 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, {
limits: {