Skip to main content

rift_core/
message.rs

1//! Identifier types used across the protocol and storage layers.
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
6pub struct PeerId(pub [u8; 32]);
7
8impl PeerId {
9    /// Encode the peer id as hex for logging and UI.
10    pub fn to_hex(&self) -> String {
11        hex::encode(self.0)
12    }
13}
14
15impl std::fmt::Display for PeerId {
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        write!(f, "{}", self.to_hex())
18    }
19}
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
22pub struct ChannelId(pub [u8; 32]);
23
24impl ChannelId {
25    /// Derive a channel id from a channel name and optional password.
26    pub fn from_channel(channel: &str, password: Option<&str>) -> Self {
27        let mut hasher = blake3::Hasher::new();
28        hasher.update(channel.as_bytes());
29        hasher.update(b":");
30        if let Some(password) = password {
31            hasher.update(password.as_bytes());
32        }
33        let hash = hasher.finalize();
34        ChannelId(*hash.as_bytes())
35    }
36
37    /// Encode the channel id as hex.
38    pub fn to_hex(&self) -> String {
39        hex::encode(self.0)
40    }
41}
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
44pub struct MessageId(pub [u8; 32]);
45
46impl MessageId {
47    /// Create a message id by hashing sender + timestamp + text.
48    /// This provides stable ids across transports.
49    pub fn new(from: PeerId, timestamp: u64, text: &str) -> Self {
50        let mut hasher = blake3::Hasher::new();
51        hasher.update(&from.0);
52        hasher.update(&timestamp.to_le_bytes());
53        hasher.update(text.as_bytes());
54        let hash = hasher.finalize();
55        MessageId(*hash.as_bytes())
56    }
57}