casper_types/contract_messages/
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
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
use crate::{
    bytesrepr::{self, FromBytes, ToBytes},
    checksummed_hex, BlockTime,
};

use core::convert::TryFrom;

use alloc::{string::String, vec::Vec};
use core::fmt::{Debug, Display, Formatter};

#[cfg(feature = "datasize")]
use datasize::DataSize;
#[cfg(any(feature = "testing", test))]
use rand::{
    distributions::{Distribution, Standard},
    Rng,
};
#[cfg(feature = "json-schema")]
use schemars::JsonSchema;
use serde::{de::Error as SerdeError, Deserialize, Deserializer, Serialize, Serializer};

use super::error::FromStrError;

/// The length in bytes of a topic name hash.
pub const TOPIC_NAME_HASH_LENGTH: usize = 32;

/// The hash of the name of the message topic.
#[derive(Default, PartialOrd, Ord, PartialEq, Eq, Clone, Copy, Hash)]
#[cfg_attr(feature = "datasize", derive(DataSize))]
#[cfg_attr(
    feature = "json-schema",
    derive(JsonSchema),
    schemars(description = "The hash of the name of the message topic.")
)]
pub struct TopicNameHash(
    #[cfg_attr(feature = "json-schema", schemars(skip, with = "String"))]
    pub  [u8; TOPIC_NAME_HASH_LENGTH],
);

impl TopicNameHash {
    /// Returns a new [`TopicNameHash`] based on the specified value.
    pub const fn new(topic_name_hash: [u8; TOPIC_NAME_HASH_LENGTH]) -> TopicNameHash {
        TopicNameHash(topic_name_hash)
    }

    /// Returns inner value of the topic hash.
    pub fn value(&self) -> [u8; TOPIC_NAME_HASH_LENGTH] {
        self.0
    }

    /// Formats the [`TopicNameHash`] as a prefixed, hex-encoded string.
    pub fn to_formatted_string(self) -> String {
        base16::encode_lower(&self.0)
    }

    /// Parses a string formatted as per `Self::to_formatted_string()` into a [`TopicNameHash`].
    pub fn from_formatted_str(input: &str) -> Result<Self, FromStrError> {
        let bytes =
            <[u8; TOPIC_NAME_HASH_LENGTH]>::try_from(checksummed_hex::decode(input)?.as_ref())?;
        Ok(TopicNameHash(bytes))
    }
}

impl ToBytes for TopicNameHash {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut buffer = bytesrepr::allocate_buffer(self)?;
        buffer.append(&mut self.0.to_bytes()?);
        Ok(buffer)
    }

    fn serialized_length(&self) -> usize {
        self.0.serialized_length()
    }
}

impl FromBytes for TopicNameHash {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (hash, rem) = FromBytes::from_bytes(bytes)?;
        Ok((TopicNameHash(hash), rem))
    }
}

impl Serialize for TopicNameHash {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        if serializer.is_human_readable() {
            self.to_formatted_string().serialize(serializer)
        } else {
            self.0.serialize(serializer)
        }
    }
}

impl<'de> Deserialize<'de> for TopicNameHash {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        if deserializer.is_human_readable() {
            let formatted_string = String::deserialize(deserializer)?;
            TopicNameHash::from_formatted_str(&formatted_string).map_err(SerdeError::custom)
        } else {
            let bytes = <[u8; TOPIC_NAME_HASH_LENGTH]>::deserialize(deserializer)?;
            Ok(TopicNameHash(bytes))
        }
    }
}

impl Display for TopicNameHash {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", base16::encode_lower(&self.0))
    }
}

impl Debug for TopicNameHash {
    fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
        write!(f, "MessageTopicHash({})", base16::encode_lower(&self.0))
    }
}

#[cfg(any(feature = "testing", test))]
impl Distribution<TopicNameHash> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> TopicNameHash {
        TopicNameHash(rng.gen())
    }
}

impl From<[u8; TOPIC_NAME_HASH_LENGTH]> for TopicNameHash {
    fn from(value: [u8; TOPIC_NAME_HASH_LENGTH]) -> Self {
        TopicNameHash(value)
    }
}

