Skip to main content

weirdnet_sync/
rotation.rs

1//! Real key rotation: random epoch keys sealed to each remaining device.
2//!
3//! Every device holds the identity seed, so a seed-derived key can never shut a revoked
4//! device out. A rotation therefore makes a fresh random epoch key and seals one copy to
5//! each remaining device's exchange key (X25519, derived from its node key). The sealed
6//! copies travel in the roster ([`Roster::chain`]). A device that is not a recipient,
7//! revoked or restored from the seed alone, cannot open the new key; a restored device
8//! is let back in by an [`Admission`] from a device that holds the key.
9//!
10//! Rules (all checked on every device, so they converge):
11//!
12//! - A [`DeviceKey`] is signed by the device's own node key, so no other device (even
13//!   one holding the user key) can swap in its own exchange key.
14//! - A [`Rotation`] is signed by its creator's node key. It is valid when the creator has
15//!   an active cert and is a member of the parent rotation, and its epoch is the parent's
16//!   plus one. A root (no parent) is valid when its creator is a member of it. A
17//!   revoked creator's rotations count only when an active device built on them, so a
18//!   chain started by a device revoked later lives on, and whatever a revoked device
19//!   makes on its own drops out.
20//! - Once a device holds a key from a root it keeps that root ([`KeyChain::root`]); a
21//!   later root from someone holding only the seed is ignored. Two devices can each
22//!   start a root before they know of each other; a root whose creator is a member of
23//!   the chain a device follows is trusted, and the earliest trusted root wins. A
24//!   device in both chains admits the devices it approved into both, so they merge.
25//! - The members of a rotation are its recipients plus devices admitted to it by a
26//!   member. The head is the valid rotation with the highest epoch, then one with no
27//!   revoked member, then the lowest id. A head with a revoked member needs another
28//!   rotation; [`crate::pull_from`] makes it.
29//! - A service device with sync types is never sealed the epoch key (since 0.8.3): the
30//!   rotation's creator admits it with the new rotation's type-scoped keys for its grant
31//!   ([`Roster::scoped_types`], [`EpochKeys::get_scoped`]), so it can open only those types.
32use crate::error::{Result, SyncError};
33use crate::net::SyncState;
34use crate::protocol::{decode, encode};
35use crate::roster::Roster;
36use crate::seal::{SyncKey, rotated_sync_key};
37use serde::{Deserialize, Serialize};
38use std::collections::{BTreeMap, BTreeSet};
39use weirdnet_keys::exchange::{self, ExchangeSecret};
40use weirdnet_keys::mac::HmacSha256;
41use weirdnet_keys::{Key32, Sealed, kdf, open, seal};
42use weirdnet_net::profile::WEIRDNET;
43use weirdnet_net::user::NodeCert;
44use weirdnet_net::{Keypair, PeerId, PublicKey};
45use zeroize::{Zeroize, Zeroizing};
46
47const DEVICE_KEY: &str = "weirdnet-sync/v1/device-key";
48const ROTATION: &str = "weirdnet-sync/v1/rotation";
49const ADMISSION: &str = "weirdnet-sync/v1/admission";
50const SEAL_KEY: &[u8] = b"weirdnet-sync/v1/seal-key";
51const SEAL_SAS: &[u8] = b"weirdnet-sync/v1/seal-sas";
52
53/// The node public key inside an Ed25519 (identity-multihash) peer id.
54pub fn peer_public(peer: &str) -> Option<PublicKey> {
55    let pid: PeerId = peer.parse().ok()?;
56    let bytes = pid.to_bytes();
57    if bytes.len() < 2 || bytes[0] != 0 || bytes.len() != 2 + bytes[1] as usize {
58        return None;
59    }
60    let key = PublicKey::try_decode_protobuf(&bytes[2..]).ok()?;
61    (key.to_peer_id() == pid).then_some(key)
62}
63
64fn hash_hex(domain: &[u8], data: &[u8], n: usize) -> String {
65    let mut h = HmacSha256::new(domain);
66    h.update(data);
67    hex::encode(&h.finalize()[..n])
68}
69
70fn key_check(key: &Key32) -> String {
71    let mut h = HmacSha256::new(&key.0);
72    h.update(b"weirdnet-sync/v1/key-check");
73    hex::encode(&h.finalize()[..16])
74}
75
76fn crypto(msg: impl Into<String>) -> SyncError {
77    SyncError::Crypto(msg.into())
78}
79
80/// A device's public exchange key, signed by the device's node key.
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub struct DeviceKey {
83    pub peer_id: String,
84    /// X25519 public key, hex.
85    pub exchange: String,
86    pub at_ms: i64,
87    pub sig: Vec<u8>,
88}
89
90impl DeviceKey {
91    fn signing_bytes(peer: &str, exchange: &str, at: i64) -> Vec<u8> {
92        format!("{DEVICE_KEY}\n{peer}\n{exchange}\n{at}").into_bytes()
93    }
94
95    /// The signature is the device's own and the key is well formed.
96    pub fn verify(&self) -> bool {
97        self.public().is_some()
98            && peer_public(&self.peer_id).is_some_and(|k| k.verify(&Self::signing_bytes(&self.peer_id, &self.exchange, self.at_ms), &self.sig))
99    }
100
101    pub fn public(&self) -> Option<[u8; 32]> {
102        hex::decode(&self.exchange).ok()?.try_into().ok()
103    }
104
105    /// A short code to compare on both screens before re-admitting a device.
106    pub fn fingerprint(&self) -> String {
107        let h = hash_hex(b"weirdnet-sync/v1/fingerprint", format!("{}|{}", self.peer_id, self.exchange).as_bytes(), 6);
108        format!("{}-{}-{}", &h[..4], &h[4..8], &h[8..])
109    }
110}
111
112/// This device's signing and exchange secrets. The exchange secret is derived from the
113/// node key, so nothing new has to be stored.
114pub struct Device {
115    node: Keypair,
116    exchange: ExchangeSecret,
117}
118
119impl Clone for Device {
120    fn clone(&self) -> Self {
121        Self { node: self.node.clone(), exchange: ExchangeSecret::from_bytes(*self.exchange.to_bytes()) }
122    }
123}
124
125impl std::fmt::Debug for Device {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        write!(f, "Device({})", self.peer_id())
128    }
129}
130
131impl Device {
132    pub fn from_node_key(node: &Keypair) -> Result<Self> {
133        let bytes = Zeroizing::new(node.to_protobuf_encoding().map_err(|e| crypto(format!("node key: {e}")))?);
134        let k = kdf::hkdf(&bytes, Some(b"weirdnet-sync/v1"), b"weirdnet-sync/v1/exchange")?;
135        Ok(Self { node: node.clone(), exchange: ExchangeSecret::from_bytes(k.0) })
136    }
137
138    pub fn peer_id(&self) -> String {
139        self.node.public().to_peer_id().to_string()
140    }
141
142    pub fn device_key(&self, at_ms: i64) -> Result<DeviceKey> {
143        let peer = self.peer_id();
144        let exchange = hex::encode(self.exchange.public());
145        let sig = self.sign(&DeviceKey::signing_bytes(&peer, &exchange, at_ms))?;
146        Ok(DeviceKey { peer_id: peer, exchange, at_ms, sig })
147    }
148
149    pub(crate) fn sign(&self, bytes: &[u8]) -> Result<Vec<u8>> {
150        self.node.sign(bytes).map_err(|e| crypto(format!("sign: {e}")))
151    }
152}
153
154/// One recipient's copy of an epoch key.
155#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub struct SealedKey {
157    pub peer_id: String,
158    pub sealed: Sealed,
159}
160
161/// A new random epoch key, sealed to each remaining device.
162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
163pub struct Rotation {
164    pub epoch: u32,
165    /// The rotation this one replaces; `None` for the first one (out of seed-derived keys).
166    pub parent: Option<String>,
167    pub by: String,
168    pub at_ms: i64,
169    /// Ephemeral X25519 public key, hex.
170    pub eph: String,
171    /// Commitment to the key, so every holder can tell it got the same one.
172    pub check: String,
173    pub keys: Vec<SealedKey>,
174    pub sig: Vec<u8>,
175}
176
177impl Rotation {
178    fn body(&self) -> Vec<u8> {
179        encode(&(ROTATION, self.epoch, &self.parent, &self.by, self.at_ms, &self.eph, &self.check, &self.keys)).unwrap_or_default()
180    }
181
182    pub fn id(&self) -> String {
183        hash_hex(ROTATION.as_bytes(), &self.body(), 16)
184    }
185
186    fn signed(&self) -> bool {
187        peer_public(&self.by).is_some_and(|k| k.verify(&self.body(), &self.sig))
188    }
189
190    pub fn recipients(&self) -> impl Iterator<Item = &str> {
191        self.keys.iter().map(|k| k.peer_id.as_str())
192    }
193
194    fn transcript(&self, recipient: &str, recipient_pub: &[u8; 32]) -> Vec<u8> {
195        let parent = self.parent.as_deref().unwrap_or("-");
196        format!("{ROTATION}|e{}|{parent}|{}|{recipient}|{}|{}", self.epoch, self.by, self.eph, hex::encode(recipient_pub)).into_bytes()
197    }
198}
199
200/// A member's grant of the current key (and the older ones it holds) to a device,
201/// such as one restored from the seed.
202#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
203pub struct Admission {
204    pub rotation: String,
205    pub peer_id: String,
206    pub by: String,
207    pub at_ms: i64,
208    pub eph: String,
209    pub sealed: Sealed,
210    pub sig: Vec<u8>,
211}
212
213impl Admission {
214    fn body(&self) -> Vec<u8> {
215        encode(&(ADMISSION, &self.rotation, &self.peer_id, &self.by, self.at_ms, &self.eph, &self.sealed)).unwrap_or_default()
216    }
217
218    pub fn id(&self) -> String {
219        hash_hex(ADMISSION.as_bytes(), &self.body(), 16)
220    }
221
222    fn signed(&self) -> bool {
223        peer_public(&self.by).is_some_and(|k| k.verify(&self.body(), &self.sig))
224    }
225
226    fn transcript(&self, recipient_pub: &[u8; 32]) -> Vec<u8> {
227        format!("{ADMISSION}|{}|{}|{}|{}|{}", self.rotation, self.peer_id, self.by, self.eph, hex::encode(recipient_pub)).into_bytes()
228    }
229}
230
231/// The public part of rotation: device keys, rotations and admissions. Gossiped with the
232/// roster; holds no secret.
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
234pub struct KeyChain {
235    #[serde(default)]
236    pub devices: Vec<DeviceKey>,
237    #[serde(default)]
238    pub rotations: Vec<Rotation>,
239    #[serde(default)]
240    pub admissions: Vec<Admission>,
241    /// The root this device follows, once it holds a key from it. Local; never merged.
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub root: Option<String>,
244    /// Devices the user approved on this device (by linking) that wait for an
245    /// admission. Local; never merged.
246    #[serde(default, skip_serializing_if = "Vec::is_empty")]
247    pub approved: Vec<String>,
248}
249
250impl KeyChain {
251    pub fn is_empty(&self) -> bool {
252        self.devices.is_empty() && self.rotations.is_empty() && self.admissions.is_empty()
253    }
254
255    pub fn is_empty_and_rootless(&self) -> bool {
256        self.is_empty() && self.root.is_none() && self.approved.is_empty()
257    }
258
259    pub fn device(&self, peer_id: &str) -> Option<&DeviceKey> {
260        self.devices.iter().find(|d| d.peer_id == peer_id)
261    }
262
263    /// Add or replace (newer `at_ms`) a device key. Returns false if it does not verify.
264    pub fn add_device(&mut self, dk: DeviceKey) -> bool {
265        if !dk.verify() {
266            return false;
267        }
268        match self.devices.iter_mut().find(|d| d.peer_id == dk.peer_id) {
269            Some(d) if d.at_ms < dk.at_ms => *d = dk,
270            Some(_) => {}
271            None => self.devices.push(dk),
272        }
273        true
274    }
275
276    /// Take another replica's device keys, rotations and admissions (signed ones only).
277    /// `root` stays ours.
278    pub fn merge(&mut self, other: &KeyChain) {
279        for d in &other.devices {
280            self.add_device(d.clone());
281        }
282        let have: BTreeSet<String> = self.rotations.iter().map(Rotation::id).collect();
283        for r in &other.rotations {
284            if !have.contains(&r.id()) && r.signed() {
285                self.rotations.push(r.clone());
286            }
287        }
288        let have: BTreeSet<String> = self.admissions.iter().map(Admission::id).collect();
289        for a in &other.admissions {
290            if !have.contains(&a.id()) && a.signed() {
291                self.admissions.push(a.clone());
292            }
293        }
294    }
295
296    /// This chain without the local `root` and `approved`, for the wire.
297    pub fn shared(&self) -> KeyChain {
298        KeyChain { root: None, approved: Vec::new(), ..self.clone() }
299    }
300}
301
302/// A rotation that counts, with its members.
303#[derive(Debug, Clone)]
304pub struct ValidRotation {
305    pub id: String,
306    pub epoch: u32,
307    pub members: BTreeSet<String>,
308    pub clean: bool,
309}
310
311/// A chain entry with its id.
312type Ided<'a, T> = (String, &'a T);
313
314/// The chain as this roster sees it: valid rotations from the root, and the head.
315#[derive(Debug, Clone, Default)]
316pub struct ChainView {
317    pub root: Option<String>,
318    pub valid: BTreeMap<String, ValidRotation>,
319    pub admissions: Vec<String>,
320    pub head: Option<String>,
321}
322
323impl ChainView {
324    pub fn head(&self) -> Option<&ValidRotation> {
325        self.head.as_ref().and_then(|h| self.valid.get(h))
326    }
327
328    /// The head has a member that has since been revoked.
329    pub fn dirty(&self) -> bool {
330        self.head().is_some_and(|h| !h.clean)
331    }
332}
333
334impl Roster {
335    fn revoked_set(&self) -> BTreeSet<&str> {
336        self.certs.iter().filter(|c| !c.active()).map(|c| c.peer_id.as_str()).collect()
337    }
338
339    fn active_set(&self) -> BTreeSet<&str> {
340        self.active().map(|c| c.peer_id.as_str()).collect()
341    }
342
343    fn signed_parts(&self) -> (Vec<Ided<'_, Rotation>>, Vec<Ided<'_, Admission>>) {
344        let active = self.active_set();
345        let known: BTreeSet<&str> = self.certs.iter().map(|c| c.peer_id.as_str()).collect();
346        // What a service device signs once it is one does not count: it may not rotate or admit.
347        let by_service = |by: &str, at: i64| self.service_since(by).is_some_and(|t| at >= t);
348        let rots = self
349            .chain
350            .rotations
351            .iter()
352            .filter(|r| known.contains(r.by.as_str()) && !by_service(&r.by, r.at_ms) && r.signed())
353            .map(|r| (r.id(), r))
354            .collect();
355        let adms = self
356            .chain
357            .admissions
358            .iter()
359            .filter(|a| active.contains(a.by.as_str()) && !by_service(&a.by, a.at_ms) && a.signed())
360            .map(|a| (a.id(), a))
361            .collect();
362        (rots, adms)
363    }
364
365    /// The view from every root, the followed one or not. A device that is in two
366    /// chains (two first roots made at once) uses these to bring the devices it
367    /// approved into both, so the chains can merge.
368    pub fn all_views(&self) -> Vec<ChainView> {
369        let revoked = self.revoked_set();
370        let (rots, adms) = self.signed_parts();
371        rots.iter()
372            .filter(|(_, r)| r.parent.is_none() && r.recipients().any(|p| p == r.by))
373            .map(|root| self.view_from(root, &rots, &adms, &revoked))
374            .collect()
375    }
376
377    /// Work out which rotations count, their members, and the head.
378    pub fn chain_view(&self) -> ChainView {
379        let revoked = self.revoked_set();
380        let (rots, adms) = self.signed_parts();
381
382        let roots: Vec<&(String, &Rotation)> = rots.iter().filter(|(_, r)| r.parent.is_none() && r.recipients().any(|p| p == r.by)).collect();
383        fn order(r: &(String, &Rotation)) -> (u32, String) {
384            (r.1.epoch, r.0.clone())
385        }
386        let mut root = match &self.chain.root {
387            Some(id) => roots.iter().find(|(rid, _)| rid == id).copied(),
388            None => roots.iter().copied().min_by_key(|r| order(r)),
389        };
390        // Two devices can start a root at once (both saw themselves as the first). A
391        // root whose creator is a member of the chain we follow is trusted; the earliest
392        // trusted root wins, so every device ends up on the same one. A root from a
393        // device nobody in our chain admitted stays ignored.
394        let mut seen = BTreeSet::new();
395        while let Some(cur) = root {
396            if !seen.insert(cur.0.clone()) {
397                break;
398            }
399            let view = self.view_from(cur, &rots, &adms, &revoked);
400            let trusted = |r: &&&(String, &Rotation)| view.valid.values().any(|v| v.members.contains(&r.1.by));
401            match roots.iter().filter(trusted).min_by_key(|r| order(r)) {
402                Some(best) if order(best) < order(cur) => root = Some(best),
403                _ => return view,
404            }
405        }
406        root.map(|r| self.view_from(r, &rots, &adms, &revoked)).unwrap_or_default()
407    }
408
409    fn view_from(
410        &self,
411        (root_id, root_rot): &(String, &Rotation),
412        rots: &[(String, &Rotation)],
413        adms: &[(String, &Admission)],
414        revoked: &BTreeSet<&str>,
415    ) -> ChainView {
416        let mut view = ChainView { root: Some(root_id.clone()), ..ChainView::default() };
417
418        let members_of = |id: &str, r: &Rotation, admitted: &mut Vec<String>| -> BTreeSet<String> {
419            let mut m: BTreeSet<String> = r.recipients().map(str::to_string).collect();
420            loop {
421                let mut grew = false;
422                for (aid, a) in adms.iter().filter(|(_, a)| a.rotation == id) {
423                    if m.contains(&a.by) && !revoked.contains(a.by.as_str()) && !m.contains(&a.peer_id) {
424                        m.insert(a.peer_id.clone());
425                        admitted.push(aid.clone());
426                        grew = true;
427                    }
428                }
429                if !grew {
430                    return m;
431                }
432            }
433        };
434        let mut admitted = Vec::new();
435        let add = |view: &mut ChainView, id: &str, r: &Rotation, admitted: &mut Vec<String>| {
436            let members = members_of(id, r, admitted);
437            let clean = !members.iter().any(|m| revoked.contains(m.as_str()));
438            view.valid.insert(id.to_string(), ValidRotation { id: id.to_string(), epoch: r.epoch, members, clean });
439        };
440        add(&mut view, root_id, root_rot, &mut admitted);
441        loop {
442            let mut grew = false;
443            for (id, r) in rots {
444                if view.valid.contains_key(id) {
445                    continue;
446                }
447                let Some(p) = r.parent.as_ref().and_then(|p| view.valid.get(p)) else { continue };
448                if r.epoch == p.epoch.saturating_add(1) && p.members.contains(&r.by) && r.recipients().any(|x| x == r.by) {
449                    add(&mut view, id, r, &mut admitted);
450                    grew = true;
451                }
452            }
453            if !grew {
454                break;
455            }
456        }
457        // A revoked device's rotations count only when a device still active built on
458        // them (so the chain it started before its revocation lives on); whatever it
459        // made on its own, unaware or not, drops out with it.
460        let parent: BTreeMap<&str, Option<&str>> = rots.iter().map(|(id, r)| (id.as_str(), r.parent.as_deref())).collect();
461        let mut keep: BTreeSet<String> = BTreeSet::new();
462        for (id, r) in rots {
463            if !view.valid.contains_key(id) || revoked.contains(r.by.as_str()) {
464                continue;
465            }
466            let mut cur = Some(id.as_str());
467            while let Some(c) = cur {
468                if !keep.insert(c.to_string()) {
469                    break;
470                }
471                cur = parent.get(c).copied().flatten();
472            }
473        }
474        view.valid.retain(|id, _| keep.contains(id));
475        if view.valid.is_empty() {
476            return ChainView::default();
477        }
478        let kept_adm: BTreeSet<String> = adms.iter().filter(|(_, a)| view.valid.contains_key(&a.rotation)).map(|(id, _)| id.clone()).collect();
479        admitted.retain(|id| kept_adm.contains(id));
480        view.admissions = admitted;
481        view.head = view
482            .valid
483            .values()
484            .max_by(|a, b| (a.epoch, a.clean, std::cmp::Reverse(&a.id)).cmp(&(b.epoch, b.clean, std::cmp::Reverse(&b.id))))
485            .map(|v| v.id.clone());
486        view
487    }
488
489    /// The head rotation id, if the chain has started.
490    pub fn head_id(&self) -> Option<String> {
491        self.chain_view().head
492    }
493}
494
495/// The epoch keys this device holds, by rotation id. Secret: the application stores it
496/// encrypted ([`EpochKeys::export`]) and never logs it.
497///
498/// Since 0.8.3 it may also hold type-scoped keys: one type's [`SyncKey`] under one rotation,
499/// by (rotation id, type). A service device holds only those, for the types in its grant
500/// ([`Roster::scoped_types`]), never an epoch key, so it can open no other type's pages and
501/// no sealed record. Every key is zeroized on drop.
502#[derive(Clone, Default, PartialEq)]
503pub struct EpochKeys {
504    keys: BTreeMap<String, (u32, Key32)>,
505    scoped: BTreeMap<(String, String), (u32, SyncKey)>,
506}
507
508impl std::fmt::Debug for EpochKeys {
509    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
510        if self.scoped.is_empty() {
511            write!(f, "EpochKeys({} keys)", self.keys.len())
512        } else {
513            write!(f, "EpochKeys({} keys, {} scoped)", self.keys.len(), self.scoped.len())
514        }
515    }
516}
517
518/// One stored key. `typ` (since 0.8.3) marks a type-scoped key; left off the wire for an
519/// epoch key, so 0.8.0 to 0.8.2 read exports and admissions of epoch keys unchanged.
520#[derive(Serialize, Deserialize)]
521struct KeyEntry {
522    id: String,
523    epoch: u32,
524    key: [u8; 32],
525    #[serde(default, skip_serializing_if = "Option::is_none")]
526    typ: Option<String>,
527}
528
529impl EpochKeys {
530    pub fn new() -> Self {
531        Self::default()
532    }
533    /// The epoch key of rotation `id`. `None` for a rotation held only as type-scoped keys.
534    pub fn get(&self, id: &str) -> Option<&Key32> {
535        self.keys.get(id).map(|(_, k)| k)
536    }
537    /// Whether any key of rotation `id` is held: its epoch key or a type-scoped key.
538    pub fn has(&self, id: &str) -> bool {
539        self.keys.contains_key(id) || self.scoped_types(id).next().is_some()
540    }
541    /// Whether the epoch key of rotation `id` is held (since 0.8.3).
542    pub fn has_epoch_key(&self, id: &str) -> bool {
543        self.keys.contains_key(id)
544    }
545    pub fn insert(&mut self, id: String, epoch: u32, key: Key32) {
546        self.keys.insert(id, (epoch, key));
547    }
548    /// The type-scoped key of `typ` under rotation `id` (since 0.8.3).
549    pub fn get_scoped(&self, id: &str, typ: &str) -> Option<&SyncKey> {
550        self.scoped.get(&(id.to_string(), typ.to_string())).map(|(_, k)| k)
551    }
552    /// Hold `typ`'s key under rotation `id` (since 0.8.3).
553    pub fn insert_scoped(&mut self, id: String, typ: String, epoch: u32, key: SyncKey) {
554        self.scoped.insert((id, typ), (epoch, key));
555    }
556    /// The types held as scoped keys under rotation `id` (since 0.8.3).
557    pub fn scoped_types<'a>(&'a self, id: &'a str) -> impl Iterator<Item = &'a str> + 'a {
558        self.scoped.range((id.to_string(), String::new())..).take_while(move |((i, _), _)| i == id).map(|((_, t), _)| t.as_str())
559    }
560    /// Every key held: epoch keys and type-scoped keys.
561    pub fn len(&self) -> usize {
562        self.keys.len() + self.scoped.len()
563    }
564    /// Epoch keys held (since 0.8.3). Always 0 on a service device.
565    pub fn epoch_key_count(&self) -> usize {
566        self.keys.len()
567    }
568    /// Type-scoped keys held (since 0.8.3).
569    pub fn scoped_len(&self) -> usize {
570        self.scoped.len()
571    }
572    pub fn is_empty(&self) -> bool {
573        self.keys.is_empty() && self.scoped.is_empty()
574    }
575    /// The rotations held, with their epochs (an epoch key or any scoped key).
576    pub fn ids(&self) -> impl Iterator<Item = (&str, u32)> {
577        let mut all: BTreeMap<&str, u32> = self.keys.iter().map(|(id, (e, _))| (id.as_str(), *e)).collect();
578        for ((id, _), (e, _)) in &self.scoped {
579            all.entry(id.as_str()).or_insert(*e);
580        }
581        all.into_iter()
582    }
583    /// `typ`'s [`SyncKey`] under rotation `id` at `epoch` (since 0.8.3): derived from the
584    /// epoch key when held ([`rotated_sync_key`]), otherwise the scoped key.
585    pub fn sync_key(&self, user_id: &str, typ: &str, epoch: u32, id: &str) -> Result<SyncKey> {
586        if let Some((_, k)) = self.keys.get(id) {
587            return rotated_sync_key(k, user_id, typ, epoch, id);
588        }
589        match self.scoped.get(&(id.to_string(), typ.to_string())) {
590            Some((e, k)) if *e == epoch => Ok(k.clone()),
591            Some(_) => Err(crypto("the scoped key is for another epoch")),
592            None if self.has(id) => Err(crypto("no key for this type under this rotation")),
593            None => Err(crypto("unknown epoch key")),
594        }
595    }
596    /// Type-scoped keys for `types` under every rotation held (since 0.8.3): derived from the
597    /// epoch keys, plus scoped keys already held for those types. Holds no epoch key: what a
598    /// service device is given.
599    pub fn scope(&self, user_id: &str, types: &[String]) -> Result<EpochKeys> {
600        self.scope_where(user_id, types, |_| true)
601    }
602
603    fn scope_where(&self, user_id: &str, types: &[String], only: impl Fn(&str) -> bool) -> Result<EpochKeys> {
604        let mut out = EpochKeys::new();
605        for (id, (epoch, key)) in self.keys.iter().filter(|(id, _)| only(id)) {
606            for t in types {
607                out.scoped.insert((id.clone(), t.clone()), (*epoch, rotated_sync_key(key, user_id, t, *epoch, id)?));
608            }
609        }
610        for ((id, t), v) in &self.scoped {
611            if only(id) && types.contains(t) {
612                out.scoped.entry((id.clone(), t.clone())).or_insert_with(|| v.clone());
613            }
614        }
615        Ok(out)
616    }
617
618    /// Replace every epoch key with type-scoped keys for `types`, and drop scoped keys of
619    /// other types (since 0.8.3): what a service device keeps.
620    pub fn narrow_to(&mut self, user_id: &str, types: &[String]) -> Result<()> {
621        *self = self.scope(user_id, types)?;
622        Ok(())
623    }
624
625    /// Take keys held by another copy of this state (keys are never dropped).
626    pub fn merge(&mut self, other: &EpochKeys) {
627        for (id, v) in &other.keys {
628            self.keys.entry(id.clone()).or_insert_with(|| v.clone());
629        }
630        for (k, v) in &other.scoped {
631            self.scoped.entry(k.clone()).or_insert_with(|| v.clone());
632        }
633    }
634
635    fn entries(&self, only: impl Fn(&str) -> bool) -> Zeroizing<Vec<u8>> {
636        let mut list: Vec<KeyEntry> =
637            self.keys.iter().filter(|(id, _)| only(id)).map(|(id, (e, k))| KeyEntry { id: id.clone(), epoch: *e, key: k.0, typ: None }).collect();
638        list.extend(self.scoped.iter().filter(|((id, _), _)| only(id)).map(|((id, t), (e, k))| KeyEntry {
639            id: id.clone(),
640            epoch: *e,
641            key: k.0,
642            typ: Some(t.clone()),
643        }));
644        let out = Zeroizing::new(encode(&list).unwrap_or_default());
645        for e in &mut list {
646            e.key.zeroize();
647        }
648        out
649    }
650
651    /// Take the keys in `bytes` that `accept(id, epoch, typ, key)` allows (`typ` is `None`
652    /// for an epoch key) and that are not held yet.
653    fn absorb(&mut self, bytes: &[u8], accept: impl Fn(&str, u32, Option<&str>, &Key32) -> bool) -> Result<usize> {
654        let mut list: Vec<KeyEntry> = decode(bytes)?;
655        let mut n = 0;
656        for e in &mut list {
657            let key = Key32(e.key);
658            e.key.zeroize();
659            match e.typ.take() {
660                None if !self.keys.contains_key(&e.id) && accept(&e.id, e.epoch, None, &key) => {
661                    self.keys.insert(e.id.clone(), (e.epoch, key));
662                    n += 1;
663                }
664                Some(t) if !self.scoped.contains_key(&(e.id.clone(), t.clone())) && accept(&e.id, e.epoch, Some(&t), &key) => {
665                    self.scoped.insert((e.id.clone(), t), (e.epoch, key));
666                    n += 1;
667                }
668                _ => {}
669            }
670        }
671        Ok(n)
672    }
673
674    /// CBOR for the application's encrypted store.
675    pub fn export(&self) -> Zeroizing<Vec<u8>> {
676        self.entries(|_| true)
677    }
678
679    pub fn import(bytes: &[u8]) -> Result<Self> {
680        let mut k = Self::new();
681        k.absorb(bytes, |_, _, _, _| true)?;
682        Ok(k)
683    }
684}
685
686fn seal_to(eph: &ExchangeSecret, to: &[u8; 32], transcript: &[u8], plain: &[u8]) -> Result<Sealed> {
687    let shared = eph.agree(to).ok_or_else(|| crypto("low-order device key"))?;
688    let (k, _) = exchange::derive(&shared, transcript, SEAL_KEY, SEAL_SAS)?;
689    Ok(seal(&k, plain, transcript)?)
690}
691
692fn open_from(me: &ExchangeSecret, eph_hex: &str, transcript: &[u8], sealed: &Sealed) -> Result<Zeroizing<Vec<u8>>> {
693    let eph: [u8; 32] = hex::decode(eph_hex).ok().and_then(|b| b.try_into().ok()).ok_or_else(|| crypto("bad ephemeral key"))?;
694    let shared = me.agree(&eph).ok_or_else(|| crypto("low-order ephemeral key"))?;
695    let (k, _) = exchange::derive(&shared, transcript, SEAL_KEY, SEAL_SAS)?;
696    Ok(open(&k, sealed, transcript)?)
697}
698
699/// Where this device stands with rotated keys.
700#[derive(Debug, Clone, PartialEq, Eq)]
701pub enum KeyStatus {
702    /// No rotation yet: keys come from the seed, as in 0.2.
703    Seed,
704    /// Holding the head key at this epoch.
705    Current { epoch: u32 },
706    /// The chain has moved on and this device was not given the key: another device
707    /// must re-admit it (for example after a restore from the recovery words).
708    NeedsAdmission,
709    /// This device has been revoked.
710    Revoked,
711    /// A service device linked without data keys (a roster-only grant): it syncs the
712    /// roster and nothing else, and never needs admission.
713    RosterOnly,
714}
715
716impl SyncState {
717    /// Put this device's exchange key in the roster so rotations can include it.
718    pub fn publish_device_key(&mut self, at_ms: i64) -> Result<()> {
719        let device = self.device.as_ref().ok_or_else(|| SyncError::Protocol("no device key".into()))?;
720        if self.roster.chain.device(&device.peer_id()).is_none() {
721            let dk = device.device_key(at_ms)?;
722            self.roster.chain.add_device(dk);
723        }
724        Ok(())
725    }
726
727    pub fn key_status(&self) -> KeyStatus {
728        if self.roster.get(&self.our_cert.peer_id).is_some_and(|c| !c.active()) || !self.our_cert.active() {
729            return KeyStatus::Revoked;
730        }
731        if !self.roster.holds_keys(&self.our_cert.peer_id) {
732            return KeyStatus::RosterOnly;
733        }
734        let view = self.roster.chain_view();
735        match view.head() {
736            None => KeyStatus::Seed,
737            Some(h) if self.keys.has(&h.id) => KeyStatus::Current { epoch: h.epoch },
738            Some(_) => KeyStatus::NeedsAdmission,
739        }
740    }
741
742    pub fn needs_admission(&self) -> bool {
743        self.key_status() == KeyStatus::NeedsAdmission
744    }
745
746    /// Active devices that have not published a device key yet (not upgraded, or not
747    /// synced since). A rotation now leaves them out; they would need re-admission.
748    /// Apps warn before revoking while this is not empty.
749    /// Roster-only service devices never need one and are not listed.
750    pub fn devices_without_key(&self) -> Vec<NodeCert> {
751        self.roster
752            .active()
753            .filter(|c| self.roster.holds_keys(&c.peer_id) && self.roster.chain.device(&c.peer_id).is_none_or(|d| !d.verify()))
754            .cloned()
755            .collect()
756    }
757
758    /// The first rotation should happen now, on this device: there is no rotation yet,
759    /// at least two devices are linked, every active device has published its device
760    /// key, and this device has the lowest peer id among them (so only one device
761    /// starts the chain). Covers both "right after the first link" and "once after an
762    /// upgrade from seed-only keys". [`crate::pull_from`] does it when
763    /// [`SyncState::auto_first_rotation`] is on; apps may also call
764    /// [`SyncState::rotate_if_first_due`].
765    pub fn first_rotation_due(&self) -> bool {
766        let Some(device) = &self.device else { return false };
767        if self.is_service() || self.key_status() != KeyStatus::Seed {
768            return false;
769        }
770        // Only devices that may rotate take part in choosing who starts the chain.
771        let active: Vec<&NodeCert> = self.roster.active().filter(|c| !self.roster.is_service(&c.peer_id)).collect();
772        let me = device.peer_id();
773        active.len() >= 2 && active.iter().any(|c| c.peer_id == me) && self.devices_without_key().is_empty() && active.iter().all(|c| c.peer_id >= me)
774    }
775
776    /// Make the first rotation if [`SyncState::first_rotation_due`]. Returns its id.
777    pub fn rotate_if_first_due(&mut self, at_ms: i64) -> Result<Option<String>> {
778        if self.first_rotation_due() { self.rotate(at_ms).map(Some) } else { Ok(None) }
779    }
780
781    /// The head has a revoked member and this device can replace it.
782    pub fn needs_rotation(&self) -> bool {
783        let view = self.roster.chain_view();
784        self.device.is_some()
785            && !self.is_service()
786            && view.dirty()
787            && view.head().is_some_and(|h| self.keys.has(&h.id))
788            && self.key_status() != KeyStatus::Revoked
789    }
790
791    /// Open every key sealed or admitted to this device and adopt the root. Returns how
792    /// many keys were new.
793    pub fn refresh_keys(&mut self) -> usize {
794        let Some(device) = self.device.clone() else { return 0 };
795        let me = device.peer_id();
796        let Some(my_pub) = self.roster.chain.device(&me).and_then(DeviceKey::public) else { return 0 };
797        let view = self.roster.chain_view();
798        let views = self.roster.all_views();
799        let valid = |id: &str| views.iter().any(|v| v.valid.contains_key(id));
800        let mut n = 0;
801        let checks: BTreeMap<String, (u32, String)> = self.roster.chain.rotations.iter().map(|r| (r.id(), (r.epoch, r.check.clone()))).collect();
802        for r in &self.roster.chain.rotations {
803            let id = r.id();
804            if !valid(&id) || self.keys.has(&id) {
805                continue;
806            }
807            let Some(sk) = r.keys.iter().find(|k| k.peer_id == me) else { continue };
808            if let Ok(plain) = open_from(&device.exchange, &r.eph, &r.transcript(&me, &my_pub), &sk.sealed)
809                && let Ok(key) = Key32::from_slice(&plain)
810                && key_check(&key) == r.check
811            {
812                self.keys.insert(id, r.epoch, key);
813                n += 1;
814            }
815        }
816        for a in &self.roster.chain.admissions {
817            if a.peer_id != me || !views.iter().any(|v| v.admissions.contains(&a.id())) {
818                continue;
819            }
820            if let Ok(plain) = open_from(&device.exchange, &a.eph, &a.transcript(&my_pub), &a.sealed) {
821                // An epoch key must match its rotation's commitment. A type-scoped key (a
822                // service device's) cannot be checked against it; it counts for the
823                // admission's rotation epoch, sealed and signed by a member.
824                let accept = |id: &str, epoch: u32, typ: Option<&str>, key: &Key32| {
825                    valid(id)
826                        && checks.get(id).is_some_and(|(e, c)| match typ {
827                            None => *c == key_check(key),
828                            Some(_) => *e == epoch,
829                        })
830                };
831                n += self.keys.absorb(&plain, accept).unwrap_or(0);
832            }
833        }
834        self.narrow_keys();
835        if self.roster.chain.root.is_none()
836            && let Some(root) = &view.root
837            && view.valid.keys().any(|id| self.keys.has(id))
838        {
839            self.roster.chain.root = Some(root.clone());
840        }
841        if let Some(h) = view.head() {
842            self.roster.epoch = self.roster.epoch.max(h.epoch);
843        }
844        n
845    }
846
847    /// Make a fresh random epoch key and seal it to every remaining device that has
848    /// published a device key. Returns the new rotation id.
849    pub fn rotate(&mut self, at_ms: i64) -> Result<String> {
850        let view = self.roster.chain_view();
851        self.rotate_on(&view, at_ms)
852    }
853
854    /// Rotate on top of `view`'s head (taken before a revocation, whose creator's
855    /// rotations would otherwise drop out of the view until someone builds on them).
856    fn rotate_on(&mut self, view: &ChainView, at_ms: i64) -> Result<String> {
857        if self.is_service() {
858            return Err(SyncError::NotPermitted("rotate".into()));
859        }
860        let device = self.device.clone().ok_or_else(|| SyncError::Protocol("no device key".into()))?;
861        let me = device.peer_id();
862        self.publish_device_key(at_ms)?;
863        if self.key_status() == KeyStatus::Revoked {
864            return Err(SyncError::Refused("revoked".into()));
865        }
866        let active: BTreeSet<String> = self.roster.active().map(|c| c.peer_id.clone()).collect();
867        let (parent, epoch, mut candidates): (Option<String>, u32, BTreeSet<String>) = match view.head() {
868            Some(h) if !self.keys.has(&h.id) => return Err(SyncError::Refused("needs-admission".into())),
869            Some(h) => (Some(h.id.clone()), h.epoch.saturating_add(1), h.members.clone()),
870            None => (None, self.roster.epoch.saturating_add(1), active.clone()),
871        };
872        candidates.extend(self.roster.chain.approved.iter().cloned());
873        // Service devices with sync types got their keys at link time, not as members of a
874        // rotation: keep them in. Roster-only ones never get a key.
875        candidates.extend(self.roster.active().filter(|c| self.roster.is_service(&c.peer_id)).map(|c| c.peer_id.clone()));
876        candidates.retain(|p| self.roster.holds_keys(p));
877        let key = Key32::random()?;
878        let eph = ExchangeSecret::generate();
879        let mut r = Rotation {
880            epoch,
881            parent,
882            by: me.clone(),
883            at_ms,
884            eph: hex::encode(eph.public()),
885            check: key_check(&key),
886            keys: Vec::new(),
887            sig: Vec::new(),
888        };
889        let mut recipients: Vec<String> = candidates.into_iter().filter(|p| active.contains(p)).collect();
890        if !recipients.contains(&me) {
891            recipients.push(me.clone());
892        }
893        // Service devices with sync types never get the epoch key: they are admitted to the
894        // new rotation with type-scoped keys below (the scoped keys bind the rotation id,
895        // which is only known once the rotation is signed).
896        let mut scoped = Vec::new();
897        for peer in recipients {
898            let Some(public) = self.roster.chain.device(&peer).and_then(DeviceKey::public) else { continue };
899            if peer != me
900                && let Some(types) = self.roster.scoped_types(&peer)
901            {
902                scoped.push((peer, public, types));
903                continue;
904            }
905            let sealed = seal_to(&eph, &public, &r.transcript(&peer, &public), &key.0)?;
906            r.keys.push(SealedKey { peer_id: peer, sealed });
907        }
908        r.sig = device.sign(&r.body())?;
909        let id = r.id();
910        if r.parent.is_none() {
911            self.roster.chain.root = Some(id.clone());
912        }
913        self.roster.chain.rotations.push(r);
914        self.keys.insert(id.clone(), epoch, key);
915        self.roster.epoch = self.roster.epoch.max(epoch);
916        for (peer, public, types) in scoped {
917            let plain = self.keys.scope_where(&self.user_id, &types, |k| k == id)?.entries(|_| true);
918            self.push_admission(&device, &id, &peer, &public, &plain, at_ms)?;
919        }
920        Ok(id)
921    }
922
923    /// Revoke a device and, when this state has a device key, rotate so the revoked
924    /// device cannot read anything written afterwards even though it holds the seed.
925    pub fn revoke(&mut self, user: &Keypair, peer_id: &str, at_ms: i64) -> Result<NodeCert> {
926        if self.is_service() {
927            return Err(SyncError::NotPermitted("revoke".into()));
928        }
929        let before = self.roster.chain_view();
930        let cert = self.roster.revoke(&WEIRDNET, user, peer_id, at_ms)?;
931        if self.device.is_some() {
932            self.rotate_on(&before, at_ms)?;
933        }
934        Ok(cert)
935    }
936
937    /// The user approved this device here (as when linking it). It is admitted now if
938    /// its device key is known, otherwise as soon as one of its hellos brings the key.
939    /// Returns whether it was admitted now.
940    pub fn approve(&mut self, cert: NodeCert, at_ms: i64) -> Result<bool> {
941        if self.is_service() {
942            return Err(SyncError::NotPermitted("approve".into()));
943        }
944        if !WEIRDNET.verify_cert(&self.user_key, &cert) || !cert.active() || cert.user_id != self.user_id {
945            return Err(SyncError::Refused("wrong-user".into()));
946        }
947        if self.roster.get(&cert.peer_id).is_some_and(|c| !c.active()) {
948            return Err(SyncError::Refused("revoked".into()));
949        }
950        let peer = cert.peer_id.clone();
951        self.roster.upsert(cert);
952        if !self.roster.holds_keys(&peer) {
953            // A roster-only service device: in the roster, never in the key chain.
954            return Ok(false);
955        }
956        if !self.roster.chain.approved.contains(&peer) {
957            self.roster.chain.approved.push(peer.clone());
958        }
959        Ok(self.admit_approved(at_ms).contains(&peer))
960    }
961
962    /// Admit every approved device whose device key is known and that is not yet a
963    /// member of the head, in every chain whose head key this device holds (normally
964    /// one; two when two first roots were made at once). Members of all of them and
965    /// revoked devices leave the list. Returns the devices admitted.
966    pub fn admit_approved(&mut self, at_ms: i64) -> Vec<String> {
967        let mut admitted = Vec::new();
968        if self.roster.chain.approved.is_empty() || self.device.is_none() || self.is_service() {
969            return admitted;
970        }
971        let roster = &self.roster;
972        let drop: Vec<String> = roster.chain.approved.iter().filter(|p| !roster.holds_keys(p)).cloned().collect();
973        self.roster.chain.approved.retain(|p| !drop.contains(p));
974        for peer in self.roster.chain.approved.clone() {
975            let active = self.roster.get(&peer).is_some_and(|c| c.active());
976            let mut done = active;
977            let mut any = false;
978            for view in self.roster.all_views() {
979                let Some(head) = view.head() else { continue };
980                if !self.keys.has(&head.id) {
981                    if view.root == self.roster.chain_view().root {
982                        done = false;
983                    }
984                    continue;
985                }
986                any = true;
987                if !active || head.members.contains(&peer) {
988                    continue;
989                }
990                let admitted_now = self.roster.chain.device(&peer).is_some()
991                    && self.roster.get(&peer).cloned().is_some_and(|cert| self.admit_to(cert, &view, at_ms).unwrap_or(false));
992                if admitted_now {
993                    if !admitted.contains(&peer) {
994                        admitted.push(peer.clone());
995                    }
996                } else {
997                    done = false;
998                }
999            }
1000            if !active || (any && done) {
1001                self.roster.chain.approved.retain(|p| p != &peer);
1002            }
1003        }
1004        admitted
1005    }
1006
1007    /// Let a device back in (after the user approved it on this device, as when
1008    /// linking; [`SyncState::approve`] waits for its device key): seal the head key and the older keys this device holds to its device
1009    /// key. Returns false when there is nothing to admit to (no rotation yet: the seed
1010    /// is enough).
1011    pub fn admit(&mut self, cert: NodeCert, at_ms: i64) -> Result<bool> {
1012        if !WEIRDNET.verify_cert(&self.user_key, &cert) || !cert.active() || cert.user_id != self.user_id {
1013            return Err(SyncError::Refused("wrong-user".into()));
1014        }
1015        if self.roster.get(&cert.peer_id).is_some_and(|c| !c.active()) {
1016            return Err(SyncError::Refused("revoked".into()));
1017        }
1018        self.roster.upsert(cert.clone());
1019        let view = self.roster.chain_view();
1020        self.admit_to(cert, &view, at_ms)
1021    }
1022
1023    fn admit_to(&mut self, cert: NodeCert, view: &ChainView, at_ms: i64) -> Result<bool> {
1024        if self.is_service() {
1025            return Err(SyncError::NotPermitted("admit".into()));
1026        }
1027        if !self.roster.holds_keys(&cert.peer_id) {
1028            return Ok(false);
1029        }
1030        let device = self.device.clone().ok_or_else(|| SyncError::Protocol("no device key".into()))?;
1031        let peer = cert.peer_id.clone();
1032        let Some(head) = view.head() else { return Ok(false) };
1033        if !self.keys.has(&head.id) {
1034            return Err(SyncError::Refused("needs-admission".into()));
1035        }
1036        let public = self
1037            .roster
1038            .chain
1039            .device(&peer)
1040            .and_then(DeviceKey::public)
1041            .ok_or_else(|| SyncError::Protocol(format!("no device key for {peer} yet")))?;
1042        // A service device with sync types gets type-scoped keys for its grant, never the
1043        // epoch keys.
1044        let plain = match self.roster.scoped_types(&peer) {
1045            Some(types) => self.keys.scope_where(&self.user_id, &types, |id| view.valid.contains_key(id))?.entries(|_| true),
1046            None => self.keys.entries(|id| view.valid.contains_key(id)),
1047        };
1048        self.push_admission(&device, &head.id, &peer, &public, &plain, at_ms)?;
1049        Ok(true)
1050    }
1051
1052    /// Seal `plain` (key entries) to `peer` as an admission to `rotation`, signed by `device`.
1053    fn push_admission(&mut self, device: &Device, rotation: &str, peer: &str, public: &[u8; 32], plain: &[u8], at_ms: i64) -> Result<()> {
1054        let eph = ExchangeSecret::generate();
1055        let mut a = Admission {
1056            rotation: rotation.to_string(),
1057            peer_id: peer.to_string(),
1058            by: device.peer_id(),
1059            at_ms,
1060            eph: hex::encode(eph.public()),
1061            sealed: Sealed { nonce: String::new(), ct: String::new() },
1062            sig: Vec::new(),
1063        };
1064        a.sealed = seal_to(&eph, public, &a.transcript(public), plain)?;
1065        a.sig = device.sign(&a.body())?;
1066        self.roster.chain.admissions.push(a);
1067        Ok(())
1068    }
1069
1070    /// On a service device, keep only type-scoped keys for the types in its grant: an
1071    /// epoch key that reached it (from a 0.8.2 device's link or rotation) is replaced by
1072    /// the scoped keys it allows, and dropped.
1073    pub(crate) fn narrow_keys(&mut self) {
1074        if !self.is_service() {
1075            return;
1076        }
1077        let Some(types) = self.roster.scoped_types(&self.our_cert.peer_id) else {
1078            if self.roster.grant_of(&self.our_cert.peer_id).is_some_and(crate::roster::DeviceGrant::roster_only) {
1079                self.keys = EpochKeys::new();
1080            }
1081            return;
1082        };
1083        if self.keys.epoch_key_count() == 0 && self.keys.ids().all(|(id, _)| self.keys.scoped_types(id).all(|t| types.iter().any(|x| x == t))) {
1084            return;
1085        }
1086        let user_id = self.user_id.clone();
1087        if self.keys.narrow_to(&user_id, &types).is_err() {
1088            self.keys = EpochKeys::new();
1089        }
1090    }
1091}
1092
1093#[cfg(test)]
1094mod tests {
1095    use super::*;
1096
1097    #[test]
1098    fn a_device_key_verifies_only_for_its_own_node() {
1099        let node = Keypair::generate_ed25519();
1100        let d = Device::from_node_key(&node).unwrap();
1101        let dk = d.device_key(5).unwrap();
1102        assert!(dk.verify());
1103        assert_eq!(dk.peer_id, node.public().to_peer_id().to_string());
1104        // Same node key, same exchange key (nothing new to store).
1105        assert_eq!(Device::from_node_key(&node).unwrap().device_key(5).unwrap().exchange, dk.exchange);
1106        let other = Device::from_node_key(&Keypair::generate_ed25519()).unwrap().device_key(5).unwrap();
1107        assert!(!DeviceKey { exchange: other.exchange.clone(), ..dk.clone() }.verify(), "a swapped exchange key fails");
1108        assert!(!DeviceKey { peer_id: other.peer_id.clone(), ..dk.clone() }.verify());
1109        assert_eq!(dk.fingerprint().len(), 14);
1110        assert!(format!("{d:?}").starts_with("Device(12D3"));
1111    }
1112
1113    #[test]
1114    fn epoch_keys_export_and_import() {
1115        let mut k = EpochKeys::new();
1116        k.insert("a".into(), 1, Key32::random().unwrap());
1117        k.insert("b".into(), 2, Key32::random().unwrap());
1118        let back = EpochKeys::import(&k.export()).unwrap();
1119        assert_eq!(back, k);
1120        assert_eq!(format!("{k:?}"), "EpochKeys(2 keys)");
1121    }
1122
1123    #[test]
1124    fn a_sealed_copy_opens_only_for_its_recipient() {
1125        let a = Device::from_node_key(&Keypair::generate_ed25519()).unwrap();
1126        let b = Device::from_node_key(&Keypair::generate_ed25519()).unwrap();
1127        let eph = ExchangeSecret::generate();
1128        let to = a.exchange.public();
1129        let s = seal_to(&eph, &to, b"t", b"key").unwrap();
1130        let eph_hex = hex::encode(eph.public());
1131        assert_eq!(&open_from(&a.exchange, &eph_hex, b"t", &s).unwrap()[..], b"key");
1132        assert!(open_from(&b.exchange, &eph_hex, b"t", &s).is_err());
1133        assert!(open_from(&a.exchange, &eph_hex, b"other", &s).is_err());
1134    }
1135
1136    #[test]
1137    fn peer_public_round_trips() {
1138        let k = Keypair::generate_ed25519();
1139        let pid = k.public().to_peer_id().to_string();
1140        assert_eq!(peer_public(&pid).unwrap(), k.public());
1141        assert!(peer_public("not-a-peer").is_none());
1142    }
1143}