-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathget-gossip-peers.ts
49 lines (45 loc) · 1.12 KB
/
get-gossip-peers.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
import { shuffle, hasGossipProtocol } from './utils'
import Gossipsub = require('./index')
/**
* Given a topic, returns up to count peers subscribed to that topic
* that pass an optional filter function
*
* @param {Gossipsub} router
* @param {String} topic
* @param {Number} count
* @param {Function} [filter] a function to filter acceptable peers
* @returns {Set<string>}
*
*/
export function getGossipPeers (
router: Gossipsub,
topic: string,
count: number,
filter: (id: string) => boolean = () => true
): Set<string> {
const peersInTopic = router.topics.get(topic)
if (!peersInTopic) {
return new Set()
}
// Adds all peers using our protocol
// that also pass the filter function
let peers: string[] = []
peersInTopic.forEach((id) => {
const peerStreams = router.peers.get(id)
if (!peerStreams) {
return
}
if (
hasGossipProtocol(peerStreams.protocol) &&
filter(id)
) {
peers.push(id)
}
})
// Pseudo-randomly shuffles peers
peers = shuffle(peers)
if (count > 0 && peers.length > count) {
peers = peers.slice(0, count)
}
return new Set(peers)
}