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