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