Skip to main content

qualia_core_db/p2p/
social_webnet.rs

1// SocialWebNet — the managed userspace-WireGuard mesh keyed by peer identity.
2//
3// `wireguard_runtime::WgTunnel` is a single point-to-point tunnel. `SocialWebNet` is the layer
4// above it: the node's whole set of tunnels, one per peer, keyed by a stable peer id (the
5// pairwise DID the coordination plane uses). It is the mechanism the *social* layer drives —
6// the address book / connection-identifier exchange decides *who* to peer with and hands this
7// mesh the peer's WireGuard public key and (once known) endpoint; this mesh owns the crypto
8// state and the sockets.
9//
10// Application payload on an established tunnel is an inner IPv6/UDP datagram
11// ([`super::mesh_datagram`]). Chat stays on `ports::CHAT`. QDNF QFrames use
12// `ports::QDNF` through [`super::social_qdnf`] — WireGuard remains the labelled
13// transition carrier; this path is not Native Independent and does not use libp2p.
14//
15// Separation of concerns:
16//   * **This module (core-db)** owns the mesh mechanism: bind sockets, build `Tunn`s, drive
17//     handshakes/timers, route inner packets to/from the right peer. It speaks raw keys and
18//     endpoints, so it is testable with zero social/identity dependencies (two meshes on
19//     loopback, below).
20//   * **The client-core social layer** binds this to identity: it feeds `add_peer` from the
21//     `social_peers` store + `node_identity`, and learns endpoints from `connection_identifier`
22//     rendezvous hints. That wiring lives there, not here.
23//
24// Socket model: **one UDP socket per peer** (each tunnel binds its own port). This is the
25// straightforward, fully-working design — each peer's coordination record advertises that peer's
26// port. WireGuard's own kernel implementation instead multiplexes all peers over a single socket,
27// demultiplexing by the receiver-index in each datagram; adopting that here is a pure efficiency
28// refinement (fewer sockets) and is noted as future work — it does not change correctness.
29//
30// Native-only (`boringtun` does not build for wasm32); WASM peers use a relay.
31#![cfg(not(target_arch = "wasm32"))]
32
33use std::collections::HashMap;
34use std::net::{IpAddr, SocketAddr};
35use std::time::Duration;
36
37use super::wireguard_runtime::{TunnelEvent, WgTunnel};
38use super::wireguard_userspace::{public_key_from_hex, WgKeypair};
39
40/// A decrypted inner IPv6 packet, tagged with the peer it came from.
41#[derive(Debug)]
42pub struct MeshPacket {
43    /// The peer id (pairwise DID) the packet arrived from.
44    pub peer_id: String,
45    /// The decrypted inner IPv6 packet.
46    pub inner: Vec<u8>,
47}
48
49/// The node's managed WireGuard mesh: a set of peer tunnels sharing this node's static keypair.
50pub struct SocialWebNet {
51    /// This node's WireGuard static keypair (shared by every tunnel).
52    keys: WgKeypair,
53    /// The IP to bind each per-peer socket on (port is always OS-chosen).
54    bind_ip: IpAddr,
55    /// peer id (pairwise DID) → its tunnel.
56    tunnels: HashMap<String, WgTunnel>,
57    /// Monotonic WireGuard session index handed to each new tunnel (must be distinct per tunnel).
58    next_index: u32,
59    /// Read timeout applied to each peer socket so pumping never blocks the mesh loop.
60    read_timeout: Option<Duration>,
61}
62
63impl SocialWebNet {
64    /// Create an empty mesh for this node. `bind_ip` is where per-peer sockets bind (e.g.
65    /// `0.0.0.0` / `::` in production, `127.0.0.1` in tests); `read_timeout` bounds each
66    /// [`pump`](SocialWebNet::pump) so a quiet peer does not stall the loop.
67    pub fn new(keys: WgKeypair, bind_ip: IpAddr, read_timeout: Option<Duration>) -> SocialWebNet {
68        SocialWebNet {
69            keys,
70            bind_ip,
71            tunnels: HashMap::new(),
72            next_index: 1,
73            read_timeout,
74        }
75    }
76
77    /// This node's WireGuard public key as lowercase hex — what peers need to address it.
78    pub fn public_key_hex(&self) -> String {
79        self.keys.public_hex()
80    }
81
82    /// The peer ids currently in the mesh.
83    pub fn peers(&self) -> Vec<String> {
84        self.tunnels.keys().cloned().collect()
85    }
86
87    /// Add a peer to the mesh: bind a fresh socket and build its tunnel.
88    ///
89    /// `peer_pubkey_hex` is the peer's WireGuard public key (64 hex chars — as stored on a
90    /// `SocialPeer` / carried in a `ConnectionIdentifier`). `endpoint` is where to send to if
91    /// already known (else `None`, and it is learned by roaming from the first authenticated
92    /// packet). Returns the local socket address bound for this peer, so the caller can advertise
93    /// it back through the coordination plane. Idempotent-ish: adding an existing peer id replaces
94    /// its tunnel (a fresh socket + handshake state).
95    pub fn add_peer(
96        &mut self,
97        peer_id: &str,
98        peer_pubkey_hex: &str,
99        endpoint: Option<SocketAddr>,
100    ) -> Result<SocketAddr, String> {
101        let peer_public = public_key_from_hex(peer_pubkey_hex)?;
102        let index = self.next_index;
103        self.next_index = self.next_index.wrapping_add(1);
104
105        let bind_addr = SocketAddr::new(self.bind_ip, 0);
106        let mut tunnel = WgTunnel::bind(&self.keys, peer_public, bind_addr, index)?;
107        tunnel.set_read_timeout(self.read_timeout)?;
108        if let Some(ep) = endpoint {
109            tunnel.set_peer_endpoint(ep);
110        }
111        let local = tunnel.local_addr()?;
112        self.tunnels.insert(peer_id.to_string(), tunnel);
113        Ok(local)
114    }
115
116    /// Remove a peer and drop its tunnel/socket. Returns whether the peer was present.
117    pub fn remove_peer(&mut self, peer_id: &str) -> bool {
118        self.tunnels.remove(peer_id).is_some()
119    }
120
121    fn tunnel_mut(&mut self, peer_id: &str) -> Result<&mut WgTunnel, String> {
122        self.tunnels
123            .get_mut(peer_id)
124            .ok_or_else(|| format!("unknown peer '{peer_id}'"))
125    }
126
127    /// The local socket address bound for a peer, if present.
128    pub fn local_addr(&self, peer_id: &str) -> Option<SocketAddr> {
129        self.tunnels.get(peer_id).and_then(|t| t.local_addr().ok())
130    }
131
132    /// Point a peer's tunnel at `addr` (e.g. once its endpoint is learned from the coordination plane).
133    pub fn set_peer_endpoint(&mut self, peer_id: &str, addr: SocketAddr) -> Result<(), String> {
134        self.tunnel_mut(peer_id)?.set_peer_endpoint(addr);
135        Ok(())
136    }
137
138    /// Whether a live WireGuard session exists with a peer.
139    pub fn has_session(&self, peer_id: &str) -> bool {
140        self.tunnels.get(peer_id).is_some_and(|t| t.has_session())
141    }
142
143    /// Start the handshake with a peer (initiator side). Requires the peer's endpoint to be set.
144    pub fn initiate_handshake(&mut self, peer_id: &str) -> Result<(), String> {
145        self.tunnel_mut(peer_id)?.initiate_handshake()
146    }
147
148    /// Encrypt and send one inner IPv6 packet to a peer. See [`WgTunnel::send_packet`] for the
149    /// pre-session behaviour (a handshake init is sent and the caller retries once established).
150    pub fn send_to(&mut self, peer_id: &str, inner: &[u8]) -> Result<bool, String> {
151        self.tunnel_mut(peer_id)?.send_packet(inner)
152    }
153
154    /// Frame `payload` as an overlay IPv6/UDP datagram addressed to `dst_port` (from `src_port`) and
155    /// send it to a peer. This is the application-message path over the mesh: the receiver recovers
156    /// `(src_port, dst_port, payload)` with
157    /// [`mesh_datagram::decode_datagram`](super::mesh_datagram::decode_datagram) on the
158    /// [`MeshPacket::inner`] it pumps. See [`super::mesh_datagram::ports`] for well-known ports.
159    pub fn send_datagram(
160        &mut self,
161        peer_id: &str,
162        src_port: u16,
163        dst_port: u16,
164        payload: &[u8],
165    ) -> Result<bool, String> {
166        let pkt = super::mesh_datagram::encode_datagram(src_port, dst_port, payload);
167        self.send_to(peer_id, &pkt)
168    }
169
170    /// Send one QDNF QFrame as an overlay datagram on [`super::mesh_datagram::ports::QDNF`].
171    ///
172    /// The frame bytes are already encoded (`encode_frame`). Chat and other overlay
173    /// ports are unchanged; receivers demultiplex on destination port.
174    pub fn send_qdnf_frame(&mut self, peer_id: &str, frame: &[u8]) -> Result<bool, String> {
175        let port = super::mesh_datagram::ports::QDNF;
176        self.send_datagram(peer_id, port, port, frame)
177    }
178
179    /// Pump one datagram for a single peer. See [`WgTunnel::pump`].
180    pub fn pump(&mut self, peer_id: &str) -> Result<TunnelEvent, String> {
181        self.tunnel_mut(peer_id)?.pump()
182    }
183
184    /// Pump every peer once, returning any decrypted inner packets (tagged by peer). Control-only
185    /// traffic and idle sockets produce nothing. A per-peer error is surfaced against that peer id
186    /// rather than aborting the whole sweep.
187    pub fn pump_all(&mut self) -> Vec<Result<MeshPacket, (String, String)>> {
188        let ids: Vec<String> = self.tunnels.keys().cloned().collect();
189        let mut out = Vec::new();
190        for id in ids {
191            match self.pump(&id) {
192                Ok(TunnelEvent::InnerPacket(inner)) => {
193                    out.push(Ok(MeshPacket { peer_id: id, inner }))
194                }
195                Ok(_) => {}
196                Err(e) => out.push(Err((id, e))),
197            }
198        }
199        out
200    }
201
202    /// Drive WireGuard timers for every peer once (call ~1 Hz). Per-peer errors are collected, not
203    /// fatal.
204    pub fn tick_all(&mut self) -> Vec<(String, String)> {
205        let ids: Vec<String> = self.tunnels.keys().cloned().collect();
206        let mut errs = Vec::new();
207        for id in ids {
208            if let Ok(t) = self.tunnel_mut(&id) {
209                if let Err(e) = t.tick() {
210                    errs.push((id, e));
211                }
212            }
213        }
214        errs
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221    use crate::p2p::wireguard_userspace::generate_keypair;
222
223    fn v6(payload: &[u8]) -> Vec<u8> {
224        let total = 40 + payload.len();
225        let mut p = vec![0u8; total];
226        p[0] = 0x60;
227        p[4..6].copy_from_slice(&(payload.len() as u16).to_be_bytes());
228        p[6] = 17;
229        p[7] = 64;
230        p[8] = 0xfd;
231        p[23] = 0x01;
232        p[24] = 0xfd;
233        p[39] = 0x02;
234        p[40..].copy_from_slice(payload);
235        p
236    }
237
238    /// Two full meshes, each holding the other as its single peer, over real loopback sockets:
239    /// bring up the tunnel via the mesh API and carry an inner IPv6 packet A→B by peer id.
240    #[test]
241    fn two_meshes_peer_and_exchange_by_id() {
242        let a_keys = generate_keypair();
243        let b_keys = generate_keypair();
244        let a_pub = a_keys.public_hex();
245        let b_pub = b_keys.public_hex();
246
247        let to = Some(Duration::from_millis(300));
248        let mut a = SocialWebNet::new(a_keys, "127.0.0.1".parse().unwrap(), to);
249        let mut b = SocialWebNet::new(b_keys, "127.0.0.1".parse().unwrap(), to);
250
251        // Each adds the other by peer id; endpoints unknown until both sockets are bound.
252        let a_local = a.add_peer("did:wf:bob", &b_pub, None).expect("A adds B");
253        let b_local = b.add_peer("did:wf:alice", &a_pub, None).expect("B adds A");
254
255        // Exchange the freshly-bound endpoints (the coordination plane's job in production).
256        a.set_peer_endpoint("did:wf:bob", b_local).unwrap();
257        b.set_peer_endpoint("did:wf:alice", a_local).unwrap();
258
259        // A initiates; drive both meshes until A holds a session.
260        a.initiate_handshake("did:wf:bob").expect("A initiates");
261        for _ in 0..20 {
262            if a.has_session("did:wf:bob") {
263                break;
264            }
265            let _ = b.pump_all();
266            let _ = a.pump_all();
267        }
268        assert!(
269            a.has_session("did:wf:bob"),
270            "A established a session with B"
271        );
272        let _ = b.pump_all(); // B consumes the keepalive to establish too
273        assert!(
274            b.has_session("did:wf:alice"),
275            "B established a session with A"
276        );
277
278        // A sends an inner IPv6 packet addressed to peer id "did:wf:bob".
279        let payload = v6(b"mesh packet by peer id");
280        assert!(a.send_to("did:wf:bob", &payload).expect("A sends"));
281
282        let mut got = None;
283        for _ in 0..10 {
284            for evt in b.pump_all() {
285                if let Ok(pkt) = evt {
286                    assert_eq!(pkt.peer_id, "did:wf:alice", "tagged with the sending peer");
287                    got = Some(pkt.inner);
288                }
289            }
290            if got.is_some() {
291                break;
292            }
293        }
294        assert_eq!(got.expect("B received the inner packet"), payload);
295    }
296
297    /// Two meshes exchange an *application datagram* (framed IPv6/UDP), and the receiver recovers the
298    /// ports + payload — proving the app-message layer rides on the tunnel end-to-end.
299    #[test]
300    fn two_meshes_exchange_an_application_datagram() {
301        use super::super::mesh_datagram::{decode_datagram, ports};
302
303        let a_keys = generate_keypair();
304        let b_keys = generate_keypair();
305        let (a_pub, b_pub) = (a_keys.public_hex(), b_keys.public_hex());
306
307        let to = Some(Duration::from_millis(300));
308        let mut a = SocialWebNet::new(a_keys, "127.0.0.1".parse().unwrap(), to);
309        let mut b = SocialWebNet::new(b_keys, "127.0.0.1".parse().unwrap(), to);
310
311        let a_local = a.add_peer("b", &b_pub, None).unwrap();
312        let b_local = b.add_peer("a", &a_pub, None).unwrap();
313        a.set_peer_endpoint("b", b_local).unwrap();
314        b.set_peer_endpoint("a", a_local).unwrap();
315
316        a.initiate_handshake("b").unwrap();
317        for _ in 0..20 {
318            if a.has_session("b") {
319                break;
320            }
321            let _ = b.pump_all();
322            let _ = a.pump_all();
323        }
324        assert!(a.has_session("b"));
325        let _ = b.pump_all();
326
327        // A sends a CHAT datagram to B.
328        assert!(a
329            .send_datagram("b", ports::CHAT, ports::CHAT, b"hi over the app layer")
330            .unwrap());
331
332        let mut got = None;
333        for _ in 0..10 {
334            for evt in b.pump_all() {
335                if let Ok(pkt) = evt {
336                    got = decode_datagram(&pkt.inner);
337                }
338            }
339            if got.is_some() {
340                break;
341            }
342        }
343        let d = got.expect("B decoded the datagram");
344        assert_eq!(d.dst_port, ports::CHAT, "demuxes on the chat port");
345        assert_eq!(d.payload, b"hi over the app layer");
346    }
347
348    #[test]
349    fn add_and_remove_peer_tracks_membership() {
350        let keys = generate_keypair();
351        let peer = generate_keypair();
352        let mut mesh = SocialWebNet::new(keys, "127.0.0.1".parse().unwrap(), None);
353
354        assert!(mesh.peers().is_empty());
355        mesh.add_peer("did:wf:x", &peer.public_hex(), None).unwrap();
356        assert_eq!(mesh.peers(), vec!["did:wf:x".to_string()]);
357        assert!(mesh.local_addr("did:wf:x").is_some());
358        assert!(!mesh.has_session("did:wf:x"), "no handshake yet");
359
360        assert!(mesh.remove_peer("did:wf:x"));
361        assert!(!mesh.remove_peer("did:wf:x"), "second remove is a no-op");
362        assert!(mesh.peers().is_empty());
363    }
364
365    #[test]
366    fn bad_peer_pubkey_is_rejected() {
367        let keys = generate_keypair();
368        let mut mesh = SocialWebNet::new(keys, "127.0.0.1".parse().unwrap(), None);
369        let err = mesh.add_peer("did:wf:x", "not-hex", None).unwrap_err();
370        assert!(err.contains("hex"), "surfaces the key-parse error: {err}");
371    }
372}