Skip to main content

capsule_sdk/peering/
discovery.rs

1//! LAN discovery: the opaque, rotating advertisement and the [`Discovery`] seam.
2//!
3//! Discovery is the one genuinely new mechanism peering introduces. Devices advertise a
4//! peering service over **mDNS** and accept connections over **TCP**. mDNS broadcasts are
5//! visible to every host on the segment, so the advertisement **must not leak identity**: a
6//! device advertises an [`OpaqueAdvertisement`] — a rotated opaque instance name — never
7//! `[email protected]` or a device name. Whether two advertisements belong to the same user is
8//! established *inside* the encrypted [`channel`](super::channel), never from the broadcast.
9//!
10//! The live mDNS responder is intentionally **not** built into this change: it is inherently
11//! non-deterministic (real multicast, real timing) and belongs behind the [`Discovery`] seam,
12//! exactly as the connection-class detector kept live NIC probing behind a signal seam. Tests
13//! drive a [`MockDiscovery`]; a production responder — pure-Rust `mdns-sd` is the sanctioned
14//! choice — implements [`Discovery`] over the same [`OpaqueAdvertisement`] descriptor.
15
16use std::net::SocketAddr;
17use std::sync::{Arc, Mutex};
18
19use sha2::{Digest, Sha256};
20use tracing::instrument;
21
22use super::PeeringError;
23
24/// The mDNS service type peering advertises under. A fixed, non-identifying label shared by
25/// every Capsule device — it says "a Capsule peer is here", nothing about *who*.
26pub const SERVICE_TYPE: &str = "_capsule-peer._tcp.local.";
27
28/// The opaque instance name length in bytes (rendered as `2 * OPAQUE_BYTES` hex chars). 128
29/// bits is ample to make two devices' names collision-free on a LAN while carrying no structure
30/// an observer could decode into an identity.
31const OPAQUE_BYTES: usize = 16;
32
33/// Seconds in a day — the ceiling of the advertisement rotation band.
34const DAY_SECS: i64 = 86_400;
35
36/// A LAN peering advertisement: an **opaque, rotating** service-instance name plus the TCP port
37/// the device listens on. The name is derived purely from a per-device rotation secret and a
38/// rotation epoch, so structurally there is no user handle or device name to leak.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct OpaqueAdvertisement {
41    name: String,
42    port: u16,
43}
44
45impl OpaqueAdvertisement {
46    /// Derive the advertisement for a rotation `epoch` (see [`rotation_epoch`]). The instance
47    /// name is `hex(SHA-256("capsule-peer-advert-v2" ‖ rotation_seed ‖ boot_id ‖ day)[..16])` —
48    /// a one-way function of a secret the peer never broadcasts, so the same epoch reproduces the
49    /// same opaque name and a new epoch (a new boot, or a new UTC day) yields an unlinkable new
50    /// one. Hashing the two components separately means no two distinct epochs can collide.
51    #[must_use]
52    pub fn for_epoch(rotation_seed: &[u8; 32], epoch: RotationEpoch, port: u16) -> Self {
53        let mut hasher = Sha256::new();
54        hasher.update(b"capsule-peer-advert-v2");
55        hasher.update(rotation_seed);
56        hasher.update(epoch.boot_id.to_le_bytes());
57        hasher.update(epoch.day.to_le_bytes());
58        let digest = hasher.finalize();
59        Self {
60            name: hex::encode(&digest[..OPAQUE_BYTES]),
61            port,
62        }
63    }
64
65    /// The opaque service-instance name that goes on the wire. Carries no identity.
66    #[must_use]
67    pub fn advertised_name(&self) -> &str {
68        &self.name
69    }
70
71    /// The fixed, non-identifying mDNS service type.
72    #[must_use]
73    pub fn service_type(&self) -> &'static str {
74        SERVICE_TYPE
75    }
76
77    /// The TCP port the peering listener is bound to.
78    #[must_use]
79    pub fn port(&self) -> u16 {
80        self.port
81    }
82}
83
84/// The rotation epoch an advertisement is derived for: the boot it was made in and the UTC day.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub struct RotationEpoch {
87    /// A per-boot identifier, drawn fresh at every boot (see [`new_boot_id`]).
88    pub boot_id: u64,
89    /// The UTC day number (`unix_secs / 86_400`, floored).
90    pub day: i64,
91}
92
93/// A fresh random per-boot identifier — what a device draws once at boot and feeds to
94/// [`rotation_epoch`] for the life of that boot.
95#[must_use]
96pub fn new_boot_id() -> u64 {
97    u64::from_le_bytes(capsule_core::crypto::rng::random_array::<8>())
98}
99
100/// Compute the rotation epoch from a per-boot identifier and the current UTC time.
101///
102/// The peering doc requires the opaque advertisement to rotate **at every boot and at least every
103/// 24 h**. The epoch changes whenever `boot_id` changes (a new boot), and within one boot at every
104/// UTC-day boundary, so no advertised name outlives 24 h. A device re-advertises when the epoch
105/// it computes differs from the one it last advertised.
106#[must_use]
107pub fn rotation_epoch(boot_id: u64, unix_secs: i64) -> RotationEpoch {
108    RotationEpoch {
109        boot_id,
110        day: unix_secs.div_euclid(DAY_SECS),
111    }
112}
113
114/// A peer found on the LAN: its opaque instance name and the socket to dial.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct DiscoveredPeer {
117    /// The peer's opaque mDNS instance name (non-identifying).
118    pub instance_name: String,
119    /// The address to open the peering [`channel`](super::channel) to.
120    pub addr: SocketAddr,
121}
122
123/// The LAN discovery seam. Abstracted so the (non-deterministic, multicast) mDNS responder is
124/// mocked in tests while a production `mdns-sd`-backed implementation plugs in unchanged. A
125/// device both **advertises** its own opaque service and **browses** for peers; peering is
126/// best-effort, so a browse that finds nothing simply returns an empty list.
127pub trait Discovery {
128    /// Publish `advert` for `addr` on the LAN. Idempotent — re-advertising a rotated name
129    /// replaces the previous one.
130    fn advertise(&self, advert: &OpaqueAdvertisement, addr: SocketAddr)
131    -> Result<(), PeeringError>;
132
133    /// Browse the LAN for currently-advertised peers. Never blocks indefinitely and never errors
134    /// on "no peers" — an empty vector means fall back to server sync.
135    fn browse(&self) -> Result<Vec<DiscoveredPeer>, PeeringError>;
136}
137
138/// A deterministic in-memory [`Discovery`] for tests: a shared registry of advertised peers.
139/// Cloning shares the registry, so a test can advertise on one handle and browse on another —
140/// standing in for two devices on the same segment.
141#[derive(Debug, Clone, Default)]
142pub struct MockDiscovery {
143    registry: Arc<Mutex<Vec<DiscoveredPeer>>>,
144}
145
146impl MockDiscovery {
147    /// A fresh, empty discovery registry.
148    #[must_use]
149    pub fn new() -> Self {
150        Self::default()
151    }
152}
153
154impl Discovery for MockDiscovery {
155    #[instrument(skip(self), fields(name = advert.advertised_name(), %addr))]
156    fn advertise(
157        &self,
158        advert: &OpaqueAdvertisement,
159        addr: SocketAddr,
160    ) -> Result<(), PeeringError> {
161        let mut reg = self
162            .registry
163            .lock()
164            .map_err(|_| PeeringError::Discovery("registry poisoned".into()))?;
165        let peer = DiscoveredPeer {
166            instance_name: advert.advertised_name().to_string(),
167            addr,
168        };
169        // Rotated re-advertise: replace any prior entry for this exact name.
170        reg.retain(|p| p.instance_name != peer.instance_name);
171        tracing::debug!("advertising opaque peering service on the LAN");
172        reg.push(peer);
173        Ok(())
174    }
175
176    fn browse(&self) -> Result<Vec<DiscoveredPeer>, PeeringError> {
177        let reg = self
178            .registry
179            .lock()
180            .map_err(|_| PeeringError::Discovery("registry poisoned".into()))?;
181        Ok(reg.clone())
182    }
183}