Skip to main content

weirdnet_net/
names.rs

1//! Names: where a peer is now, as signed records.
2//!
3//! A [`PeerRecord`] says "this node of this user is at these addresses" (direct ones and
4//! relay circuits), signed by the node key and chained to the user key by the node's
5//! certificate. Records carry a `seq` (a higher one wins) and expire within
6//! [`MAX_RECORD_TTL_MS`]; a device republishes on network change. A [`Withdrawal`] removes a
7//! record: it is signed by a node certified by the same user, has a higher `seq`, and is
8//! kept until it expires, so stale copies can't come back.
9//!
10//! Records live, in lookup order, with trusted peers (the application pushes them), on the
11//! home relay's names server (the `names` protocol, [`NamesRequest`]), and in the Kademlia
12//! DHT under [`Profile::peer_key`] — the DHT only while the device hosts something. Every
13//! storing node runs the same rule, [`Profile::accept`]. A `_weirdnet.<name>` DNS TXT
14//! record ([`binding_txt`]) ties a domain to a user id.
15//!
16//! No DHT can force a deletion: a hostile node can keep serving an old record. Lookups
17//! drop anything expired, unsigned, revoked or below the highest `seq` seen, so a stale
18//! record leads to a failed dial, never a wrong peer (the dial is Noise-authenticated).
19use crate::addr::addr_peer;
20use crate::error::{NetError, Result};
21use crate::profile::Profile;
22use crate::user::{NodeCert, decode_public, user_id};
23use libp2p::identity::{Keypair, PublicKey};
24use libp2p::multiaddr::Protocol;
25use libp2p::{Multiaddr, PeerId};
26use serde::{Deserialize, Serialize};
27use sha2::Digest;
28use std::collections::HashMap;
29use std::sync::{Arc, Mutex};
30
31/// The longest a peer record may live.
32pub const MAX_RECORD_TTL_MS: i64 = 24 * 3600 * 1000;
33/// A withdrawal lives at least as long as the longest record, and at most a week.
34pub const MIN_WITHDRAWAL_TTL_MS: i64 = MAX_RECORD_TTL_MS;
35pub const MAX_WITHDRAWAL_TTL_MS: i64 = 7 * 24 * 3600 * 1000;
36/// Clocks may run this far ahead.
37pub const CLOCK_SKEW_MS: i64 = 5 * 60 * 1000;
38/// At most this many addresses in a record, and this many bytes in an encoded entry.
39pub const MAX_ADDRS: usize = 32;
40pub const MAX_ENTRY_BYTES: usize = 16 * 1024;
41const VERSION: u8 = 1;
42
43/// Where a user's node is, signed by the node.
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45pub struct PeerRecord {
46    pub v: u8,
47    pub user_id: String,
48    /// The user's public key (protobuf).
49    pub user_key: Vec<u8>,
50    /// The user's certificate for the node.
51    pub cert: NodeCert,
52    /// The node's public key (protobuf); its peer id is `cert.peer_id`.
53    pub node_key: Vec<u8>,
54    /// Direct addresses and relay circuits, each ending in `/p2p/<node>`.
55    pub addrs: Vec<String>,
56    /// The relay the node keeps a reservation on (`…/p2p/<relay>`), if any.
57    pub home_relay: Option<String>,
58    pub seq: u64,
59    pub issued_at: i64,
60    pub expires: i64,
61    pub sig: Vec<u8>,
62}
63
64/// The removal of a user's record, signed by one of the user's nodes.
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66pub struct Withdrawal {
67    pub v: u8,
68    pub user_id: String,
69    pub user_key: Vec<u8>,
70    pub cert: NodeCert,
71    pub node_key: Vec<u8>,
72    pub seq: u64,
73    pub issued_at: i64,
74    pub expires: i64,
75    pub sig: Vec<u8>,
76}
77
78/// What is stored under a user's key: a record or its withdrawal.
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80#[serde(tag = "kind", rename_all = "lowercase")]
81pub enum Entry {
82    Record(PeerRecord),
83    Withdrawn(Withdrawal),
84}
85
86/// What a lookup found.
87#[derive(Debug, Clone, PartialEq)]
88pub enum Lookup {
89    Found(PeerRecord),
90    Withdrawn(Withdrawal),
91    NotFound,
92}
93
94impl Entry {
95    pub fn seq(&self) -> u64 {
96        match self {
97            Entry::Record(r) => r.seq,
98            Entry::Withdrawn(w) => w.seq,
99        }
100    }
101    pub fn user_id(&self) -> &str {
102        match self {
103            Entry::Record(r) => &r.user_id,
104            Entry::Withdrawn(w) => &w.user_id,
105        }
106    }
107    pub fn expires(&self) -> i64 {
108        match self {
109            Entry::Record(r) => r.expires,
110            Entry::Withdrawn(w) => w.expires,
111        }
112    }
113    /// The node that signed it.
114    pub fn signer(&self) -> &str {
115        match self {
116            Entry::Record(r) => &r.cert.peer_id,
117            Entry::Withdrawn(w) => &w.cert.peer_id,
118        }
119    }
120    pub fn encode(&self) -> Vec<u8> {
121        serde_json::to_vec(self).unwrap_or_default()
122    }
123    pub fn decode(bytes: &[u8]) -> Result<Entry> {
124        if bytes.len() > MAX_ENTRY_BYTES {
125            return Err(NetError::invalid("peer record", "too large"));
126        }
127        Ok(serde_json::from_slice(bytes)?)
128    }
129    pub fn lookup(self) -> Lookup {
130        match self {
131            Entry::Record(r) => Lookup::Found(r),
132            Entry::Withdrawn(w) => Lookup::Withdrawn(w),
133        }
134    }
135}
136
137fn sign(node: &Keypair, bytes: &[u8]) -> Result<Vec<u8>> {
138    node.sign(bytes).map_err(|e| NetError::Crypto(format!("sign: {e}")))
139}
140
141fn record_body(domain: &str, r: &PeerRecord) -> Vec<u8> {
142    let mut r = r.clone();
143    r.sig.clear();
144    let mut b = format!("{domain}\n").into_bytes();
145    b.extend(serde_json::to_vec(&r).unwrap_or_default());
146    b
147}
148
149fn withdrawal_body(domain: &str, w: &Withdrawal) -> Vec<u8> {
150    let mut w = w.clone();
151    w.sig.clear();
152    let mut b = format!("{domain}\n").into_bytes();
153    b.extend(serde_json::to_vec(&w).unwrap_or_default());
154    b
155}
156
157fn bad(msg: impl Into<String>) -> NetError {
158    NetError::Crypto(format!("peer record: {}", msg.into()))
159}
160
161impl Profile {
162    /// The Kademlia key of a user's record: `SHA-256(peer_key + user id)`.
163    pub fn record_key(&self, user: &str) -> Vec<u8> {
164        sha2::Sha256::digest(format!("{}{user}", self.peer_key).as_bytes()).to_vec()
165    }
166
167    /// Sign a record for `node`, certified by `cert` under `user_key`, valid `ttl_ms` from
168    /// `now`. `seq` must grow with every record and withdrawal of this user (the time in
169    /// milliseconds works across the user's devices).
170    #[allow(clippy::too_many_arguments)]
171    pub fn peer_record(
172        &self,
173        node: &Keypair,
174        user_key: &PublicKey,
175        cert: &NodeCert,
176        addrs: &[Multiaddr],
177        home_relay: Option<&Multiaddr>,
178        seq: u64,
179        now: i64,
180        ttl_ms: i64,
181    ) -> Result<PeerRecord> {
182        let peer = node.public().to_peer_id();
183        if cert.peer_id != peer.to_string() {
184            return Err(NetError::invalid("peer record", "the certificate is for another node"));
185        }
186        if ttl_ms <= 0 || ttl_ms > MAX_RECORD_TTL_MS {
187            return Err(NetError::invalid("peer record", "a record lives up to 24 hours"));
188        }
189        let addrs: Vec<String> = addrs
190            .iter()
191            .take(MAX_ADDRS)
192            .map(|a| if addr_peer(a) == Some(peer) { a.to_string() } else { a.clone().with(Protocol::P2p(peer)).to_string() })
193            .collect();
194        let mut r = PeerRecord {
195            v: VERSION,
196            user_id: user_id(user_key),
197            user_key: user_key.encode_protobuf(),
198            cert: cert.clone(),
199            node_key: node.public().encode_protobuf(),
200            addrs,
201            home_relay: home_relay.map(|a| a.to_string()),
202            seq,
203            issued_at: now,
204            expires: now + ttl_ms,
205            sig: vec![],
206        };
207        r.sig = sign(node, &record_body(self.peer_record, &r))?;
208        self.verify_record(&r, now)?;
209        Ok(r)
210    }
211
212    /// Sign the withdrawal of a user's record by one of the user's nodes; `seq` must be
213    /// higher than the record's, and it lives `ttl_ms` (one day to a week).
214    pub fn withdrawal(&self, node: &Keypair, user_key: &PublicKey, cert: &NodeCert, seq: u64, now: i64, ttl_ms: i64) -> Result<Withdrawal> {
215        if cert.peer_id != node.public().to_peer_id().to_string() {
216            return Err(NetError::invalid("withdrawal", "the certificate is for another node"));
217        }
218        if !(MIN_WITHDRAWAL_TTL_MS..=MAX_WITHDRAWAL_TTL_MS).contains(&ttl_ms) {
219            return Err(NetError::invalid("withdrawal", "a withdrawal lives one day to a week"));
220        }
221        let mut w = Withdrawal {
222            v: VERSION,
223            user_id: user_id(user_key),
224            user_key: user_key.encode_protobuf(),
225            cert: cert.clone(),
226            node_key: node.public().encode_protobuf(),
227            seq,
228            issued_at: now,
229            expires: now + ttl_ms,
230            sig: vec![],
231        };
232        w.sig = sign(node, &withdrawal_body(self.withdrawal, &w))?;
233        self.verify_withdrawal(&w, now)?;
234        Ok(w)
235    }
236
237    /// The user and node behind a record or withdrawal: the keys match the ids, and the
238    /// user certified the node and has not revoked it.
239    fn check_signer(&self, user: &str, user_key: &[u8], cert: &NodeCert, node_key: &[u8]) -> Result<(PublicKey, PeerId)> {
240        let ukey = decode_public(user_key)?;
241        if user_id(&ukey) != user || cert.user_id != user {
242            return Err(bad("the user id does not match the key"));
243        }
244        let nkey = decode_public(node_key)?;
245        let peer = nkey.to_peer_id();
246        if cert.peer_id != peer.to_string() {
247            return Err(bad("the certificate is for another node"));
248        }
249        if !cert.active() || !self.verify_cert(&ukey, cert) {
250            return Err(bad("the node certificate does not verify or is revoked"));
251        }
252        Ok((nkey, peer))
253    }
254
255    /// Check a record: version, signer, signature, lifetime and addresses.
256    pub fn verify_record(&self, r: &PeerRecord, now: i64) -> Result<PeerId> {
257        if r.v != VERSION {
258            return Err(bad(format!("version {} is not {VERSION}", r.v)));
259        }
260        let (nkey, peer) = self.check_signer(&r.user_id, &r.user_key, &r.cert, &r.node_key)?;
261        if !nkey.verify(&record_body(self.peer_record, r), &r.sig) {
262            return Err(bad("bad signature"));
263        }
264        if r.issued_at > now + CLOCK_SKEW_MS || r.expires <= now || r.expires - r.issued_at > MAX_RECORD_TTL_MS {
265            return Err(bad("expired, from the future, or living too long"));
266        }
267        if r.addrs.len() > MAX_ADDRS {
268            return Err(bad("too many addresses"));
269        }
270        for a in &r.addrs {
271            let m: Multiaddr = a.parse().map_err(|_| bad(format!("`{a}` is not an address")))?;
272            if addr_peer(&m) != Some(peer) {
273                return Err(bad(format!("`{a}` is not the node's")));
274            }
275        }
276        if let Some(h) = &r.home_relay {
277            let m: Multiaddr = h.parse().map_err(|_| bad("bad home relay"))?;
278            if addr_peer(&m).is_none() {
279                return Err(bad("the home relay has no /p2p/"));
280            }
281        }
282        Ok(peer)
283    }
284
285    /// Check a withdrawal: version, signer, signature and lifetime.
286    pub fn verify_withdrawal(&self, w: &Withdrawal, now: i64) -> Result<PeerId> {
287        if w.v != VERSION {
288            return Err(bad(format!("version {} is not {VERSION}", w.v)));
289        }
290        let (nkey, peer) = self.check_signer(&w.user_id, &w.user_key, &w.cert, &w.node_key)?;
291        if !nkey.verify(&withdrawal_body(self.withdrawal, w), &w.sig) {
292            return Err(bad("bad signature"));
293        }
294        if w.issued_at > now + CLOCK_SKEW_MS || w.expires <= now || w.expires - w.issued_at > MAX_WITHDRAWAL_TTL_MS {
295            return Err(bad("expired, from the future, or living too long"));
296        }
297        Ok(peer)
298    }
299
300    pub fn verify_entry(&self, e: &Entry, now: i64) -> Result<PeerId> {
301        match e {
302            Entry::Record(r) => self.verify_record(r, now),
303            Entry::Withdrawn(w) => self.verify_withdrawal(w, now),
304        }
305    }
306
307    /// The rule every storing node runs: keep `incoming` instead of `existing`? It must
308    /// verify, and its `seq` must be higher than an unexpired existing entry's (so a
309    /// withdrawal holds until it expires). Errors say why it was refused.
310    pub fn accept(&self, existing: Option<&Entry>, incoming: &Entry, now: i64) -> Result<()> {
311        self.verify_entry(incoming, now)?;
312        if let Some(old) = existing.filter(|o| o.expires() > now) {
313            if old.user_id() != incoming.user_id() {
314                return Err(bad("another user's key"));
315            }
316            if incoming.seq() <= old.seq() {
317                return Err(bad(format!("seq {} is not above {}", incoming.seq(), old.seq())));
318            }
319        }
320        Ok(())
321    }
322
323    /// The freshest valid entry among `entries` for `user`, as a lookup result.
324    pub fn newest<'a>(&self, user: &str, entries: impl IntoIterator<Item = &'a Entry>, now: i64) -> Lookup {
325        entries
326            .into_iter()
327            .filter(|e| e.user_id() == user && self.verify_entry(e, now).is_ok())
328            .max_by_key(|e| e.seq())
329            .cloned()
330            .map(Entry::lookup)
331            .unwrap_or(Lookup::NotFound)
332    }
333}
334
335/// The DNS name of a domain's binding: `_weirdnet.<name>`.
336pub fn binding_name(name: &str) -> String {
337    format!("_weirdnet.{}", name.trim().trim_end_matches('.'))
338}
339
340/// The TXT value binding a domain to a user: `v=1 user=<user id>`.
341pub fn binding_txt(user: &str) -> String {
342    format!("v=1 user={user}")
343}
344
345/// The user id in a binding TXT value.
346pub fn parse_binding(txt: &str) -> Result<String> {
347    let txt = txt.trim().trim_matches('"');
348    let mut v = None;
349    let mut user = None;
350    for part in txt.split_whitespace() {
351        match part.split_once('=') {
352            Some(("v", x)) => v = Some(x),
353            Some(("user", x)) => user = Some(x),
354            _ => {}
355        }
356    }
357    if v != Some("1") {
358        return Err(NetError::invalid("name binding", "not `v=1`"));
359    }
360    match user {
361        Some(u) if u.len() == 32 && u.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()) => Ok(u.to_string()),
362        _ => Err(NetError::invalid("name binding", "no user id")),
363    }
364}
365
366/// The names protocol: register an entry on a names server, or look a user up there.
367#[derive(Debug, Clone, Serialize, Deserialize)]
368pub enum NamesRequest {
369    /// Store a record (sent by the node it is about) or a withdrawal (by any of the user's nodes).
370    Register(Box<Entry>),
371    Discover {
372        user_id: String,
373    },
374}
375
376#[derive(Debug, Clone, Serialize, Deserialize)]
377pub enum NamesResponse {
378    Registered,
379    Found(Option<Box<Entry>>),
380    Refused(String),
381}
382
383/// Where a names server keeps entries. Entries arrive checked; the store only keeps them.
384pub trait NameStore: Send + Sync + 'static {
385    fn get(&self, user: &str) -> Option<Entry>;
386    fn put(&self, entry: &Entry);
387    /// Drop entries that expired before `now`.
388    fn prune(&self, now: i64);
389}
390
391/// Entries in memory.
392#[derive(Default)]
393pub struct MemoryNames(Mutex<HashMap<String, Entry>>);
394
395impl NameStore for MemoryNames {
396    fn get(&self, user: &str) -> Option<Entry> {
397        self.0.lock().ok()?.get(user).cloned()
398    }
399    fn put(&self, entry: &Entry) {
400        if let Ok(mut m) = self.0.lock() {
401            m.insert(entry.user_id().to_string(), entry.clone());
402        }
403    }
404    fn prune(&self, now: i64) {
405        if let Ok(mut m) = self.0.lock() {
406            m.retain(|_, e| e.expires() > now);
407        }
408    }
409}
410
411/// A names store handed to a node through [`crate::NodeConfig::names_server`].
412#[derive(Clone)]
413pub struct Names(pub Arc<dyn NameStore>);
414
415impl Names {
416    pub fn memory() -> Self {
417        Names(Arc::new(MemoryNames::default()))
418    }
419}
420
421impl std::fmt::Debug for Names {
422    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
423        f.write_str("Names(..)")
424    }
425}
426
427/// How a names server answers: `from` is the Noise-authenticated sender.
428pub fn serve(p: &Profile, store: &dyn NameStore, from: &PeerId, req: NamesRequest, now: i64) -> NamesResponse {
429    match req {
430        NamesRequest::Discover { user_id } => NamesResponse::Found(store.get(&user_id).filter(|e| e.expires() > now).map(Box::new)),
431        NamesRequest::Register(e) => {
432            let e = *e;
433            if let Entry::Record(r) = &e
434                && r.cert.peer_id != from.to_string()
435            {
436                return NamesResponse::Refused("a node registers only its own record".into());
437            }
438            if let Entry::Withdrawn(w) = &e
439                && w.cert.peer_id != from.to_string()
440            {
441                return NamesResponse::Refused("a withdrawal comes from the node that signed it".into());
442            }
443            match p.accept(store.get(e.user_id()).as_ref(), &e, now) {
444                Ok(()) => {
445                    store.put(&e);
446                    NamesResponse::Registered
447                }
448                Err(err) => NamesResponse::Refused(err.to_string()),
449            }
450        }
451    }
452}