Skip to main content

qualia_core_db/p2p/
outbound_relay.rs

1//! Outbound packet relay — both peers dial the hub; the hub forwards datagrams.
2//!
3//! This is the DERP/TURN *shape* for SocialWebNet: neither side listens on a
4//! public UDP port. WireGuard `Tunn` packets are opaque payloads. An in-process
5//! hub proves the contract. A public WSS/443 deployment is a separate operator
6//! step (see `qdnf-imp/nat-traversal-expert-brief.md`).
7//!
8//! Labelled transition. Not Native Independent. Not an internet handshake.
9
10#![cfg(not(target_arch = "wasm32"))]
11
12use std::sync::{Arc, Mutex};
13
14/// Bounded datagram size (WireGuard handshake/data frames fit).
15pub const MAX_DATAGRAM: usize = 2048;
16const QUEUE: usize = 16;
17
18#[derive(Clone, Copy)]
19struct Slot {
20    len: usize,
21    bytes: [u8; MAX_DATAGRAM],
22}
23
24impl Slot {
25    const EMPTY: Self = Self {
26        len: 0,
27        bytes: [0u8; MAX_DATAGRAM],
28    };
29}
30
31struct HubState {
32    a_to_b: [Slot; QUEUE],
33    a_len: usize,
34    b_to_a: [Slot; QUEUE],
35    b_len: usize,
36}
37
38impl HubState {
39    fn push(&mut self, from_a: bool, datagram: &[u8]) -> Result<usize, &'static str> {
40        let (q, n) = if from_a {
41            (&mut self.a_to_b, &mut self.a_len)
42        } else {
43            (&mut self.b_to_a, &mut self.b_len)
44        };
45        if *n >= QUEUE {
46            return Err("would-block");
47        }
48        q[*n].len = datagram.len();
49        q[*n].bytes[..datagram.len()].copy_from_slice(datagram);
50        *n += 1;
51        Ok(datagram.len())
52    }
53
54    fn pop(&mut self, into_a: bool, out: &mut [u8]) -> Result<usize, &'static str> {
55        let (q, n) = if into_a {
56            (&mut self.b_to_a, &mut self.b_len)
57        } else {
58            (&mut self.a_to_b, &mut self.a_len)
59        };
60        if *n == 0 {
61            return Err("would-block");
62        }
63        let slot = q[0];
64        if slot.len > out.len() {
65            return Err("capacity");
66        }
67        out[..slot.len].copy_from_slice(&slot.bytes[..slot.len]);
68        let mut i = 0;
69        while i + 1 < *n {
70            q[i] = q[i + 1];
71            i += 1;
72        }
73        *n -= 1;
74        q[*n] = Slot::EMPTY;
75        Ok(slot.len)
76    }
77}
78
79/// One dialed end of an outbound relay pair.
80pub struct RelayEndpoint {
81    is_a: bool,
82    hub: Arc<Mutex<HubState>>,
83}
84
85/// Both endpoints have already “dialed out”. There is no listen socket.
86pub fn relay_pair() -> (RelayEndpoint, RelayEndpoint) {
87    let hub = Arc::new(Mutex::new(HubState {
88        a_to_b: [Slot::EMPTY; QUEUE],
89        a_len: 0,
90        b_to_a: [Slot::EMPTY; QUEUE],
91        b_len: 0,
92    }));
93    (
94        RelayEndpoint {
95            is_a: true,
96            hub: hub.clone(),
97        },
98        RelayEndpoint { is_a: false, hub },
99    )
100}
101
102impl RelayEndpoint {
103    /// Queue `datagram` for the peer. Fails closed if full or oversize.
104    pub fn send(&mut self, datagram: &[u8]) -> Result<usize, &'static str> {
105        if datagram.len() > MAX_DATAGRAM {
106            return Err("capacity");
107        }
108        self.hub
109            .lock()
110            .map_err(|_| "closed")?
111            .push(self.is_a, datagram)
112    }
113
114    /// Pop one datagram. `Err("would-block")` if empty.
115    pub fn recv(&mut self, out: &mut [u8]) -> Result<usize, &'static str> {
116        self.hub.lock().map_err(|_| "closed")?.pop(self.is_a, out)
117    }
118}
119
120/// Recommendation for this pod’s measured class, not a universal connectivity theorem.
121/// See `address_dependent_is_not_universal_relay_law`.
122pub const fn relay_required_for_address_dependent() -> bool {
123    true
124}
125
126/// A public internet relay has not been dialed from this build.
127pub const fn public_relay_dialed() -> bool {
128    false
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use crate::p2p::wireguard_userspace::{generate_keypair, new_tunnel};
135    use boringtun::noise::TunnResult;
136
137    fn ipv6_hello() -> Vec<u8> {
138        let payload = b"relaywg";
139        let mut p = vec![0u8; 40 + payload.len()];
140        p[0] = 0x60;
141        p[4..6].copy_from_slice(&(payload.len() as u16).to_be_bytes());
142        p[6] = 17;
143        p[7] = 64;
144        p[8] = 0xfd;
145        p[23] = 1;
146        p[24] = 0xfd;
147        p[39] = 2;
148        p[40..].copy_from_slice(payload);
149        p
150    }
151
152    fn shuttle(
153        from: &mut RelayEndpoint,
154        to: &mut RelayEndpoint,
155        buf: &[u8],
156        out: &mut [u8],
157    ) -> usize {
158        from.send(buf).expect("relay send");
159        to.recv(out).expect("relay recv")
160    }
161
162    #[test]
163    fn two_outbound_dials_forward_a_datagram() {
164        let (mut a, mut b) = relay_pair();
165        assert_eq!(a.send(b"ping").unwrap(), 4);
166        let mut out = [0u8; 16];
167        assert_eq!(b.recv(&mut out).unwrap(), 4);
168        assert_eq!(&out[..4], b"ping");
169        assert_eq!(a.recv(&mut out), Err("would-block"));
170    }
171
172    #[test]
173    fn oversize_datagram_fails_closed() {
174        let (mut a, _b) = relay_pair();
175        let too_big = [0u8; MAX_DATAGRAM + 1];
176        assert_eq!(a.send(&too_big), Err("capacity"));
177    }
178
179    #[test]
180    fn wireguard_handshake_and_data_over_outbound_relay() {
181        let a_keys = generate_keypair();
182        let b_keys = generate_keypair();
183        let mut ta = new_tunnel(&a_keys, b_keys.public, 1).unwrap();
184        let mut tb = new_tunnel(&b_keys, a_keys.public, 2).unwrap();
185        let (mut ea, mut eb) = relay_pair();
186
187        let mut scratch = [0u8; MAX_DATAGRAM];
188        let mut in_flight = match ta.encapsulate(&[], &mut scratch) {
189            TunnResult::WriteToNetwork(p) => p.to_vec(),
190            other => panic!("expected handshake init, got {other:?}"),
191        };
192
193        let mut to_b = true;
194        let mut handshake_done = false;
195        for _ in 0..12 {
196            let n = if to_b {
197                shuttle(&mut ea, &mut eb, &in_flight, &mut scratch)
198            } else {
199                shuttle(&mut eb, &mut ea, &in_flight, &mut scratch)
200            };
201            let pkt = scratch[..n].to_vec();
202            let recv = if to_b { &mut tb } else { &mut ta };
203            match recv.decapsulate(None, &pkt, &mut scratch) {
204                TunnResult::WriteToNetwork(p) => {
205                    in_flight = p.to_vec();
206                    to_b = !to_b;
207                }
208                TunnResult::Done | TunnResult::WriteToTunnelV6(_, _) => {
209                    handshake_done = true;
210                    break;
211                }
212                TunnResult::WriteToTunnelV4(_, _) => panic!("IPv4 inner not used"),
213                TunnResult::Err(e) => panic!("{e:?}"),
214            }
215        }
216        assert!(handshake_done, "handshake did not converge over the relay");
217
218        let inner = ipv6_hello();
219        let mut got: Option<Vec<u8>> = None;
220        for _ in 0..4 {
221            let mut enc = [0u8; MAX_DATAGRAM];
222            match ta.encapsulate(&inner, &mut enc) {
223                TunnResult::WriteToNetwork(p) => {
224                    let cipher = p.to_vec();
225                    let n = shuttle(&mut ea, &mut eb, &cipher, &mut scratch);
226                    let pkt = scratch[..n].to_vec();
227                    match tb.decapsulate(None, &pkt, &mut enc) {
228                        TunnResult::WriteToTunnelV6(data, _) => {
229                            got = Some(data.to_vec());
230                            break;
231                        }
232                        TunnResult::WriteToNetwork(reply) => {
233                            let reply = reply.to_vec();
234                            let n = shuttle(&mut eb, &mut ea, &reply, &mut scratch);
235                            let back = scratch[..n].to_vec();
236                            let _ = ta.decapsulate(None, &back, &mut enc);
237                        }
238                        TunnResult::Done => {}
239                        TunnResult::WriteToTunnelV4(_, _) => panic!("IPv4 inner not used"),
240                        TunnResult::Err(e) => panic!("{e:?}"),
241                    }
242                }
243                TunnResult::Done => {}
244                other => panic!("unexpected A encapsulate: {other:?}"),
245            }
246        }
247        assert_eq!(got.expect("B never received inner IPv6"), inner);
248        assert!(!public_relay_dialed());
249        assert!(relay_required_for_address_dependent());
250    }
251}