Skip to main content

federation_net/
protocol.rs

1//! Protocol constants, network/schema identifiers and internal wire structures.
2
3use std::fmt;
4
5use serde::{Deserialize, Serialize};
6
7/// ALPN identifier for the federation-net protocol.
8///
9/// [`NetworkId`] and [`SchemaId`] are deliberately not part of the ALPN;
10/// they are verified during the application-level handshake instead.
11pub const ALPN: &[u8] = b"/federation-net/1";
12
13/// Version of the application-level wire protocol.
14pub const PROTOCOL_VERSION: u16 = 1;
15
16/// Maximum size of an encoded handshake frame.
17///
18/// Handshake frames are tiny; this limit only guards against malicious peers.
19pub(crate) const MAX_HANDSHAKE_FRAME_SIZE: usize = 16 * 1024;
20
21fn hash_with_domain(domain: &str, name: &str) -> [u8; 32] {
22    let mut hasher = blake3::Hasher::new();
23    hasher.update(domain.as_bytes());
24    hasher.update(name.as_bytes());
25    *hasher.finalize().as_bytes()
26}
27
28fn fmt_id(bytes: &[u8; 32], f: &mut fmt::Formatter<'_>) -> fmt::Result {
29    for byte in bytes {
30        write!(f, "{byte:02x}")?;
31    }
32    Ok(())
33}
34
35/// Identifier of a distinct P2P network.
36///
37/// Peers with different network ids refuse to establish an application-level
38/// session even though they share the same transport protocol.
39#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
40pub struct NetworkId([u8; 32]);
41
42impl NetworkId {
43    /// Creates a network id from raw bytes.
44    pub fn from_bytes(bytes: [u8; 32]) -> Self {
45        Self(bytes)
46    }
47
48    /// Derives a network id from a human-readable name.
49    ///
50    /// The derivation is deterministic: the same name always yields the same
51    /// id. Internally this computes `BLAKE3("federation-net:network:" + name)`.
52    pub fn from_name(name: &str) -> Self {
53        Self(hash_with_domain("federation-net:network:", name))
54    }
55
56    /// Returns the raw bytes of this id.
57    pub fn as_bytes(&self) -> &[u8; 32] {
58        &self.0
59    }
60}
61
62impl fmt::Display for NetworkId {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        fmt_id(&self.0, f)
65    }
66}
67
68impl fmt::Debug for NetworkId {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        write!(f, "NetworkId(")?;
71        fmt_id(&self.0, f)?;
72        write!(f, ")")
73    }
74}
75
76/// Identifier of the domain message schema used on top of the network.
77///
78/// Peers on the same network but with different schema ids reject each other,
79/// because they would not be able to decode each other's messages. A backwards
80/// incompatible change to the domain message type requires a new schema id.
81#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
82pub struct SchemaId([u8; 32]);
83
84impl SchemaId {
85    /// Creates a schema id from raw bytes.
86    pub fn from_bytes(bytes: [u8; 32]) -> Self {
87        Self(bytes)
88    }
89
90    /// Derives a schema id from a human-readable name.
91    ///
92    /// The derivation is deterministic: the same name always yields the same
93    /// id. Internally this computes `BLAKE3("federation-net:schema:" + name)`.
94    pub fn from_name(name: &str) -> Self {
95        Self(hash_with_domain("federation-net:schema:", name))
96    }
97
98    /// Returns the raw bytes of this id.
99    pub fn as_bytes(&self) -> &[u8; 32] {
100        &self.0
101    }
102}
103
104impl fmt::Display for SchemaId {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        fmt_id(&self.0, f)
107    }
108}
109
110impl fmt::Debug for SchemaId {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        write!(f, "SchemaId(")?;
113        fmt_id(&self.0, f)?;
114        write!(f, ")")
115    }
116}
117
118/// Handshake sent by the connecting side on the first bidirectional stream.
119#[derive(Debug, Clone, Serialize, Deserialize)]
120pub(crate) struct Handshake {
121    pub protocol_version: u16,
122    pub network_id: NetworkId,
123    pub schema_id: SchemaId,
124}
125
126/// Reply to a [`Handshake`], sent by the accepting side.
127#[derive(Debug, Clone, Serialize, Deserialize)]
128pub(crate) struct HandshakeAck {
129    pub accepted: bool,
130    pub error: Option<HandshakeErrorCode>,
131}
132
133/// Reasons for rejecting a handshake.
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
135pub(crate) enum HandshakeErrorCode {
136    UnsupportedProtocolVersion,
137    NetworkMismatch,
138    SchemaMismatch,
139    InvalidHandshake,
140}
141
142/// A single domain message request, sent on its own bidirectional stream.
143#[derive(Debug, Clone, Serialize, Deserialize)]
144pub(crate) struct MessageRequest {
145    pub request_id: [u8; 16],
146    pub payload: Vec<u8>,
147}
148
149/// Reasons for rejecting a [`MessageRequest`].
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
151pub(crate) enum MessageRejectReason {
152    /// The payload could not be decoded into the domain message type.
153    MalformedPayload,
154    /// The receiving peer is shutting down.
155    ShuttingDown,
156    /// The receiving peer is overloaded and dropped the message.
157    Overloaded,
158}
159
160impl fmt::Display for MessageRejectReason {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        match self {
163            Self::MalformedPayload => write!(f, "malformed payload"),
164            Self::ShuttingDown => write!(f, "peer is shutting down"),
165            Self::Overloaded => write!(f, "peer is overloaded"),
166        }
167    }
168}
169
170/// Reply to a [`MessageRequest`].
171#[derive(Debug, Clone, Serialize, Deserialize)]
172pub(crate) enum MessageResponse {
173    Accepted {
174        request_id: [u8; 16],
175    },
176    Rejected {
177        request_id: [u8; 16],
178        reason: MessageRejectReason,
179    },
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    #[test]
187    fn network_id_from_name_is_deterministic() {
188        let a = NetworkId::from_name("example-network");
189        let b = NetworkId::from_name("example-network");
190        assert_eq!(a, b);
191    }
192
193    #[test]
194    fn different_network_names_produce_different_ids() {
195        let a = NetworkId::from_name("network-a");
196        let b = NetworkId::from_name("network-b");
197        assert_ne!(a, b);
198    }
199
200    #[test]
201    fn schema_id_from_name_is_deterministic() {
202        let a = SchemaId::from_name("demo-message-v1");
203        let b = SchemaId::from_name("demo-message-v1");
204        assert_eq!(a, b);
205        assert_ne!(a, SchemaId::from_name("demo-message-v2"));
206    }
207
208    #[test]
209    fn network_and_schema_domains_are_separated() {
210        // The same name hashed under different domain prefixes must differ.
211        let network = NetworkId::from_name("same-name");
212        let schema = SchemaId::from_name("same-name");
213        assert_ne!(network.as_bytes(), schema.as_bytes());
214    }
215}