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