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