-
Notifications
You must be signed in to change notification settings - Fork 41
/
index.ts
719 lines (633 loc) · 18.5 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
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-ignore
import { utils } from 'libp2p-pubsub'
import { MessageCache } from './messageCache'
import {
RPCCodec,
RPC, Message, InMessage,
ControlMessage, ControlIHave, ControlGraft, ControlIWant, ControlPrune
} from './message'
import * as constants from './constants'
import { Heartbeat } from './heartbeat'
import { getGossipPeers } from './getGossipPeers'
import { createGossipRpc } from './utils'
import { Peer, Registrar } from './peer'
// @ts-ignore
import TimeCache = require('time-cache')
import PeerId = require('peer-id')
import BasicPubsub = require('./pubsub')
interface GossipOptions {
emitSelf: boolean
gossipIncoming: boolean
fallbackToFloodsub: boolean
msgIdFn: (msg: Message) => string
messageCache: MessageCache
}
class Gossipsub extends BasicPubsub {
peers: Map<string, Peer>
topics: Map<string, Set<Peer>>
mesh: Map<string, Set<Peer>>
fanout: Map<string, Set<Peer>>
lastpub: Map<string, number>
gossip: Map<Peer, ControlIHave[]>
control: Map<Peer, ControlMessage>
_options: GossipOptions
public static multicodec: string = constants.GossipsubID
/**
* @param {PeerId} peerId instance of the peer's PeerId
* @param {Object} registrar
* @param {function} registrar.handle
* @param {function} registrar.register
* @param {function} registrar.unregister
* @param {Object} [options]
* @param {bool} [options.emitSelf] if publish should emit to self, if subscribed, defaults to false
* @param {bool} [options.gossipIncoming] if incoming messages on a subscribed topic should be automatically gossiped, defaults to true
* @param {bool} [options.fallbackToFloodsub] if dial should fallback to floodsub, defaults to true
* @param {function} [options.msgIdFn] override the default message id function
* @param {Object} [options.messageCache] override the default MessageCache
* @constructor
*/
constructor (peerId: PeerId, registrar: Registrar, options: Partial<GossipOptions> = {}) {
const multicodecs = [constants.GossipsubID]
const _options = {
gossipIncoming: true,
fallbackToFloodsub: true,
...options
}
// Also wants to get notified of peers connected using floodsub
if (_options.fallbackToFloodsub) {
multicodecs.push(constants.FloodSubID)
}
super({
debugName: 'libp2p:gossipsub',
multicodecs,
peerId,
registrar,
options: _options as GossipOptions
})
/**
* Cache of seen messages
*
* @type {TimeCache}
*/
this.seenCache = new TimeCache()
/**
* Map of topic meshes
*
* @type {Map<string, Set<Peer>>}
*/
this.mesh = new Map()
/**
* Map of topics to set of peers. These mesh peers are the ones to which we are publishing without a topic membership
*
* @type {Map<string, Set<Peer>>}
*/
this.fanout = new Map()
/**
* Map of last publish time for fanout topics
*
* @type {Map<string, Number>}
*/
this.lastpub = new Map()
/**
* Map of pending messages to gossip
*
* @type {Map<Peer, Array<ControlIHave object>> }
*/
this.gossip = new Map()
/**
* Map of control messages
*
* @type {Map<Peer, ControlMessage object>}
*/
this.control = new Map()
/**
* Use the overriden mesgIdFn or the default one.
*/
this._msgIdFn = options.msgIdFn || this.defaultMsgIdFn
/**
* A message cache that contains the messages for last few hearbeat ticks
*
*/
this.messageCache = options.messageCache || new MessageCache(constants.GossipsubHistoryGossip, constants.GossipsubHistoryLength, this._msgIdFn)
/**
* A heartbeat timer that maintains the mesh
*/
this.heartbeat = new Heartbeat(this)
}
/**
* Removes a peer from the router
* @override
* @param {Peer} peer
* @returns {Peer}
*/
_removePeer (peer: Peer): Peer {
super._removePeer(peer)
// Remove this peer from the mesh
// eslint-disable-next-line no-unused-vars
for (const peers of this.mesh.values()) {
peers.delete(peer)
}
// Remove this peer from the fanout
// eslint-disable-next-line no-unused-vars
for (const peers of this.fanout.values()) {
peers.delete(peer)
}
// Remove from gossip mapping
this.gossip.delete(peer)
// Remove from control mapping
this.control.delete(peer)
return peer
}
/**
* Handles an rpc request from a peer
*
* @override
* @param {String} idB58Str
* @param {Peer} peer
* @param {RPC} rpc
* @returns {void}
*/
_processRpc (idB58Str: string, peer: Peer, rpc: RPC): void {
super._processRpc(idB58Str, peer, rpc)
if (rpc.control) {
this._processRpcControlMessage(peer, rpc.control)
}
}
/**
* Handles an rpc control message from a peer
* @param {Peer} peer
* @param {ControlMessage} controlMsg
* @returns {void}
*/
_processRpcControlMessage (peer: Peer, controlMsg: ControlMessage): void {
if (!controlMsg) {
return
}
const iwant = this._handleIHave(peer, controlMsg.ihave)
const ihave = this._handleIWant(peer, controlMsg.iwant)
const prune = this._handleGraft(peer, controlMsg.graft)
this._handlePrune(peer, controlMsg.prune)
if (!iwant || !ihave || !prune) {
return
}
const outRpc = createGossipRpc(ihave, { iwant: [iwant], prune })
this._sendRpc(peer, outRpc)
}
/**
* Process incoming message,
* emitting locally and forwarding on to relevant floodsub and gossipsub peers
* @override
* @param {Peer} peer
* @param {Message} msg
*/
_processRpcMessage (peer: Peer, msg: InMessage): void {
const msgID = this.getMsgId(msg)
// Ignore if we've already seen the message
if (this.seenCache.has(msgID)) {
return
}
this.seenCache.put(msgID)
super._processRpcMessage(peer, msg)
const topics = msg.topicIDs
// If options.gossipIncoming is false, do NOT emit incoming messages to peers
if (!this._options.gossipIncoming) {
return
}
// Emit to floodsub peers
this.peers.forEach((peer) => {
if (peer.protocols.includes(constants.FloodSubID) &&
peer.id.toB58String() !== msg.from &&
utils.anyMatch(peer.topics, topics) &&
peer.isWritable
) {
peer.sendMessages(utils.normalizeOutRpcMessages([msg]))
this.log('publish msg on topics - floodsub', topics, peer.id.toB58String())
}
})
// Emit to peers in the mesh
topics.forEach((topic) => {
const meshPeers = this.mesh.get(topic)
if (!meshPeers) {
return
}
meshPeers.forEach((peer) => {
if (!peer.isWritable || peer.id.toB58String() === msg.from) {
return
}
peer.sendMessages(utils.normalizeOutRpcMessages([msg]))
this.log('publish msg on topic - meshsub', topic, peer.id.toB58String())
})
})
}
/**
* Handles IHAVE messages
* @param {Peer} peer
* @param {Array<ControlIHave>} ihave
* @returns {ControlIWant}
*/
_handleIHave (peer: Peer, ihave: ControlIHave[]): ControlIWant | undefined {
const iwant = new Set<string>()
ihave.forEach(({ topicID, messageIDs }) => {
if (!topicID || !this.mesh.has(topicID)) {
return
}
messageIDs.forEach((msgID) => {
if (this.seenCache.has(msgID)) {
return
}
iwant.add(msgID)
})
})
if (!iwant.size) {
return
}
this.log('IHAVE: Asking for %d messages from %s', iwant.size, peer.id.toB58String())
return {
messageIDs: Array.from(iwant)
}
}
/**
* Handles IWANT messages
* Returns messages to send back to peer
* @param {Peer} peer
* @param {Array<ControlIWant>} iwant
* @returns {Array<Message>}
*/
_handleIWant (peer: Peer, iwant: ControlIWant[]): Message[] | undefined {
// @type {Map<string, Message>}
const ihave = new Map<string, Message>()
iwant.forEach(({ messageIDs }) => {
messageIDs.forEach((msgID) => {
const msg = this.messageCache.get(msgID)
if (msg) {
ihave.set(msgID, msg)
}
})
})
if (!ihave.size) {
return
}
this.log('IWANT: Sending %d messages to %s', ihave.size, peer.id.toB58String())
return Array.from(ihave.values())
}
/**
* Handles Graft messages
* @param {Peer} peer
* @param {Array<ControlGraft>} graft
* @return {Array<ControlPrune>}
*/
_handleGraft (peer: Peer, graft: ControlGraft[]): ControlPrune[] | undefined {
const prune: string[] = []
graft.forEach(({ topicID }) => {
if (!topicID) {
return
}
const peers = this.mesh.get(topicID)
if (!peers) {
prune.push(topicID)
} else {
this.log('GRAFT: Add mesh link from %s in %s', peer.id.toB58String(), topicID)
peers.add(peer)
peer.topics.add(topicID)
this.mesh.set(topicID, peers)
}
})
if (!prune.length) {
return
}
const buildCtrlPruneMsg = (topic: string) => {
return {
topicID: topic
}
}
return prune.map(buildCtrlPruneMsg)
}
/**
* Handles Prune messages
* @param {Peer} peer
* @param {Array<ControlPrune>} prune
* @returns {void}
*/
_handlePrune (peer: Peer, prune: ControlPrune[]): void {
prune.forEach(({ topicID }) => {
if (!topicID) {
return
}
const peers = this.mesh.get(topicID)
if (peers) {
this.log('PRUNE: Remove mesh link to %s in %s', peer.id.toB58String(), topicID)
peers.delete(peer)
peer.topics.delete(topicID)
}
})
}
/**
* Mounts the gossipsub protocol onto the libp2p node and sends our
* our subscriptions to every peer connected
* @override
* @returns {Promise}
*/
async start (): Promise<void> {
await super.start()
this.heartbeat.start()
}
/**
* Unmounts the gossipsub protocol and shuts down every connection
* @override
* @returns {Promise}
*/
async stop (): Promise<void> {
await super.stop()
this.heartbeat.stop()
this.mesh = new Map()
this.fanout = new Map()
this.lastpub = new Map()
this.gossip = new Map()
this.control = new Map()
}
/**
* Subscribes to topics
*
* @override
* @param {Array<string>} topics
* @returns {void}
*/
_subscribe (topics: string[]): void {
super._subscribe(topics)
this.join(topics)
}
/**
* Unsubscribes to topics
*
* @override
* @param {Array<string>} topics
* @returns {void}
*/
_unsubscribe (topics: string[]): void {
super._unsubscribe(topics)
this.leave(topics)
}
/**
* Join topics
* @param {Array<string>|string} topics
* @returns {void}
*/
join (topics: string[] | string): void {
if (!this.started) {
throw new Error('Gossipsub has not started')
}
topics = utils.ensureArray(topics)
this.log('JOIN %s', topics)
;(topics as string[]).forEach((topic) => {
// Send GRAFT to mesh peers
const fanoutPeers = this.fanout.get(topic)
if (fanoutPeers) {
this.mesh.set(topic, fanoutPeers)
this.fanout.delete(topic)
this.lastpub.delete(topic)
} else {
const peers = getGossipPeers(this, topic, constants.GossipsubD)
this.mesh.set(topic, peers)
}
this.mesh.get(topic)!.forEach((peer) => {
this.log('JOIN: Add mesh link to %s in %s', peer.id.toB58String(), topic)
this._sendGraft(peer, topic)
})
})
}
/**
* Leave topics
* @param {Array<string>|string} topics
* @returns {void}
*/
leave (topics: string[] | string): void {
topics = utils.ensureArray(topics)
this.log('LEAVE %s', topics)
;(topics as string[]).forEach((topic) => {
// Send PRUNE to mesh peers
const meshPeers = this.mesh.get(topic)
if (meshPeers) {
meshPeers.forEach((peer) => {
this.log('LEAVE: Remove mesh link to %s in %s', peer.id.toB58String(), topic)
this._sendPrune(peer, topic)
})
this.mesh.delete(topic)
}
})
}
/**
* Override the default implementation in BasicPubSub.
* If we don't provide msgIdFn in constructor option, it's the same.
* @override
* @param {Message} msg the message object
* @returns {string} message id as string
*/
getMsgId (msg: InMessage): string {
return this._msgIdFn(msg)
}
/**
* Publish messages
*
* Note: this function assumes all messages are well-formed RPC objects
* @override
* @param {Array<Message>} msgs
* @returns {void}
*/
_publish (msgs: InMessage[]): void {
msgs.forEach((msgObj) => {
const msgID = this.getMsgId(msgObj)
// put in seen cache
this.seenCache.put(msgID)
this.messageCache.put(msgObj)
const tosend = new Set<Peer>()
msgObj.topicIDs.forEach((topic) => {
const peersInTopic = this.topics.get(topic)
if (!peersInTopic) {
return
}
// floodsub peers
peersInTopic.forEach((peer) => {
if (peer.protocols.includes(constants.FloodSubID)) {
tosend.add(peer)
}
})
// Gossipsub peers handling
let meshPeers = this.mesh.get(topic)
if (!meshPeers || !meshPeers.size) {
// We are not in the mesh for topic, use fanout peers
meshPeers = this.fanout.get(topic)
if (!meshPeers) {
// If we are not in the fanout, then pick any peers in topic
const peers = getGossipPeers(this, topic, constants.GossipsubD)
if (peers.size > 0) {
meshPeers = peers
this.fanout.set(topic, peers)
} else {
meshPeers = new Set()
}
}
// Store the latest publishing time
this.lastpub.set(topic, this._now())
}
meshPeers!.forEach((peer) => {
tosend.add(peer)
})
})
// Publish messages to peers
tosend.forEach((peer) => {
if (peer.id.toB58String() === msgObj.from) {
return
}
this._sendRpc(peer, createGossipRpc([utils.normalizeOutRpcMessage(msgObj)]))
})
})
}
/**
* Sends a GRAFT message to a peer
* @param {Peer} peer
* @param {String} topic
* @returns {void}
*/
_sendGraft (peer: Peer, topic: string): void {
const graft = [{
topicID: topic
}]
const out = createGossipRpc([], { graft })
this._sendRpc(peer, out)
}
/**
* Sends a PRUNE message to a peer
* @param {Peer} peer
* @param {String} topic
* @returns {void}
*/
_sendPrune (peer: Peer, topic: string): void {
const prune = [{
topicID: topic
}]
const out = createGossipRpc([], { prune })
this._sendRpc(peer, out)
}
_sendRpc (peer: Peer, outRpc: RPC): void {
if (!peer || !peer.isWritable) {
return
}
// piggyback control message retries
const ctrl = this.control.get(peer)
if (ctrl) {
this._piggybackControl(peer, outRpc, ctrl)
this.control.delete(peer)
}
// piggyback gossip
const ihave = this.gossip.get(peer)
if (ihave) {
this._piggybackGossip(peer, outRpc, ihave)
this.gossip.delete(peer)
}
peer.write(RPCCodec.encode(outRpc))
}
_piggybackControl (peer: Peer, outRpc: RPC, ctrl: ControlMessage): void {
const tograft = (ctrl.graft || [])
.filter(({ topicID }) => (topicID && this.mesh.get(topicID) || new Set()).has(peer))
const toprune = (ctrl.prune || [])
.filter(({ topicID }) => !(topicID && this.mesh.get(topicID) || new Set()).has(peer))
if (!tograft.length && !toprune.length) {
return
}
if (outRpc.control) {
outRpc.control.graft = outRpc.control.graft.concat(tograft)
outRpc.control.prune = outRpc.control.prune.concat(toprune)
} else {
outRpc.control = { ihave: [], iwant: [], graft: tograft, prune: toprune }
}
}
_piggybackGossip (peer: Peer, outRpc: RPC, ihave: ControlIHave[]): void {
if (!outRpc.control) {
outRpc.control = { ihave: [], iwant: [], graft: [], prune: [] }
}
outRpc.control.ihave = ihave
}
/**
* Send graft and prune messages
* @param {Map<Peer, Array<String>>} tograft
* @param {Map<Peer, Array<String>>} toprune
*/
_sendGraftPrune (tograft: Map<Peer, string[]>, toprune: Map<Peer, string[]>): void {
for (const [p, topics] of tograft) {
const graft = topics.map((topicID) => ({ topicID }))
let prune: ControlPrune[] = []
// If a peer also has prunes, process them now
const pruneMsg = toprune.get(p)
if (pruneMsg) {
prune = pruneMsg.map((topicID) => ({ topicID }))
toprune.delete(p)
}
const outRpc = createGossipRpc([], { graft, prune })
this._sendRpc(p, outRpc)
}
for (const [p, topics] of toprune) {
const prune = topics.map((topicID) => ({ topicID }))
const outRpc = createGossipRpc([], { prune })
this._sendRpc(p, outRpc)
}
}
/**
* Emits gossip to peers in a particular topic
* @param {String} topic
* @param {Set<Peer>} peers - peers to exclude
* @returns {void}
*/
_emitGossip (topic: string, peers: Set<Peer>): void {
const messageIDs = this.messageCache.getGossipIDs(topic)
if (!messageIDs.length) {
return
}
const gossipSubPeers = getGossipPeers(this, topic, constants.GossipsubD)
gossipSubPeers.forEach((peer) => {
// skip mesh peers
if (!peers.has(peer)) {
this._pushGossip(peer, {
topicID: topic,
messageIDs: messageIDs
})
}
})
}
/**
* Flush gossip and control messages
*/
_flush (): void {
// send gossip first, which will also piggyback control
for (const [peer, ihave] of this.gossip.entries()) {
this.gossip.delete(peer)
const out = createGossipRpc([], { ihave })
this._sendRpc(peer, out)
}
// send the remaining control messages
for (const [peer, control] of this.control.entries()) {
this.control.delete(peer)
const out = createGossipRpc([], { graft: control.graft, prune: control.prune })
this._sendRpc(peer, out)
}
}
/**
* Adds new IHAVE messages to pending gossip
* @param {Peer} peer
* @param {Array<ControlIHave>} controlIHaveMsgs
* @returns {void}
*/
_pushGossip (peer: Peer, controlIHaveMsgs: ControlIHave): void {
this.log('Add gossip to %s', peer.id.toB58String())
const gossip = this.gossip.get(peer) || []
this.gossip.set(peer, gossip.concat(controlIHaveMsgs))
}
/**
* Returns the current time in milliseconds
* @returns {number}
*/
_now (): number {
return Date.now()
}
}
export = Gossipsub