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