//! Pinnacle's peer-to-peer layer, as a pure state machine like the network //! stack: datagrams in ([`Node::receive`]), datagrams out //! ([`Node::transmit`]), events for the apps ([`Node::event`]), time a //! parameter. No server anywhere: every device is a node of a Kademlia DHT. //! //! - A node's id is the SHA-256 of its identity key. Lookups ask the nodes //! closest (by XOR) to a target for still closer ones, three at a time. //! - Each device publishes a **presence record** (its keys and address, //! signed by its identity, valid ten minutes) at the nodes closest to //! SHA-256("presence" ‖ identity), and refreshes it every minute. The //! address is the one it was told (a forwarded port), else the one the //! nodes it pings see it at, once two agree. //! - To reach a contact, a device looks up that record, then opens an end-to- //! end encrypted session (`session`) straight to the address in it. //! Messages wait in a queue until the session is up. //! - Joining needs the address of one node already in: any known device. //! //! Through NATs, with no server, as ICE does with one: //! - A device keeps up to two **introducers**, nodes it pings every twenty //! seconds, so its NAT keeps a way in from each; its presence record //! names them, and its address on its own network. //! - A HELLO to a contact goes to its published address and to its local //! one (the same network, behind the same NAT, where most NATs do not //! turn a datagram for their own public address back in); with it goes an //! INTRODUCE to each of the contact's introducers, which passes a PUNCH on //! to the contact, saying where it sees this device. The contact sends a //! HELLO there: each side has now sent to the other, so each NAT lets the //! other's datagrams through. Behind two NATs that map anew for every //! address they send to (symmetric), it does not; that needs a relay. //! //! A session heals itself, as WireGuard's do and further: //! - **Roaming**: an authentic datagram from a new address moves where the //! contact is answered. A device that sees its own address change //! ([`Node::network_changed`], or the nodes it pings seeing it elsewhere) //! sends every session a keepalive at once and publishes its presence //! anew. //! - **Keepalives**: a device owes a contact a datagram within ten seconds //! of any it received, and sends one every ten seconds while a stream is //! open, which also keeps a NAT's mapping. //! - **Found again**: when nothing comes back for fifteen seconds, a device //! sends a new HELLO where the contact was, looks its presence up in the //! DHT, and asks where it is seen itself; every five seconds until it //! answers. So two devices that both moved at once still meet, where //! WireGuard needs one of them to stay put. //! - **New keys** every two minutes of use; sessions unused for three //! minutes, with no stream open, are let go. //! //! On a session go app payloads (messages, calls' frames: lost when lost) //! and the frames of reliable, ordered streams (`stream`), which outlive any //! one session. #![no_std] extern crate alloc; pub mod delivery; pub mod identity; pub mod link; pub mod session; pub mod stream; use alloc::collections::VecDeque; use alloc::string::String; use alloc::vec::Vec; use identity::{Card, Identity, Key, Rng}; use pinnacle_crypto::{ed25519, sha2::Sha256}; use session::{Pending, Session}; use stream::{Header, Stream}; pub type NodeId = [u8; 32]; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Addr { pub ip: [u8; 4], pub port: u16, } impl Addr { fn to_bytes(self) -> [u8; 6] { let p = self.port.to_be_bytes(); [self.ip[0], self.ip[1], self.ip[2], self.ip[3], p[0], p[1]] } fn from_bytes(b: &[u8]) -> Option { let b: &[u8; 6] = b.get(..6)?.try_into().ok()?; Some(Addr { ip: [b[0], b[1], b[2], b[3]], port: u16::from_be_bytes([b[4], b[5]]), }) } } const PING: u8 = 1; const PONG: u8 = 2; const FIND: u8 = 3; const NODES: u8 = 4; const STORE: u8 = 5; /// To an introducer: pass a PUNCH on to the node whose id follows. const INTRODUCE: u8 = 6; /// From an introducer: a device (its identity key, and where the introducer /// sees it) wants a session; send a HELLO there. const PUNCH: u8 = 7; /// Keep a link record (`link`): its place, then the record. const STORE_LINK: u8 = 8; /// Link records a node holds at most, and for how long. const LINKS: usize = 64; const LINK_MS: u64 = 600_000; const HELLO: u8 = 0x10; const WELCOME: u8 = 0x11; const DATA: u8 = 0x12; /// What a DATA datagram's sealed payload is, by its first byte; an empty /// one is a keepalive. const APP: u8 = 0; const STREAM: u8 = 1; /// The longest service tag a stream opens with. pub const MAX_SERVICE: usize = 64; /// Closest nodes a lookup keeps, and how many it asks at once. const K: usize = 8; const ALPHA: usize = 3; const TABLE: usize = 256; const STORED: usize = 1024; const LOOKUP_MS: u64 = 4000; const PUBLISH_MS: u64 = 60_000; const RECORD_MS: u64 = 600_000; const RETRY_MS: u64 = 3000; /// A presence record with no introducer: identity, key-exchange key, /// address, stamp, local address, the introducers' count, signature; each /// introducer adds an address. const PRESENCE: usize = 32 + 32 + 6 + 8 + 6 + 1 + 64; const INTRODUCERS: usize = 2; /// How often a device pings its introducers and another node, which also /// tell it where they see it. Under the thirty seconds after which the /// quickest NATs forget a mapping. const PING_MS: u64 = 20_000; /// An introducer not heard from in this long is replaced. const INTRODUCER_MS: u64 = 3 * PING_MS; /// How long after a node was last heard from it is still introduced to: /// its NAT may have forgotten the way in since. const INTRODUCE_MS: u64 = 2 * PING_MS; /// How often a contact is punched to, or a node introduced, at most: an /// INTRODUCE costs the device it reaches one HELLO, sent where it is told. const PUNCH_MS: u64 = 1000; /// How long what a node said it sees counts. const REPORT_MS: u64 = 60_000; const KEEPALIVE_MS: u64 = 10_000; /// Unanswered this long, a session is taken for lost and healed, again /// every `HEAL_MS` until it answers. const STALE_MS: u64 = 15_000; const HEAL_MS: u64 = 5000; const REKEY_MS: u64 = 120_000; const IDLE_MS: u64 = 180_000; /// A stamp's low bits: milliseconds since the device started. const EPOCH_SHIFT: u32 = 40; #[derive(Debug, PartialEq, Eq)] pub enum Event { /// A contact's payload, decrypted and authenticated. Received { from: Key, payload: Vec }, /// A session with a contact is up (either side opened it); not said /// again when its keys are renewed. Connected { contact: Key }, /// A contact could not be found or reached. Unreachable { contact: Key }, /// A contact opened a stream to `service` (its tag, [`Node::open_stream`]). StreamOpened { contact: Key, stream: u32, service: String, }, /// The next bytes of a stream, in order. StreamData { contact: Key, stream: u32, data: Vec, }, /// The contact has finished writing to a stream. StreamFinished { contact: Key, stream: u32 }, /// A stream ended before it was finished: the contact reset it, or /// restarted, or was not heard from for five minutes. StreamReset { contact: Key, stream: u32 }, /// A link record was found where [`Node::find_link`] looked. LinkFound { place: [u8; 32], record: Vec }, } pub fn node_id(key: &Key) -> NodeId { Sha256::digest(key) } fn presence_key(identity: &Key) -> [u8; 32] { Sha256::digest(&[b"presence".as_slice(), identity].concat()) } fn distance(a: &[u8; 32], b: &[u8; 32]) -> [u8; 32] { core::array::from_fn(|i| a[i] ^ b[i]) } /// What a signed presence record says. struct Presence { identity: Key, dh: Key, addr: Addr, time: u64, /// Its address on its own network, where that differs from `addr`. local: Option, introducers: Vec, } /// A presence record, if well formed and signed. fn check_presence(record: &[u8]) -> Option { let count = usize::from(*record.get(84)?); let signed = PRESENCE - 64 + 6 * count; if count > INTRODUCERS || record.len() != signed + 64 { return None; } let identity: Key = record[..32].try_into().unwrap(); let signature: [u8; 64] = record[signed..].try_into().unwrap(); if !ed25519::verify(&identity, &record[..signed], &signature) { return None; } Some(Presence { identity, dh: record[32..64].try_into().unwrap(), addr: Addr::from_bytes(&record[64..70])?, time: u64::from_le_bytes(record[70..78].try_into().unwrap()), local: Addr::from_bytes(&record[78..84]).filter(|a| a.port != 0), introducers: record[85..signed] .chunks(6) .filter_map(Addr::from_bytes) .collect(), }) } #[derive(Clone, Copy, PartialEq, Eq)] enum Purpose { Join, Publish, Find(Key), /// Storing the link record at the lookup's target. StoreLink, FindLink, } struct Lookup { target: [u8; 32], purpose: Purpose, tx: u32, /// (id, address, asked, answered), the closest first. nodes: Vec<(NodeId, Addr, bool, bool)>, started: u64, } struct Peer { card: Card, addr: Option, /// From its presence record: its address on its own network, and the /// nodes that introduce others to it. local: Option, introducers: Vec, /// The HELLO waiting for its answer, as sent: sent again at once where /// a punch or a HELLO of the contact's shows a way in. hello: Vec, /// When a PUNCH from it was last acted on. punched: Option, session: Option, /// The session before the last handshake: what was sent on it may /// still come. previous: Option, /// Whether the contact is known to hold the session: a responder /// sends on the previous one until the first datagram on the new, so /// a lost WELCOME loses nothing. confirmed: bool, pending: Option<(Pending, u64)>, /// HELLOs sent for this handshake that went unanswered. tries: u32, outbox: VecDeque>, finding: bool, /// The newest stamp taken from the contact's HELLOs, and the epoch its /// last handshake carried (a higher one: it restarted). stamp: Option, epoch: Option, /// When the session began, and when anything was last sent, received, /// or used (an app payload or a stream frame, either way). since: u64, last_sent: u64, last_received: u64, last_used: u64, /// Since when a datagram wanting an answer has had none. awaiting: Option, /// Since when this device owes the contact a datagram. owe: Option, healed: Option, streams: Vec, } pub struct Node { identity: Identity, card: Card, id: NodeId, rng: Rng, epoch: u64, public: Option, /// Where the nodes this device pings see it, once two agree. observed: Option, /// (node, where it sees this device, when it said so). reports: Vec<(NodeId, Addr, u64)>, /// This device's address on its own network. local: Option, /// (node, address, when it last answered a ping). introducers: Vec<(NodeId, Addr, u64)>, /// Nodes this device passed a PUNCH on to, and when. introduced: Vec<(NodeId, u64)>, pinged: Option, ping_next: usize, table: Vec<(NodeId, Addr, u64)>, store: Vec<([u8; 32], Vec, u64)>, /// Link records held: place, record, until when. links: Vec<([u8; 32], Vec, u64)>, lookups: Vec, peers: Vec, out: VecDeque<(Addr, Vec)>, events: VecDeque, next_tx: u32, published: Option, } impl Node { pub fn new(identity: Identity, name: &str, rng_seed: [u8; 32]) -> Node { let card = identity.card(name); let id = node_id(&identity.public); Node { identity, card, id, rng: Rng::new(rng_seed), epoch: 0, public: None, observed: None, reports: Vec::new(), local: None, introducers: Vec::new(), introduced: Vec::new(), pinged: None, ping_next: 0, table: Vec::new(), store: Vec::new(), links: Vec::new(), lookups: Vec::new(), peers: Vec::new(), out: VecDeque::new(), events: VecDeque::new(), next_tx: 1, published: None, } } /// How many times this identity has started, kept by the caller across /// restarts: stamps (presence records, handshakes) then only grow, so /// the newest record wins everywhere and a replayed HELLO is refused. pub fn set_epoch(&mut self, epoch: u64) { self.epoch = epoch; } fn stamp(&self, now: u64) -> u64 { (self.epoch << EPOCH_SHIFT) | (now & ((1 << EPOCH_SHIFT) - 1)) } pub fn card(&self) -> &Card { &self.card } pub fn add_contact(&mut self, card: Card) { if card.key != self.card.key && !self.peers.iter().any(|p| p.card.key == card.key) { self.peers.push(Peer { card, addr: None, local: None, introducers: Vec::new(), hello: Vec::new(), punched: None, session: None, previous: None, confirmed: false, pending: None, tries: 0, outbox: VecDeque::new(), finding: false, stamp: None, epoch: None, since: 0, last_sent: 0, last_received: 0, last_used: 0, awaiting: None, owe: None, healed: None, streams: Vec::new(), }); } } /// Forgets the contact `key`: its session and streams go with it, and /// what it sends after is not answered, as from any stranger. pub fn remove_contact(&mut self, key: &Key) { self.peers.retain(|p| p.card.key != *key); } pub fn contacts(&self) -> impl Iterator { self.peers.iter().map(|p| &p.card) } /// The address others reach this device at, when known (a forwarded /// port); otherwise the one nodes see it at is used. pub fn set_public_address(&mut self, addr: Addr) { self.public = Some(addr); } /// This device's address on its own network (its IP and the port it /// listens on), which a contact behind the same NAT reaches it at. pub fn set_local_address(&mut self, addr: Addr) { self.local = Some(addr); } /// Where this device is published as reachable, if anywhere yet. pub fn address(&self) -> Option { self.public.or(self.observed) } /// The device's own network changed (a new IP address, another /// network): what nodes saw it at no longer holds, so it asks again, /// and every contact with a session hears from the new address at once. pub fn network_changed(&mut self, now: u64) { self.reports.clear(); self.ping_some(now); for i in 0..self.peers.len() { self.keepalive(i, now); } } /// Joins through a node at `addr`. pub fn bootstrap(&mut self, addr: Addr, now: u64) { self.send_dht(addr, PING, &[]); let _ = now; } pub fn transmit(&mut self) -> Option<(Addr, Vec)> { self.out.pop_front() } pub fn event(&mut self) -> Option { self.events.pop_front() } /// Nodes in the routing table. pub fn known_nodes(&self) -> usize { self.table.len() } /// Stores a link record (`link`) at the nodes closest to `place`, and /// here: called again, it is stored again, for nodes that came since. pub fn put_link(&mut self, place: [u8; 32], record: Vec, now: u64) { if record.len() != link::RECORD { return; } self.keep_link(place, record, now); self.start_lookup(place, Purpose::StoreLink, now); } /// Looks for the link record at `place`: [`Event::LinkFound`] when it is /// there, nothing when not (look again). pub fn find_link(&mut self, place: [u8; 32], now: u64) { if let Some(e) = self.links.iter().find(|e| e.0 == place) { let record = e.1.clone(); self.events.push_back(Event::LinkFound { place, record }); return; } self.start_lookup(place, Purpose::FindLink, now); } fn keep_link(&mut self, place: [u8; 32], record: Vec, now: u64) { self.links.retain(|e| e.0 != place); if self.links.len() >= LINKS { self.links.remove(0); } self.links.push((place, record, now + LINK_MS)); } fn send_dht(&mut self, to: Addr, kind: u8, body: &[u8]) { let mut m = Vec::with_capacity(33 + body.len()); m.push(kind); m.extend_from_slice(&self.id); m.extend_from_slice(body); self.out.push_back((to, m)); } fn learn(&mut self, id: NodeId, addr: Addr, now: u64) { if id == self.id { return; } if let Some(entry) = self.table.iter_mut().find(|e| e.0 == id) { entry.1 = addr; entry.2 = now; return; } if self.table.len() >= TABLE { // The longest unheard-from goes. let oldest = (0..self.table.len()).min_by_key(|&i| self.table[i].2).unwrap(); self.table.swap_remove(oldest); } self.table.push((id, addr, now)); } fn closest(&self, target: &[u8; 32], n: usize) -> Vec<(NodeId, Addr)> { let mut nodes: Vec<(NodeId, Addr)> = self.table.iter().map(|e| (e.0, e.1)).collect(); nodes.sort_by_key(|(id, _)| distance(id, target)); nodes.truncate(n); nodes } /// Pings the introducers, keeping their way in open, and nodes of the /// table in turn, two at least; each answers where it sees this device. fn ping_some(&mut self, now: u64) { self.pinged = Some(now); self.introducers.retain(|e| now - e.2 < INTRODUCER_MS); let mut to: Vec = self.introducers.iter().map(|e| e.1).collect(); let n = self.table.len(); for k in 0..n.min(2) { let addr = self.table[(self.ping_next + k) % n].1; if !to.contains(&addr) { to.push(addr); } } self.ping_next = self.ping_next.wrapping_add(2); for addr in to { self.send_dht(addr, PING, &[]); } } /// A node answered a ping: it introduces others to this device, while /// fewer than two do. fn answered(&mut self, node: NodeId, addr: Addr, now: u64) { let full = self.introducers.len() >= INTRODUCERS; match self.introducers.iter_mut().find(|e| e.0 == node) { Some(e) => { e.1 = addr; e.2 = now; } None if !full => { self.introducers.push((node, addr, now)); // Contacts learn of it with the next record. if self.published.is_some() { self.publish(now); } } None => {} } } /// A node sees this device at `seen`. The newest report is believed /// once two nodes agree (one, while only one has answered): a single /// node that lies cannot move where the device is published. fn observe(&mut self, reporter: NodeId, seen: Addr, now: u64) { self.reports.retain(|r| r.0 != reporter && now - r.2 < REPORT_MS); self.reports.push((reporter, seen, now)); let agree = self.reports.iter().filter(|r| r.1 == seen).count(); if agree < self.reports.len().min(2) || self.observed == Some(seen) { return; } let before = self.observed.replace(seen); if self.public.is_none() { self.publish(now); if before.is_some() { for i in 0..self.peers.len() { self.keepalive(i, now); } } } } fn presence(&self, now: u64) -> Option> { let addr = self.address()?; let introducers = &self.introducers[..self.introducers.len().min(INTRODUCERS)]; let mut r = Vec::with_capacity(PRESENCE + 6 * introducers.len()); r.extend_from_slice(&self.identity.public); r.extend_from_slice(&self.identity.dh_public); r.extend_from_slice(&addr.to_bytes()); r.extend_from_slice(&self.stamp(now).to_le_bytes()); let local = self.local.filter(|l| *l != addr); r.extend_from_slice(&local.map_or([0; 6], Addr::to_bytes)); r.push(introducers.len() as u8); for e in introducers { r.extend_from_slice(&e.1.to_bytes()); } let signature = self.identity.sign(&r); r.extend_from_slice(&signature); Some(r) } fn keep(&mut self, key: [u8; 32], record: Vec, now: u64) { let Some(Presence { identity, time, .. }) = check_presence(&record) else { return; }; if presence_key(&identity) != key { return; } match self.store.iter_mut().find(|e| e.0 == key) { Some(entry) => { let held = u64::from_le_bytes(entry.1[70..78].try_into().unwrap()); if time >= held { entry.1 = record; entry.2 = now + RECORD_MS; } } None => { if self.store.len() >= STORED { self.store.remove(0); } self.store.push((key, record, now + RECORD_MS)); } } } fn start_lookup(&mut self, target: [u8; 32], purpose: Purpose, now: u64) { let tx = self.next_tx; self.next_tx += 1; let nodes = self .closest(&target, K) .into_iter() .map(|(id, a)| (id, a, false, false)) .collect(); self.lookups.push(Lookup { target, purpose, tx, nodes, started: now, }); self.advance_lookups(now); } /// Asks the closest unasked nodes of each lookup, ALPHA in flight; ends /// the ones that are done. fn advance_lookups(&mut self, now: u64) { let mut finished = Vec::new(); for i in 0..self.lookups.len() { let l = &mut self.lookups[i]; let in_flight = l.nodes.iter().filter(|n| n.2 && !n.3).count(); let mut asks = Vec::new(); for n in l .nodes .iter_mut() .filter(|n| !n.2) .take(ALPHA.saturating_sub(in_flight)) { n.2 = true; asks.push(n.1); } let (tx, target) = (l.tx, l.target); let done = l.nodes.iter().all(|n| n.3) || now - l.started > LOOKUP_MS; for addr in asks { let mut body = tx.to_le_bytes().to_vec(); body.extend_from_slice(&target); self.send_dht(addr, FIND, &body); } if done { finished.push(i); } } for i in finished.into_iter().rev() { let l = self.lookups.remove(i); self.finish_lookup(l, now); } } fn finish_lookup(&mut self, l: Lookup, now: u64) { match l.purpose { Purpose::Join => {} Purpose::Publish => { if let Some(record) = self.presence(now) { let key = presence_key(&self.identity.public); self.keep(key, record.clone(), now); for (_, addr, _, answered) in l.nodes.iter().take(K) { if *answered { let mut body = key.to_vec(); body.extend_from_slice(&record); self.send_dht(*addr, STORE, &body); } } } } Purpose::StoreLink => { let Some(record) = self.links.iter().find(|e| e.0 == l.target).map(|e| e.1.clone()) else { return; }; for (_, addr, _, answered) in l.nodes.iter().take(K) { if *answered { let mut body = l.target.to_vec(); body.extend_from_slice(&record); self.send_dht(*addr, STORE_LINK, &body); } } } // Not found in time: the caller looks again. Purpose::FindLink => {} Purpose::Find(contact) => { // Not found in time (a found record ends a lookup earlier). if let Some(p) = self.peers.iter_mut().find(|p| p.card.key == contact) { p.finding = false; if p.addr.is_none() { self.events.push_back(Event::Unreachable { contact }); } } } } } /// Publishes this device's presence, and refreshes its neighbours. fn publish(&mut self, now: u64) { self.published = Some(now); let target = presence_key(&self.identity.public); self.start_lookup(target, Purpose::Publish, now); let own = self.id; self.start_lookup(own, Purpose::Join, now); } /// Timers: publishing presence, pings, lookups, and each contact's /// handshake, keepalives, healing and streams. pub fn poll(&mut self, now: u64) { if !self.table.is_empty() && self.published.is_none_or(|t| now - t >= PUBLISH_MS) { self.publish(now); } if !self.table.is_empty() && self.pinged.is_none_or(|t| now - t >= PING_MS) { self.ping_some(now); } self.store.retain(|e| e.2 > now); self.links.retain(|e| e.2 > now); self.advance_lookups(now); for i in 0..self.peers.len() { self.tend(i, now); } } fn tend(&mut self, i: usize, now: u64) { let retry = matches!(self.peers[i].pending, Some((_, sent)) if now - sent >= RETRY_MS); if retry { let peer = &mut self.peers[i]; peer.pending = None; peer.tries += 1; // Every third unanswered HELLO, the address may be stale. if peer.tries.is_multiple_of(3) { self.find(i, now); } self.connect(i, now); } let peer = &mut self.peers[i]; let mut reset = Vec::new(); peer.streams.retain(|s| { if s.oldest_unacked().is_some_and(|t| now - t >= stream::GIVE_UP_MS) { reset.push(s.id); return false; } s.done_since.is_none_or(|t| now - t < stream::LINGER_MS) }); for s in &mut peer.streams { if s.done_since.is_none() && s.is_done() { s.done_since = Some(now); } } let contact = peer.card.key; for stream in reset { self.events.push_back(Event::StreamReset { contact, stream }); } self.pump(i, now); let peer = &mut self.peers[i]; if peer.session.is_none() { return; } let open = peer.streams.iter().any(|s| s.done_since.is_none()); let stale = peer.awaiting.is_some_and(|t| now - t >= STALE_MS) || (open && now - peer.last_received >= STALE_MS); if stale && peer.healed.is_none_or(|t| now - t >= HEAL_MS) { self.heal(i, now); } else if !open && peer.outbox.is_empty() && now - peer.last_used >= IDLE_MS && now - peer.last_received >= KEEPALIVE_MS { // Unused: let go, and with it the keepalives. peer.session = None; peer.previous = None; peer.awaiting = None; peer.owe = None; } else if (open && now - peer.last_sent >= KEEPALIVE_MS) || peer.owe.is_some_and(|t| now - t >= KEEPALIVE_MS) { self.keepalive(i, now); } } /// Nothing came back: a new HELLO where the contact was, its presence /// looked up afresh, for wherever it went, and nodes asked where they /// see this device, which may be the one that moved. fn heal(&mut self, i: usize, now: u64) { if self.pinged.is_none_or(|t| now - t >= HEAL_MS) { self.ping_some(now); } let peer = &mut self.peers[i]; // `awaiting` stays: only an answer ends the healing. peer.healed = Some(now); peer.pending = None; peer.tries = 0; self.connect(i, now); self.find(i, now); } fn find(&mut self, i: usize, now: u64) { if !self.peers[i].finding { self.peers[i].finding = true; let target = presence_key(&self.peers[i].card.key); self.start_lookup(target, Purpose::Find(self.peers[i].card.key), now); } } /// Seals `plain` on the contact's session and sends it; false without /// one. Anything but a keepalive wants an answer. fn send_sealed(&mut self, i: usize, plain: &[u8], now: u64) -> bool { let peer = &mut self.peers[i]; let session = match (peer.confirmed, peer.previous.as_mut()) { (false, Some(previous)) => Some(previous), _ => peer.session.as_mut(), }; let (Some(session), Some(addr)) = (session, peer.addr) else { return false; }; let mut m = alloc::vec![DATA]; m.extend(session.seal(plain)); self.out.push_back((addr, m)); peer.last_sent = now; peer.owe = None; if !plain.is_empty() { peer.last_used = now; peer.awaiting.get_or_insert(now); } if now - peer.since >= REKEY_MS { self.connect(i, now); } true } fn keepalive(&mut self, i: usize, now: u64) { self.send_sealed(i, &[], now); } /// Sends `payload` to a contact, end-to-end encrypted, once a session is /// up: finding the contact and opening one first if need be. pub fn send(&mut self, contact: &Key, payload: Vec, now: u64) { let Some(i) = self.peers.iter().position(|p| p.card.key == *contact) else { return; }; let plain = [&[APP][..], &payload].concat(); if !self.send_sealed(i, &plain, now) { self.peers[i].outbox.push_back(payload); self.connect(i, now); } } /// Takes back the payloads to `contact` still waiting for a session /// that `take` picks, so they never go: what went another way meanwhile. pub fn withdraw(&mut self, contact: &Key, take: impl Fn(&[u8]) -> bool) { if let Some(peer) = self.peers.iter_mut().find(|p| p.card.key == *contact) { peer.outbox.retain(|p| !take(p)); } } /// A HELLO to the contact, unless one waits for its answer; first /// finding where it is, if that is not known. fn connect(&mut self, i: usize, now: u64) { let peer = &mut self.peers[i]; if peer.pending.is_some() { return; } let Some(addr) = peer.addr else { self.find(i, now); return; }; let ephemeral = self.rng.bytes::<32>(); let id = u64::from_le_bytes(self.rng.bytes::<8>()); let stamp = self.stamp(now); let (message, pending) = session::hello( &self.identity, &self.card, &self.peers[i].card.dh, ephemeral, id, stamp, ); let mut m = alloc::vec![HELLO]; m.extend(message); let peer = &mut self.peers[i]; peer.pending = Some((pending, now)); peer.hello = m.clone(); // Its own network's address too, and the introducers asked to tell // it where this device is, so it sends a HELLO back through both NATs. let local = peer.local.filter(|l| *l != addr); let introducers = peer.introducers.clone(); let target = node_id(&peer.card.key); if let Some(local) = local { self.out.push_back((local, m.clone())); } self.out.push_back((addr, m)); let mut body = target.to_vec(); body.extend_from_slice(&self.identity.public); for introducer in introducers { self.send_dht(introducer, INTRODUCE, &body); } } /// A new session with contact `i`, answered at `from`; `stamp` is the /// one its side of the handshake carried; `initiator`: this device /// sent the HELLO, so the contact holds the session already. fn established(&mut self, i: usize, session: Session, from: Addr, stamp: u64, initiator: bool, now: u64) { let contact = self.peers[i].card.key; let epoch = stamp >> EPOCH_SHIFT; let peer = &mut self.peers[i]; let restarted = peer.epoch.is_some_and(|e| epoch > e); if restarted { // It restarted: its streams and sessions are gone. for s in peer.streams.drain(..) { if s.done_since.is_none() { self.events.push_back(Event::StreamReset { contact, stream: s.id, }); } } } peer.epoch = Some(epoch); let fresh = peer.session.is_none(); peer.previous = peer.session.replace(session).filter(|_| !restarted); peer.confirmed = initiator; peer.addr = Some(from); peer.pending = None; peer.tries = 0; peer.since = now; peer.last_received = now; peer.awaiting = None; for s in &mut peer.streams { s.resend_all(); } if fresh { self.events.push_back(Event::Connected { contact }); } while let Some(payload) = self.peers[i].outbox.pop_front() { self.send_sealed(i, &[&[APP][..], &payload].concat(), now); } self.pump(i, now); } /// Sends what the contact's streams have to send: new frames, frames /// whose time ran out, acknowledgements. Without a session, opens one. fn pump(&mut self, i: usize, now: u64) { let peer = &mut self.peers[i]; if peer.session.is_none() || peer.addr.is_none() { if peer.streams.iter().any(Stream::has_output) { self.connect(i, now); } return; } let frames: Vec> = peer.streams.iter_mut().flat_map(|s| s.output(now)).collect(); for frame in frames { self.send_sealed(i, &[&[STREAM][..], &frame].concat(), now); } } /// The low bit of the ids of streams this device opens to contact `i`: /// the two sides never pick the same. fn parity(&self, i: usize) -> u32 { u32::from(self.card.key < self.peers[i].card.key) } /// Opens a stream to a contact's `service` (a name of up to /// [`MAX_SERVICE`] bytes, which the stream's first bytes carry: the /// other side learns of the stream with it, so the program that /// handles that service gets it); its id, or None for a stranger or a /// name that does not fit. pub fn open_stream(&mut self, contact: &Key, service: &str, now: u64) -> Option { if service.is_empty() || service.len() > MAX_SERVICE { return None; } let i = self.peers.iter().position(|p| p.card.key == *contact)?; let id = loop { let id = (u32::from_le_bytes(self.rng.bytes::<4>()) & !1) | self.parity(i); if !self.peers[i].streams.iter().any(|s| s.id == id) { break id; } }; let mut stream = Stream::new(id, true); stream.write(&[&[service.len() as u8][..], service.as_bytes()].concat()); self.peers[i].streams.push(stream); self.peers[i].last_used = now; self.pump(i, now); Some(id) } fn stream_mut(&mut self, contact: &Key, id: u32) -> Option<(usize, &mut Stream)> { let i = self.peers.iter().position(|p| p.card.key == *contact)?; let s = self.peers[i].streams.iter_mut().find(|s| s.id == id)?; Some((i, s)) } /// Writes to a stream; it arrives whole and in order, or the stream is /// reset. pub fn stream_write(&mut self, contact: &Key, id: u32, data: &[u8], now: u64) { if let Some((i, s)) = self.stream_mut(contact, id) { s.write(data); self.peers[i].last_used = now; self.pump(i, now); } } /// Ends this side's writing to a stream, after what was written. pub fn stream_finish(&mut self, contact: &Key, id: u32, now: u64) { if let Some((i, s)) = self.stream_mut(contact, id) { s.finish(); self.pump(i, now); } } /// Bytes written to a stream and not yet acknowledged: a writer with /// much more to send waits while this is high. pub fn stream_backlog(&mut self, contact: &Key, id: u32) -> usize { self.stream_mut(contact, id).map_or(0, |(_, s)| s.backlog()) } /// Ends a stream at once, both ways, whatever is still unsent. pub fn stream_reset(&mut self, contact: &Key, id: u32, now: u64) { let Some(i) = self.peers.iter().position(|p| p.card.key == *contact) else { return; }; self.peers[i].streams.retain(|s| s.id != id); self.send_reset(i, id, now); } fn send_reset(&mut self, i: usize, id: u32, now: u64) { let frame = Header { id, flags: stream::RESET, seq: 0, ack: 0, sack: 0, } .frame(&[]); self.send_sealed(i, &[&[STREAM][..], &frame].concat(), now); } pub fn receive(&mut self, from: Addr, data: &[u8], now: u64) { let Some(&kind) = data.first() else { return }; match kind { HELLO => self.receive_hello(from, &data[1..], now), WELCOME => self.receive_welcome(from, &data[1..], now), DATA => self.receive_data(from, &data[1..], now), PING | PONG | FIND | NODES | STORE | INTRODUCE | PUNCH | STORE_LINK if data.len() >= 33 => { let sender: NodeId = data[1..33].try_into().unwrap(); self.learn(sender, from, now); self.receive_dht(kind, sender, from, &data[33..], now); } _ => {} } } fn receive_dht(&mut self, kind: u8, sender: NodeId, from: Addr, body: &[u8], now: u64) { match kind { PING => { let you = from.to_bytes(); self.send_dht(from, PONG, &you); } PONG => { if let Some(seen) = Addr::from_bytes(body) { self.observe(sender, seen, now); } self.answered(sender, from, now); // A first contact: find our neighbours, then publish. if self.published.is_none() { self.poll(now); } } FIND if body.len() >= 36 => { let tx = &body[..4]; let target: [u8; 32] = body[4..36].try_into().unwrap(); let nodes = self.closest(&target, K); let mut reply = tx.to_vec(); reply.push(nodes.len() as u8); for (id, addr) in nodes { reply.extend_from_slice(&id); reply.extend_from_slice(&addr.to_bytes()); } let record = self .store .iter() .chain(&self.links) .find(|e| e.0 == target) .map(|e| e.1.clone()) .unwrap_or_default(); reply.extend_from_slice(&(record.len() as u16).to_le_bytes()); reply.extend_from_slice(&record); self.send_dht(from, NODES, &reply); } NODES if body.len() >= 5 => self.receive_nodes(from, body, now), STORE if body.len() >= 32 => { let key: [u8; 32] = body[..32].try_into().unwrap(); self.keep(key, body[32..].to_vec(), now); } STORE_LINK if body.len() == 32 + link::RECORD => { let place: [u8; 32] = body[..32].try_into().unwrap(); self.keep_link(place, body[32..].to_vec(), now); } INTRODUCE if body.len() >= 64 => self.introduce(from, body, now), PUNCH if body.len() >= 38 => self.punched(body, now), _ => {} } } /// Passes a PUNCH on to the node asked for, if it pinged this one lately /// (so its NAT lets this one in), saying where the asker is seen. fn introduce(&mut self, from: Addr, body: &[u8], now: u64) { let target: NodeId = body[..32].try_into().unwrap(); let Some(&(_, to, heard)) = self.table.iter().find(|e| e.0 == target) else { return; }; self.introduced.retain(|e| now - e.1 < PUNCH_MS); if now - heard >= INTRODUCE_MS || self.introduced.iter().any(|e| e.0 == target) { return; } self.introduced.push((target, now)); let mut punch = body[32..64].to_vec(); punch.extend_from_slice(&from.to_bytes()); self.send_dht(to, PUNCH, &punch); } /// A contact wants a session and is seen at the address given: a HELLO /// there opens this device's NAT to it, and passes through the /// contact's, which has sent to this device already. Only for /// contacts, once a second, and not while a session answers. A PUNCH is /// not signed: it never moves where a session sends, only where a HELLO /// goes, and a forged one costs a HELLO the forger cannot answer. fn punched(&mut self, body: &[u8], now: u64) { let key: Key = body[..32].try_into().unwrap(); let Some(at) = Addr::from_bytes(&body[32..38]) else { return; }; let Some(i) = self.peers.iter().position(|p| p.card.key == key) else { return; }; let peer = &mut self.peers[i]; let answering = peer.session.is_some() && peer.awaiting.is_none(); if answering || peer.punched.is_some_and(|t| now - t < PUNCH_MS) { return; } peer.punched = Some(now); if peer.addr.is_none() { peer.addr = Some(at); } let fresh = peer.pending.is_none(); if fresh { self.connect(i, now); } // The HELLO waiting (or just sent elsewhere), to where the way is. let peer = &self.peers[i]; if peer.pending.is_some() && !(fresh && peer.addr == Some(at)) { self.out.push_back((at, peer.hello.clone())); } } fn receive_nodes(&mut self, from: Addr, body: &[u8], now: u64) { let tx = u32::from_le_bytes(body[..4].try_into().unwrap()); let count = usize::from(body[4]); let mut at = 5; let mut found = Vec::new(); for _ in 0..count { let Some(entry) = body.get(at..at + 38) else { return; }; let id: NodeId = entry[..32].try_into().unwrap(); if let Some(addr) = Addr::from_bytes(&entry[32..]) { found.push((id, addr)); } at += 38; } let record = body .get(at..at + 2) .map(|l| usize::from(u16::from_le_bytes([l[0], l[1]]))) .and_then(|len| body.get(at + 2..at + 2 + len)) .filter(|r| !r.is_empty()) .map(<[u8]>::to_vec); let Some(index) = self.lookups.iter().position(|l| l.tx == tx) else { return; }; for (id, addr) in &found { self.learn(*id, *addr, now); } let l = &mut self.lookups[index]; for n in l.nodes.iter_mut().filter(|n| n.1 == from) { n.3 = true; } for (id, addr) in found { if id != self.id && !l.nodes.iter().any(|n| n.0 == id) { l.nodes.push((id, addr, false, false)); } } let target = l.target; l.nodes.sort_by_key(|n| distance(&n.0, &target)); l.nodes.truncate(K * 2); if let (Purpose::FindLink, Some(record)) = (l.purpose, &record) && record.len() == link::RECORD { let place = l.target; self.lookups.remove(index); self.events.push_back(Event::LinkFound { place, record: record.clone(), }); return; } if let (Purpose::Find(contact), Some(record)) = (l.purpose, record) && let Some(presence) = check_presence(&record) && presence.identity == contact { self.lookups.remove(index); if let Some(i) = self .peers .iter() .position(|p| p.card.key == contact && p.card.dh == presence.dh) { let peer = &mut self.peers[i]; let moved = peer.addr != Some(presence.addr); peer.addr = Some(presence.addr); peer.local = presence.local; peer.introducers = presence.introducers; peer.finding = false; if moved || peer.session.is_none() { // A HELLO waiting at the old address: send anew here. if moved { peer.pending = None; } self.connect(i, now); } } return; } self.advance_lookups(now); } fn receive_hello(&mut self, from: Addr, hello: &[u8], now: u64) { let ephemeral = self.rng.bytes::<32>(); let stamp = self.stamp(now); let Some(w) = session::welcome(&self.identity, hello, ephemeral, stamp) else { return; }; // Only contacts may open a session. let Some(i) = self .peers .iter() .position(|p| p.card.key == w.card.key && p.card.dh == w.card.dh) else { return; }; // Not newer than the last: replayed, or overtaken. if self.peers[i].stamp.is_some_and(|last| w.stamp <= last) { return; } // Both opened at once: the one with the lower key keeps its own, // sent again where the contact's came from, now that the way is open. if self.peers[i].pending.is_some() && self.card.key < w.card.key { let hello = self.peers[i].hello.clone(); self.out.push_back((from, hello)); return; } self.peers[i].stamp = Some(w.stamp); let mut m = alloc::vec![WELCOME]; m.extend(w.message); self.out.push_back((from, m)); self.established(i, w.session, from, w.stamp, false, now); } fn receive_welcome(&mut self, from: Addr, welcome: &[u8], now: u64) { let Some(id) = welcome .get(..8) .map(|b| u64::from_le_bytes(b.try_into().unwrap())) else { return; }; let Some(i) = self .peers .iter() .position(|p| p.pending.as_ref().is_some_and(|(pending, _)| pending.id == id)) else { return; }; // Not the answer (forged, or garbled): keep waiting for it. let (pending, _) = self.peers[i].pending.as_ref().unwrap(); let Some((session, stamp)) = pending.complete(&self.identity, welcome) else { return; }; self.established(i, session, from, stamp, true, now); } fn receive_data(&mut self, from: Addr, data: &[u8], now: u64) { let Some(id) = data.get(..8).map(|b| u64::from_le_bytes(b.try_into().unwrap())) else { return; }; let Some(i) = self.peers.iter().position(|p| { p.session.as_ref().is_some_and(|s| s.id == id) || p.previous.as_ref().is_some_and(|s| s.id == id) }) else { return; }; let peer = &mut self.peers[i]; let current = peer.session.as_ref().is_some_and(|s| s.id == id); let session = if current { peer.session.as_mut().unwrap() } else { peer.previous.as_mut().unwrap() }; let Some(plain) = session.open(data) else { return; }; peer.confirmed |= current; // The contact may have moved: answer where it now is. peer.addr = Some(from); peer.last_received = now; peer.awaiting = None; let Some((&kind, body)) = plain.split_first() else { // A keepalive. return; }; peer.owe.get_or_insert(now); peer.last_used = now; match kind { APP => self.events.push_back(Event::Received { from: peer.card.key, payload: body.to_vec(), }), STREAM => self.receive_stream(i, body, now), _ => {} } } fn receive_stream(&mut self, i: usize, frame: &[u8], now: u64) { let Some((h, data)) = Header::parse(frame) else { return; }; let contact = self.peers[i].card.key; let known = self.peers[i].streams.iter().position(|s| s.id == h.id); if h.flags & stream::RESET != 0 { if let Some(at) = known { let s = self.peers[i].streams.remove(at); // One whose tag never came was never said to have opened. if s.done_since.is_none() && s.tag.is_none() { self.events.push_back(Event::StreamReset { contact, stream: h.id, }); } } return; } let at = match known { Some(at) => at, None if h.flags & stream::OPEN != 0 && h.id & 1 != self.parity(i) => { // Said once its tag has come, in its first bytes. self.peers[i].streams.push(Stream::new(h.id, false)); self.peers[i].streams.len() - 1 } None => { // Not one this device knows: gone (it restarted), or one // whose opening frame is still on its way. if h.id & 1 == self.parity(i) || h.seq >= stream::WINDOW { self.send_reset(i, h.id, now); } return; } }; let delivered = self.peers[i].streams[at].receive(&h, data, now); for mut data in delivered.data { let s = &mut self.peers[i].streams[at]; if let Some(tag) = &mut s.tag { // The service tag: a length byte and the name. tag.extend_from_slice(&data); let Some(&len) = tag.first() else { continue; }; let len = usize::from(len); if len == 0 || len > MAX_SERVICE { self.peers[i].streams.remove(at); self.send_reset(i, h.id, now); return; } if tag.len() < 1 + len { continue; } let rest = tag.split_off(1 + len); let Ok(service) = String::from_utf8(tag[1..].to_vec()) else { self.peers[i].streams.remove(at); self.send_reset(i, h.id, now); return; }; s.tag = None; self.events.push_back(Event::StreamOpened { contact, stream: h.id, service, }); data = rest; } if !data.is_empty() { self.events.push_back(Event::StreamData { contact, stream: h.id, data, }); } } if delivered.fin && self.peers[i].streams[at].tag.is_some() { // Finished before saying what it was for: nothing to deliver. self.peers[i].streams.remove(at); self.send_reset(i, h.id, now); return; } if delivered.fin { self.events.push_back(Event::StreamFinished { contact, stream: h.id, }); } self.pump(i, now); } } #[cfg(test)] mod tests;