/// Summary of a message topic that will be stored in global state.
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "datasize", derive(DataSize))]
#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
pub struct MessageTopicSummary {
    /// Number of messages in this topic.
    pub(crate) message_count: u32,
    /// Block timestamp in which these messages were emitted.
    pub(crate) blocktime: BlockTime,
    /// Name of the topic.
    pub(crate) topic_name: String,
}

impl MessageTopicSummary {
    /// Creates a new topic summary.
    pub fn new(message_count: u32, blocktime: BlockTime, topic_name: String) -> Self {
        Self {
            message_count,
            blocktime,
            topic_name,
        }
    }

    /// Returns the number of messages that were sent on this topic.
    pub fn message_count(&self) -> u32 {
        self.message_count
    }

    /// Returns the block time.
    pub fn blocktime(&self) -> BlockTime {
        self.blocktime
    }

    /// Returns the topic name.
    pub fn topic_name(&self) -> String {
        self.topic_name.clone()
    }
}

impl ToBytes for MessageTopicSummary {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut buffer = bytesrepr::allocate_buffer(self)?;
        buffer.append(&mut self.message_count.to_bytes()?);
        buffer.append(&mut self.blocktime.to_bytes()?);
        buffer.append(&mut self.topic_name.to_bytes()?);
        Ok(buffer)
    }

    fn serialized_length(&self) -> usize {
        self.message_count.serialized_length()
            + self.blocktime.serialized_length()
            + self.topic_name.serialized_length()
    }
}

impl FromBytes for MessageTopicSummary {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (message_count, rem) = FromBytes::from_bytes(bytes)?;
        let (blocktime, rem) = FromBytes::from_bytes(rem)?;
        let (topic_name, rem) = FromBytes::from_bytes(rem)?;
        Ok((
            MessageTopicSummary {
                message_count,
                blocktime,
                topic_name,
            },
            rem,
        ))
    }
}

const TOPIC_OPERATION_ADD_TAG: u8 = 0;
const OPERATION_MAX_SERIALIZED_LEN: usize = 1;

/// Operations that can be performed on message topics.
#[derive(Debug, PartialEq)]
pub enum MessageTopicOperation {
    /// Add a new message topic.
    Add,
}

impl MessageTopicOperation {
    /// Maximum serialized length of a message topic operation.
    pub const fn max_serialized_len() -> usize {
        OPERATION_MAX_SERIALIZED_LEN
    }
}

impl ToBytes for MessageTopicOperation {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        let mut buffer = bytesrepr::allocate_buffer(self)?;
        match self {
            MessageTopicOperation::Add => buffer.push(TOPIC_OPERATION_ADD_TAG),
        }
        Ok(buffer)
    }

    fn serialized_length(&self) -> usize {
        match self {
            MessageTopicOperation::Add => 1,
        }
    }
}

impl FromBytes for MessageTopicOperation {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (tag, remainder): (u8, &[u8]) = FromBytes::from_bytes(bytes)?;
        match tag {
            TOPIC_OPERATION_ADD_TAG => Ok((MessageTopicOperation::Add, remainder)),
            _ => Err(bytesrepr::Error::Formatting),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::bytesrepr;

    use super::*;

    #[test]
    fn serialization_roundtrip() {
        let topic_name_hash = TopicNameHash::new([0x4du8; TOPIC_NAME_HASH_LENGTH]);
        bytesrepr::test_serialization_roundtrip(&topic_name_hash);

        let topic_summary =
            MessageTopicSummary::new(10, BlockTime::new(100), "topic_name".to_string());
        bytesrepr::test_serialization_roundtrip(&topic_summary);

        let topic_operation = MessageTopicOperation::Add;
        bytesrepr::test_serialization_roundtrip(&topic_operation);
    }

    #[test]
    fn json_roundtrip() {
        let topic_name_hash = TopicNameHash::new([0x4du8; TOPIC_NAME_HASH_LENGTH]);
        let json_string = serde_json::to_string_pretty(&topic_name_hash).unwrap();
        let decoded: TopicNameHash = serde_json::from_str(&json_string).unwrap();
        assert_eq!(decoded, topic_name_hash);

        let topic_summary =
            MessageTopicSummary::new(10, BlockTime::new(100), "topic_name".to_string());
        let json_string = serde_json::to_string_pretty(&topic_summary).unwrap();
        let decoded: MessageTopicSummary = serde_json::from_str(&json_string).unwrap();
        assert_eq!(decoded, topic_summary);
    }
}