Skip to main content

datex_core/global/protocol_structures/
routing_header.rs

1use super::serializable::Serializable;
2use crate::values::core_values::endpoint::Endpoint;
3
4use crate::{prelude::*, shared_values::RemotePointerAddress};
5use binrw::{BinRead, BinWrite};
6use core::fmt::Display;
7use itertools::Itertools;
8use modular_bitfield::prelude::*;
9
10// 2 bit
11#[derive(
12    serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone, Specifier,
13)]
14#[bits = 2]
15pub enum SignatureType {
16    None = 0b00,
17    Unencrypted = 0b10,
18    Encrypted = 0b11,
19}
20
21#[allow(clippy::derivable_impls)]
22impl Default for SignatureType {
23    /// Sets the default signature type based on whether the "crypto_enabled" feature is enabled.
24    /// When "crypto_enabled" is enabled, the default signature type is set to Unencrypted
25    /// Otherwise, it is set to None.
26    fn default() -> Self {
27        #[cfg(not(feature = "crypto_enabled"))]
28        {
29            SignatureType::None
30        }
31        #[cfg(feature = "crypto_enabled")]
32        {
33            SignatureType::Unencrypted
34        }
35    }
36}
37
38// 1 bit
39#[derive(
40    serde::Serialize,
41    serde::Deserialize,
42    Debug,
43    PartialEq,
44    Clone,
45    Default,
46    Specifier,
47)]
48pub enum EncryptionType {
49    #[default]
50    None = 0b0,
51    Encrypted = 0b1,
52}
53
54// 2 bit + 1 bit + 2 bit + 1 bit + 1 bit + 1 bit = 1 byte
55#[bitfield]
56#[derive(BinWrite, BinRead, Clone, Copy, Debug, PartialEq)]
57#[bw(map = |&x| Self::into_bytes(x))]
58#[br(map = Self::from_bytes)]
59pub struct Flags {
60    pub signature_type: SignatureType,   // 2 bit
61    pub encryption_type: EncryptionType, // 1 bit
62    pub receiver_type: ReceiverType,     // 2 bit
63    pub is_bounce_back: bool,            // 1 bit
64    pub has_checksum: bool,              // 1 bit
65
66    #[allow(unused)]
67    unused_2: bool,
68}
69
70impl Default for Flags {
71    fn default() -> Self {
72        Flags::new()
73            .with_signature_type(SignatureType::default())
74            .with_encryption_type(EncryptionType::default())
75            .with_receiver_type(ReceiverType::default())
76            .with_is_bounce_back(false)
77            .with_has_checksum(false)
78    }
79}
80
81mod flags_serde {
82    use super::*;
83    use crate::global::protocol_structures::routing_header::Flags;
84    use serde::{Deserialize, Deserializer, Serialize, Serializer};
85    #[derive(Serialize, Deserialize)]
86    struct FlagsHelper {
87        signature_type: SignatureType,
88        encryption_type: EncryptionType,
89        receiver_type: ReceiverType,
90        is_bounce_back: bool,
91        has_checksum: bool,
92    }
93
94    impl Serialize for Flags {
95        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
96        where
97            S: Serializer,
98        {
99            let helper = FlagsHelper {
100                signature_type: self.signature_type(),
101                encryption_type: self.encryption_type(),
102                receiver_type: self.receiver_type(),
103                is_bounce_back: self.is_bounce_back(),
104                has_checksum: self.has_checksum(),
105            };
106            helper.serialize(serializer)
107        }
108    }
109
110    impl<'de> Deserialize<'de> for Flags {
111        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
112        where
113            D: Deserializer<'de>,
114        {
115            let helper = FlagsHelper::deserialize(deserializer)?;
116            Ok(Flags::new()
117                .with_signature_type(helper.signature_type)
118                .with_encryption_type(helper.encryption_type)
119                .with_receiver_type(helper.receiver_type)
120                .with_is_bounce_back(helper.is_bounce_back)
121                .with_has_checksum(helper.has_checksum))
122        }
123    }
124}
125
126// 2 bit
127#[derive(
128    serde::Serialize,
129    serde::Deserialize,
130    Debug,
131    PartialEq,
132    Clone,
133    Default,
134    Specifier,
135)]
136#[bits = 2]
137pub enum ReceiverType {
138    #[default]
139    None = 0b00,
140    Pointer = 0b01,
141    Receivers = 0b10,
142    ReceiversWithKeys = 0b11,
143}
144
145// <count>: 1 byte + (21 byte * count)
146// min: 2 bytes
147#[derive(
148    serde::Serialize,
149    serde::Deserialize,
150    Debug,
151    Clone,
152    Default,
153    BinWrite,
154    BinRead,
155    PartialEq,
156)]
157pub struct ReceiverEndpoints {
158    #[serde(rename = "number_of_receivers")]
159    pub count: u8,
160    #[br(count = count)]
161    #[serde(rename = "receivers")]
162    pub endpoints: Vec<Endpoint>,
163}
164
165impl ReceiverEndpoints {
166    pub fn new(endpoints: Vec<Endpoint>) -> Self {
167        let count = endpoints.len() as u8;
168        ReceiverEndpoints { count, endpoints }
169    }
170}
171
172// <count>: 1 byte + (21 byte * count) + (512 byte * count)
173// min: 2 bytes
174#[derive(
175    serde::Serialize,
176    serde::Deserialize,
177    Debug,
178    Clone,
179    Default,
180    BinWrite,
181    BinRead,
182    PartialEq,
183)]
184pub struct ReceiverEndpointsWithKeys {
185    #[serde(rename = "number_of_receivers")]
186    count: u8,
187    #[br(count = count)]
188    #[serde(rename = "receivers_with_keys")]
189    pub endpoints_with_keys: Vec<(Endpoint, Key512)>,
190}
191
192#[derive(
193    serde::Serialize,
194    serde::Deserialize,
195    Debug,
196    Clone,
197    BinWrite,
198    BinRead,
199    PartialEq,
200)]
201pub struct Key512(#[serde(with = "serde_big_array::BigArray")] [u8; 512]);
202impl Default for Key512 {
203    fn default() -> Self {
204        Key512([0u8; 512])
205    }
206}
207impl From<[u8; 512]> for Key512 {
208    fn from(arr: [u8; 512]) -> Self {
209        Key512(arr)
210    }
211}
212
213impl ReceiverEndpointsWithKeys {
214    pub fn new<T>(endpoints_with_keys: Vec<(Endpoint, T)>) -> Self
215    where
216        T: Into<Key512>,
217    {
218        let count = endpoints_with_keys.len() as u8;
219        ReceiverEndpointsWithKeys {
220            count,
221            endpoints_with_keys: endpoints_with_keys
222                .into_iter()
223                .map(|(ep, key)| (ep, key.into()))
224                .collect(),
225        }
226    }
227}
228
229// min: 11 byte + 2 byte + 21 byte + 1 byte = 35 bytes
230#[derive(
231    serde::Serialize,
232    serde::Deserialize,
233    Debug,
234    Clone,
235    BinWrite,
236    BinRead,
237    PartialEq,
238)]
239#[brw(little, magic = b"\x01\x64")]
240pub struct RoutingHeader {
241    pub version: u8,
242    pub block_size: u16,
243    pub flags: Flags,
244
245    #[brw(if(flags.has_checksum()))]
246    checksum: Option<u32>,
247
248    pub distance: i8,
249    pub ttl: u8,
250
251    pub sender: Endpoint,
252
253    // TODO #115: add custom match receiver queries
254    #[brw(if(flags.receiver_type() == ReceiverType::Pointer))]
255    receivers_pointer_id: Option<RemotePointerAddress>,
256    #[brw(if(flags.receiver_type() == ReceiverType::Receivers))]
257    #[serde(flatten)]
258    receivers_endpoints: Option<ReceiverEndpoints>,
259    #[brw(if(flags.receiver_type() == ReceiverType::ReceiversWithKeys))]
260    #[serde(flatten)]
261    receivers_endpoints_with_keys: Option<ReceiverEndpointsWithKeys>,
262}
263
264impl Serializable for RoutingHeader {}
265
266impl RoutingHeader {
267    pub fn unsigned() -> Self {
268        RoutingHeader {
269            flags: Flags::new().with_signature_type(SignatureType::None),
270            ..RoutingHeader::default()
271        }
272    }
273}
274
275impl Default for RoutingHeader {
276    fn default() -> Self {
277        RoutingHeader {
278            version: 1,
279            distance: 0,
280            ttl: 42,
281            flags: Flags::default(),
282            checksum: None,
283            block_size: 0,
284            sender: Endpoint::default(),
285            receivers_pointer_id: None,
286            receivers_endpoints: None,
287            receivers_endpoints_with_keys: None,
288        }
289    }
290}
291
292#[derive(Debug, Clone, PartialEq)]
293pub enum Receivers {
294    None,
295    // TODO #431 rename to PointerAddress
296    PointerId(RemotePointerAddress),
297    Endpoints(Vec<Endpoint>),
298    EndpointsWithKeys(Vec<(Endpoint, Key512)>),
299}
300impl Display for Receivers {
301    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
302        match self {
303            Receivers::None => core::write!(f, "No receivers"),
304            Receivers::PointerId(pid) => {
305                core::write!(f, "Pointer ID: {:?}", pid)
306            }
307            Receivers::Endpoints(endpoints) => {
308                core::write!(
309                    f,
310                    "{}",
311                    endpoints.iter().map(|ep| ep.to_string()).join(", ")
312                )
313            }
314            Receivers::EndpointsWithKeys(endpoints_with_keys) => {
315                core::write!(
316                    f,
317                    "{} (with keys)",
318                    endpoints_with_keys
319                        .iter()
320                        .map(|(ep, _key)| ep.to_string())
321                        .join(", ")
322                )
323            }
324        }
325    }
326}
327
328impl<T> From<T> for Receivers
329where
330    T: Into<RemotePointerAddress>,
331{
332    fn from(pid: T) -> Self {
333        Receivers::PointerId(pid.into())
334    }
335}
336impl From<Vec<Endpoint>> for Receivers {
337    fn from(endpoints: Vec<Endpoint>) -> Self {
338        Receivers::from(endpoints.as_slice())
339    }
340}
341impl From<&Vec<Endpoint>> for Receivers {
342    fn from(endpoints: &Vec<Endpoint>) -> Self {
343        Receivers::from(endpoints.as_slice())
344    }
345}
346impl From<&[Endpoint]> for Receivers {
347    fn from(endpoints: &[Endpoint]) -> Self {
348        if endpoints.is_empty() {
349            Receivers::None
350        } else {
351            Receivers::Endpoints(endpoints.to_vec())
352        }
353    }
354}
355impl<T> From<Vec<(Endpoint, T)>> for Receivers
356where
357    T: Into<Key512>,
358{
359    fn from(endpoints_with_keys: Vec<(Endpoint, T)>) -> Self {
360        if endpoints_with_keys.is_empty() {
361            Receivers::None
362        } else {
363            Receivers::EndpointsWithKeys(
364                endpoints_with_keys
365                    .into_iter()
366                    .map(|(ep, key)| (ep, key.into()))
367                    .collect(),
368            )
369        }
370    }
371}
372
373impl RoutingHeader {
374    pub fn with_sender(&mut self, sender: Endpoint) -> &mut Self {
375        self.sender = sender;
376        self
377    }
378    pub fn with_receivers(&mut self, receivers: Receivers) -> &mut Self {
379        self.set_receivers(receivers);
380        self
381    }
382    pub fn with_ttl(&mut self, ttl: u8) -> &mut Self {
383        self.ttl = ttl;
384        self
385    }
386}
387
388impl RoutingHeader {
389    pub fn new(
390        ttl: u8,
391        flags: Flags,
392        sender: Endpoint,
393        receivers: Receivers,
394    ) -> Self {
395        let mut routing_header = RoutingHeader {
396            sender,
397            ttl,
398            flags,
399            ..RoutingHeader::default()
400        };
401        routing_header.set_receivers(receivers);
402        routing_header
403    }
404
405    pub fn set_size(&mut self, size: u16) {
406        self.block_size = size;
407    }
408
409    pub fn set_receivers(&mut self, receivers: Receivers) {
410        self.receivers_endpoints = None;
411        self.receivers_pointer_id = None;
412        self.receivers_endpoints_with_keys = None;
413        self.flags.set_receiver_type(ReceiverType::None);
414
415        match receivers {
416            Receivers::PointerId(pid) => {
417                self.receivers_pointer_id = Some(pid);
418                self.flags.set_receiver_type(ReceiverType::Pointer);
419            }
420            Receivers::Endpoints(endpoints) => {
421                if !endpoints.is_empty() {
422                    self.receivers_endpoints =
423                        Some(ReceiverEndpoints::new(endpoints));
424                    self.flags.set_receiver_type(ReceiverType::Receivers);
425                }
426            }
427            Receivers::EndpointsWithKeys(endpoints_with_keys) => {
428                if !endpoints_with_keys.is_empty() {
429                    self.receivers_endpoints_with_keys = Some(
430                        ReceiverEndpointsWithKeys::new(endpoints_with_keys),
431                    );
432                    self.flags
433                        .set_receiver_type(ReceiverType::ReceiversWithKeys);
434                }
435            }
436            Receivers::None => {}
437        }
438    }
439
440    /// Get the receivers from the routing header
441    pub fn receivers(&self) -> Receivers {
442        if let Some(pid) = &self.receivers_pointer_id {
443            Receivers::PointerId(pid.clone())
444        } else if let Some(endpoints) = &self.receivers_endpoints
445            && endpoints.count > 0
446        {
447            Receivers::Endpoints(endpoints.endpoints.clone())
448        } else if let Some(endpoints_with_keys) =
449            &self.receivers_endpoints_with_keys
450            && endpoints_with_keys.count > 0
451        {
452            Receivers::EndpointsWithKeys(
453                endpoints_with_keys.endpoints_with_keys.clone(),
454            )
455        } else {
456            Receivers::None
457        }
458    }
459}
460
461#[cfg(test)]
462mod tests {
463    use core::str::FromStr;
464
465    use super::*;
466    #[test]
467    fn single_receiver() {
468        let routing_header = RoutingHeader::default()
469            .with_sender(Endpoint::from_str("@jonas").unwrap())
470            .with_ttl(64)
471            .with_receivers(Receivers::Endpoints(vec![
472                Endpoint::from_str("@alice").unwrap(),
473            ]))
474            .to_owned();
475        assert_eq!(
476            routing_header.sender,
477            Endpoint::from_str("@jonas").unwrap()
478        );
479        assert_eq!(routing_header.ttl, 64);
480        assert_eq!(
481            routing_header.receivers(),
482            Receivers::Endpoints(vec![Endpoint::from_str("@alice").unwrap()])
483        );
484        assert_eq!(
485            routing_header.flags.receiver_type(),
486            ReceiverType::Receivers
487        );
488    }
489
490    #[test]
491    fn multiple_receivers() {
492        let routing_header = RoutingHeader::default()
493            .with_receivers(Receivers::Endpoints(vec![
494                Endpoint::from_str("@alice").unwrap(),
495                Endpoint::from_str("@bob").unwrap(),
496            ]))
497            .to_owned();
498        assert_eq!(
499            routing_header.receivers(),
500            Receivers::Endpoints(vec![
501                Endpoint::from_str("@alice").unwrap(),
502                Endpoint::from_str("@bob").unwrap(),
503            ])
504        );
505        assert_eq!(
506            routing_header.flags.receiver_type(),
507            ReceiverType::Receivers
508        );
509    }
510
511    #[test]
512    fn no_receivers() {
513        let routing_header = RoutingHeader::default()
514            .with_receivers(Receivers::None)
515            .to_owned();
516        assert_eq!(routing_header.receivers(), Receivers::None);
517
518        let routing_header = RoutingHeader::default()
519            .with_receivers(Receivers::Endpoints(vec![]))
520            .to_owned();
521        assert_eq!(routing_header.receivers(), Receivers::None);
522        assert_eq!(routing_header.flags.receiver_type(), ReceiverType::None);
523    }
524}