fuel_core_p2p/gossipsub/
topics.rs

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
use libp2p::gossipsub::{
    Sha256Topic,
    Topic,
    TopicHash,
};

use super::messages::{
    GossipTopicTag,
    GossipsubBroadcastRequest,
};

pub const NEW_TX_GOSSIP_TOPIC: &str = "new_tx";

/// Holds used Gossipsub Topics
/// Each field contains TopicHash of existing topics
/// in order to avoid converting topics to TopicHash on each received message
#[derive(Debug)]
pub struct GossipsubTopics {
    new_tx_topic: TopicHash,
}

impl GossipsubTopics {
    pub fn new(network_name: &str) -> Self {
        let new_tx_topic: Sha256Topic =
            Topic::new(format!("{NEW_TX_GOSSIP_TOPIC}/{network_name}"));

        Self {
            new_tx_topic: new_tx_topic.hash(),
        }
    }

    /// Given a TopicHash it will return a matching GossipTopicTag
    pub fn get_gossipsub_tag(
        &self,
        incoming_topic: &TopicHash,
    ) -> Option<GossipTopicTag> {
        match incoming_topic {
            hash if hash == &self.new_tx_topic => Some(GossipTopicTag::NewTx),
            _ => None,
        }
    }

    /// Given a `GossipsubBroadcastRequest` returns a `TopicHash`
    /// which is broadcast over the network with the serialized inner value of `GossipsubBroadcastRequest`
    pub fn get_gossipsub_topic_hash(
        &self,
        outgoing_request: &GossipsubBroadcastRequest,
    ) -> TopicHash {
        match outgoing_request {
            GossipsubBroadcastRequest::NewTx(_) => self.new_tx_topic.clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use fuel_core_types::fuel_tx::Transaction;
    use libp2p::gossipsub::Topic;
    use std::sync::Arc;

    #[test]
    fn test_gossipsub_topics() {
        let network_name = "fuel_test_network";
        let new_tx_topic: Sha256Topic =
            Topic::new(format!("{NEW_TX_GOSSIP_TOPIC}/{network_name}"));

        let gossipsub_topics = GossipsubTopics::new(network_name);

        // Test matching Topic Hashes
        assert_eq!(gossipsub_topics.new_tx_topic, new_tx_topic.hash());

        // Test given a TopicHash that `get_gossipsub_tag()` returns matching `GossipTopicTag`
        assert_eq!(
            gossipsub_topics.get_gossipsub_tag(&new_tx_topic.hash()),
            Some(GossipTopicTag::NewTx)
        );

        // Test given a `GossipsubBroadcastRequest` that `get_gossipsub_topic_hash()` returns matching `TopicHash`
        let broadcast_req =
            GossipsubBroadcastRequest::NewTx(Arc::new(Transaction::default_test_tx()));
        assert_eq!(
            gossipsub_topics.get_gossipsub_topic_hash(&broadcast_req),
            new_tx_topic.hash()
        );
    }
}