Skip to main content

weirdnet_sync/
net.rs

1//! The pull protocol running on a [`weirdnet_net::Node`] (`/weirdnet/sync/2`).
2//!
3//! The official WeirdBrains relay must not store pages; this module only exchanges
4//! sealed envelopes between the user's own nodes.
5use crate::error::{Result, SyncError};
6use crate::hlc::{Hlc, NodeId};
7use crate::log::OpLog;
8use crate::protocol::{Ack, Envelope, Hello, HelloOk, KeyRef, Message, PAGE_MAX, Pull, Refuse, RosterMsg, SYNC_PROFILE, decode, encode};
9use crate::record::{RecordOptions, base_type, chunk_type, is_chunk_type};
10use crate::roster::{Roster, SessionCheck};
11use crate::rotation::{Device, EpochKeys, KeyChain};
12use std::collections::BTreeMap;
13use std::sync::{Arc, Mutex};
14use weirdnet_net::user::NodeCert;
15use weirdnet_net::{Handler, Keypair, Multiaddr, Node, NodeConfig, PeerId, PublicKey, WEIRDNET};
16
17/// Mutable state a sync node answers from and applies pages into.
18pub struct SyncState {
19    pub seed: Vec<u8>,
20    pub user_id: String,
21    pub user_key: PublicKey,
22    pub our_cert: NodeCert,
23    pub our_node: NodeId,
24    pub types: Vec<String>,
25    pub roster: Roster,
26    pub log: OpLog,
27    pub clock: Option<Hlc>,
28    /// This device's node and exchange secrets. Without them the state stays on
29    /// seed-derived keys and cannot rotate or open a rotated key.
30    pub device: Option<Device>,
31    /// Rotated epoch keys this device holds (secret; persist encrypted).
32    pub keys: EpochKeys,
33    /// Make the first rotation automatically once it is due (see
34    /// [`SyncState::first_rotation_due`]): right after the first link, and once after an
35    /// upgrade from seed-only keys. On in [`SyncState::new`].
36    pub auto_first_rotation: bool,
37    /// Per-type write options (sealed, size limits); see [`SyncState::configure`].
38    pub records: BTreeMap<String, RecordOptions>,
39}
40
41impl SyncState {
42    /// A state for this device. With `node_key`, it publishes its device key so
43    /// rotations can include it.
44    pub fn new(seed: Vec<u8>, user_key: PublicKey, our_cert: NodeCert, node_key: Option<&Keypair>, types: Vec<String>) -> Result<Self> {
45        let device = node_key.map(Device::from_node_key).transpose()?;
46        let mut roster = Roster::new();
47        roster.upsert(our_cert.clone());
48        let mut st = Self {
49            seed,
50            user_id: our_cert.user_id.clone(),
51            user_key,
52            our_node: NodeId::new(our_cert.peer_id.clone()),
53            our_cert,
54            types,
55            roster,
56            log: OpLog::new(),
57            clock: None,
58            device,
59            keys: EpochKeys::new(),
60            auto_first_rotation: true,
61            records: BTreeMap::new(),
62        };
63        if st.device.is_some() {
64            st.publish_device_key(st.our_cert.issued_at)?;
65        }
66        Ok(st)
67    }
68
69    /// The key new envelopes are sealed with: the head epoch key when we hold it,
70    /// otherwise the seed-derived key (enough to catch up and be re-admitted).
71    pub fn current_key(&self) -> KeyRef {
72        match self.roster.head_id() {
73            Some(id) if self.keys.has(&id) => {
74                let epoch = self.roster.chain_view().head().map(|h| h.epoch).unwrap_or(self.roster.epoch);
75                KeyRef { epoch, id: Some(id) }
76            }
77            _ => KeyRef::seed(self.roster.epoch),
78        }
79    }
80
81    pub fn seal_envelope(&self, key: &KeyRef, typ: &str, peer: &str, msg: &Message) -> Result<Envelope> {
82        match &key.id {
83            None => Envelope::seal(&self.seed, &self.user_id, typ, key.epoch, peer, msg),
84            Some(id) => {
85                let k = self.keys.get(id).ok_or_else(|| SyncError::Crypto("unknown epoch key".into()))?;
86                Envelope::seal_keyed(k, id, &self.user_id, typ, key.epoch, peer, msg)
87            }
88        }
89    }
90
91    pub fn open_envelope(&self, env: &Envelope, peer: &str) -> Result<Message> {
92        match &env.key {
93            None => env.open(&self.seed, &self.user_id, peer),
94            Some(id) => {
95                let k = self.keys.get(id).ok_or_else(|| SyncError::Crypto("unknown epoch key".into()))?;
96                env.open_keyed(k, &self.user_id, peer)
97            }
98        }
99    }
100
101    fn roster_msg(&self) -> Message {
102        Message::Roster(RosterMsg { certs: self.roster.certs.clone(), epoch: self.roster.epoch, chain: self.roster.chain.shared() })
103    }
104
105    /// Merge certs, epoch and chain from a peer, then open any key sealed to us.
106    fn absorb(&mut self, certs: Vec<NodeCert>, epoch: u32, chain: KeyChain) {
107        let key = self.user_key.clone();
108        self.roster.merge(&Roster { epoch, certs, chain }, &key, &WEIRDNET);
109        self.refresh_keys();
110    }
111
112    /// Take the epoch keys (and adopted root) another copy of this state picked up,
113    /// for apps that pull into a snapshot and fold it back. Merge the roster as well.
114    pub fn take_keys_from(&mut self, other: &SyncState) {
115        self.keys.merge(&other.keys);
116        if self.roster.chain.root.is_none() {
117            self.roster.chain.root = other.roster.chain.root.clone();
118        }
119    }
120
121    fn is_revoked(&self, peer: &str) -> bool {
122        self.roster.get(peer).is_some_and(|c| !c.active())
123    }
124
125    pub fn handle(&mut self, from: &str, env: Envelope) -> Result<Envelope> {
126        let key = KeyRef { epoch: env.epoch, id: env.key.clone() };
127        // Open with our keys and user id; a foreign user fails here (wrong-user).
128        let msg = match self.open_envelope(&env, from) {
129            Ok(m) => m,
130            // Sealed under a rotation we don't hold: we are behind. Say so under the seed
131            // key, so the asker sends us its roster.
132            Err(_) if env.key.is_some() => return self.refuse(from, &env.typ, env.epoch, "unknown-key"),
133            Err(_) => return self.refuse(from, &env.typ, env.epoch, "wrong-user"),
134        };
135        let head = self.roster.head_id();
136        // After a rotation only the head key carries data; older and seed-derived keys
137        // (which a revoked device may hold) only get the roster.
138        let at_head = head.is_none() || env.key == head;
139        let reply = match msg {
140            Message::Hello(h) => self.on_hello(from, h, at_head),
141            Message::Pull(_) if !at_head => Message::Refuse(Refuse::new("epoch-behind")),
142            Message::Pull(_) if self.is_revoked(from) => Message::Refuse(Refuse::new("revoked")),
143            Message::Pull(p) => self.on_pull(p),
144            // An ack is the puller's progress, not ours: it must not move our cursors.
145            Message::Ack(a) => Message::Ack(Ack { node_id: a.node_id, last_seq: a.last_seq }),
146            Message::Roster(r) => {
147                self.absorb(r.certs, r.epoch, r.chain);
148                self.roster_msg()
149            }
150            Message::HelloOk(_) | Message::Page(_) | Message::Refuse(_) => {
151                return Err(SyncError::Protocol("unexpected request".into()));
152            }
153        };
154        // Answer under the key the request came in, so a peer behind us can read it.
155        self.seal_envelope(&key, &env.typ, from, &reply)
156    }
157
158    fn refuse(&self, from: &str, typ: &str, epoch: u32, reason: &'static str) -> Result<Envelope> {
159        Envelope::seal(&self.seed, &self.user_id, typ, epoch, from, &Message::Refuse(Refuse::new(reason)))
160    }
161
162    fn on_hello(&mut self, _from: &str, h: Hello, at_head: bool) -> Message {
163        let rotated = self.roster.head_id().is_some();
164        // After a rotation the key decides who is current, not the epoch number.
165        let epoch = if rotated { self.roster.epoch } else { h.epoch };
166        let check = self.roster.check_session(
167            &WEIRDNET,
168            &self.user_key,
169            &self.user_id,
170            &crate::roster::SessionOffer { cert: &h.cert, epoch, types: &h.types },
171            &self.types,
172        );
173        if matches!(check, SessionCheck::WrongUser | SessionCheck::Revoked) {
174            return Message::Refuse(Refuse::new(check.reason().unwrap_or("wrong-user")));
175        }
176        // Learn the peer's device key and rotations (signed; checked on merge).
177        if !h.chain.is_empty() {
178            self.roster.chain.merge(&h.chain);
179            self.refresh_keys();
180            // A device the user approved here, saying hello for the first time: admit it
181            // now, so the roster reply below already carries its admission.
182            self.admit_approved(now_ms() as i64);
183        }
184        if (rotated && !at_head) || check == SessionCheck::EpochBehind {
185            // A valid, unrevoked device of this user that missed a revocation or a
186            // rotation, or one waiting to be re-admitted: send the roster (user-signed
187            // certs and revocations, and the key chain) so it can catch up and retry.
188            return self.roster_msg();
189        }
190        if check != SessionCheck::Ok {
191            return Message::Refuse(Refuse::new(check.reason().unwrap_or("wrong-user")));
192        }
193        let cursors = self.log.cursors().into_iter().collect();
194        let revocations = self.roster.certs.iter().filter(|c| !c.active()).cloned().collect();
195        Message::HelloOk(HelloOk { cert: self.our_cert.clone(), epoch: self.roster.epoch, cursors, revocations, chain: self.roster.chain.shared() })
196    }
197
198    fn on_pull(&self, p: Pull) -> Message {
199        // A type's chunks are served wherever the type is.
200        let served = base_type(&p.typ).unwrap_or(&p.typ);
201        if !self.types.iter().any(|t| t == served) {
202            return Message::Refuse(Refuse::new("type-off"));
203        }
204        let limit = (p.limit as usize).clamp(1, 4096);
205        let known = self.log.cursor_for(&p.node_id, &p.typ);
206        let page = self.log.page_of_type(&p.node_id, &p.typ, p.after_seq, known, limit);
207        Message::Page(crate::protocol::Page { typ: p.typ, page })
208    }
209
210    /// A local write: tick the clock, append one log op. Returns its seq. For values
211    /// that may be large or that are sealed, use [`SyncState::write`].
212    pub fn local_op(&mut self, now_ms: u64, typ: &str, record_id: &str, op: Vec<u8>) -> u64 {
213        let hlc = self.tick(now_ms);
214        self.log.append(self.our_node.clone(), hlc, typ, record_id, op).seq
215    }
216
217    pub(crate) fn tick(&mut self, now_ms: u64) -> Hlc {
218        let hlc = Hlc::tick(self.clock.as_ref(), now_ms, self.our_node.clone());
219        self.clock = Some(hlc.clone());
220        hlc
221    }
222}
223
224/// Request-response handler that talks [`Envelope`] on [`SYNC_PROFILE`].
225pub struct SyncHandler {
226    pub state: Arc<Mutex<SyncState>>,
227}
228
229impl Handler<Vec<u8>, Vec<u8>> for SyncHandler {
230    fn request(&self, from: &PeerId, req: Vec<u8>) -> Vec<u8> {
231        let env: Envelope = match decode(&req) {
232            Ok(e) => e,
233            Err(e) => return error_bytes(&e.to_string()),
234        };
235        let mut st = self.state.lock().expect("sync state");
236        match st.handle(&from.to_string(), env) {
237            Ok(reply) => encode(&reply).unwrap_or_else(|e| error_bytes(&e.to_string())),
238            Err(e) => error_bytes(&e.to_string()),
239        }
240    }
241}
242
243fn error_bytes(msg: &str) -> Vec<u8> {
244    encode(&Message::Refuse(Refuse { reason: format!("codec:{msg}") })).unwrap_or_default()
245}
246
247/// Listen with the in-memory transport (tests) or the caller's config, 256 KiB caps.
248pub fn node_config(listen_memory: bool) -> NodeConfig {
249    NodeConfig {
250        listen: if listen_memory { vec!["/memory/0".parse().expect("memory addr")] } else { Vec::new() },
251        memory: listen_memory,
252        request_max: PAGE_MAX as u64,
253        response_max: PAGE_MAX as u64,
254        label: "sync".into(),
255        ..Default::default()
256    }
257}
258
259/// Start a sync node on [`SYNC_PROFILE`].
260pub fn start_node(key: Keypair, cfg: NodeConfig, state: Arc<Mutex<SyncState>>) -> Result<Node<Vec<u8>, Vec<u8>>> {
261    Ok(Node::start(&SYNC_PROFILE, key, cfg, Arc::new(SyncHandler { state }))?)
262}
263
264/// Hello then pull every roster member the peer advertised, applying pages and acking.
265///
266/// Catches up on revocations and rotations both ways, and replaces a head rotation
267/// that still includes a revoked device. Fails with `Refused("needs-admission")` when
268/// the chain has moved on without this device (restored from the seed): another device
269/// has to [`SyncState::admit`] it.
270pub fn pull_from(state: &mut SyncState, node: &Node<Vec<u8>, Vec<u8>>, peer: PeerId, addrs: &[Multiaddr], typ_name: &str) -> Result<usize> {
271    let from = node.peer_id().to_string();
272    let mut catch_ups = 0;
273    let mut pushed = false;
274    let ok = loop {
275        let key = state.current_key();
276        let hello = Message::Hello(Hello {
277            cert: state.our_cert.clone(),
278            user_id: state.user_id.clone(),
279            epoch: key.epoch,
280            types: state.types.clone(),
281            our_cursors: state.log.cursors().into_iter().collect(),
282            our_hlc: state.clock.clone().unwrap_or_else(|| Hlc::new(0, 0, state.our_node.clone())),
283            chain: state.roster.chain.shared(),
284        });
285        let env = state.seal_envelope(&key, typ_name, &from, &hello)?;
286        let reply = request(node, peer, addrs, &env)?;
287        match state.open_envelope(&reply, &from)? {
288            Message::HelloOk(ok) => break ok,
289            // We are behind a revocation or rotation: take the peer's signed roster and
290            // chain, then hello again.
291            Message::Roster(r) if catch_ups < 3 => {
292                state.absorb(r.certs, r.epoch, r.chain);
293                if !state.roster.get(&state.our_cert.peer_id).is_none_or(|c| c.active()) {
294                    return Err(SyncError::Refused("revoked".into()));
295                }
296                if state.current_key() == key {
297                    let reason = if state.needs_admission() { "needs-admission" } else { "epoch-behind" };
298                    return Err(SyncError::Refused(reason.into()));
299                }
300                catch_ups += 1;
301            }
302            // The peer missed a rotation we hold: hand it our roster under the seed key
303            // (the chain is public; the epoch keys inside are sealed), then hello again.
304            Message::Refuse(r) if r.reason == "unknown-key" && !pushed => {
305                let env = state.seal_envelope(&KeyRef::seed(state.roster.epoch), typ_name, &from, &state.roster_msg())?;
306                if let Ok(Message::Roster(back)) = request(node, peer, addrs, &env).and_then(|e| state.open_envelope(&e, &from)) {
307                    state.absorb(back.certs, back.epoch, back.chain);
308                }
309                pushed = true;
310            }
311            Message::Refuse(r) => return Err(SyncError::Refused(r.reason)),
312            _ => return Err(SyncError::Protocol("expected HelloOk".into())),
313        }
314    };
315    let behind = ok.epoch < state.roster.epoch;
316    state.absorb(ok.revocations.into_iter().chain([ok.cert]).collect(), ok.epoch, ok.chain);
317    let key = state.current_key();
318    if behind {
319        // The peer missed a revocation we hold: hand it our roster so it can catch up.
320        let env = state.seal_envelope(&key, typ_name, &from, &state.roster_msg())?;
321        let _ = request(node, peer, addrs, &env)?;
322    }
323    let mut applied = 0;
324    let mut to_pull: Vec<(NodeId, u64)> = ok.cursors;
325    // Also pull the peer's own node if it wasn't in cursors yet.
326    if !to_pull.iter().any(|(n, _)| n.0 == peer.to_string()) {
327        to_pull.push((NodeId(peer.to_string()), 0));
328    }
329    applied += pull_type(state, node, peer, addrs, &key, &to_pull, typ_name, false)?;
330    // Chunks of entries that are still incomplete come along with their type.
331    if !is_chunk_type(typ_name) && state.options(typ_name).limits.eager_chunks && !state.log.pending_blobs(typ_name).is_empty() {
332        pull_type(state, node, peer, addrs, &key, &to_pull, &chunk_type(typ_name), true)?;
333    }
334    observe(state, now_ms());
335    if state.auto_first_rotation && state.first_rotation_due() {
336        // Linked devices still on seed-derived keys, all with device keys: start the
337        // chain while every device is trusted.
338        state.rotate(now_ms() as i64)?;
339    } else if state.needs_rotation() {
340        // The head still includes a device that has since been revoked (say, revoked
341        // on a device without a node key): replace it.
342        state.rotate(now_ms() as i64)?;
343    }
344    Ok(applied)
345}
346
347/// Pull `typ_name` of every node in `nodes` under `key`. With `optional`, a server that
348/// does not serve the type (an older peer asked for chunks) ends it quietly.
349#[allow(clippy::too_many_arguments)]
350fn pull_type(
351    state: &mut SyncState,
352    node: &Node<Vec<u8>, Vec<u8>>,
353    peer: PeerId,
354    addrs: &[Multiaddr],
355    key: &KeyRef,
356    nodes: &[(NodeId, u64)],
357    typ_name: &str,
358    optional: bool,
359) -> Result<usize> {
360    let from = node.peer_id().to_string();
361    let mut applied = 0;
362    for (nid, _their) in nodes {
363        loop {
364            // Resume per type: a pull of another type over the same stream must not
365            // move this type's position.
366            let after = state.log.cursor_for(nid, typ_name);
367            let pull = Message::Pull(Pull { node_id: nid.clone(), after_seq: after, typ: typ_name.into(), limit: 512 });
368            let env = state.seal_envelope(key, typ_name, &from, &pull)?;
369            let reply = request(node, peer, addrs, &env)?;
370            match state.open_envelope(&reply, &from)? {
371                Message::Page(p) => {
372                    let last = p.page.to_seq;
373                    if p.typ != typ_name || p.page.node_id != *nid || p.page.ops.iter().any(|e| e.typ != typ_name) {
374                        return Err(SyncError::Protocol("page of another type or node".into()));
375                    }
376                    if last <= after {
377                        break;
378                    }
379                    applied += state.log.integrate(&p.page);
380                    state.log.set_cursor_for(nid, typ_name, last);
381                    if last > state.log.cursor(nid) {
382                        state.log.set_cursor(nid, last);
383                    }
384                    let ack = Message::Ack(Ack { node_id: nid.clone(), last_seq: last });
385                    let env = state.seal_envelope(key, typ_name, &from, &ack)?;
386                    let _ = request(node, peer, addrs, &env)?;
387                }
388                Message::Refuse(r) if optional && r.reason == "type-off" => return Ok(applied),
389                Message::Refuse(r) => return Err(SyncError::Refused(r.reason)),
390                // Anything else from a peer that does not serve chunks.
391                _ if optional => return Ok(applied),
392                _ => return Err(SyncError::Protocol("expected Page".into())),
393            }
394        }
395    }
396    Ok(applied)
397}
398
399/// Pull the chunks of `typ` (for [`crate::Limits::eager_chunks`] off, or to retry):
400/// the same session as [`pull_from`], for the companion type [`chunk_type`]`(typ)`.
401pub fn pull_chunks(state: &mut SyncState, node: &Node<Vec<u8>, Vec<u8>>, peer: PeerId, addrs: &[Multiaddr], typ: &str) -> Result<usize> {
402    pull_from(state, node, peer, addrs, &chunk_type(typ))
403}
404
405/// Advance our clock past the newest op held, so the next local write orders after
406/// everything this node has seen (a visit after a remote clear, say).
407pub fn observe(state: &mut SyncState, wall_ms: u64) {
408    if let Some(h) = state.log.newest_hlc().cloned()
409        && state.clock.as_ref().is_none_or(|c| h.cmp_total(c).is_gt())
410    {
411        state.clock = Some(Hlc::receive(state.clock.as_ref(), &h, wall_ms, state.our_node.clone()));
412    }
413}
414
415fn now_ms() -> u64 {
416    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
417}
418
419fn request(node: &Node<Vec<u8>, Vec<u8>>, peer: PeerId, addrs: &[Multiaddr], env: &Envelope) -> Result<Envelope> {
420    let bytes = encode(env)?;
421    let reply = node.request(peer, addrs, bytes)?;
422    decode(&reply)
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428    use crate::roster::Roster;
429    use crate::rotation::KeyStatus;
430    use crate::seal::typ;
431    use weirdnet_net::user;
432
433    const SEED: [u8; 32] = *b"DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD";
434
435    fn addrs(n: &Node<Vec<u8>, Vec<u8>>) -> Vec<Multiaddr> {
436        n.reachable_addrs().into_iter().map(|s| s.parse().expect("addr")).collect()
437    }
438
439    fn pair() -> (Keypair, Keypair, Keypair, String) {
440        let user = Keypair::generate_ed25519();
441        let a = Keypair::generate_ed25519();
442        let b = Keypair::generate_ed25519();
443        let uid = user::user_id(&user.public());
444        (user, a, b, uid)
445    }
446
447    fn state(user: &Keypair, node_key: &Keypair, uid: &str, label: &str, types: &[&str]) -> (Arc<Mutex<SyncState>>, NodeId) {
448        let peer = node_key.public().to_peer_id().to_string();
449        let cert = Roster::self_certify(&WEIRDNET, user, &peer, label, 1).unwrap();
450        let mut roster = Roster::new();
451        roster.upsert(cert.clone());
452        let node = NodeId(peer.clone());
453        let st = SyncState {
454            seed: SEED.to_vec(),
455            user_id: uid.into(),
456            user_key: user.public(),
457            our_cert: cert,
458            our_node: node.clone(),
459            types: types.iter().map(|s| s.to_string()).collect(),
460            roster,
461            log: OpLog::new(),
462            clock: None,
463            device: Some(Device::from_node_key(node_key).unwrap()),
464            keys: EpochKeys::new(),
465            auto_first_rotation: false,
466            records: BTreeMap::new(),
467        };
468        let mut st = st;
469        st.publish_device_key(1).unwrap();
470        (Arc::new(Mutex::new(st)), node)
471    }
472
473    #[test]
474    fn two_memory_nodes_hello_and_pull_a_bookmark_op() {
475        let (user, ka, kb, uid) = pair();
476        let (sa, _) = state(&user, &ka, &uid, "a", &["bookmarks"]);
477        let (sb, _) = state(&user, &kb, &uid, "b", &["bookmarks"]);
478        // Each roster starts as one; at hello they learn the other.
479        {
480            let mut a = sa.lock().unwrap();
481            a.local_op(1_000, typ::BOOKMARKS, "bm-1", b"{\"title\":\"Rust\"}".to_vec());
482            a.local_op(1_001, typ::HISTORY, "v-1", b"https://example".to_vec());
483            a.local_op(1_002, typ::BOOKMARKS, "bm-2", b"{}".to_vec());
484        }
485        let na = start_node(ka, node_config(true), sa.clone()).unwrap();
486        let nb = start_node(kb, node_config(true), sb.clone()).unwrap();
487        // Put each other in the roster (as a QR link would, plus hello).
488        {
489            let ca = sa.lock().unwrap().our_cert.clone();
490            let cb = sb.lock().unwrap().our_cert.clone();
491            sa.lock().unwrap().roster.upsert(cb);
492            sb.lock().unwrap().roster.upsert(ca);
493        }
494        let mut st_b = sb.lock().unwrap();
495        let applied = pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap();
496        assert!(applied >= 1, "applied {applied}");
497        let entry = st_b.log.get(&NodeId(na.peer_id().to_string()), 1).expect("bookmark op");
498        assert_eq!(entry.typ, typ::BOOKMARKS);
499        assert_eq!(entry.record_id, "bm-1");
500        assert_eq!(entry.op, b"{\"title\":\"Rust\"}");
501        let hist_visible = st_b.log.iter_node(&NodeId(na.peer_id().to_string())).any(|e| e.typ == typ::HISTORY);
502        assert!(!hist_visible, "a bookmarks pull must not apply history ops");
503        assert!(st_b.clock.as_ref().is_some_and(|c| c.physical_ms >= 1_000), "the clock moved past what was pulled");
504
505        // The history op sits between two bookmarks on one stream: a later history pull
506        // must still find it (0.1.0 lost it because the bookmarks pull moved one cursor
507        // past it).
508        let a_node = NodeId(na.peer_id().to_string());
509        assert_eq!(st_b.log.get(&a_node, 3).expect("second bookmark").record_id, "bm-2");
510        st_b.types.push(typ::HISTORY.into());
511        sa.lock().unwrap().types.push(typ::HISTORY.into());
512        let applied = pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::HISTORY).unwrap();
513        assert_eq!(applied, 1);
514        assert_eq!(st_b.log.get(&a_node, 2).expect("history op").record_id, "v-1");
515        assert_eq!(pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap(), 0);
516        assert_eq!(st_b.log.cursor_for(&a_node, typ::HISTORY), 3, "contiguous after both types");
517        assert_eq!(pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::HISTORY).unwrap(), 0);
518        assert_eq!(sa.lock().unwrap().log.cursor_for(&a_node, typ::BOOKMARKS), 3, "acks never move the server's cursors");
519        drop(st_b);
520
521        // A revoked B cannot pull after A revokes B and bumps the epoch.
522        {
523            let mut a = sa.lock().unwrap();
524            let b_peer = nb.peer_id().to_string();
525            a.roster.revoke(&WEIRDNET, &user, &b_peer, 9).unwrap();
526        }
527        let mut st_b = sb.lock().unwrap();
528        let err = pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap_err();
529        match err {
530            SyncError::Refused(r) => assert!(r == "revoked" || r == "epoch-behind" || r == "wrong-user", "got {r}"),
531            other => panic!("expected refuse, got {other}"),
532        }
533    }
534
535    #[test]
536    fn a_revocation_reaches_the_other_devices_both_ways() {
537        let user = Keypair::generate_ed25519();
538        let uid = user::user_id(&user.public());
539        let (ka, kb, kc, kd) = (Keypair::generate_ed25519(), Keypair::generate_ed25519(), Keypair::generate_ed25519(), Keypair::generate_ed25519());
540        let types = ["bookmarks"];
541        let (sa, _) = state(&user, &ka, &uid, "a", &types);
542        let (sb, _) = state(&user, &kb, &uid, "b", &types);
543        let (sc, _) = state(&user, &kc, &uid, "c", &types);
544        let (sd, _) = state(&user, &kd, &uid, "d", &types);
545        let all = [&sa, &sb, &sc, &sd];
546        let certs: Vec<_> = all.iter().map(|s| s.lock().unwrap().our_cert.clone()).collect();
547        for s in all {
548            for c in &certs {
549                s.lock().unwrap().roster.upsert(c.clone());
550            }
551        }
552        sa.lock().unwrap().local_op(1, typ::BOOKMARKS, "a-1", vec![1]);
553        let na = start_node(ka, node_config(true), sa.clone()).unwrap();
554        let nb = start_node(kb, node_config(true), sb.clone()).unwrap();
555        let nc = start_node(kc, node_config(true), sc.clone()).unwrap();
556        let nd = start_node(kd, node_config(true), sd.clone()).unwrap();
557        let c_peer = nc.peer_id().to_string();
558        sa.lock().unwrap().roster.revoke(&WEIRDNET, &user, &c_peer, 9).unwrap();
559
560        // B is a revocation behind A: A answers with its roster, B catches up and pulls.
561        let applied = pull_from(&mut sb.lock().unwrap(), &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap();
562        assert_eq!(applied, 1);
563        {
564            let b = sb.lock().unwrap();
565            assert_eq!(b.roster.epoch, 1);
566            assert!(!b.roster.get(&c_peer).unwrap().active());
567        }
568        // A pulls from D (still behind): A pushes its roster to D.
569        pull_from(&mut sa.lock().unwrap(), &na, nd.peer_id(), &addrs(&nd), typ::BOOKMARKS).unwrap();
570        assert_eq!(sd.lock().unwrap().roster.epoch, 1);
571        assert!(!sd.lock().unwrap().roster.get(&c_peer).unwrap().active());
572        // C is refused everywhere that learned, and a roster reply never lets it back in.
573        for (n, label) in [(&nb, "b"), (&nd, "d"), (&na, "a")] {
574            let err = pull_from(&mut sc.lock().unwrap(), &nc, n.peer_id(), &addrs(n), typ::BOOKMARKS).unwrap_err();
575            assert!(matches!(err, SyncError::Refused(ref r) if r == "revoked"), "{label}: {err}");
576        }
577    }
578
579    #[test]
580    fn a_foreign_user_is_refused() {
581        let (user_a, ka, _, uid_a) = pair();
582        let (user_b, kb, _, uid_b) = pair();
583        let (sa, _) = state(&user_a, &ka, &uid_a, "a", &["bookmarks"]);
584        let (sb, _) = state(&user_b, &kb, &uid_b, "b", &["bookmarks"]);
585        let na = start_node(ka, node_config(true), sa.clone()).unwrap();
586        let nb = start_node(kb, node_config(true), sb.clone()).unwrap();
587        let mut st_b = sb.lock().unwrap();
588        let err = pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap_err();
589        match err {
590            SyncError::Refused(r) => assert_eq!(r, "wrong-user"),
591            // Opening the reply can also fail if A sealed a refuse under A's user id.
592            SyncError::Crypto(_) => {}
593            other => panic!("expected wrong-user, got {other}"),
594        }
595    }
596
597    type Sn = (Arc<Mutex<SyncState>>, Node<Vec<u8>, Vec<u8>>);
598
599    /// `n` linked devices of one user: every roster holds every cert, every chain every
600    /// device key (as one round of sync would leave them), each on a memory node.
601    fn linked(user: &Keypair, labels: &[&str]) -> Vec<Sn> {
602        let uid = user::user_id(&user.public());
603        let made: Vec<(Arc<Mutex<SyncState>>, Keypair)> = labels
604            .iter()
605            .map(|l| {
606                let k = Keypair::generate_ed25519();
607                (state(user, &k, &uid, l, &["bookmarks"]).0, k)
608            })
609            .collect();
610        let certs: Vec<_> = made.iter().map(|(s, _)| s.lock().unwrap().our_cert.clone()).collect();
611        let chains: Vec<_> = made.iter().map(|(s, _)| s.lock().unwrap().roster.chain.clone()).collect();
612        for (s, _) in &made {
613            let mut st = s.lock().unwrap();
614            for c in &certs {
615                st.roster.upsert(c.clone());
616            }
617            for ch in &chains {
618                st.roster.chain.merge(ch);
619            }
620        }
621        made.into_iter().map(|(s, k)| (s.clone(), start_node(k, node_config(true), s).unwrap())).collect()
622    }
623
624    fn pull(a: &Sn, b: &Sn) -> Result<usize> {
625        pull_from(&mut a.0.lock().unwrap(), &a.1, b.1.peer_id(), &addrs(&b.1), typ::BOOKMARKS)
626    }
627
628    fn head(s: &Sn) -> Option<String> {
629        s.0.lock().unwrap().roster.head_id()
630    }
631
632    fn records(s: &Sn) -> Vec<String> {
633        let st = s.0.lock().unwrap();
634        let mut v: Vec<String> = st.log.cursors().keys().flat_map(|n| st.log.iter_node(n).map(|e| e.record_id.clone()).collect::<Vec<_>>()).collect();
635        v.sort();
636        v
637    }
638
639    fn peer(s: &Sn) -> String {
640        s.1.peer_id().to_string()
641    }
642
643    #[test]
644    fn a_revoked_device_cannot_read_ops_written_after_the_rotation() {
645        let user = Keypair::generate_ed25519();
646        let g = linked(&user, &["a", "b", "c"]);
647        let (a, b, c) = (&g[0], &g[1], &g[2]);
648        a.0.lock().unwrap().local_op(1, typ::BOOKMARKS, "before", vec![1]);
649        assert_eq!(pull(c, a).unwrap(), 1, "c reads what was written before");
650
651        let rot = {
652            let mut st = a.0.lock().unwrap();
653            st.revoke(&user, &peer(c), 9).unwrap();
654            st.local_op(10, typ::BOOKMARKS, "after", vec![2]);
655            st.roster.head_id().unwrap()
656        };
657        {
658            let st = a.0.lock().unwrap();
659            let view = st.roster.chain_view();
660            let h = view.head().unwrap();
661            assert!(h.members.contains(&peer(a)) && h.members.contains(&peer(b)));
662            assert!(!h.members.contains(&peer(c)), "the revoked device is not sealed a copy");
663            assert_eq!(st.key_status(), KeyStatus::Current { epoch: h.epoch });
664        }
665
666        // B catches up through the roster reply and reads the new op.
667        assert_eq!(pull(b, a).unwrap(), 2);
668        assert_eq!(head(b).as_deref(), Some(rot.as_str()));
669        assert!(b.0.lock().unwrap().keys.has(&rot));
670
671        // C is refused, and learning the whole chain gives it no key.
672        assert!(matches!(pull(c, a), Err(SyncError::Refused(ref r)) if r == "revoked"));
673        let chain = a.0.lock().unwrap().roster.clone();
674        {
675            let mut st = c.0.lock().unwrap();
676            let key = st.user_key.clone();
677            st.roster.merge(&chain, &key, &WEIRDNET);
678            st.refresh_keys();
679            assert!(!st.keys.has(&rot));
680            assert_eq!(st.key_status(), KeyStatus::Revoked);
681        }
682
683        // B's page with the post-rotation op, as it crosses the wire.
684        let a_node = NodeId(peer(a));
685        let page_env = {
686            let bs = b.0.lock().unwrap();
687            let pull = Message::Pull(Pull { node_id: a_node.clone(), after_seq: 0, typ: typ::BOOKMARKS.into(), limit: 10 });
688            let env = bs.seal_envelope(&bs.current_key(), typ::BOOKMARKS, &peer(b), &pull).unwrap();
689            a.0.lock().unwrap().handle(&peer(b), env).unwrap()
690        };
691        match b.0.lock().unwrap().open_envelope(&page_env, &peer(b)).unwrap() {
692            Message::Page(p) => assert!(p.page.ops.iter().any(|e| e.record_id == "after")),
693            other => panic!("expected a page, got {other:?}"),
694        }
695        let cs = c.0.lock().unwrap();
696        assert!(cs.open_envelope(&page_env, &peer(b)).is_err(), "c holds the seed and every old key, and still cannot open it");
697        assert!(page_env.open(&cs.seed, &cs.user_id, &peer(b)).is_err());
698        // Nor can it pull with the seed-derived key, as itself or claiming to be B.
699        for (from, label) in [(peer(c), "as c"), (peer(b), "as b")] {
700            let pull = Message::Pull(Pull { node_id: a_node.clone(), after_seq: 0, typ: typ::BOOKMARKS.into(), limit: 10 });
701            let env = cs.seal_envelope(&KeyRef::seed(cs.roster.epoch), typ::BOOKMARKS, &from, &pull).unwrap();
702            let reply = a.0.lock().unwrap().handle(&from, env).unwrap();
703            match cs.open_envelope(&reply, &from).unwrap() {
704                Message::Refuse(r) => assert_eq!(r.reason, "epoch-behind", "{label}"),
705                other => panic!("{label}: expected a refusal, got {other:?}"),
706            }
707        }
708        drop(cs);
709
710        // A new node certified with the seed's user key (what a revoked holder can mint)
711        // gets the roster, not the key.
712        let mint = Keypair::generate_ed25519();
713        let uid = user::user_id(&user.public());
714        let (ms, _) = state(&user, &mint, &uid, "minted", &["bookmarks"]);
715        let mn = start_node(mint, node_config(true), ms.clone()).unwrap();
716        let minted = (ms, mn);
717        assert!(matches!(pull(&minted, a), Err(SyncError::Refused(ref r)) if r == "needs-admission"));
718        assert!(!records(&minted).contains(&"after".to_string()));
719    }
720
721    #[test]
722    fn the_remaining_devices_converge_after_a_rotation() {
723        let user = Keypair::generate_ed25519();
724        let g = linked(&user, &["a", "b", "c", "d"]);
725        let (a, b, c, d) = (&g[0], &g[1], &g[2], &g[3]);
726        a.0.lock().unwrap().local_op(1, typ::BOOKMARKS, "a-1", vec![1]);
727        a.0.lock().unwrap().revoke(&user, &peer(c), 5).unwrap();
728        a.0.lock().unwrap().local_op(6, typ::BOOKMARKS, "a-2", vec![2]);
729        // A pulls from B, which has not heard: B cannot open A's hello, A hands it the
730        // roster, and the pull goes through under the new key.
731        b.0.lock().unwrap().local_op(7, typ::BOOKMARKS, "b-1", vec![3]);
732        assert_eq!(pull(a, b).unwrap(), 1);
733        assert_eq!(head(b), head(a));
734        // D was offline; it catches up from B, not from A.
735        assert_eq!(pull(d, b).unwrap(), 1);
736        assert_eq!(head(d), head(a));
737        d.0.lock().unwrap().local_op(8, typ::BOOKMARKS, "d-1", vec![4]);
738        assert_eq!(pull(a, d).unwrap(), 1);
739        assert_eq!(pull(b, d).unwrap(), 1);
740        pull(b, a).unwrap();
741        pull(d, a).unwrap();
742        let want = vec!["a-1", "a-2", "b-1", "d-1"];
743        for (s, label) in [(a, "a"), (b, "b"), (d, "d")] {
744            assert_eq!(records(s), want, "{label}");
745            assert!(matches!(s.0.lock().unwrap().key_status(), KeyStatus::Current { .. }), "{label}");
746        }
747        assert!(matches!(pull(c, d), Err(SyncError::Refused(ref r)) if r == "revoked"));
748    }
749
750    #[test]
751    fn a_restored_device_is_re_admitted_and_catches_up() {
752        let user = Keypair::generate_ed25519();
753        let g = linked(&user, &["a", "b", "c"]);
754        let (a, b, c) = (&g[0], &g[1], &g[2]);
755        a.0.lock().unwrap().local_op(1, typ::BOOKMARKS, "old", vec![1]);
756        let first = {
757            let mut st = a.0.lock().unwrap();
758            st.revoke(&user, &peer(c), 2).unwrap();
759            st.roster.head_id().unwrap()
760        };
761        let second = a.0.lock().unwrap().rotate(3).unwrap();
762        a.0.lock().unwrap().local_op(4, typ::BOOKMARKS, "new", vec![2]);
763        pull(b, a).unwrap();
764
765        // Restored from the recovery words: same seed and user, a new node key.
766        let uid = user::user_id(&user.public());
767        let rk = Keypair::generate_ed25519();
768        let (rs, _) = state(&user, &rk, &uid, "restored", &["bookmarks"]);
769        let r = (rs.clone(), start_node(rk, node_config(true), rs).unwrap());
770        assert!(matches!(pull(&r, a), Err(SyncError::Refused(ref x)) if x == "needs-admission"));
771        assert_eq!(r.0.lock().unwrap().key_status(), KeyStatus::NeedsAdmission);
772        assert!(r.0.lock().unwrap().roster.head_id().is_some(), "it knows the chain moved on");
773
774        // On A the user approves it (as when linking). A learned its device key from the hello.
775        let cert = r.0.lock().unwrap().our_cert.clone();
776        let fp = r.0.lock().unwrap().roster.chain.device(&peer(&r)).unwrap().fingerprint();
777        assert_eq!(a.0.lock().unwrap().roster.chain.device(&peer(&r)).unwrap().fingerprint(), fp);
778        assert!(a.0.lock().unwrap().admit(cert, 5).unwrap());
779
780        assert_eq!(pull(&r, a).unwrap(), 2);
781        assert_eq!(records(&r), vec!["new", "old"]);
782        {
783            let st = r.0.lock().unwrap();
784            assert!(st.keys.has(&first) && st.keys.has(&second), "older epochs come along for history");
785            assert!(matches!(st.key_status(), KeyStatus::Current { .. }));
786        }
787        // It writes; B learns of it from A and then pulls from it directly.
788        r.0.lock().unwrap().local_op(6, typ::BOOKMARKS, "restored-1", vec![3]);
789        pull(b, a).unwrap();
790        assert_eq!(pull(b, &r).unwrap(), 1);
791        // A device approved before its key is known (the link flow) is admitted by its
792        // first hello and catches up in that same pull.
793        let rk2 = Keypair::generate_ed25519();
794        let (rs2, _) = state(&user, &rk2, &uid, "restored-2", &["bookmarks"]);
795        let r2 = (rs2.clone(), start_node(rk2, node_config(true), rs2).unwrap());
796        let cert2 = r2.0.lock().unwrap().our_cert.clone();
797        assert!(!a.0.lock().unwrap().approve(cert2, 8).unwrap(), "no device key yet");
798        assert_eq!(a.0.lock().unwrap().roster.chain.approved, vec![peer(&r2)]);
799        assert_eq!(pull(&r2, a).unwrap(), 2);
800        assert!(a.0.lock().unwrap().roster.chain.approved.is_empty());
801        assert!(a.0.lock().unwrap().roster.chain_view().head().unwrap().members.contains(&peer(&r2)));
802        // A revoked device cannot be admitted again.
803        let c_cert = c.0.lock().unwrap().our_cert.clone();
804        assert!(matches!(a.0.lock().unwrap().admit(c_cert, 7), Err(SyncError::Refused(ref x)) if x == "revoked"));
805    }
806
807    #[test]
808    fn concurrent_rotations_settle_on_one_head() {
809        let user = Keypair::generate_ed25519();
810        let g = linked(&user, &["a", "b"]);
811        let (a, b) = (&g[0], &g[1]);
812        a.0.lock().unwrap().rotate(1).unwrap();
813        pull(b, a).unwrap();
814        let ra = a.0.lock().unwrap().rotate(2).unwrap();
815        let rb = b.0.lock().unwrap().rotate(2).unwrap();
816        assert_ne!(ra, rb);
817        a.0.lock().unwrap().local_op(3, typ::BOOKMARKS, "a-1", vec![1]);
818        assert_eq!(pull(b, a).unwrap(), 1);
819        pull(a, b).unwrap();
820        let h = head(a).unwrap();
821        assert_eq!(head(b).as_deref(), Some(h.as_str()));
822        assert_eq!(h, ra.clone().min(rb.clone()), "the lower id wins a tie");
823        assert!(a.0.lock().unwrap().keys.has(&ra) && a.0.lock().unwrap().keys.has(&rb));
824    }
825
826    #[test]
827    fn two_first_roots_made_at_once_settle_on_one() {
828        // A links B, then C, before anyone syncs. B knows only A and itself, sees itself
829        // as the lowest and starts a root; C knows all three and starts another.
830        let user = Keypair::generate_ed25519();
831        let mut g = linked(&user, &["a", "b", "c"]);
832        g.sort_by_key(peer);
833        let (lo, mid, hi) = (&g[0], &g[1], &g[2]);
834        let lo_cert = lo.0.lock().unwrap().our_cert.clone();
835        let lo_key = lo.0.lock().unwrap().roster.chain.device(&peer(lo)).cloned().unwrap();
836        {
837            let mut st = mid.0.lock().unwrap();
838            st.roster.certs.retain(|c| c.peer_id != peer(lo));
839            st.roster.chain.devices.retain(|d| d.peer_id != peer(lo));
840            st.rotate(1).unwrap();
841            st.roster.upsert(lo_cert.clone());
842            st.roster.chain.devices.push(lo_key);
843        }
844        lo.0.lock().unwrap().rotate(1).unwrap();
845        // The device that linked the late one approved it.
846        hi.0.lock().unwrap().approve(lo_cert, 2).unwrap();
847        for _ in 0..3 {
848            for i in 0..3 {
849                for j in 0..3 {
850                    if i != j {
851                        let _ = pull(&g[i], &g[j]);
852                    }
853                }
854            }
855        }
856        let heads: Vec<_> = g.iter().map(head).collect();
857        assert!(heads[0].is_some() && heads.iter().all(|h| *h == heads[0]), "{heads:?}");
858        for s in &g {
859            assert!(matches!(s.0.lock().unwrap().key_status(), KeyStatus::Current { .. }));
860        }
861    }
862
863    #[test]
864    fn a_late_root_and_a_revoked_creator_do_not_move_the_head() {
865        let user = Keypair::generate_ed25519();
866        let g = linked(&user, &["a", "b", "c"]);
867        let (a, b, c) = (&g[0], &g[1], &g[2]);
868        a.0.lock().unwrap().rotate(1).unwrap();
869        pull(b, a).unwrap();
870        pull(c, a).unwrap();
871        a.0.lock().unwrap().revoke(&user, &peer(c), 2).unwrap();
872        let h = head(a).unwrap();
873        // C, unaware, rotates off the root it still holds. Its rotation stops counting
874        // once its revocation is known, so it never becomes the head.
875        c.0.lock().unwrap().rotate(3).unwrap();
876        c.0.lock().unwrap().rotate(4).unwrap();
877        assert!(c.0.lock().unwrap().roster.chain_view().head().unwrap().epoch > a.0.lock().unwrap().roster.chain_view().head().unwrap().epoch);
878        // A seed holder with a fresh node starts its own root that includes everyone.
879        let uid = user::user_id(&user.public());
880        let mk = Keypair::generate_ed25519();
881        let (ms, _) = state(&user, &mk, &uid, "minted", &["bookmarks"]);
882        {
883            let mut m = ms.lock().unwrap();
884            let r = a.0.lock().unwrap().roster.clone();
885            let mut plain =
886                Roster { epoch: r.epoch, certs: r.certs.clone(), chain: KeyChain { devices: r.chain.devices.clone(), ..Default::default() } };
887            plain.certs.retain(|x| x.active());
888            let key = m.user_key.clone();
889            m.roster.merge(&plain, &key, &WEIRDNET);
890            m.rotate(1).unwrap();
891            assert!(m.roster.chain_view().head().unwrap().epoch > 2, "it outnumbers the real head");
892        }
893        let minted_cert = ms.lock().unwrap().our_cert.clone();
894        let minted_chain = ms.lock().unwrap().roster.chain.clone();
895        let c_roster = c.0.lock().unwrap().roster.clone();
896        {
897            let mut st = a.0.lock().unwrap();
898            let key = st.user_key.clone();
899            st.roster.merge(&c_roster, &key, &WEIRDNET);
900            st.roster.upsert(minted_cert);
901            st.roster.chain.merge(&minted_chain);
902            st.refresh_keys();
903            assert_eq!(st.roster.head_id().as_deref(), Some(h.as_str()));
904            assert!(!st.needs_rotation());
905        }
906    }
907
908    #[test]
909    fn revoking_the_device_that_started_the_chain_keeps_the_chain() {
910        let user = Keypair::generate_ed25519();
911        let g = linked(&user, &["a", "b", "c"]);
912        let (a, b, c) = (&g[0], &g[1], &g[2]);
913        let root = c.0.lock().unwrap().rotate(1).unwrap();
914        pull(a, c).unwrap();
915        pull(b, c).unwrap();
916        a.0.lock().unwrap().revoke(&user, &peer(c), 2).unwrap();
917        let h = head(a).unwrap();
918        assert_ne!(h, root);
919        assert_eq!(a.0.lock().unwrap().roster.chain_view().root.as_deref(), Some(root.as_str()), "the chain C started lives on");
920        a.0.lock().unwrap().local_op(3, typ::BOOKMARKS, "a-1", vec![1]);
921        pull(b, a).unwrap();
922        assert_eq!(head(b).as_deref(), Some(h.as_str()));
923        assert!(matches!(b.0.lock().unwrap().key_status(), KeyStatus::Current { .. }));
924        assert_eq!(records(b), vec!["a-1"]);
925        // What C makes on its own after the revocation does not count.
926        let _ = pull(c, a);
927        let _ = c.0.lock().unwrap().rotate(4);
928        let c_roster = c.0.lock().unwrap().roster.clone();
929        let mut st = a.0.lock().unwrap();
930        st.roster.chain.merge(&c_roster.chain);
931        assert_eq!(st.roster.head_id().as_deref(), Some(h.as_str()));
932        assert!(!c.0.lock().unwrap().keys.has(&h));
933    }
934
935    #[test]
936    fn a_head_that_still_includes_a_revoked_device_is_replaced() {
937        let user = Keypair::generate_ed25519();
938        let g = linked(&user, &["a", "b", "c"]);
939        let (a, b, c) = (&g[0], &g[1], &g[2]);
940        let root = a.0.lock().unwrap().rotate(1).unwrap();
941        pull(b, a).unwrap();
942        // Revoked without a rotation (a 0.2 device, or one without its node key).
943        b.0.lock().unwrap().roster.revoke(&WEIRDNET, &user, &peer(c), 2).unwrap();
944        assert!(b.0.lock().unwrap().needs_rotation());
945        pull(b, a).unwrap();
946        let h = head(b).unwrap();
947        assert_ne!(h, root);
948        assert!(!b.0.lock().unwrap().needs_rotation());
949        pull(a, b).unwrap();
950        assert_eq!(head(a).as_deref(), Some(h.as_str()));
951        assert!(!a.0.lock().unwrap().roster.chain_view().head().unwrap().members.contains(&peer(c)));
952    }
953
954    #[test]
955    fn the_first_rotation_starts_once_every_linked_device_has_a_key() {
956        let user = Keypair::generate_ed25519();
957        let uid = user::user_id(&user.public());
958        let (ka, kb) = (Keypair::generate_ed25519(), Keypair::generate_ed25519());
959        let (sa, _) = state(&user, &ka, &uid, "a", &["bookmarks"]);
960        let (sb, _) = state(&user, &kb, &uid, "b", &["bookmarks"]);
961        for s in [&sa, &sb] {
962            s.lock().unwrap().auto_first_rotation = true;
963        }
964        assert!(!sa.lock().unwrap().first_rotation_due(), "one device: nothing to rotate for");
965        let a = (sa.clone(), start_node(ka, node_config(true), sa.clone()).unwrap());
966        let b = (sb.clone(), start_node(kb, node_config(true), sb.clone()).unwrap());
967        // The first link: each learns the other's cert, not yet its device key.
968        let (ca, cb) = (sa.lock().unwrap().our_cert.clone(), sb.lock().unwrap().our_cert.clone());
969        sa.lock().unwrap().roster.upsert(cb);
970        sb.lock().unwrap().roster.upsert(ca);
971        for s in [&sa, &sb] {
972            let st = s.lock().unwrap();
973            assert!(!st.first_rotation_due());
974            assert_eq!(st.devices_without_key().len(), 1, "the other device has no key yet");
975        }
976        let (low, high) = if peer(&a) < peer(&b) { (&a, &b) } else { (&b, &a) };
977        sa.lock().unwrap().local_op(1, typ::BOOKMARKS, "a-1", vec![1]);
978        // The higher peer pulls first: it learns the lower one's key, but leaves the
979        // first rotation to it.
980        pull(high, low).unwrap();
981        assert_eq!(head(high), None);
982        assert!(low.0.lock().unwrap().first_rotation_due(), "the hello brought the other key");
983        pull(low, high).unwrap();
984        let root = head(low).expect("the lowest peer started the chain");
985        assert!(!low.0.lock().unwrap().first_rotation_due());
986        pull(high, low).unwrap();
987        assert_eq!(head(high).as_deref(), Some(root.as_str()));
988        assert!(matches!(high.0.lock().unwrap().key_status(), KeyStatus::Current { .. }));
989        assert_eq!(records(&b), vec!["a-1"]);
990        // Never again: later passes keep the same head.
991        pull(low, high).unwrap();
992        pull(high, low).unwrap();
993        assert_eq!(head(low).as_deref(), Some(root.as_str()));
994        assert_eq!(head(high).as_deref(), Some(root.as_str()));
995    }
996
997    #[test]
998    fn an_upgrade_rotates_once_and_waits_for_every_device_key() {
999        let user = Keypair::generate_ed25519();
1000        let g = linked(&user, &["a", "b", "c"]);
1001        // C has not upgraded yet: drop its device key everywhere.
1002        let c_peer = peer(&g[2]);
1003        for s in &g {
1004            let mut st = s.0.lock().unwrap();
1005            st.roster.chain.devices.retain(|d| d.peer_id != c_peer);
1006            st.auto_first_rotation = true;
1007        }
1008        for x in &g[..2] {
1009            let st = x.0.lock().unwrap();
1010            assert_eq!(st.devices_without_key().iter().map(|c| c.peer_id.clone()).collect::<Vec<_>>(), vec![c_peer.clone()]);
1011            assert!(!st.first_rotation_due());
1012        }
1013        assert_eq!(g[0].0.lock().unwrap().rotate_if_first_due(1).unwrap(), None);
1014        // C upgrades: its key spreads with its hellos, and the lowest peer rotates once.
1015        g[2].0.lock().unwrap().publish_device_key(2).unwrap();
1016        for i in 0..3 {
1017            for j in 0..3 {
1018                if i != j {
1019                    let _ = pull(&g[i], &g[j]);
1020                }
1021            }
1022        }
1023        for _ in 0..2 {
1024            for i in 0..3 {
1025                for j in 0..3 {
1026                    if i != j {
1027                        pull(&g[i], &g[j]).unwrap();
1028                    }
1029                }
1030            }
1031        }
1032        let heads: Vec<_> = g.iter().map(head).collect();
1033        assert!(heads[0].is_some() && heads.iter().all(|h| *h == heads[0]), "{heads:?}");
1034        for s in &g {
1035            let st = s.0.lock().unwrap();
1036            assert_eq!(st.roster.chain.rotations.len(), 1, "exactly one first rotation");
1037            assert!(matches!(st.key_status(), KeyStatus::Current { .. }));
1038        }
1039    }
1040
1041    fn pull_t(a: &Sn, b: &Sn, typ: &str) -> Result<usize> {
1042        pull_from(&mut a.0.lock().unwrap(), &a.1, b.1.peer_id(), &addrs(&b.1), typ)
1043    }
1044
1045    /// Every entry of `rid` in `typ` that `s` holds, oldest first.
1046    fn versions(s: &Sn, typ: &str, rid: &str) -> Vec<crate::LogEntry> {
1047        let st = s.0.lock().unwrap();
1048        let mut v: Vec<crate::LogEntry> = st
1049            .log
1050            .cursors()
1051            .keys()
1052            .flat_map(|n| st.log.iter_node(n).filter(|e| e.typ == typ && e.record_id == rid).cloned().collect::<Vec<_>>())
1053            .collect();
1054        v.sort_by(|a, b| a.hlc.cmp_total(&b.hlc));
1055        v
1056    }
1057
1058    fn read(s: &Sn, e: &crate::LogEntry) -> Result<Vec<u8>> {
1059        match s.0.lock().unwrap().read(e)? {
1060            crate::RecordValue::Ready(v) => Ok(v.to_vec()),
1061            crate::RecordValue::Pending { missing } => Err(SyncError::Protocol(format!("{} chunks missing", missing.len()))),
1062        }
1063    }
1064
1065    fn latest(s: &Sn, typ: &str, rid: &str) -> Result<Vec<u8>> {
1066        let e = versions(s, typ, rid).pop().ok_or_else(|| SyncError::Protocol(format!("no {rid}")))?;
1067        read(s, &e)
1068    }
1069
1070    fn big(len: usize, salt: u8) -> Vec<u8> {
1071        (0..len).map(|i| ((i * 131 + salt as usize) % 251) as u8).collect()
1072    }
1073
1074    fn sealed() -> RecordOptions {
1075        RecordOptions { sealed: true, ..Default::default() }
1076    }
1077
1078    #[test]
1079    fn a_record_larger_than_a_page_syncs_in_chunks() {
1080        let user = Keypair::generate_ed25519();
1081        let g = linked(&user, &["a", "b", "c"]);
1082        let (a, b, c) = (&g[0], &g[1], &g[2]);
1083        for s in &g {
1084            s.0.lock().unwrap().configure("notes", RecordOptions::default()).unwrap();
1085        }
1086        let lazy = RecordOptions { limits: crate::Limits { eager_chunks: false, ..Default::default() }, ..Default::default() };
1087        c.0.lock().unwrap().configure("notes", lazy).unwrap();
1088        let data = big(1024 * 1024 + 17, 1);
1089        {
1090            let mut st = a.0.lock().unwrap();
1091            st.write(1, "notes", "small", b"short").unwrap();
1092            st.write_with_fallback(2, "notes", "answer", &data, b"clipped preview".to_vec()).unwrap();
1093            assert!(st.log.get(&st.our_node, 1).unwrap().value.is_none(), "a small plain value is a plain op");
1094            let chunks = st.log.iter_node(&st.our_node).filter(|e| e.typ == chunk_type("notes")).count();
1095            assert_eq!(chunks, data.len().div_ceil(crate::Limits::default().chunk_size));
1096            // The same value again reuses this node's chunks.
1097            st.write(3, "notes", "copy", &data).unwrap();
1098            assert_eq!(st.log.iter_node(&st.our_node).filter(|e| e.typ == chunk_type("notes")).count(), chunks);
1099            assert!(matches!(st.write(4, "notes", "huge", &big(17 * 1024 * 1024, 2)), Err(SyncError::Protocol(_))));
1100            assert!(st.write(4, &chunk_type("notes"), "x", b"y").is_err());
1101        }
1102        assert_eq!(pull_t(b, a, "notes").unwrap(), 3);
1103        assert_eq!(latest(b, "notes", "small").unwrap(), b"short");
1104        assert_eq!(latest(b, "notes", "answer").unwrap(), data);
1105        assert_eq!(latest(b, "notes", "copy").unwrap(), data);
1106        let e = versions(b, "notes", "answer").pop().unwrap();
1107        assert_eq!(e.op, b"clipped preview", "older peers and plain readers see the fallback");
1108        assert!(b.0.lock().unwrap().log.pending_blobs("notes").is_empty());
1109
1110        // C pulls chunks only when asked, and here from B, which relays A's chunks.
1111        assert_eq!(pull_t(c, b, "notes").unwrap(), 3);
1112        assert!(
1113            matches!(c.0.lock().unwrap().read(&e).unwrap(), crate::RecordValue::Pending { ref missing } if missing.len() == data.len().div_ceil(crate::Limits::default().chunk_size))
1114        );
1115        assert_eq!(
1116            pull_chunks(&mut c.0.lock().unwrap(), &c.1, b.1.peer_id(), &addrs(&b.1), "notes").unwrap(),
1117            data.len().div_ceil(crate::Limits::default().chunk_size)
1118        );
1119        assert_eq!(latest(c, "notes", "answer").unwrap(), data);
1120    }
1121
1122    #[test]
1123    fn sealed_records_follow_rotation_across_three_devices() {
1124        let user = Keypair::generate_ed25519();
1125        let uid = user::user_id(&user.public());
1126        let g = linked(&user, &["a", "b", "c"]);
1127        let (a, b, c) = (&g[0], &g[1], &g[2]);
1128        for s in &g {
1129            s.0.lock().unwrap().configure("secrets", sealed()).unwrap();
1130        }
1131        // Seed-derived keys are held by every seed holder: nothing is sealed under them.
1132        assert!(matches!(a.0.lock().unwrap().write(1, "secrets", "k1", b"one"), Err(SyncError::Refused(ref r)) if r == "no-epoch-key"));
1133        let root = a.0.lock().unwrap().rotate(1).unwrap();
1134        let secret = big(150_000, 3);
1135        {
1136            let mut st = a.0.lock().unwrap();
1137            st.write(2, "secrets", "k1", b"one").unwrap();
1138            st.write(3, "secrets", "big", &secret).unwrap();
1139        }
1140        pull_t(b, a, "secrets").unwrap();
1141        pull_t(c, a, "secrets").unwrap();
1142        for (s, label) in [(a, "a"), (b, "b"), (c, "c")] {
1143            assert!(s.0.lock().unwrap().keys.has(&root), "{label}");
1144            assert_eq!(latest(s, "secrets", "k1").unwrap(), b"one", "{label}");
1145            assert_eq!(latest(s, "secrets", "big").unwrap(), secret, "{label}");
1146        }
1147        // At rest, the entry holds ciphertext and an empty fallback.
1148        let e = versions(b, "secrets", "k1").pop().unwrap();
1149        assert!(e.op.is_empty());
1150        let v = e.value.clone().unwrap();
1151        assert_eq!(v.seal.as_ref().unwrap().key, root);
1152        assert!(!v.body.windows(3).any(|w| w == b"one"));
1153        // An unsealed entry in a sealed type (a seed holder writing around the seal) is refused.
1154        let forged = crate::LogEntry { value: None, op: b"evil".to_vec(), ..e.clone() };
1155        assert!(b.0.lock().unwrap().read(&forged).is_err());
1156
1157        // A revokes C and rotates; new and updated secrets go under the new head.
1158        let (second, a_written) = {
1159            let mut st = a.0.lock().unwrap();
1160            st.revoke(&user, &peer(c), 9).unwrap();
1161            let head = st.roster.head_id().unwrap();
1162            let from = st.log.cursor(&st.our_node);
1163            st.write(10, "secrets", "k2", b"two").unwrap();
1164            st.write(11, "secrets", "k1", b"one, changed").unwrap();
1165            st.write(12, "secrets", "big2", &big(150_000, 4)).unwrap();
1166            (head, from)
1167        };
1168        assert_ne!(second, root);
1169        pull_t(b, a, "secrets").unwrap();
1170        assert_eq!(head(b).as_deref(), Some(second.as_str()));
1171        assert_eq!(latest(b, "secrets", "k2").unwrap(), b"two");
1172        assert_eq!(latest(b, "secrets", "k1").unwrap(), b"one, changed");
1173        assert_eq!(latest(b, "secrets", "big2").unwrap(), big(150_000, 4));
1174        let k1 = versions(b, "secrets", "k1");
1175        assert_eq!(read(b, &k1[0]).unwrap(), b"one", "members keep older epochs readable");
1176
1177        // C is refused, and even holding A's raw entries (a backup, a relay) it cannot open
1178        // anything written after the rotation, though it holds the seed and the root key.
1179        assert!(matches!(pull_t(c, a, "secrets"), Err(SyncError::Refused(ref r)) if r == "revoked"));
1180        let leaked: Vec<crate::LogEntry> = {
1181            let st = a.0.lock().unwrap();
1182            st.log.iter_node(&st.our_node).filter(|e| e.seq > a_written).cloned().collect()
1183        };
1184        {
1185            let mut st = c.0.lock().unwrap();
1186            let page = crate::LogPage { node_id: NodeId(peer(a)), from_seq: a_written + 1, to_seq: a_written + leaked.len() as u64, ops: leaked };
1187            st.log.integrate(&page);
1188            assert!(st.keys.has(&root) && !st.keys.has(&second));
1189        }
1190        for rid in ["k2", "k1", "big2"] {
1191            assert!(matches!(latest(c, "secrets", rid), Err(SyncError::Crypto(_))), "c must not read {rid}");
1192        }
1193        assert_eq!(read(c, &versions(c, "secrets", "k1")[0]).unwrap(), b"one", "what it read before stays what it was");
1194
1195        // Optional re-seal moves the record still under the root key to the head key.
1196        let done = a.0.lock().unwrap().reseal_stale(13, "secrets").unwrap();
1197        assert_eq!(done, vec!["big".to_string()]);
1198        assert!(a.0.lock().unwrap().reseal_stale(14, "secrets").unwrap().is_empty());
1199        pull_t(b, a, "secrets").unwrap();
1200        let resealed = versions(b, "secrets", "big").pop().unwrap();
1201        assert_eq!(resealed.value.as_ref().unwrap().seal.as_ref().unwrap().key, second);
1202        assert_eq!(read(b, &resealed).unwrap(), secret);
1203        {
1204            let mut st = c.0.lock().unwrap();
1205            let a_log = a.0.lock().unwrap();
1206            let ops: Vec<crate::LogEntry> = a_log.log.iter_node(&a_log.our_node).cloned().collect();
1207            st.log.integrate(&crate::LogPage { node_id: a_log.our_node.clone(), from_seq: 1, to_seq: ops.len() as u64, ops });
1208            assert!(st.log.pending_blobs("secrets").is_empty(), "c holds every chunk");
1209        }
1210        assert!(matches!(read(c, &resealed), Err(SyncError::Crypto(_))));
1211
1212        // B writes under the head too, and A reads it.
1213        b.0.lock().unwrap().write(15, "secrets", "k3", b"three").unwrap();
1214        pull_t(a, b, "secrets").unwrap();
1215        assert_eq!(latest(a, "secrets", "k3").unwrap(), b"three");
1216
1217        // A device restored and admitted later reads the secrets of both epochs.
1218        let rk = Keypair::generate_ed25519();
1219        let (rs, _) = state(&user, &rk, &uid, "restored", &["bookmarks"]);
1220        let r = (rs.clone(), start_node(rk, node_config(true), rs).unwrap());
1221        r.0.lock().unwrap().configure("secrets", sealed()).unwrap();
1222        let cert = r.0.lock().unwrap().our_cert.clone();
1223        a.0.lock().unwrap().approve(cert, 16).unwrap();
1224        pull_t(&r, a, "secrets").unwrap();
1225        for (rid, want) in [("k1", b"one, changed".to_vec()), ("k2", b"two".to_vec()), ("k3", b"three".to_vec()), ("big", secret.clone())] {
1226            assert_eq!(latest(&r, "secrets", rid).unwrap(), want, "{rid}");
1227        }
1228        assert_eq!(read(&r, &versions(&r, "secrets", "k1")[0]).unwrap(), b"one");
1229    }
1230}