1use 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#[derive(Clone)]
25pub struct SyncState {
26 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 pub device: Option<Device>,
40 pub keys: EpochKeys,
42 pub auto_first_rotation: bool,
46 pub records: BTreeMap<String, RecordOptions>,
48 pub voter: Option<crate::lease::Voter>,
51}
52
53impl SyncState {
54 pub fn new(seed: Vec<u8>, user_key: PublicKey, our_cert: NodeCert, node_key: Option<&Keypair>, types: Vec<String>) -> Result<Self> {
57 let device = node_key.map(Device::from_node_key).transpose()?;
58 let mut roster = Roster::new();
59 roster.upsert(our_cert.clone());
60 let mut st = Self {
61 seed: Some(seed),
62 user_id: our_cert.user_id.clone(),
63 user_key,
64 our_node: NodeId::new(our_cert.peer_id.clone()),
65 our_cert,
66 types,
67 roster,
68 log: OpLog::new(),
69 clock: None,
70 device,
71 keys: EpochKeys::new(),
72 auto_first_rotation: true,
73 records: BTreeMap::new(),
74 voter: None,
75 };
76 if st.device.is_some() {
77 st.publish_device_key(st.our_cert.issued_at)?;
78 }
79 Ok(st)
80 }
81
82 pub fn new_service(user_key: PublicKey, our_cert: NodeCert, node_key: &Keypair, types: Vec<String>, bundle: &LinkBundle) -> Result<Self> {
87 let peer = node_key.public().to_peer_id().to_string();
88 if our_cert.peer_id != peer || !our_cert.active() || !WEIRDNET.verify_cert(&user_key, &our_cert) {
89 return Err(SyncError::Refused("the certificate is not this node's".into()));
90 }
91 let g = &bundle.grant;
92 if g.peer_id != peer || g.class != DeviceClass::Service || !g.verify(&user_key) {
93 return Err(SyncError::Refused("the grant is not a service grant for this node".into()));
94 }
95 let mut roster = Roster::new();
96 roster.merge(&bundle.roster, &user_key, &WEIRDNET);
97 roster.upsert(our_cert.clone());
98 roster.add_grant(g.clone(), &user_key);
99 let keys = match (&bundle.keys, g.roster_only()) {
100 (Some(k), false) => EpochKeys::import(k)?,
101 _ => EpochKeys::new(),
102 };
103 let mut st = Self {
104 seed: None,
105 user_id: our_cert.user_id.clone(),
106 user_key,
107 our_node: NodeId::new(our_cert.peer_id.clone()),
108 our_cert,
109 types,
110 roster,
111 log: OpLog::new(),
112 clock: None,
113 device: Some(Device::from_node_key(node_key)?),
114 keys,
115 auto_first_rotation: false,
116 records: BTreeMap::new(),
117 voter: None,
118 };
119 let at = st.our_cert.issued_at;
120 st.publish_device_key(at)?;
121 st.refresh_keys();
122 Ok(st)
123 }
124
125 pub fn is_service(&self) -> bool {
127 self.seed.is_none()
128 }
129
130 fn user_keypair(&self, what: &str) -> Result<Keypair> {
132 let seed = self.seed.as_ref().ok_or_else(|| SyncError::NotPermitted(what.into()))?;
133 let mut bytes: [u8; 32] = seed.as_slice().try_into().map_err(|_| SyncError::Crypto("the identity seed is not 32 bytes".into()))?;
134 let kp = Keypair::ed25519_from_bytes(&mut bytes).map_err(|e| SyncError::Crypto(format!("identity seed: {e}")));
135 bytes.zeroize();
136 kp
137 }
138
139 pub fn grant(&mut self, peer_id: &str, class: DeviceClass, roles: &[String], types: &[String], at_ms: i64) -> Result<DeviceGrant> {
142 let user = self.user_keypair("grant")?;
143 let g = DeviceGrant::sign(&user, peer_id, class, roles, types, at_ms)?;
144 let key = self.user_key.clone();
145 if !self.roster.add_grant(g.clone(), &key) {
146 return Err(SyncError::Protocol("a newer grant for this device is already held".into()));
147 }
148 Ok(g)
149 }
150
151 pub fn service_bundle(&mut self, peer_id: &str, roles: &[String], types: &[String], at_ms: i64) -> Result<LinkBundle> {
159 let grant = self.grant(peer_id, DeviceClass::Service, roles, types, at_ms)?;
160 let keys = if grant.roster_only() {
161 None
162 } else {
163 if self.roster.head_id().is_none() {
164 self.rotate(at_ms)?;
165 }
166 if !matches!(self.key_status(), KeyStatus::Current { .. }) {
167 return Err(SyncError::Refused("needs-admission".into()));
168 }
169 let types = grant.scoped_types().unwrap_or_default();
170 Some(self.keys.scope(&self.user_id, &types)?.export().to_vec())
171 };
172 let mut roster = self.roster.clone();
173 roster.chain = roster.chain.shared();
174 Ok(LinkBundle { roster, grant, keys })
175 }
176
177 pub fn current_key(&self) -> KeyRef {
180 match self.roster.head_id() {
181 Some(id) if self.keys.has(&id) => {
182 let epoch = self.roster.chain_view().head().map(|h| h.epoch).unwrap_or(self.roster.epoch);
183 KeyRef { epoch, id: Some(id) }
184 }
185 _ => KeyRef::seed(self.roster.epoch),
186 }
187 }
188
189 pub fn seal_envelope(&self, key: &KeyRef, typ: &str, peer: &str, msg: &Message) -> Result<Envelope> {
190 match &key.id {
191 None => match &self.seed {
192 Some(seed) => Envelope::seal(seed, &self.user_id, typ, key.epoch, peer, msg),
193 None => Err(SyncError::Crypto("no epoch key yet (a service device has no seed-derived key)".into())),
194 },
195 Some(id) => {
198 let k = self.keys.sync_key(&self.user_id, typ, key.epoch, id)?;
199 Envelope::seal_scoped(&k, id, typ, key.epoch, peer, msg)
200 }
201 }
202 }
203
204 pub fn open_envelope(&self, env: &Envelope, peer: &str) -> Result<Message> {
205 if env.clear {
206 return env.open_clear();
207 }
208 match &env.key {
209 None => match &self.seed {
210 Some(seed) => env.open(seed, &self.user_id, peer),
211 None => Err(SyncError::Crypto("seed-sealed envelope on a service device".into())),
212 },
213 Some(id) => {
214 let k = self.keys.sync_key(&self.user_id, &env.typ, env.epoch, id)?;
215 env.open_scoped(&k, peer)
216 }
217 }
218 }
219
220 fn roster_msg(&self) -> Message {
221 Message::Roster(RosterMsg {
222 certs: self.roster.certs.clone(),
223 epoch: self.roster.epoch,
224 chain: self.roster.chain.shared(),
225 grants: self.roster.grants.clone(),
226 })
227 }
228
229 fn absorb(&mut self, certs: Vec<NodeCert>, epoch: u32, chain: KeyChain, grants: Vec<DeviceGrant>) {
231 let key = self.user_key.clone();
232 self.roster.merge(&Roster { epoch, certs, chain, grants }, &key, &WEIRDNET);
233 self.refresh_keys();
234 }
235
236 #[deprecated(since = "0.5.1", note = "use `SyncState::merge_back`, which also merges the roster, the log, cursors and the clock")]
239 pub fn take_keys_from(&mut self, other: &SyncState) {
240 self.merge_keys(other);
241 }
242
243 fn merge_keys(&mut self, other: &SyncState) -> usize {
244 let before = self.keys.len();
245 self.keys.merge(&other.keys);
246 self.narrow_keys();
247 if self.roster.chain.root.is_none() {
248 self.roster.chain.root = other.roster.chain.root.clone();
249 }
250 self.keys.len().saturating_sub(before)
251 }
252
253 pub fn snapshot(&self) -> SyncState {
257 self.clone()
258 }
259
260 pub fn merge_back(&mut self, pulled: &SyncState) -> MergeOutcome {
277 let mut out = MergeOutcome::default();
278 let revoked_before = self.roster.certs.iter().filter(|c| !c.active()).count();
279 let key = self.user_key.clone();
280 self.roster.merge(&pulled.roster, &key, &WEIRDNET);
281 out.revocations = self.roster.certs.iter().filter(|c| !c.active()).count() - revoked_before;
282 out.keys = self.merge_keys(pulled);
283 out.keys += self.refresh_keys();
284 let admitted: Vec<&str> = pulled.roster.chain.admissions.iter().map(|a| a.peer_id.as_str()).collect();
285 let still = &pulled.roster.chain.approved;
286 self.roster.chain.approved.retain(|p| still.contains(p) || !admitted.contains(&p.as_str()));
287 let mut run: Vec<crate::log::LogEntry> = Vec::new();
289 for e in pulled.log.iter() {
290 if run.first().is_some_and(|f| f.node_id != e.node_id) {
291 out.entries += self.integrate_run(std::mem::take(&mut run));
292 }
293 if self.log.get(&e.node_id, e.seq).is_none() {
294 run.push(e.clone());
295 }
296 }
297 out.entries += self.integrate_run(run);
298 for (node, seq) in pulled.log.cursors() {
299 if seq > self.log.cursor(&node) {
300 self.log.set_cursor(&node, seq);
301 }
302 }
303 for ((node, typ), seq) in pulled.log.type_cursors() {
304 if seq > self.log.cursor_for(&node, &typ) {
305 self.log.set_cursor_for(&node, &typ, seq);
306 }
307 }
308 if let Some(theirs) = &pulled.clock
309 && self.clock.as_ref().is_none_or(|ours| theirs.cmp_total(ours).is_gt())
310 {
311 self.clock = Some(Hlc::receive(self.clock.as_ref(), theirs, now_ms(), self.our_node.clone()));
312 }
313 observe(self, now_ms());
314 out
315 }
316
317 fn integrate_run(&mut self, ops: Vec<crate::log::LogEntry>) -> usize {
318 let (Some(first), Some(last)) = (ops.first(), ops.last()) else { return 0 };
319 let page = crate::log::Page { node_id: first.node_id.clone(), from_seq: first.seq, to_seq: last.seq, ops: ops.clone() };
320 self.log.integrate(&page)
321 }
322
323 fn is_revoked(&self, peer: &str) -> bool {
324 self.roster.get(peer).is_some_and(|c| !c.active())
325 }
326
327 pub fn handle(&mut self, from: &str, env: Envelope) -> Result<Envelope> {
328 if env.clear {
329 return self.handle_clear(from, env);
330 }
331 let key = KeyRef { epoch: env.epoch, id: env.key.clone() };
332 let msg = match self.open_envelope(&env, from) {
334 Ok(m) => m,
335 Err(_) if env.key.as_deref().is_some_and(|id| self.is_service() && self.keys.has(id)) => {
339 return self.refuse(from, &env.typ, env.epoch, "type-not-granted");
340 }
341 Err(_) if env.key.is_some() => return self.refuse(from, &env.typ, env.epoch, "unknown-key"),
342 Err(_) => return self.refuse(from, &env.typ, env.epoch, "wrong-user"),
343 };
344 let head = self.roster.head_id();
345 let at_head = head.is_none() || env.key == head;
348 let granted = |t: &str| self.roster.may_sync(from, t);
352 let reply = match msg {
353 Message::Hello(_) | Message::Pull(_) | Message::Ack(_) if !granted(&env.typ) => Message::Refuse(Refuse::new("type-not-granted")),
354 Message::Pull(ref p) if !granted(&p.typ) => Message::Refuse(Refuse::new("type-not-granted")),
355 Message::Pull(ref p) if p.typ != env.typ => Message::Refuse(Refuse::new("type-mismatch")),
357 Message::LeaseAsk(_) | Message::LeaseFree(_) if !granted(crate::lease::LEASE_TYPE) => Message::Refuse(Refuse::new("type-not-granted")),
358 Message::Hello(h) => self.on_hello(from, h, at_head),
359 Message::Pull(_) if !at_head => Message::Refuse(Refuse::new("epoch-behind")),
360 Message::Pull(_) if self.is_revoked(from) => Message::Refuse(Refuse::new("revoked")),
361 Message::Pull(p) => self.on_pull(p),
362 Message::Ack(a) => Message::Ack(Ack { node_id: a.node_id, last_seq: a.last_seq }),
364 Message::Roster(r) => {
365 self.absorb(r.certs, r.epoch, r.chain, r.grants);
366 self.roster_msg()
367 }
368 m @ (Message::LeaseAsk(_) | Message::LeaseFree(_)) if at_head => self.on_lease(from, m),
370 Message::LeaseAsk(_) | Message::LeaseFree(_) => Message::Refuse(Refuse::new("epoch-behind")),
371 Message::HelloOk(_) | Message::Page(_) | Message::Refuse(_) | Message::LeaseGrant(_) | Message::LeaseDeny(_) => {
372 return Err(SyncError::Protocol("unexpected request".into()));
373 }
374 };
375 self.seal_envelope(&key, &env.typ, from, &reply)
377 }
378
379 fn refuse(&self, from: &str, typ: &str, epoch: u32, reason: &'static str) -> Result<Envelope> {
382 let msg = Message::Refuse(Refuse::new(reason));
383 match &self.seed {
384 Some(seed) => Envelope::seal(seed, &self.user_id, typ, epoch, from, &msg),
385 None => Envelope::clear(typ, epoch, &msg),
386 }
387 }
388
389 fn handle_clear(&mut self, from: &str, env: Envelope) -> Result<Envelope> {
393 let r = match env.open_clear()? {
394 Message::Roster(r) => r,
395 _ => return Err(SyncError::Protocol("unexpected request".into())),
396 };
397 let key = self.user_key.clone();
400 let mut probe = Roster { epoch: self.roster.epoch, certs: self.roster.certs.clone(), ..Roster::default() };
401 probe.merge(&Roster { certs: r.certs.clone(), ..Roster::default() }, &key, &WEIRDNET);
402 let presented = probe.get(from).cloned();
403 let reply = match probe.check_caller(&WEIRDNET, &key, from, presented.as_ref()) {
404 CallerCheck::Linked | CallerCheck::NotAdmitted => {
405 self.absorb(r.certs, r.epoch, r.chain, r.grants);
406 self.roster_msg()
407 }
408 other => Message::Refuse(Refuse::new(other.reason().unwrap_or("wrong-user"))),
409 };
410 Envelope::clear(&env.typ, env.epoch, &reply)
411 }
412
413 fn on_hello(&mut self, from: &str, mut h: Hello, at_head: bool) -> Message {
414 let offered = h.types.len();
416 h.types.retain(|t| self.roster.may_sync(from, t));
417 if offered > 0 && h.types.is_empty() {
418 return Message::Refuse(Refuse::new("type-not-granted"));
419 }
420 let rotated = self.roster.head_id().is_some();
421 let epoch = if rotated { self.roster.epoch } else { h.epoch };
423 let check = self.roster.check_session(
424 &WEIRDNET,
425 &self.user_key,
426 &self.user_id,
427 &crate::roster::SessionOffer { cert: &h.cert, epoch, types: &h.types },
428 &self.types,
429 );
430 if matches!(check, SessionCheck::WrongUser | SessionCheck::Revoked) {
431 return Message::Refuse(Refuse::new(check.reason().unwrap_or("wrong-user")));
432 }
433 if !h.chain.is_empty() {
435 self.roster.chain.merge(&h.chain);
436 self.refresh_keys();
437 self.admit_approved(now_ms() as i64);
440 }
441 if (rotated && !at_head) || check == SessionCheck::EpochBehind {
442 return self.roster_msg();
446 }
447 if check != SessionCheck::Ok {
448 return Message::Refuse(Refuse::new(check.reason().unwrap_or("wrong-user")));
449 }
450 let cursors = self.log.cursors().into_iter().collect();
451 let revocations = self.roster.certs.clone();
454 Message::HelloOk(HelloOk {
455 cert: self.our_cert.clone(),
456 epoch: self.roster.epoch,
457 cursors,
458 revocations,
459 chain: self.roster.chain.shared(),
460 grants: self.roster.grants.clone(),
461 })
462 }
463
464 fn on_pull(&self, p: Pull) -> Message {
465 let served = base_type(&p.typ).unwrap_or(&p.typ);
467 if !self.types.iter().any(|t| t == served) {
468 return Message::Refuse(Refuse::new("type-off"));
469 }
470 let limit = (p.limit as usize).clamp(1, 4096);
471 let known = self.log.cursor_for(&p.node_id, &p.typ);
472 let page = self.log.page_of_type(&p.node_id, &p.typ, p.after_seq, known, limit);
473 Message::Page(crate::protocol::Page { typ: p.typ, page })
474 }
475
476 pub fn local_op(&mut self, now_ms: u64, typ: &str, record_id: &str, op: Vec<u8>) -> u64 {
479 let hlc = self.tick(now_ms);
480 self.log.append(self.our_node.clone(), hlc, typ, record_id, op).seq
481 }
482
483 pub(crate) fn tick(&mut self, now_ms: u64) -> Hlc {
484 let hlc = Hlc::tick(self.clock.as_ref(), now_ms, self.our_node.clone());
485 self.clock = Some(hlc.clone());
486 hlc
487 }
488}
489
490#[derive(Clone, Serialize, Deserialize)]
497pub struct LinkBundle {
498 pub roster: Roster,
499 pub grant: DeviceGrant,
500 #[serde(default, skip_serializing_if = "Option::is_none", with = "crate::bytes::option")]
501 pub keys: Option<Vec<u8>>,
502}
503
504impl LinkBundle {
505 pub fn to_bytes(&self) -> Result<zeroize::Zeroizing<Vec<u8>>> {
506 Ok(zeroize::Zeroizing::new(encode(self)?))
507 }
508
509 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
510 decode(bytes)
511 }
512}
513
514impl Drop for LinkBundle {
515 fn drop(&mut self) {
516 if let Some(k) = self.keys.as_mut() {
517 k.zeroize();
518 }
519 }
520}
521
522impl std::fmt::Debug for LinkBundle {
523 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
524 f.debug_struct("LinkBundle").field("grant", &self.grant).field("keys", &self.keys.is_some()).finish_non_exhaustive()
525 }
526}
527
528pub struct SyncHandler {
530 pub state: Arc<Mutex<SyncState>>,
531}
532
533impl Handler<Vec<u8>, Vec<u8>> for SyncHandler {
534 fn request(&self, from: &PeerId, req: Vec<u8>) -> Vec<u8> {
535 let env: Envelope = match decode(&req) {
536 Ok(e) => e,
537 Err(e) => return error_bytes(&e.to_string()),
538 };
539 let mut st = self.state.lock().expect("sync state");
540 match st.handle(&from.to_string(), env) {
541 Ok(reply) => encode(&reply).unwrap_or_else(|e| error_bytes(&e.to_string())),
542 Err(e) => error_bytes(&e.to_string()),
543 }
544 }
545}
546
547#[derive(Debug, Clone, Default, PartialEq, Eq)]
549#[non_exhaustive]
550pub struct MergeOutcome {
551 pub entries: usize,
553 pub keys: usize,
555 pub revocations: usize,
557}
558
559#[derive(Debug)]
565#[non_exhaustive]
566pub struct PullOutcome {
567 pub applied: usize,
569 pub error: Option<SyncError>,
571}
572
573impl PullOutcome {
574 pub fn is_ok(&self) -> bool {
575 self.error.is_none()
576 }
577
578 pub fn into_result(self) -> Result<usize> {
580 match self.error {
581 None => Ok(self.applied),
582 Some(e) => Err(e),
583 }
584 }
585}
586
587fn error_bytes(msg: &str) -> Vec<u8> {
588 encode(&Message::Refuse(Refuse { reason: format!("codec:{msg}") })).unwrap_or_default()
589}
590
591pub fn node_config(listen_memory: bool) -> NodeConfig {
593 NodeConfig {
594 listen: if listen_memory { vec!["/memory/0".parse().expect("memory addr")] } else { Vec::new() },
595 memory: listen_memory,
596 request_max: PAGE_MAX as u64,
597 response_max: PAGE_MAX as u64,
598 label: "sync".into(),
599 ..Default::default()
600 }
601}
602
603pub fn start_node(key: Keypair, cfg: NodeConfig, state: Arc<Mutex<SyncState>>) -> Result<Node<Vec<u8>, Vec<u8>>> {
605 Ok(Node::start(&SYNC_PROFILE, key, cfg, Arc::new(SyncHandler { state }))?)
606}
607
608pub fn pull_from(state: &mut SyncState, node: &Node<Vec<u8>, Vec<u8>>, peer: PeerId, addrs: &[Multiaddr], typ_name: &str) -> Result<usize> {
618 pull_from_outcome(state, node, peer, addrs, typ_name).into_result()
619}
620
621pub fn pull_from_outcome(state: &mut SyncState, node: &Node<Vec<u8>, Vec<u8>>, peer: PeerId, addrs: &[Multiaddr], typ_name: &str) -> PullOutcome {
624 let mut applied = 0;
625 let error = pull_session(state, node, peer, addrs, typ_name, &mut applied).err();
626 PullOutcome { applied, error }
627}
628
629pub fn pull_from_shared(state: &Mutex<SyncState>, node: &Node<Vec<u8>, Vec<u8>>, peer: PeerId, addrs: &[Multiaddr], typ_name: &str) -> PullOutcome {
637 let mut snap = match state.lock() {
638 Ok(st) => st.snapshot(),
639 Err(_) => return PullOutcome { applied: 0, error: Some(SyncError::Protocol("sync state lock poisoned".into())) },
640 };
641 let out = pull_from_outcome(&mut snap, node, peer, addrs, typ_name);
642 match state.lock() {
643 Ok(mut st) => {
644 st.merge_back(&snap);
645 out
646 }
647 Err(_) => PullOutcome { applied: out.applied, error: Some(SyncError::Protocol("sync state lock poisoned".into())) },
648 }
649}
650
651pub fn pull_types(state: &mut SyncState, node: &Node<Vec<u8>, Vec<u8>>, peer: PeerId, addrs: &[Multiaddr], types: &[&str]) -> PullTypesOutcome {
662 let mut asked: Vec<&str> = Vec::new();
663 for t in types {
664 if !asked.contains(t) {
665 asked.push(t);
666 }
667 }
668 let mut out: Vec<(String, PullOutcome)> = Vec::with_capacity(asked.len());
669 let done = |t: &str, applied: usize, error: Option<SyncError>| (t.to_string(), PullOutcome { applied, error });
670 let own = state.our_cert.peer_id.clone();
672 let mut todo: Vec<&str> = Vec::new();
673 for t in asked {
674 if state.is_service() && !state.roster.may_sync(&own, t) {
675 out.push(done(t, 0, Some(SyncError::Refused("type-not-granted".into()))));
676 } else {
677 todo.push(t);
678 }
679 }
680 let mut session = None;
682 while session.is_none() && !todo.is_empty() {
683 let first = todo[0];
684 match open_session(state, node, peer, addrs, first) {
685 Ok(Some(s)) => session = Some(s),
686 Ok(None) => {
688 out.extend(todo.drain(..).map(|t| done(t, 0, None)));
689 return PullTypesOutcome::ordered(out, types);
690 }
691 Err(SyncError::Refused(r)) if r == "type-not-granted" => {
692 out.push(done(first, 0, Some(SyncError::Refused(r))));
693 todo.remove(0);
694 }
695 Err(e) => {
696 out.extend(todo.drain(..).map(|t| done(t, 0, Some(copy_error(&e)))));
697 return PullTypesOutcome::ordered(out, types);
698 }
699 }
700 }
701 let Some(session) = session else { return PullTypesOutcome::ordered(out, types) };
702 let mut any_ok = false;
703 for t in todo {
704 let mut applied = 0;
705 let error = pull_with(state, node, peer, addrs, &session, t, &mut applied).err();
706 any_ok |= error.is_none();
707 out.push(done(t, applied, error));
708 }
709 if any_ok && let Err(e) = close_session(state) {
710 for (_, o) in out.iter_mut().filter(|(_, o)| o.error.is_none()) {
713 o.error = Some(copy_error(&e));
714 }
715 }
716 PullTypesOutcome::ordered(out, types)
717}
718
719pub fn pull_types_shared(
722 state: &Mutex<SyncState>,
723 node: &Node<Vec<u8>, Vec<u8>>,
724 peer: PeerId,
725 addrs: &[Multiaddr],
726 types: &[&str],
727) -> PullTypesOutcome {
728 let mut snap = match state.lock() {
729 Ok(st) => st.snapshot(),
730 Err(_) => return PullTypesOutcome::failed(types, &SyncError::Protocol("sync state lock poisoned".into())),
731 };
732 let mut out = pull_types(&mut snap, node, peer, addrs, types);
733 match state.lock() {
734 Ok(mut st) => {
735 st.merge_back(&snap);
736 }
737 Err(_) => {
738 for (_, o) in out.types.iter_mut() {
739 o.error = Some(SyncError::Protocol("sync state lock poisoned".into()));
740 }
741 }
742 }
743 out
744}
745
746#[derive(Debug, Default)]
748#[non_exhaustive]
749pub struct PullTypesOutcome {
750 pub types: Vec<(String, PullOutcome)>,
752}
753
754impl PullTypesOutcome {
755 fn ordered(mut got: Vec<(String, PullOutcome)>, asked: &[&str]) -> Self {
756 let mut types = Vec::with_capacity(got.len());
757 for t in asked {
758 if let Some(i) = got.iter().position(|(g, _)| g == t) {
759 types.push(got.swap_remove(i));
760 }
761 }
762 Self { types }
763 }
764
765 fn failed(asked: &[&str], e: &SyncError) -> Self {
766 let mut types: Vec<(String, PullOutcome)> = Vec::new();
767 for t in asked {
768 if !types.iter().any(|(g, _)| g == t) {
769 types.push((t.to_string(), PullOutcome { applied: 0, error: Some(copy_error(e)) }));
770 }
771 }
772 Self { types }
773 }
774
775 pub fn is_ok(&self) -> bool {
777 self.types.iter().all(|(_, o)| o.is_ok())
778 }
779
780 pub fn applied(&self) -> usize {
782 self.types.iter().map(|(_, o)| o.applied).sum()
783 }
784
785 pub fn get(&self, typ: &str) -> Option<&PullOutcome> {
787 self.types.iter().find(|(t, _)| t == typ).map(|(_, o)| o)
788 }
789}
790
791fn copy_error(e: &SyncError) -> SyncError {
793 match e {
794 SyncError::Crypto(m) => SyncError::Crypto(m.clone()),
795 SyncError::Refused(m) => SyncError::Refused(m.clone()),
796 SyncError::Codec(m) => SyncError::Codec(m.clone()),
797 SyncError::Protocol(m) => SyncError::Protocol(m.clone()),
798 SyncError::Io(m) => SyncError::Io(m.clone()),
799 SyncError::Identity(m) => SyncError::Identity(m.clone()),
800 SyncError::NotPermitted(m) => SyncError::NotPermitted(m.clone()),
801 }
802}
803
804fn pull_session(
805 state: &mut SyncState,
806 node: &Node<Vec<u8>, Vec<u8>>,
807 peer: PeerId,
808 addrs: &[Multiaddr],
809 typ_name: &str,
810 applied: &mut usize,
811) -> Result<()> {
812 let Some(session) = open_session(state, node, peer, addrs, typ_name)? else { return Ok(()) };
813 pull_with(state, node, peer, addrs, &session, typ_name, applied)?;
814 close_session(state)
815}
816
817struct Session {
820 key: KeyRef,
821 nodes: Vec<(NodeId, u64)>,
822}
823
824fn open_session(state: &mut SyncState, node: &Node<Vec<u8>, Vec<u8>>, peer: PeerId, addrs: &[Multiaddr], typ_name: &str) -> Result<Option<Session>> {
827 let from = node.peer_id().to_string();
828 if state.key_status() == KeyStatus::RosterOnly || !state.roster.holds_keys(&peer.to_string()) {
830 roster_exchange(state, node, peer, addrs, typ_name)?;
831 return Ok(None);
832 }
833 if state.is_service() && state.current_key().id.is_none() {
836 roster_exchange(state, node, peer, addrs, typ_name)?;
837 if state.current_key().id.is_none() {
838 return Err(SyncError::Refused("needs-admission".into()));
839 }
840 }
841 let mut catch_ups = 0;
842 let mut pushed = false;
843 let ok = loop {
844 let key = state.current_key();
845 let hello = Message::Hello(Hello {
846 cert: state.our_cert.clone(),
847 user_id: state.user_id.clone(),
848 epoch: key.epoch,
849 types: state.types.clone(),
850 our_cursors: state.log.cursors().into_iter().collect(),
851 our_hlc: state.clock.clone().unwrap_or_else(|| Hlc::new(0, 0, state.our_node.clone())),
852 chain: state.roster.chain.shared(),
853 });
854 let env = state.seal_envelope(&key, typ_name, &from, &hello)?;
855 let reply = request(node, peer, addrs, &env)?;
856 let clear = reply.clear;
857 match state.open_envelope(&reply, &from)? {
858 Message::HelloOk(ok) => break ok,
859 Message::Roster(r) if catch_ups < 3 => {
862 state.absorb(r.certs, r.epoch, r.chain, r.grants);
863 if !state.roster.get(&state.our_cert.peer_id).is_none_or(|c| c.active()) {
864 return Err(SyncError::Refused("revoked".into()));
865 }
866 if state.current_key() == key {
867 let reason = if state.needs_admission() { "needs-admission" } else { "epoch-behind" };
868 return Err(SyncError::Refused(reason.into()));
869 }
870 catch_ups += 1;
871 }
872 Message::Refuse(r) if r.reason == "unknown-key" && !pushed => {
877 let env = if clear || state.is_service() {
878 Envelope::clear(typ_name, state.roster.epoch, &state.roster_msg())?
879 } else {
880 state.seal_envelope(&KeyRef::seed(state.roster.epoch), typ_name, &from, &state.roster_msg())?
881 };
882 if let Ok(Message::Roster(back)) = request(node, peer, addrs, &env).and_then(|e| state.open_envelope(&e, &from)) {
883 state.absorb(back.certs, back.epoch, back.chain, back.grants);
884 }
885 pushed = true;
886 }
887 Message::Refuse(r) => return Err(SyncError::Refused(r.reason)),
888 _ => return Err(SyncError::Protocol("expected HelloOk".into())),
889 }
890 };
891 let behind =
895 ok.epoch < state.roster.epoch || peer_lacks_certs(&state.roster, &ok.revocations, &ok.cert) || peer_lacks_grants(&state.roster, &ok.grants);
896 state.absorb(ok.revocations.into_iter().chain([ok.cert]).collect(), ok.epoch, ok.chain, ok.grants);
897 let key = state.current_key();
898 if behind {
899 let env = state.seal_envelope(&key, typ_name, &from, &state.roster_msg())?;
901 let _ = request(node, peer, addrs, &env)?;
902 }
903 let mut nodes: Vec<(NodeId, u64)> = ok.cursors;
904 if !nodes.iter().any(|(n, _)| n.0 == peer.to_string()) {
906 nodes.push((NodeId(peer.to_string()), 0));
907 }
908 Ok(Some(Session { key, nodes }))
909}
910
911fn pull_with(
913 state: &mut SyncState,
914 node: &Node<Vec<u8>, Vec<u8>>,
915 peer: PeerId,
916 addrs: &[Multiaddr],
917 s: &Session,
918 typ_name: &str,
919 applied: &mut usize,
920) -> Result<()> {
921 pull_type(state, node, peer, addrs, &s.key, &s.nodes, typ_name, false, applied)?;
922 if !is_chunk_type(typ_name) && state.options(typ_name).limits.eager_chunks && !state.log.pending_blobs(typ_name).is_empty() {
925 pull_type(state, node, peer, addrs, &s.key, &s.nodes, &chunk_type(typ_name), true, &mut 0)?;
926 }
927 Ok(())
928}
929
930fn close_session(state: &mut SyncState) -> Result<()> {
932 observe(state, now_ms());
933 if state.auto_first_rotation && state.first_rotation_due() {
934 state.rotate(now_ms() as i64)?;
937 } else if state.needs_rotation() {
938 state.rotate(now_ms() as i64)?;
941 }
942 Ok(())
943}
944
945fn peer_lacks_grants(ours: &Roster, theirs: &[DeviceGrant]) -> bool {
948 ours.grants.iter().any(|g| !theirs.iter().any(|t| t.peer_id == g.peer_id && t.issued_at >= g.issued_at))
949}
950
951fn roster_exchange(state: &mut SyncState, node: &Node<Vec<u8>, Vec<u8>>, peer: PeerId, addrs: &[Multiaddr], typ_name: &str) -> Result<()> {
955 let env = Envelope::clear(typ_name, state.roster.epoch, &state.roster_msg())?;
956 let reply = request(node, peer, addrs, &env)?;
957 match reply.open_clear() {
958 Ok(Message::Roster(r)) => state.absorb(r.certs, r.epoch, r.chain, r.grants),
959 Ok(Message::Refuse(r)) => return Err(SyncError::Refused(r.reason)),
960 Ok(_) => return Err(SyncError::Protocol("expected a roster".into())),
961 Err(_) => match state.open_envelope(&reply, &node.peer_id().to_string()) {
963 Ok(Message::Refuse(r)) => return Err(SyncError::Refused(r.reason)),
964 _ => return Err(SyncError::Refused("peer-too-old".into())),
965 },
966 }
967 if !state.roster.get(&state.our_cert.peer_id).is_none_or(|c| c.active()) {
968 return Err(SyncError::Refused("revoked".into()));
969 }
970 observe(state, now_ms());
971 Ok(())
972}
973
974fn peer_lacks_certs(ours: &Roster, theirs: &[NodeCert], their_cert: &NodeCert) -> bool {
977 ours.certs.iter().any(|c| match theirs.iter().chain([their_cert]).find(|t| t.peer_id == c.peer_id) {
978 None => true,
979 Some(t) => t.active() && !c.active(),
980 })
981}
982
983#[allow(clippy::too_many_arguments)]
987fn pull_type(
988 state: &mut SyncState,
989 node: &Node<Vec<u8>, Vec<u8>>,
990 peer: PeerId,
991 addrs: &[Multiaddr],
992 key: &KeyRef,
993 nodes: &[(NodeId, u64)],
994 typ_name: &str,
995 optional: bool,
996 applied: &mut usize,
997) -> Result<()> {
998 let from = node.peer_id().to_string();
999 for (nid, _their) in nodes {
1000 loop {
1001 let after = state.log.cursor_for(nid, typ_name);
1004 let pull = Message::Pull(Pull { node_id: nid.clone(), after_seq: after, typ: typ_name.into(), limit: 512 });
1005 let env = state.seal_envelope(key, typ_name, &from, &pull)?;
1006 let reply = request(node, peer, addrs, &env)?;
1007 match state.open_envelope(&reply, &from)? {
1008 Message::Page(p) => {
1009 let last = p.page.to_seq;
1010 if p.typ != typ_name || p.page.node_id != *nid || p.page.ops.iter().any(|e| e.typ != typ_name) {
1011 return Err(SyncError::Protocol("page of another type or node".into()));
1012 }
1013 if last <= after {
1014 break;
1015 }
1016 *applied += state.log.integrate(&p.page);
1017 state.log.set_cursor_for(nid, typ_name, last);
1018 if last > state.log.cursor(nid) {
1019 state.log.set_cursor(nid, last);
1020 }
1021 let ack = Message::Ack(Ack { node_id: nid.clone(), last_seq: last });
1022 let env = state.seal_envelope(key, typ_name, &from, &ack)?;
1023 let _ = request(node, peer, addrs, &env)?;
1024 }
1025 Message::Refuse(r) if optional && r.reason == "type-off" => return Ok(()),
1026 Message::Refuse(r) => return Err(SyncError::Refused(r.reason)),
1027 _ if optional => return Ok(()),
1029 _ => return Err(SyncError::Protocol("expected Page".into())),
1030 }
1031 }
1032 }
1033 Ok(())
1034}
1035
1036pub fn pull_chunks(state: &mut SyncState, node: &Node<Vec<u8>, Vec<u8>>, peer: PeerId, addrs: &[Multiaddr], typ: &str) -> Result<usize> {
1039 pull_from(state, node, peer, addrs, &chunk_type(typ))
1040}
1041
1042pub fn observe(state: &mut SyncState, wall_ms: u64) {
1045 if let Some(h) = state.log.newest_hlc().cloned()
1046 && state.clock.as_ref().is_none_or(|c| h.cmp_total(c).is_gt())
1047 {
1048 state.clock = Some(Hlc::receive(state.clock.as_ref(), &h, wall_ms, state.our_node.clone()));
1049 }
1050}
1051
1052fn now_ms() -> u64 {
1053 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
1054}
1055
1056fn request(node: &Node<Vec<u8>, Vec<u8>>, peer: PeerId, addrs: &[Multiaddr], env: &Envelope) -> Result<Envelope> {
1057 let bytes = encode(env)?;
1058 let reply = node.request(peer, addrs, bytes)?;
1059 decode(&reply)
1060}
1061
1062#[cfg(test)]
1063mod tests {
1064 use super::*;
1065 use crate::roster::Roster;
1066 use crate::rotation::KeyStatus;
1067 use crate::seal::typ;
1068 use weirdnet_net::user;
1069
1070 const SEED: [u8; 32] = *b"DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD";
1071
1072 fn addrs(n: &Node<Vec<u8>, Vec<u8>>) -> Vec<Multiaddr> {
1073 n.reachable_addrs().into_iter().map(|s| s.parse().expect("addr")).collect()
1074 }
1075
1076 fn pair() -> (Keypair, Keypair, Keypair, String) {
1077 let user = Keypair::generate_ed25519();
1078 let a = Keypair::generate_ed25519();
1079 let b = Keypair::generate_ed25519();
1080 let uid = user::user_id(&user.public());
1081 (user, a, b, uid)
1082 }
1083
1084 fn state(user: &Keypair, node_key: &Keypair, uid: &str, label: &str, types: &[&str]) -> (Arc<Mutex<SyncState>>, NodeId) {
1085 let peer = node_key.public().to_peer_id().to_string();
1086 let cert = Roster::self_certify(&WEIRDNET, user, &peer, label, 1).unwrap();
1087 let mut roster = Roster::new();
1088 roster.upsert(cert.clone());
1089 let node = NodeId(peer.clone());
1090 let st = SyncState {
1091 seed: Some(SEED.to_vec()),
1092 user_id: uid.into(),
1093 user_key: user.public(),
1094 our_cert: cert,
1095 our_node: node.clone(),
1096 types: types.iter().map(|s| s.to_string()).collect(),
1097 roster,
1098 log: OpLog::new(),
1099 clock: None,
1100 device: Some(Device::from_node_key(node_key).unwrap()),
1101 keys: EpochKeys::new(),
1102 auto_first_rotation: false,
1103 records: BTreeMap::new(),
1104 voter: None,
1105 };
1106 let mut st = st;
1107 st.publish_device_key(1).unwrap();
1108 (Arc::new(Mutex::new(st)), node)
1109 }
1110
1111 #[test]
1112 fn two_memory_nodes_hello_and_pull_a_bookmark_op() {
1113 let (user, ka, kb, uid) = pair();
1114 let (sa, _) = state(&user, &ka, &uid, "a", &["bookmarks"]);
1115 let (sb, _) = state(&user, &kb, &uid, "b", &["bookmarks"]);
1116 {
1118 let mut a = sa.lock().unwrap();
1119 a.local_op(1_000, typ::BOOKMARKS, "bm-1", b"{\"title\":\"Rust\"}".to_vec());
1120 a.local_op(1_001, typ::HISTORY, "v-1", b"https://example".to_vec());
1121 a.local_op(1_002, typ::BOOKMARKS, "bm-2", b"{}".to_vec());
1122 }
1123 let na = start_node(ka, node_config(true), sa.clone()).unwrap();
1124 let nb = start_node(kb, node_config(true), sb.clone()).unwrap();
1125 {
1127 let ca = sa.lock().unwrap().our_cert.clone();
1128 let cb = sb.lock().unwrap().our_cert.clone();
1129 sa.lock().unwrap().roster.upsert(cb);
1130 sb.lock().unwrap().roster.upsert(ca);
1131 }
1132 let mut st_b = sb.lock().unwrap();
1133 let applied = pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap();
1134 assert!(applied >= 1, "applied {applied}");
1135 let entry = st_b.log.get(&NodeId(na.peer_id().to_string()), 1).expect("bookmark op");
1136 assert_eq!(entry.typ, typ::BOOKMARKS);
1137 assert_eq!(entry.record_id, "bm-1");
1138 assert_eq!(entry.op, b"{\"title\":\"Rust\"}");
1139 let hist_visible = st_b.log.iter_node(&NodeId(na.peer_id().to_string())).any(|e| e.typ == typ::HISTORY);
1140 assert!(!hist_visible, "a bookmarks pull must not apply history ops");
1141 assert!(st_b.clock.as_ref().is_some_and(|c| c.physical_ms >= 1_000), "the clock moved past what was pulled");
1142
1143 let a_node = NodeId(na.peer_id().to_string());
1147 assert_eq!(st_b.log.get(&a_node, 3).expect("second bookmark").record_id, "bm-2");
1148 st_b.types.push(typ::HISTORY.into());
1149 sa.lock().unwrap().types.push(typ::HISTORY.into());
1150 let applied = pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::HISTORY).unwrap();
1151 assert_eq!(applied, 1);
1152 assert_eq!(st_b.log.get(&a_node, 2).expect("history op").record_id, "v-1");
1153 assert_eq!(pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap(), 0);
1154 assert_eq!(st_b.log.cursor_for(&a_node, typ::HISTORY), 3, "contiguous after both types");
1155 assert_eq!(pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::HISTORY).unwrap(), 0);
1156 assert_eq!(sa.lock().unwrap().log.cursor_for(&a_node, typ::BOOKMARKS), 3, "acks never move the server's cursors");
1157 drop(st_b);
1158
1159 {
1161 let mut a = sa.lock().unwrap();
1162 let b_peer = nb.peer_id().to_string();
1163 a.roster.revoke(&WEIRDNET, &user, &b_peer, 9).unwrap();
1164 }
1165 let mut st_b = sb.lock().unwrap();
1166 let err = pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap_err();
1167 match err {
1168 SyncError::Refused(r) => assert!(r == "revoked" || r == "epoch-behind" || r == "wrong-user", "got {r}"),
1169 other => panic!("expected refuse, got {other}"),
1170 }
1171 }
1172
1173 #[test]
1174 fn a_revocation_reaches_the_other_devices_both_ways() {
1175 let user = Keypair::generate_ed25519();
1176 let uid = user::user_id(&user.public());
1177 let (ka, kb, kc, kd) = (Keypair::generate_ed25519(), Keypair::generate_ed25519(), Keypair::generate_ed25519(), Keypair::generate_ed25519());
1178 let types = ["bookmarks"];
1179 let (sa, _) = state(&user, &ka, &uid, "a", &types);
1180 let (sb, _) = state(&user, &kb, &uid, "b", &types);
1181 let (sc, _) = state(&user, &kc, &uid, "c", &types);
1182 let (sd, _) = state(&user, &kd, &uid, "d", &types);
1183 let all = [&sa, &sb, &sc, &sd];
1184 let certs: Vec<_> = all.iter().map(|s| s.lock().unwrap().our_cert.clone()).collect();
1185 for s in all {
1186 for c in &certs {
1187 s.lock().unwrap().roster.upsert(c.clone());
1188 }
1189 }
1190 sa.lock().unwrap().local_op(1, typ::BOOKMARKS, "a-1", vec![1]);
1191 let na = start_node(ka, node_config(true), sa.clone()).unwrap();
1192 let nb = start_node(kb, node_config(true), sb.clone()).unwrap();
1193 let nc = start_node(kc, node_config(true), sc.clone()).unwrap();
1194 let nd = start_node(kd, node_config(true), sd.clone()).unwrap();
1195 let c_peer = nc.peer_id().to_string();
1196 sa.lock().unwrap().roster.revoke(&WEIRDNET, &user, &c_peer, 9).unwrap();
1197
1198 let applied = pull_from(&mut sb.lock().unwrap(), &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap();
1200 assert_eq!(applied, 1);
1201 {
1202 let b = sb.lock().unwrap();
1203 assert_eq!(b.roster.epoch, 1);
1204 assert!(!b.roster.get(&c_peer).unwrap().active());
1205 }
1206 pull_from(&mut sa.lock().unwrap(), &na, nd.peer_id(), &addrs(&nd), typ::BOOKMARKS).unwrap();
1208 assert_eq!(sd.lock().unwrap().roster.epoch, 1);
1209 assert!(!sd.lock().unwrap().roster.get(&c_peer).unwrap().active());
1210 for (n, label) in [(&nb, "b"), (&nd, "d"), (&na, "a")] {
1212 let err = pull_from(&mut sc.lock().unwrap(), &nc, n.peer_id(), &addrs(n), typ::BOOKMARKS).unwrap_err();
1213 assert!(matches!(err, SyncError::Refused(ref r) if r == "revoked"), "{label}: {err}");
1214 }
1215 }
1216
1217 #[test]
1218 fn a_foreign_user_is_refused() {
1219 let (user_a, ka, _, uid_a) = pair();
1220 let (user_b, kb, _, uid_b) = pair();
1221 let (sa, _) = state(&user_a, &ka, &uid_a, "a", &["bookmarks"]);
1222 let (sb, _) = state(&user_b, &kb, &uid_b, "b", &["bookmarks"]);
1223 let na = start_node(ka, node_config(true), sa.clone()).unwrap();
1224 let nb = start_node(kb, node_config(true), sb.clone()).unwrap();
1225 let mut st_b = sb.lock().unwrap();
1226 let err = pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap_err();
1227 match err {
1228 SyncError::Refused(r) => assert_eq!(r, "wrong-user"),
1229 SyncError::Crypto(_) => {}
1231 other => panic!("expected wrong-user, got {other}"),
1232 }
1233 }
1234
1235 type Sn = (Arc<Mutex<SyncState>>, Node<Vec<u8>, Vec<u8>>);
1236
1237 fn linked(user: &Keypair, labels: &[&str]) -> Vec<Sn> {
1240 let uid = user::user_id(&user.public());
1241 let made: Vec<(Arc<Mutex<SyncState>>, Keypair)> = labels
1242 .iter()
1243 .map(|l| {
1244 let k = Keypair::generate_ed25519();
1245 (state(user, &k, &uid, l, &["bookmarks"]).0, k)
1246 })
1247 .collect();
1248 let certs: Vec<_> = made.iter().map(|(s, _)| s.lock().unwrap().our_cert.clone()).collect();
1249 let chains: Vec<_> = made.iter().map(|(s, _)| s.lock().unwrap().roster.chain.clone()).collect();
1250 for (s, _) in &made {
1251 let mut st = s.lock().unwrap();
1252 for c in &certs {
1253 st.roster.upsert(c.clone());
1254 }
1255 for ch in &chains {
1256 st.roster.chain.merge(ch);
1257 }
1258 }
1259 made.into_iter().map(|(s, k)| (s.clone(), start_node(k, node_config(true), s).unwrap())).collect()
1260 }
1261
1262 fn pull(a: &Sn, b: &Sn) -> Result<usize> {
1263 pull_from(&mut a.0.lock().unwrap(), &a.1, b.1.peer_id(), &addrs(&b.1), typ::BOOKMARKS)
1264 }
1265
1266 fn head(s: &Sn) -> Option<String> {
1267 s.0.lock().unwrap().roster.head_id()
1268 }
1269
1270 fn records(s: &Sn) -> Vec<String> {
1271 let st = s.0.lock().unwrap();
1272 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();
1273 v.sort();
1274 v
1275 }
1276
1277 fn peer(s: &Sn) -> String {
1278 s.1.peer_id().to_string()
1279 }
1280
1281 #[test]
1282 fn a_revoked_device_cannot_read_ops_written_after_the_rotation() {
1283 let user = Keypair::generate_ed25519();
1284 let g = linked(&user, &["a", "b", "c"]);
1285 let (a, b, c) = (&g[0], &g[1], &g[2]);
1286 a.0.lock().unwrap().local_op(1, typ::BOOKMARKS, "before", vec![1]);
1287 assert_eq!(pull(c, a).unwrap(), 1, "c reads what was written before");
1288
1289 let rot = {
1290 let mut st = a.0.lock().unwrap();
1291 st.revoke(&user, &peer(c), 9).unwrap();
1292 st.local_op(10, typ::BOOKMARKS, "after", vec![2]);
1293 st.roster.head_id().unwrap()
1294 };
1295 {
1296 let st = a.0.lock().unwrap();
1297 let view = st.roster.chain_view();
1298 let h = view.head().unwrap();
1299 assert!(h.members.contains(&peer(a)) && h.members.contains(&peer(b)));
1300 assert!(!h.members.contains(&peer(c)), "the revoked device is not sealed a copy");
1301 assert_eq!(st.key_status(), KeyStatus::Current { epoch: h.epoch });
1302 }
1303
1304 assert_eq!(pull(b, a).unwrap(), 2);
1306 assert_eq!(head(b).as_deref(), Some(rot.as_str()));
1307 assert!(b.0.lock().unwrap().keys.has(&rot));
1308
1309 assert!(matches!(pull(c, a), Err(SyncError::Refused(ref r)) if r == "revoked"));
1311 let chain = a.0.lock().unwrap().roster.clone();
1312 {
1313 let mut st = c.0.lock().unwrap();
1314 let key = st.user_key.clone();
1315 st.roster.merge(&chain, &key, &WEIRDNET);
1316 st.refresh_keys();
1317 assert!(!st.keys.has(&rot));
1318 assert_eq!(st.key_status(), KeyStatus::Revoked);
1319 }
1320
1321 let a_node = NodeId(peer(a));
1323 let page_env = {
1324 let bs = b.0.lock().unwrap();
1325 let pull = Message::Pull(Pull { node_id: a_node.clone(), after_seq: 0, typ: typ::BOOKMARKS.into(), limit: 10 });
1326 let env = bs.seal_envelope(&bs.current_key(), typ::BOOKMARKS, &peer(b), &pull).unwrap();
1327 a.0.lock().unwrap().handle(&peer(b), env).unwrap()
1328 };
1329 match b.0.lock().unwrap().open_envelope(&page_env, &peer(b)).unwrap() {
1330 Message::Page(p) => assert!(p.page.ops.iter().any(|e| e.record_id == "after")),
1331 other => panic!("expected a page, got {other:?}"),
1332 }
1333 let cs = c.0.lock().unwrap();
1334 assert!(cs.open_envelope(&page_env, &peer(b)).is_err(), "c holds the seed and every old key, and still cannot open it");
1335 assert!(page_env.open(cs.seed.as_ref().unwrap(), &cs.user_id, &peer(b)).is_err());
1336 for (from, label) in [(peer(c), "as c"), (peer(b), "as b")] {
1338 let pull = Message::Pull(Pull { node_id: a_node.clone(), after_seq: 0, typ: typ::BOOKMARKS.into(), limit: 10 });
1339 let env = cs.seal_envelope(&KeyRef::seed(cs.roster.epoch), typ::BOOKMARKS, &from, &pull).unwrap();
1340 let reply = a.0.lock().unwrap().handle(&from, env).unwrap();
1341 match cs.open_envelope(&reply, &from).unwrap() {
1342 Message::Refuse(r) => assert_eq!(r.reason, "epoch-behind", "{label}"),
1343 other => panic!("{label}: expected a refusal, got {other:?}"),
1344 }
1345 }
1346 drop(cs);
1347
1348 let mint = Keypair::generate_ed25519();
1351 let uid = user::user_id(&user.public());
1352 let (ms, _) = state(&user, &mint, &uid, "minted", &["bookmarks"]);
1353 let mn = start_node(mint, node_config(true), ms.clone()).unwrap();
1354 let minted = (ms, mn);
1355 assert!(matches!(pull(&minted, a), Err(SyncError::Refused(ref r)) if r == "needs-admission"));
1356 assert!(!records(&minted).contains(&"after".to_string()));
1357 }
1358
1359 #[test]
1360 fn the_remaining_devices_converge_after_a_rotation() {
1361 let user = Keypair::generate_ed25519();
1362 let g = linked(&user, &["a", "b", "c", "d"]);
1363 let (a, b, c, d) = (&g[0], &g[1], &g[2], &g[3]);
1364 a.0.lock().unwrap().local_op(1, typ::BOOKMARKS, "a-1", vec![1]);
1365 a.0.lock().unwrap().revoke(&user, &peer(c), 5).unwrap();
1366 a.0.lock().unwrap().local_op(6, typ::BOOKMARKS, "a-2", vec![2]);
1367 b.0.lock().unwrap().local_op(7, typ::BOOKMARKS, "b-1", vec![3]);
1370 assert_eq!(pull(a, b).unwrap(), 1);
1371 assert_eq!(head(b), head(a));
1372 assert_eq!(pull(d, b).unwrap(), 1);
1374 assert_eq!(head(d), head(a));
1375 d.0.lock().unwrap().local_op(8, typ::BOOKMARKS, "d-1", vec![4]);
1376 assert_eq!(pull(a, d).unwrap(), 1);
1377 assert_eq!(pull(b, d).unwrap(), 1);
1378 pull(b, a).unwrap();
1379 pull(d, a).unwrap();
1380 let want = vec!["a-1", "a-2", "b-1", "d-1"];
1381 for (s, label) in [(a, "a"), (b, "b"), (d, "d")] {
1382 assert_eq!(records(s), want, "{label}");
1383 assert!(matches!(s.0.lock().unwrap().key_status(), KeyStatus::Current { .. }), "{label}");
1384 }
1385 assert!(matches!(pull(c, d), Err(SyncError::Refused(ref r)) if r == "revoked"));
1386 }
1387
1388 #[test]
1389 fn a_restored_device_is_re_admitted_and_catches_up() {
1390 let user = Keypair::generate_ed25519();
1391 let g = linked(&user, &["a", "b", "c"]);
1392 let (a, b, c) = (&g[0], &g[1], &g[2]);
1393 a.0.lock().unwrap().local_op(1, typ::BOOKMARKS, "old", vec![1]);
1394 let first = {
1395 let mut st = a.0.lock().unwrap();
1396 st.revoke(&user, &peer(c), 2).unwrap();
1397 st.roster.head_id().unwrap()
1398 };
1399 let second = a.0.lock().unwrap().rotate(3).unwrap();
1400 a.0.lock().unwrap().local_op(4, typ::BOOKMARKS, "new", vec![2]);
1401 pull(b, a).unwrap();
1402
1403 let uid = user::user_id(&user.public());
1405 let rk = Keypair::generate_ed25519();
1406 let (rs, _) = state(&user, &rk, &uid, "restored", &["bookmarks"]);
1407 let r = (rs.clone(), start_node(rk, node_config(true), rs).unwrap());
1408 assert!(matches!(pull(&r, a), Err(SyncError::Refused(ref x)) if x == "needs-admission"));
1409 assert_eq!(r.0.lock().unwrap().key_status(), KeyStatus::NeedsAdmission);
1410 assert!(r.0.lock().unwrap().roster.head_id().is_some(), "it knows the chain moved on");
1411
1412 let cert = r.0.lock().unwrap().our_cert.clone();
1414 let fp = r.0.lock().unwrap().roster.chain.device(&peer(&r)).unwrap().fingerprint();
1415 assert_eq!(a.0.lock().unwrap().roster.chain.device(&peer(&r)).unwrap().fingerprint(), fp);
1416 assert!(a.0.lock().unwrap().admit(cert, 5).unwrap());
1417
1418 assert_eq!(pull(&r, a).unwrap(), 2);
1419 assert_eq!(records(&r), vec!["new", "old"]);
1420 {
1421 let st = r.0.lock().unwrap();
1422 assert!(st.keys.has(&first) && st.keys.has(&second), "older epochs come along for history");
1423 assert!(matches!(st.key_status(), KeyStatus::Current { .. }));
1424 }
1425 r.0.lock().unwrap().local_op(6, typ::BOOKMARKS, "restored-1", vec![3]);
1427 pull(b, a).unwrap();
1428 assert_eq!(pull(b, &r).unwrap(), 1);
1429 let rk2 = Keypair::generate_ed25519();
1432 let (rs2, _) = state(&user, &rk2, &uid, "restored-2", &["bookmarks"]);
1433 let r2 = (rs2.clone(), start_node(rk2, node_config(true), rs2).unwrap());
1434 let cert2 = r2.0.lock().unwrap().our_cert.clone();
1435 assert!(!a.0.lock().unwrap().approve(cert2, 8).unwrap(), "no device key yet");
1436 assert_eq!(a.0.lock().unwrap().roster.chain.approved, vec![peer(&r2)]);
1437 assert_eq!(pull(&r2, a).unwrap(), 2);
1438 assert!(a.0.lock().unwrap().roster.chain.approved.is_empty());
1439 assert!(a.0.lock().unwrap().roster.chain_view().head().unwrap().members.contains(&peer(&r2)));
1440 let c_cert = c.0.lock().unwrap().our_cert.clone();
1442 assert!(matches!(a.0.lock().unwrap().admit(c_cert, 7), Err(SyncError::Refused(ref x)) if x == "revoked"));
1443 }
1444
1445 #[test]
1446 fn concurrent_rotations_settle_on_one_head() {
1447 let user = Keypair::generate_ed25519();
1448 let g = linked(&user, &["a", "b"]);
1449 let (a, b) = (&g[0], &g[1]);
1450 a.0.lock().unwrap().rotate(1).unwrap();
1451 pull(b, a).unwrap();
1452 let ra = a.0.lock().unwrap().rotate(2).unwrap();
1453 let rb = b.0.lock().unwrap().rotate(2).unwrap();
1454 assert_ne!(ra, rb);
1455 a.0.lock().unwrap().local_op(3, typ::BOOKMARKS, "a-1", vec![1]);
1456 assert_eq!(pull(b, a).unwrap(), 1);
1457 pull(a, b).unwrap();
1458 let h = head(a).unwrap();
1459 assert_eq!(head(b).as_deref(), Some(h.as_str()));
1460 assert_eq!(h, ra.clone().min(rb.clone()), "the lower id wins a tie");
1461 assert!(a.0.lock().unwrap().keys.has(&ra) && a.0.lock().unwrap().keys.has(&rb));
1462 }
1463
1464 #[test]
1465 fn two_first_roots_made_at_once_settle_on_one() {
1466 let user = Keypair::generate_ed25519();
1469 let mut g = linked(&user, &["a", "b", "c"]);
1470 g.sort_by_key(peer);
1471 let (lo, mid, hi) = (&g[0], &g[1], &g[2]);
1472 let lo_cert = lo.0.lock().unwrap().our_cert.clone();
1473 let lo_key = lo.0.lock().unwrap().roster.chain.device(&peer(lo)).cloned().unwrap();
1474 {
1475 let mut st = mid.0.lock().unwrap();
1476 st.roster.certs.retain(|c| c.peer_id != peer(lo));
1477 st.roster.chain.devices.retain(|d| d.peer_id != peer(lo));
1478 st.rotate(1).unwrap();
1479 st.roster.upsert(lo_cert.clone());
1480 st.roster.chain.devices.push(lo_key);
1481 }
1482 lo.0.lock().unwrap().rotate(1).unwrap();
1483 hi.0.lock().unwrap().approve(lo_cert, 2).unwrap();
1485 for _ in 0..3 {
1486 for i in 0..3 {
1487 for j in 0..3 {
1488 if i != j {
1489 let _ = pull(&g[i], &g[j]);
1490 }
1491 }
1492 }
1493 }
1494 let heads: Vec<_> = g.iter().map(head).collect();
1495 assert!(heads[0].is_some() && heads.iter().all(|h| *h == heads[0]), "{heads:?}");
1496 for s in &g {
1497 assert!(matches!(s.0.lock().unwrap().key_status(), KeyStatus::Current { .. }));
1498 }
1499 }
1500
1501 #[test]
1502 fn a_late_root_and_a_revoked_creator_do_not_move_the_head() {
1503 let user = Keypair::generate_ed25519();
1504 let g = linked(&user, &["a", "b", "c"]);
1505 let (a, b, c) = (&g[0], &g[1], &g[2]);
1506 a.0.lock().unwrap().rotate(1).unwrap();
1507 pull(b, a).unwrap();
1508 pull(c, a).unwrap();
1509 a.0.lock().unwrap().revoke(&user, &peer(c), 2).unwrap();
1510 let h = head(a).unwrap();
1511 c.0.lock().unwrap().rotate(3).unwrap();
1514 c.0.lock().unwrap().rotate(4).unwrap();
1515 assert!(c.0.lock().unwrap().roster.chain_view().head().unwrap().epoch > a.0.lock().unwrap().roster.chain_view().head().unwrap().epoch);
1516 let uid = user::user_id(&user.public());
1518 let mk = Keypair::generate_ed25519();
1519 let (ms, _) = state(&user, &mk, &uid, "minted", &["bookmarks"]);
1520 {
1521 let mut m = ms.lock().unwrap();
1522 let r = a.0.lock().unwrap().roster.clone();
1523 let mut plain = Roster {
1524 epoch: r.epoch,
1525 certs: r.certs.clone(),
1526 chain: KeyChain { devices: r.chain.devices.clone(), ..Default::default() },
1527 grants: vec![],
1528 };
1529 plain.certs.retain(|x| x.active());
1530 let key = m.user_key.clone();
1531 m.roster.merge(&plain, &key, &WEIRDNET);
1532 m.rotate(1).unwrap();
1533 assert!(m.roster.chain_view().head().unwrap().epoch > 2, "it outnumbers the real head");
1534 }
1535 let minted_cert = ms.lock().unwrap().our_cert.clone();
1536 let minted_chain = ms.lock().unwrap().roster.chain.clone();
1537 let c_roster = c.0.lock().unwrap().roster.clone();
1538 {
1539 let mut st = a.0.lock().unwrap();
1540 let key = st.user_key.clone();
1541 st.roster.merge(&c_roster, &key, &WEIRDNET);
1542 st.roster.upsert(minted_cert);
1543 st.roster.chain.merge(&minted_chain);
1544 st.refresh_keys();
1545 assert_eq!(st.roster.head_id().as_deref(), Some(h.as_str()));
1546 assert!(!st.needs_rotation());
1547 }
1548 }
1549
1550 #[test]
1551 fn revoking_the_device_that_started_the_chain_keeps_the_chain() {
1552 let user = Keypair::generate_ed25519();
1553 let g = linked(&user, &["a", "b", "c"]);
1554 let (a, b, c) = (&g[0], &g[1], &g[2]);
1555 let root = c.0.lock().unwrap().rotate(1).unwrap();
1556 pull(a, c).unwrap();
1557 pull(b, c).unwrap();
1558 a.0.lock().unwrap().revoke(&user, &peer(c), 2).unwrap();
1559 let h = head(a).unwrap();
1560 assert_ne!(h, root);
1561 assert_eq!(a.0.lock().unwrap().roster.chain_view().root.as_deref(), Some(root.as_str()), "the chain C started lives on");
1562 a.0.lock().unwrap().local_op(3, typ::BOOKMARKS, "a-1", vec![1]);
1563 pull(b, a).unwrap();
1564 assert_eq!(head(b).as_deref(), Some(h.as_str()));
1565 assert!(matches!(b.0.lock().unwrap().key_status(), KeyStatus::Current { .. }));
1566 assert_eq!(records(b), vec!["a-1"]);
1567 let _ = pull(c, a);
1569 let _ = c.0.lock().unwrap().rotate(4);
1570 let c_roster = c.0.lock().unwrap().roster.clone();
1571 let mut st = a.0.lock().unwrap();
1572 st.roster.chain.merge(&c_roster.chain);
1573 assert_eq!(st.roster.head_id().as_deref(), Some(h.as_str()));
1574 assert!(!c.0.lock().unwrap().keys.has(&h));
1575 }
1576
1577 #[test]
1578 fn a_head_that_still_includes_a_revoked_device_is_replaced() {
1579 let user = Keypair::generate_ed25519();
1580 let g = linked(&user, &["a", "b", "c"]);
1581 let (a, b, c) = (&g[0], &g[1], &g[2]);
1582 let root = a.0.lock().unwrap().rotate(1).unwrap();
1583 pull(b, a).unwrap();
1584 b.0.lock().unwrap().roster.revoke(&WEIRDNET, &user, &peer(c), 2).unwrap();
1586 assert!(b.0.lock().unwrap().needs_rotation());
1587 pull(b, a).unwrap();
1588 let h = head(b).unwrap();
1589 assert_ne!(h, root);
1590 assert!(!b.0.lock().unwrap().needs_rotation());
1591 pull(a, b).unwrap();
1592 assert_eq!(head(a).as_deref(), Some(h.as_str()));
1593 assert!(!a.0.lock().unwrap().roster.chain_view().head().unwrap().members.contains(&peer(c)));
1594 }
1595
1596 #[test]
1597 fn the_first_rotation_starts_once_every_linked_device_has_a_key() {
1598 let user = Keypair::generate_ed25519();
1599 let uid = user::user_id(&user.public());
1600 let (ka, kb) = (Keypair::generate_ed25519(), Keypair::generate_ed25519());
1601 let (sa, _) = state(&user, &ka, &uid, "a", &["bookmarks"]);
1602 let (sb, _) = state(&user, &kb, &uid, "b", &["bookmarks"]);
1603 for s in [&sa, &sb] {
1604 s.lock().unwrap().auto_first_rotation = true;
1605 }
1606 assert!(!sa.lock().unwrap().first_rotation_due(), "one device: nothing to rotate for");
1607 let a = (sa.clone(), start_node(ka, node_config(true), sa.clone()).unwrap());
1608 let b = (sb.clone(), start_node(kb, node_config(true), sb.clone()).unwrap());
1609 let (ca, cb) = (sa.lock().unwrap().our_cert.clone(), sb.lock().unwrap().our_cert.clone());
1611 sa.lock().unwrap().roster.upsert(cb);
1612 sb.lock().unwrap().roster.upsert(ca);
1613 for s in [&sa, &sb] {
1614 let st = s.lock().unwrap();
1615 assert!(!st.first_rotation_due());
1616 assert_eq!(st.devices_without_key().len(), 1, "the other device has no key yet");
1617 }
1618 let (low, high) = if peer(&a) < peer(&b) { (&a, &b) } else { (&b, &a) };
1619 sa.lock().unwrap().local_op(1, typ::BOOKMARKS, "a-1", vec![1]);
1620 pull(high, low).unwrap();
1623 assert_eq!(head(high), None);
1624 assert!(low.0.lock().unwrap().first_rotation_due(), "the hello brought the other key");
1625 pull(low, high).unwrap();
1626 let root = head(low).expect("the lowest peer started the chain");
1627 assert!(!low.0.lock().unwrap().first_rotation_due());
1628 pull(high, low).unwrap();
1629 assert_eq!(head(high).as_deref(), Some(root.as_str()));
1630 assert!(matches!(high.0.lock().unwrap().key_status(), KeyStatus::Current { .. }));
1631 assert_eq!(records(&b), vec!["a-1"]);
1632 pull(low, high).unwrap();
1634 pull(high, low).unwrap();
1635 assert_eq!(head(low).as_deref(), Some(root.as_str()));
1636 assert_eq!(head(high).as_deref(), Some(root.as_str()));
1637 }
1638
1639 #[test]
1640 fn an_upgrade_rotates_once_and_waits_for_every_device_key() {
1641 let user = Keypair::generate_ed25519();
1642 let g = linked(&user, &["a", "b", "c"]);
1643 let c_peer = peer(&g[2]);
1645 for s in &g {
1646 let mut st = s.0.lock().unwrap();
1647 st.roster.chain.devices.retain(|d| d.peer_id != c_peer);
1648 st.auto_first_rotation = true;
1649 }
1650 for x in &g[..2] {
1651 let st = x.0.lock().unwrap();
1652 assert_eq!(st.devices_without_key().iter().map(|c| c.peer_id.clone()).collect::<Vec<_>>(), vec![c_peer.clone()]);
1653 assert!(!st.first_rotation_due());
1654 }
1655 assert_eq!(g[0].0.lock().unwrap().rotate_if_first_due(1).unwrap(), None);
1656 g[2].0.lock().unwrap().publish_device_key(2).unwrap();
1658 for i in 0..3 {
1659 for j in 0..3 {
1660 if i != j {
1661 let _ = pull(&g[i], &g[j]);
1662 }
1663 }
1664 }
1665 for _ in 0..2 {
1666 for i in 0..3 {
1667 for j in 0..3 {
1668 if i != j {
1669 pull(&g[i], &g[j]).unwrap();
1670 }
1671 }
1672 }
1673 }
1674 let heads: Vec<_> = g.iter().map(head).collect();
1675 assert!(heads[0].is_some() && heads.iter().all(|h| *h == heads[0]), "{heads:?}");
1676 for s in &g {
1677 let st = s.0.lock().unwrap();
1678 assert_eq!(st.roster.chain.rotations.len(), 1, "exactly one first rotation");
1679 assert!(matches!(st.key_status(), KeyStatus::Current { .. }));
1680 }
1681 }
1682
1683 fn pull_t(a: &Sn, b: &Sn, typ: &str) -> Result<usize> {
1684 pull_from(&mut a.0.lock().unwrap(), &a.1, b.1.peer_id(), &addrs(&b.1), typ)
1685 }
1686
1687 fn versions(s: &Sn, typ: &str, rid: &str) -> Vec<crate::LogEntry> {
1689 let st = s.0.lock().unwrap();
1690 let mut v: Vec<crate::LogEntry> = st
1691 .log
1692 .cursors()
1693 .keys()
1694 .flat_map(|n| st.log.iter_node(n).filter(|e| e.typ == typ && e.record_id == rid).cloned().collect::<Vec<_>>())
1695 .collect();
1696 v.sort_by(|a, b| a.hlc.cmp_total(&b.hlc));
1697 v
1698 }
1699
1700 fn read(s: &Sn, e: &crate::LogEntry) -> Result<Vec<u8>> {
1701 match s.0.lock().unwrap().read(e)? {
1702 crate::RecordValue::Ready(v) => Ok(v.to_vec()),
1703 crate::RecordValue::Pending { missing } => Err(SyncError::Protocol(format!("{} chunks missing", missing.len()))),
1704 }
1705 }
1706
1707 fn latest(s: &Sn, typ: &str, rid: &str) -> Result<Vec<u8>> {
1708 let e = versions(s, typ, rid).pop().ok_or_else(|| SyncError::Protocol(format!("no {rid}")))?;
1709 read(s, &e)
1710 }
1711
1712 fn big(len: usize, salt: u8) -> Vec<u8> {
1713 (0..len).map(|i| ((i * 131 + salt as usize) % 251) as u8).collect()
1714 }
1715
1716 fn sealed() -> RecordOptions {
1717 RecordOptions { sealed: true, ..Default::default() }
1718 }
1719
1720 #[test]
1721 fn a_record_larger_than_a_page_syncs_in_chunks() {
1722 let user = Keypair::generate_ed25519();
1723 let g = linked(&user, &["a", "b", "c"]);
1724 let (a, b, c) = (&g[0], &g[1], &g[2]);
1725 for s in &g {
1726 s.0.lock().unwrap().configure("notes", RecordOptions::default()).unwrap();
1727 }
1728 let lazy = RecordOptions { limits: crate::Limits { eager_chunks: false, ..Default::default() }, ..Default::default() };
1729 c.0.lock().unwrap().configure("notes", lazy).unwrap();
1730 let data = big(1024 * 1024 + 17, 1);
1731 {
1732 let mut st = a.0.lock().unwrap();
1733 st.write(1, "notes", "small", b"short").unwrap();
1734 st.write_with_fallback(2, "notes", "answer", &data, b"clipped preview".to_vec()).unwrap();
1735 assert!(st.log.get(&st.our_node, 1).unwrap().value.is_none(), "a small plain value is a plain op");
1736 let chunks = st.log.iter_node(&st.our_node).filter(|e| e.typ == chunk_type("notes")).count();
1737 assert_eq!(chunks, data.len().div_ceil(crate::Limits::default().chunk_size));
1738 st.write(3, "notes", "copy", &data).unwrap();
1740 assert_eq!(st.log.iter_node(&st.our_node).filter(|e| e.typ == chunk_type("notes")).count(), chunks);
1741 assert!(matches!(st.write(4, "notes", "huge", &big(17 * 1024 * 1024, 2)), Err(SyncError::Protocol(_))));
1742 assert!(st.write(4, &chunk_type("notes"), "x", b"y").is_err());
1743 }
1744 assert_eq!(pull_t(b, a, "notes").unwrap(), 3);
1745 assert_eq!(latest(b, "notes", "small").unwrap(), b"short");
1746 assert_eq!(latest(b, "notes", "answer").unwrap(), data);
1747 assert_eq!(latest(b, "notes", "copy").unwrap(), data);
1748 let e = versions(b, "notes", "answer").pop().unwrap();
1749 assert_eq!(e.op, b"clipped preview", "older peers and plain readers see the fallback");
1750 assert!(b.0.lock().unwrap().log.pending_blobs("notes").is_empty());
1751
1752 assert_eq!(pull_t(c, b, "notes").unwrap(), 3);
1754 assert!(
1755 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))
1756 );
1757 assert_eq!(
1758 pull_chunks(&mut c.0.lock().unwrap(), &c.1, b.1.peer_id(), &addrs(&b.1), "notes").unwrap(),
1759 data.len().div_ceil(crate::Limits::default().chunk_size)
1760 );
1761 assert_eq!(latest(c, "notes", "answer").unwrap(), data);
1762 }
1763
1764 #[test]
1765 fn sealed_records_follow_rotation_across_three_devices() {
1766 let user = Keypair::generate_ed25519();
1767 let uid = user::user_id(&user.public());
1768 let g = linked(&user, &["a", "b", "c"]);
1769 let (a, b, c) = (&g[0], &g[1], &g[2]);
1770 for s in &g {
1771 s.0.lock().unwrap().configure("secrets", sealed()).unwrap();
1772 }
1773 assert!(matches!(a.0.lock().unwrap().write(1, "secrets", "k1", b"one"), Err(SyncError::Refused(ref r)) if r == "no-epoch-key"));
1775 let root = a.0.lock().unwrap().rotate(1).unwrap();
1776 let secret = big(150_000, 3);
1777 {
1778 let mut st = a.0.lock().unwrap();
1779 st.write(2, "secrets", "k1", b"one").unwrap();
1780 st.write(3, "secrets", "big", &secret).unwrap();
1781 }
1782 pull_t(b, a, "secrets").unwrap();
1783 pull_t(c, a, "secrets").unwrap();
1784 for (s, label) in [(a, "a"), (b, "b"), (c, "c")] {
1785 assert!(s.0.lock().unwrap().keys.has(&root), "{label}");
1786 assert_eq!(latest(s, "secrets", "k1").unwrap(), b"one", "{label}");
1787 assert_eq!(latest(s, "secrets", "big").unwrap(), secret, "{label}");
1788 }
1789 let e = versions(b, "secrets", "k1").pop().unwrap();
1791 assert!(e.op.is_empty());
1792 let v = e.value.clone().unwrap();
1793 assert_eq!(v.seal.as_ref().unwrap().key, root);
1794 assert!(!v.body.windows(3).any(|w| w == b"one"));
1795 let forged = crate::LogEntry { value: None, op: b"evil".to_vec(), ..e.clone() };
1797 assert!(b.0.lock().unwrap().read(&forged).is_err());
1798
1799 let (second, a_written) = {
1801 let mut st = a.0.lock().unwrap();
1802 st.revoke(&user, &peer(c), 9).unwrap();
1803 let head = st.roster.head_id().unwrap();
1804 let from = st.log.cursor(&st.our_node);
1805 st.write(10, "secrets", "k2", b"two").unwrap();
1806 st.write(11, "secrets", "k1", b"one, changed").unwrap();
1807 st.write(12, "secrets", "big2", &big(150_000, 4)).unwrap();
1808 (head, from)
1809 };
1810 assert_ne!(second, root);
1811 pull_t(b, a, "secrets").unwrap();
1812 assert_eq!(head(b).as_deref(), Some(second.as_str()));
1813 assert_eq!(latest(b, "secrets", "k2").unwrap(), b"two");
1814 assert_eq!(latest(b, "secrets", "k1").unwrap(), b"one, changed");
1815 assert_eq!(latest(b, "secrets", "big2").unwrap(), big(150_000, 4));
1816 let k1 = versions(b, "secrets", "k1");
1817 assert_eq!(read(b, &k1[0]).unwrap(), b"one", "members keep older epochs readable");
1818
1819 assert!(matches!(pull_t(c, a, "secrets"), Err(SyncError::Refused(ref r)) if r == "revoked"));
1822 let leaked: Vec<crate::LogEntry> = {
1823 let st = a.0.lock().unwrap();
1824 st.log.iter_node(&st.our_node).filter(|e| e.seq > a_written).cloned().collect()
1825 };
1826 {
1827 let mut st = c.0.lock().unwrap();
1828 let page = crate::LogPage { node_id: NodeId(peer(a)), from_seq: a_written + 1, to_seq: a_written + leaked.len() as u64, ops: leaked };
1829 st.log.integrate(&page);
1830 assert!(st.keys.has(&root) && !st.keys.has(&second));
1831 }
1832 for rid in ["k2", "k1", "big2"] {
1833 assert!(matches!(latest(c, "secrets", rid), Err(SyncError::Crypto(_))), "c must not read {rid}");
1834 }
1835 assert_eq!(read(c, &versions(c, "secrets", "k1")[0]).unwrap(), b"one", "what it read before stays what it was");
1836
1837 let done = a.0.lock().unwrap().reseal_stale(13, "secrets").unwrap();
1839 assert_eq!(done, vec!["big".to_string()]);
1840 assert!(a.0.lock().unwrap().reseal_stale(14, "secrets").unwrap().is_empty());
1841 pull_t(b, a, "secrets").unwrap();
1842 let resealed = versions(b, "secrets", "big").pop().unwrap();
1843 assert_eq!(resealed.value.as_ref().unwrap().seal.as_ref().unwrap().key, second);
1844 assert_eq!(read(b, &resealed).unwrap(), secret);
1845 {
1846 let mut st = c.0.lock().unwrap();
1847 let a_log = a.0.lock().unwrap();
1848 let ops: Vec<crate::LogEntry> = a_log.log.iter_node(&a_log.our_node).cloned().collect();
1849 st.log.integrate(&crate::LogPage { node_id: a_log.our_node.clone(), from_seq: 1, to_seq: ops.len() as u64, ops });
1850 assert!(st.log.pending_blobs("secrets").is_empty(), "c holds every chunk");
1851 }
1852 assert!(matches!(read(c, &resealed), Err(SyncError::Crypto(_))));
1853
1854 b.0.lock().unwrap().write(15, "secrets", "k3", b"three").unwrap();
1856 pull_t(a, b, "secrets").unwrap();
1857 assert_eq!(latest(a, "secrets", "k3").unwrap(), b"three");
1858
1859 let rk = Keypair::generate_ed25519();
1861 let (rs, _) = state(&user, &rk, &uid, "restored", &["bookmarks"]);
1862 let r = (rs.clone(), start_node(rk, node_config(true), rs).unwrap());
1863 r.0.lock().unwrap().configure("secrets", sealed()).unwrap();
1864 let cert = r.0.lock().unwrap().our_cert.clone();
1865 a.0.lock().unwrap().approve(cert, 16).unwrap();
1866 pull_t(&r, a, "secrets").unwrap();
1867 for (rid, want) in [("k1", b"one, changed".to_vec()), ("k2", b"two".to_vec()), ("k3", b"three".to_vec()), ("big", secret.clone())] {
1868 assert_eq!(latest(&r, "secrets", rid).unwrap(), want, "{rid}");
1869 }
1870 assert_eq!(read(&r, &versions(&r, "secrets", "k1")[0]).unwrap(), b"one");
1871 }
1872
1873 struct RefuseLaterPages {
1875 state: Arc<Mutex<SyncState>>,
1876 on: Arc<std::sync::atomic::AtomicBool>,
1877 }
1878
1879 impl Handler<Vec<u8>, Vec<u8>> for RefuseLaterPages {
1880 fn request(&self, from: &PeerId, req: Vec<u8>) -> Vec<u8> {
1881 if self.on.load(std::sync::atomic::Ordering::SeqCst)
1882 && let Ok(env) = decode::<Envelope>(&req)
1883 {
1884 let st = self.state.lock().unwrap();
1885 if let Ok(Message::Pull(p)) = st.open_envelope(&env, &from.to_string())
1886 && p.after_seq > 0
1887 {
1888 return encode(&st.refuse(&from.to_string(), &env.typ, env.epoch, "test-later-page").unwrap()).unwrap();
1889 }
1890 }
1891 SyncHandler { state: self.state.clone() }.request(from, req)
1892 }
1893 }
1894
1895 #[test]
1896 fn a_refused_later_page_keeps_the_pages_before_it() {
1897 let (user, ka, kb, uid) = pair();
1898 let (sa, _) = state(&user, &ka, &uid, "a", &["bookmarks"]);
1899 let (sb, _) = state(&user, &kb, &uid, "b", &["bookmarks"]);
1900 {
1901 let ca = sa.lock().unwrap().our_cert.clone();
1902 let cb = sb.lock().unwrap().our_cert.clone();
1903 sa.lock().unwrap().roster.upsert(cb);
1904 sb.lock().unwrap().roster.upsert(ca);
1905 let mut a = sa.lock().unwrap();
1906 for i in 0..600u64 {
1907 a.local_op(1_000 + i, typ::BOOKMARKS, &format!("bm-{i}"), vec![i as u8]);
1908 }
1909 }
1910 let on = Arc::new(std::sync::atomic::AtomicBool::new(true));
1911 let na = Node::start(&SYNC_PROFILE, ka, node_config(true), Arc::new(RefuseLaterPages { state: sa.clone(), on: on.clone() })).unwrap();
1912 let nb = start_node(kb, node_config(true), sb.clone()).unwrap();
1913 let a_node = NodeId(na.peer_id().to_string());
1914
1915 let mut copy = sb.lock().unwrap().snapshot();
1917 let out = pull_from_outcome(&mut copy, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS);
1918 assert_eq!(out.applied, 512);
1919 assert!(!out.is_ok());
1920 assert!(matches!(out.error, Some(SyncError::Refused(ref r)) if r == "test-later-page"), "{:?}", out.error);
1921 assert_eq!(copy.log.cursor_for(&a_node, typ::BOOKMARKS), 512);
1922 let mut copy = sb.lock().unwrap().snapshot();
1924 assert!(pull_from(&mut copy, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).is_err());
1925 assert_eq!(copy.log.iter_node(&a_node).count(), 512);
1926 assert!(sb.lock().unwrap().log.iter_node(&a_node).next().is_none(), "snapshots leave the shared state alone");
1927
1928 let out = pull_from_shared(&sb, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS);
1930 assert_eq!((out.applied, out.is_ok()), (512, false));
1931 assert_eq!(sb.lock().unwrap().log.iter_node(&a_node).count(), 512);
1932 assert_eq!(sb.lock().unwrap().log.cursor_for(&a_node, typ::BOOKMARKS), 512);
1933 on.store(false, std::sync::atomic::Ordering::SeqCst);
1934 let out = pull_from_shared(&sb, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS);
1935 assert!(out.is_ok(), "{:?}", out.error);
1936 assert_eq!(out.applied, 88);
1937 let b = sb.lock().unwrap();
1938 assert_eq!(b.log.iter_node(&a_node).count(), 600);
1939 assert_eq!(b.log.cursor_for(&a_node, typ::BOOKMARKS), 600);
1940 assert!(b.clock.as_ref().is_some_and(|c| c.physical_ms >= 1_599));
1941 }
1942
1943 #[test]
1944 fn two_shared_states_pull_from_each_other_at_once() {
1945 let user = Keypair::generate_ed25519();
1946 let g = linked(&user, &["a", "b"]);
1947 let (a, b) = (&g[0], &g[1]);
1948 a.0.lock().unwrap().local_op(1, typ::BOOKMARKS, "from-a", vec![1]);
1949 b.0.lock().unwrap().local_op(2, typ::BOOKMARKS, "from-b", vec![2]);
1950 let (ra, rb) = std::thread::scope(|s| {
1953 let ta = s.spawn(|| pull_from_shared(&a.0, &a.1, b.1.peer_id(), &addrs(&b.1), typ::BOOKMARKS));
1954 let tb = s.spawn(|| pull_from_shared(&b.0, &b.1, a.1.peer_id(), &addrs(&a.1), typ::BOOKMARKS));
1955 (ta.join().unwrap(), tb.join().unwrap())
1956 });
1957 assert!(ra.is_ok() && rb.is_ok(), "{:?} {:?}", ra.error, rb.error);
1958 assert_eq!((ra.applied, rb.applied), (1, 1));
1959 assert_eq!(records(a), ["from-a", "from-b"]);
1960 assert_eq!(records(b), ["from-a", "from-b"]);
1961 }
1962
1963 #[test]
1964 fn merge_back_folds_records_keys_roster_and_clock() {
1965 let user = Keypair::generate_ed25519();
1966 let g = linked(&user, &["a", "b", "c"]);
1967 let (a, b, c) = (&g[0], &g[1], &g[2]);
1968 for s in &g {
1969 s.0.lock().unwrap().configure("notes", RecordOptions::default()).unwrap();
1970 }
1971 let data = big(300 * 1024 + 5, 7);
1972 {
1973 let mut st = a.0.lock().unwrap();
1974 st.write(5_000, "notes", "small", b"short").unwrap();
1975 st.write(5_001, "notes", "answer", &data).unwrap();
1976 }
1977 let a_node = NodeId(peer(a));
1978
1979 let mut snap = b.0.lock().unwrap().snapshot();
1981 assert_eq!(pull_from(&mut snap, &b.1, a.1.peer_id(), &addrs(&a.1), "notes").unwrap(), 2);
1982 let head = snap.rotate(6_000).unwrap();
1983 let pulled = snap.log.iter_node(&a_node).count();
1984 assert!(pulled > 2, "the value came in chunks");
1985
1986 {
1988 let mut st = b.0.lock().unwrap();
1989 st.write(5_500, "notes", "local", b"mine").unwrap();
1990 st.roster.revoke(&WEIRDNET, &user, &peer(c), 5_600).unwrap();
1991 assert!(st.keys.is_empty());
1992 }
1993
1994 let out = b.0.lock().unwrap().merge_back(&snap);
1995 assert_eq!(out.entries, pulled);
1996 assert!(out.keys >= 1);
1997 assert_eq!(out.revocations, 0);
1998 {
1999 let st = b.0.lock().unwrap();
2000 assert!(!st.roster.get(&peer(c)).unwrap().active(), "the snapshot's active copy never un-revokes");
2001 assert!(st.keys.has(&head));
2002 assert_eq!(st.roster.chain.root, snap.roster.chain.root);
2003 assert_eq!(st.current_key().id, Some(head.clone()));
2004 assert_eq!(st.log.cursor_for(&a_node, "notes"), snap.log.cursor_for(&a_node, "notes"));
2005 assert_eq!(st.log.cursor(&a_node), snap.log.cursor(&a_node));
2006 assert!(st.log.pending_blobs("notes").is_empty());
2007 assert!(st.clock.as_ref().unwrap().cmp_total(snap.clock.as_ref().unwrap()).is_ge());
2008 }
2009 assert_eq!(latest(b, "notes", "small").unwrap(), b"short");
2010 assert_eq!(latest(b, "notes", "answer").unwrap(), data);
2011 assert_eq!(latest(b, "notes", "local").unwrap(), b"mine");
2012 let seq = b.0.lock().unwrap().write(1, "notes", "after", b"x").unwrap();
2014 let st = b.0.lock().unwrap();
2015 let after = st.log.get(&st.our_node, seq).unwrap().hlc.clone();
2016 assert!(st.log.iter_node(&a_node).all(|e| after.cmp_total(&e.hlc).is_gt()));
2017 drop(st);
2018 assert_eq!(b.0.lock().unwrap().merge_back(&snap), MergeOutcome::default());
2020 }
2021
2022 #[test]
2026 fn a_device_linked_elsewhere_reaches_the_others_in_one_pass() {
2027 let user = Keypair::generate_ed25519();
2028 let uid = user::user_id(&user.public());
2029 for a_pulls in [true, false] {
2030 let g = linked(&user, &["a", "b"]);
2031 let (a, b) = (&g[0], &g[1]);
2032 let kc = Keypair::generate_ed25519();
2033 let (sc, _) = state(&user, &kc, &uid, "c", &["bookmarks"]);
2034 let c_cert = sc.lock().unwrap().our_cert.clone();
2035 let c_peer = c_cert.peer_id.clone();
2036 b.0.lock().unwrap().approve(c_cert, 5).unwrap();
2037 assert!(a.0.lock().unwrap().roster.get(&c_peer).is_none());
2038 let out = if a_pulls {
2039 pull_from_shared(&a.0, &a.1, b.1.peer_id(), &addrs(&b.1), typ::BOOKMARKS)
2040 } else {
2041 pull_from_shared(&b.0, &b.1, a.1.peer_id(), &addrs(&a.1), typ::BOOKMARKS)
2042 };
2043 assert!(out.is_ok(), "{:?}", out.error);
2044 let st = a.0.lock().unwrap();
2045 assert!(st.roster.get(&c_peer).is_some_and(|c| c.active()), "a_pulls={a_pulls}: A never learned C");
2046 assert_eq!(st.roster.epoch, b.0.lock().unwrap().roster.epoch);
2047 }
2048 }
2049}