Skip to main content

qualia_core_db/net/peer/fabric/
mailbox.rs

1//! Invitation-scoped private mailbox. Not a public DHT.
2
3use super::carrier::prohibited;
4use super::contact::{ContactDescriptor, LocatorKind};
5use super::intent::PeerId;
6use super::kernel::FabricError;
7use super::wire::{decode_contact, encode_contact};
8use crate::net::peer::connectivity::policy::Disclosure;
9
10pub const MAX_SLOTS: usize = 16;
11
12#[derive(Debug, Clone, Copy)]
13pub struct PrivateMailbox {
14    slots: [Option<ContactDescriptor>; MAX_SLOTS],
15    last_gen: [u32; MAX_SLOTS],
16    len: usize,
17}
18
19impl PrivateMailbox {
20    /// Creates a default `PrivateMailbox`.
21    pub const fn new() -> Self {
22        Self {
23            slots: [None; MAX_SLOTS],
24            last_gen: [0; MAX_SLOTS],
25            len: 0,
26        }
27    }
28
29    fn find(&self, key: &PeerId) -> Option<usize> {
30        let mut i = 0;
31        while i < self.len {
32            if let Some(d) = self.slots[i] {
33                if &d.contact_key == key {
34                    return Some(i);
35                }
36            }
37            i += 1;
38        }
39        None
40    }
41
42    /// Store `d` only when `disclosure` permits its locator class.
43    pub fn publish_under(
44        &mut self,
45        d: ContactDescriptor,
46        disclosure: Disclosure,
47    ) -> Result<(), FabricError> {
48        if d.kind == LocatorKind::Direct
49            && prohibited(disclosure, super::carrier::PathClass::DirectV6)
50        {
51            return Err(FabricError::PolicyDenied);
52        }
53        self.publish(d)
54    }
55
56    /// Publishes `d` as the current contact.
57    pub fn publish(&mut self, d: ContactDescriptor) -> Result<(), FabricError> {
58        if d.contact_key == [0u8; 32] {
59            return Err(FabricError::Illegal);
60        }
61        if let Some(i) = self.find(&d.contact_key) {
62            if d.generation < self.last_gen[i] {
63                return Err(FabricError::StaleDescriptor);
64            }
65            self.slots[i] = Some(d);
66            self.last_gen[i] = d.generation;
67            return Ok(());
68        }
69        if self.len >= MAX_SLOTS {
70            return Err(FabricError::Capacity);
71        }
72        self.slots[self.len] = Some(d);
73        self.last_gen[self.len] = d.generation;
74        self.len += 1;
75        Ok(())
76    }
77
78    /// Resolves the published contact.
79    pub fn resolve(
80        &self,
81        key: &PeerId,
82        now_unix: u32,
83        disclosure: Disclosure,
84    ) -> Result<ContactDescriptor, FabricError> {
85        let i = self.find(key).ok_or(FabricError::Illegal)?;
86        let d = self.slots[i].ok_or(FabricError::Illegal)?;
87        if d.is_expired(now_unix) {
88            return Err(FabricError::Expired);
89        }
90        if d.is_stale(self.last_gen[i]) {
91            return Err(FabricError::StaleDescriptor);
92        }
93        if d.kind == LocatorKind::Direct
94            && prohibited(disclosure, super::carrier::PathClass::DirectV6)
95        {
96            return Err(FabricError::PolicyDenied);
97        }
98        Ok(d)
99    }
100
101    /// Ingests a wire-format contact record.
102    pub fn ingest_wire(
103        &mut self,
104        bytes: &[u8],
105        now_unix: u32,
106        disclosure: Disclosure,
107    ) -> Result<ContactDescriptor, FabricError> {
108        let d = decode_contact(bytes)?;
109        if d.is_expired(now_unix) {
110            return Err(FabricError::Expired);
111        }
112        self.publish_under(d, disclosure)?;
113        self.resolve(&d.contact_key, now_unix, disclosure)
114    }
115
116    /// Encodes the current contact for the wire.
117    pub fn encode_current(
118        &self,
119        key: &PeerId,
120        disclosure: Disclosure,
121        out: &mut [u8],
122    ) -> Result<usize, FabricError> {
123        let i = self.find(key).ok_or(FabricError::Illegal)?;
124        let d = self.slots[i].ok_or(FabricError::Illegal)?;
125        if d.kind == LocatorKind::Direct
126            && prohibited(disclosure, super::carrier::PathClass::DirectV6)
127        {
128            return Err(FabricError::PolicyDenied);
129        }
130        encode_contact(&d, out).map_err(FabricError::from)
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn stale_and_direct_forbidden() {
140        let mut m = PrivateMailbox::new();
141        let key = [7u8; 32];
142        m.publish(ContactDescriptor::mailbox(key, 5, 2_000_000_000))
143            .unwrap();
144        let old = ContactDescriptor::mailbox(key, 3, 2_000_000_000);
145        assert_eq!(m.publish(old), Err(FabricError::StaleDescriptor));
146        let mut direct = ContactDescriptor::mailbox(key, 6, 2_000_000_000);
147        direct.kind = LocatorKind::Direct;
148        m.publish(direct).unwrap();
149        assert_eq!(
150            m.resolve(&key, 10, Disclosure::ApprovedRelaysOnly),
151            Err(FabricError::PolicyDenied)
152        );
153        assert!(m.resolve(&key, 10, Disclosure::DirectPermitted).is_ok());
154        let expired = ContactDescriptor::mailbox([8u8; 32], 1, 5);
155        m.publish(expired).unwrap();
156        assert_eq!(
157            m.resolve(&[8u8; 32], 10, Disclosure::ApprovedRelaysOnly),
158            Err(FabricError::Expired)
159        );
160        let mut wire = [0u8; 256];
161        let n = m
162            .encode_current(&key, Disclosure::DirectPermitted, &mut wire)
163            .expect("direct locator export only when disclosure permits");
164        assert_eq!(
165            m.encode_current(&key, Disclosure::ApprovedRelaysOnly, &mut wire),
166            Err(FabricError::PolicyDenied)
167        );
168        let mut other = PrivateMailbox::new();
169        assert_eq!(
170            other.ingest_wire(&wire[..n], 10, Disclosure::ApprovedRelaysOnly),
171            Err(FabricError::PolicyDenied)
172        );
173        assert!(!crate::net::peer::fabric::intent::ProtectionPolicy::RELAY_ONLY.public_dht);
174    }
175
176    #[test]
177    fn ingest_relay_only_direct_does_not_retain_locator() {
178        let mut src = PrivateMailbox::new();
179        let key = [3u8; 32];
180        let mut direct = ContactDescriptor::mailbox(key, 1, 2_000_000_000);
181        direct.kind = LocatorKind::Direct;
182        src.publish(direct).unwrap();
183        let mut wire = [0u8; 256];
184        let n = src
185            .encode_current(&key, Disclosure::DirectPermitted, &mut wire)
186            .unwrap();
187        let mut dst = PrivateMailbox::new();
188        assert_eq!(
189            dst.ingest_wire(&wire[..n], 10, Disclosure::ApprovedRelaysOnly),
190            Err(FabricError::PolicyDenied)
191        );
192        assert_eq!(
193            dst.resolve(&key, 10, Disclosure::DirectPermitted),
194            Err(FabricError::Illegal)
195        );
196    }
197}