libp2p_gossipsub/
topic.rs

1// Copyright 2020 Sigma Prime Pty Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use std::fmt;
22
23use base64::prelude::*;
24use quick_protobuf::Writer;
25use sha2::{Digest, Sha256};
26
27use crate::rpc_proto::proto;
28
29/// A generic trait that can be extended for various hashing types for a topic.
30pub trait Hasher {
31    /// The function that takes a topic string and creates a topic hash.
32    fn hash(topic_string: String) -> TopicHash;
33}
34
35/// A type for representing topics who use the identity hash.
36#[derive(Debug, Clone)]
37pub struct IdentityHash {}
38impl Hasher for IdentityHash {
39    /// Creates a [`TopicHash`] as a raw string.
40    fn hash(topic_string: String) -> TopicHash {
41        TopicHash { hash: topic_string }
42    }
43}
44
45#[derive(Debug, Clone)]
46pub struct Sha256Hash {}
47impl Hasher for Sha256Hash {
48    /// Creates a [`TopicHash`] by SHA256 hashing the topic then base64 encoding the
49    /// hash.
50    fn hash(topic_string: String) -> TopicHash {
51        use quick_protobuf::MessageWrite;
52
53        let topic_descriptor = proto::TopicDescriptor {
54            name: Some(topic_string),
55            auth: None,
56            enc: None,
57        };
58        let mut bytes = Vec::with_capacity(topic_descriptor.get_size());
59        let mut writer = Writer::new(&mut bytes);
60        topic_descriptor
61            .write_message(&mut writer)
62            .expect("Encoding to succeed");
63        let hash = BASE64_STANDARD.encode(Sha256::digest(&bytes));
64        TopicHash { hash }
65    }
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
69#[cfg_attr(
70    feature = "metrics",
71    derive(prometheus_client::encoding::EncodeLabelSet)
72)]
73pub struct TopicHash {
74    /// The topic hash. Stored as a string to align with the protobuf API.
75    hash: String,
76}
77
78impl TopicHash {
79    pub fn from_raw(hash: impl Into<String>) -> TopicHash {
80        TopicHash { hash: hash.into() }
81    }
82
83    pub fn into_string(self) -> String {
84        self.hash
85    }
86
87    pub fn as_str(&self) -> &str {
88        &self.hash
89    }
90}
91
92/// A gossipsub topic.
93#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
94pub struct Topic<H: Hasher> {
95    topic: String,
96    phantom_data: std::marker::PhantomData<H>,
97}
98
99impl<H: Hasher> From<Topic<H>> for TopicHash {
100    fn from(topic: Topic<H>) -> TopicHash {
101        topic.hash()
102    }
103}
104
105impl<H: Hasher> Topic<H> {
106    pub fn new(topic: impl Into<String>) -> Self {
107        Topic {
108            topic: topic.into(),
109            phantom_data: std::marker::PhantomData,
110        }
111    }
112
113    pub fn hash(&self) -> TopicHash {
114        H::hash(self.topic.clone())
115    }
116}
117
118impl<H: Hasher> fmt::Display for Topic<H> {
119    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
120        write!(f, "{}", self.topic)
121    }
122}
123
124impl fmt::Display for TopicHash {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        write!(f, "{}", self.hash)
127    }
128}