1use crate::error::{Result, SyncError};
30use crate::net::SyncState;
31use crate::protocol::{decode, encode};
32use crate::roster::Roster;
33use serde::{Deserialize, Serialize};
34use std::collections::{BTreeMap, BTreeSet};
35use weirdnet_keys::exchange::{self, ExchangeSecret};
36use weirdnet_keys::mac::HmacSha256;
37use weirdnet_keys::{Key32, Sealed, kdf, open, seal};
38use weirdnet_net::profile::WEIRDNET;
39use weirdnet_net::user::NodeCert;
40use weirdnet_net::{Keypair, PeerId, PublicKey};
41use zeroize::{Zeroize, Zeroizing};
42
43const DEVICE_KEY: &str = "weirdnet-sync/v1/device-key";
44const ROTATION: &str = "weirdnet-sync/v1/rotation";
45const ADMISSION: &str = "weirdnet-sync/v1/admission";
46const SEAL_KEY: &[u8] = b"weirdnet-sync/v1/seal-key";
47const SEAL_SAS: &[u8] = b"weirdnet-sync/v1/seal-sas";
48
49pub fn peer_public(peer: &str) -> Option<PublicKey> {
51 let pid: PeerId = peer.parse().ok()?;
52 let bytes = pid.to_bytes();
53 if bytes.len() < 2 || bytes[0] != 0 || bytes.len() != 2 + bytes[1] as usize {
54 return None;
55 }
56 let key = PublicKey::try_decode_protobuf(&bytes[2..]).ok()?;
57 (key.to_peer_id() == pid).then_some(key)
58}
59
60fn hash_hex(domain: &[u8], data: &[u8], n: usize) -> String {
61 let mut h = HmacSha256::new(domain);
62 h.update(data);
63 hex::encode(&h.finalize()[..n])
64}
65
66fn key_check(key: &Key32) -> String {
67 let mut h = HmacSha256::new(&key.0);
68 h.update(b"weirdnet-sync/v1/key-check");
69 hex::encode(&h.finalize()[..16])
70}
71
72fn crypto(msg: impl Into<String>) -> SyncError {
73 SyncError::Crypto(msg.into())
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78pub struct DeviceKey {
79 pub peer_id: String,
80 pub exchange: String,
82 pub at_ms: i64,
83 pub sig: Vec<u8>,
84}
85
86impl DeviceKey {
87 fn signing_bytes(peer: &str, exchange: &str, at: i64) -> Vec<u8> {
88 format!("{DEVICE_KEY}\n{peer}\n{exchange}\n{at}").into_bytes()
89 }
90
91 pub fn verify(&self) -> bool {
93 self.public().is_some()
94 && peer_public(&self.peer_id).is_some_and(|k| k.verify(&Self::signing_bytes(&self.peer_id, &self.exchange, self.at_ms), &self.sig))
95 }
96
97 pub fn public(&self) -> Option<[u8; 32]> {
98 hex::decode(&self.exchange).ok()?.try_into().ok()
99 }
100
101 pub fn fingerprint(&self) -> String {
103 let h = hash_hex(b"weirdnet-sync/v1/fingerprint", format!("{}|{}", self.peer_id, self.exchange).as_bytes(), 6);
104 format!("{}-{}-{}", &h[..4], &h[4..8], &h[8..])
105 }
106}
107
108pub struct Device {
111 node: Keypair,
112 exchange: ExchangeSecret,
113}
114
115impl Clone for Device {
116 fn clone(&self) -> Self {
117 Self { node: self.node.clone(), exchange: ExchangeSecret::from_bytes(*self.exchange.to_bytes()) }
118 }
119}
120
121impl std::fmt::Debug for Device {
122 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123 write!(f, "Device({})", self.peer_id())
124 }
125}
126
127impl Device {
128 pub fn from_node_key(node: &Keypair) -> Result<Self> {
129 let bytes = Zeroizing::new(node.to_protobuf_encoding().map_err(|e| crypto(format!("node key: {e}")))?);
130 let k = kdf::hkdf(&bytes, Some(b"weirdnet-sync/v1"), b"weirdnet-sync/v1/exchange")?;
131 Ok(Self { node: node.clone(), exchange: ExchangeSecret::from_bytes(k.0) })
132 }
133
134 pub fn peer_id(&self) -> String {
135 self.node.public().to_peer_id().to_string()
136 }
137
138 pub fn device_key(&self, at_ms: i64) -> Result<DeviceKey> {
139 let peer = self.peer_id();
140 let exchange = hex::encode(self.exchange.public());
141 let sig = self.sign(&DeviceKey::signing_bytes(&peer, &exchange, at_ms))?;
142 Ok(DeviceKey { peer_id: peer, exchange, at_ms, sig })
143 }
144
145 fn sign(&self, bytes: &[u8]) -> Result<Vec<u8>> {
146 self.node.sign(bytes).map_err(|e| crypto(format!("sign: {e}")))
147 }
148}
149
150#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
152pub struct SealedKey {
153 pub peer_id: String,
154 pub sealed: Sealed,
155}
156
157#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159pub struct Rotation {
160 pub epoch: u32,
161 pub parent: Option<String>,
163 pub by: String,
164 pub at_ms: i64,
165 pub eph: String,
167 pub check: String,
169 pub keys: Vec<SealedKey>,
170 pub sig: Vec<u8>,
171}
172
173impl Rotation {
174 fn body(&self) -> Vec<u8> {
175 encode(&(ROTATION, self.epoch, &self.parent, &self.by, self.at_ms, &self.eph, &self.check, &self.keys)).unwrap_or_default()
176 }
177
178 pub fn id(&self) -> String {
179 hash_hex(ROTATION.as_bytes(), &self.body(), 16)
180 }
181
182 fn signed(&self) -> bool {
183 peer_public(&self.by).is_some_and(|k| k.verify(&self.body(), &self.sig))
184 }
185
186 pub fn recipients(&self) -> impl Iterator<Item = &str> {
187 self.keys.iter().map(|k| k.peer_id.as_str())
188 }
189
190 fn transcript(&self, recipient: &str, recipient_pub: &[u8; 32]) -> Vec<u8> {
191 let parent = self.parent.as_deref().unwrap_or("-");
192 format!("{ROTATION}|e{}|{parent}|{}|{recipient}|{}|{}", self.epoch, self.by, self.eph, hex::encode(recipient_pub)).into_bytes()
193 }
194}
195
196#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
199pub struct Admission {
200 pub rotation: String,
201 pub peer_id: String,
202 pub by: String,
203 pub at_ms: i64,
204 pub eph: String,
205 pub sealed: Sealed,
206 pub sig: Vec<u8>,
207}
208
209impl Admission {
210 fn body(&self) -> Vec<u8> {
211 encode(&(ADMISSION, &self.rotation, &self.peer_id, &self.by, self.at_ms, &self.eph, &self.sealed)).unwrap_or_default()
212 }
213
214 pub fn id(&self) -> String {
215 hash_hex(ADMISSION.as_bytes(), &self.body(), 16)
216 }
217
218 fn signed(&self) -> bool {
219 peer_public(&self.by).is_some_and(|k| k.verify(&self.body(), &self.sig))
220 }
221
222 fn transcript(&self, recipient_pub: &[u8; 32]) -> Vec<u8> {
223 format!("{ADMISSION}|{}|{}|{}|{}|{}", self.rotation, self.peer_id, self.by, self.eph, hex::encode(recipient_pub)).into_bytes()
224 }
225}
226
227#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
230pub struct KeyChain {
231 #[serde(default)]
232 pub devices: Vec<DeviceKey>,
233 #[serde(default)]
234 pub rotations: Vec<Rotation>,
235 #[serde(default)]
236 pub admissions: Vec<Admission>,
237 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub root: Option<String>,
240 #[serde(default, skip_serializing_if = "Vec::is_empty")]
243 pub approved: Vec<String>,
244}
245
246impl KeyChain {
247 pub fn is_empty(&self) -> bool {
248 self.devices.is_empty() && self.rotations.is_empty() && self.admissions.is_empty()
249 }
250
251 pub fn is_empty_and_rootless(&self) -> bool {
252 self.is_empty() && self.root.is_none() && self.approved.is_empty()
253 }
254
255 pub fn device(&self, peer_id: &str) -> Option<&DeviceKey> {
256 self.devices.iter().find(|d| d.peer_id == peer_id)
257 }
258
259 pub fn add_device(&mut self, dk: DeviceKey) -> bool {
261 if !dk.verify() {
262 return false;
263 }
264 match self.devices.iter_mut().find(|d| d.peer_id == dk.peer_id) {
265 Some(d) if d.at_ms < dk.at_ms => *d = dk,
266 Some(_) => {}
267 None => self.devices.push(dk),
268 }
269 true
270 }
271
272 pub fn merge(&mut self, other: &KeyChain) {
275 for d in &other.devices {
276 self.add_device(d.clone());
277 }
278 let have: BTreeSet<String> = self.rotations.iter().map(Rotation::id).collect();
279 for r in &other.rotations {
280 if !have.contains(&r.id()) && r.signed() {
281 self.rotations.push(r.clone());
282 }
283 }
284 let have: BTreeSet<String> = self.admissions.iter().map(Admission::id).collect();
285 for a in &other.admissions {
286 if !have.contains(&a.id()) && a.signed() {
287 self.admissions.push(a.clone());
288 }
289 }
290 }
291
292 pub fn shared(&self) -> KeyChain {
294 KeyChain { root: None, approved: Vec::new(), ..self.clone() }
295 }
296}
297
298#[derive(Debug, Clone)]
300pub struct ValidRotation {
301 pub id: String,
302 pub epoch: u32,
303 pub members: BTreeSet<String>,
304 pub clean: bool,
305}
306
307type Ided<'a, T> = (String, &'a T);
309
310#[derive(Debug, Clone, Default)]
312pub struct ChainView {
313 pub root: Option<String>,
314 pub valid: BTreeMap<String, ValidRotation>,
315 pub admissions: Vec<String>,
316 pub head: Option<String>,
317}
318
319impl ChainView {
320 pub fn head(&self) -> Option<&ValidRotation> {
321 self.head.as_ref().and_then(|h| self.valid.get(h))
322 }
323
324 pub fn dirty(&self) -> bool {
326 self.head().is_some_and(|h| !h.clean)
327 }
328}
329
330impl Roster {
331 fn revoked_set(&self) -> BTreeSet<&str> {
332 self.certs.iter().filter(|c| !c.active()).map(|c| c.peer_id.as_str()).collect()
333 }
334
335 fn active_set(&self) -> BTreeSet<&str> {
336 self.active().map(|c| c.peer_id.as_str()).collect()
337 }
338
339 fn signed_parts(&self) -> (Vec<Ided<'_, Rotation>>, Vec<Ided<'_, Admission>>) {
340 let active = self.active_set();
341 let known: BTreeSet<&str> = self.certs.iter().map(|c| c.peer_id.as_str()).collect();
342 let rots = self.chain.rotations.iter().filter(|r| known.contains(r.by.as_str()) && r.signed()).map(|r| (r.id(), r)).collect();
343 let adms = self.chain.admissions.iter().filter(|a| active.contains(a.by.as_str()) && a.signed()).map(|a| (a.id(), a)).collect();
344 (rots, adms)
345 }
346
347 pub fn all_views(&self) -> Vec<ChainView> {
351 let revoked = self.revoked_set();
352 let (rots, adms) = self.signed_parts();
353 rots.iter()
354 .filter(|(_, r)| r.parent.is_none() && r.recipients().any(|p| p == r.by))
355 .map(|root| self.view_from(root, &rots, &adms, &revoked))
356 .collect()
357 }
358
359 pub fn chain_view(&self) -> ChainView {
361 let revoked = self.revoked_set();
362 let (rots, adms) = self.signed_parts();
363
364 let roots: Vec<&(String, &Rotation)> = rots.iter().filter(|(_, r)| r.parent.is_none() && r.recipients().any(|p| p == r.by)).collect();
365 fn order(r: &(String, &Rotation)) -> (u32, String) {
366 (r.1.epoch, r.0.clone())
367 }
368 let mut root = match &self.chain.root {
369 Some(id) => roots.iter().find(|(rid, _)| rid == id).copied(),
370 None => roots.iter().copied().min_by_key(|r| order(r)),
371 };
372 let mut seen = BTreeSet::new();
377 while let Some(cur) = root {
378 if !seen.insert(cur.0.clone()) {
379 break;
380 }
381 let view = self.view_from(cur, &rots, &adms, &revoked);
382 let trusted = |r: &&&(String, &Rotation)| view.valid.values().any(|v| v.members.contains(&r.1.by));
383 match roots.iter().filter(trusted).min_by_key(|r| order(r)) {
384 Some(best) if order(best) < order(cur) => root = Some(best),
385 _ => return view,
386 }
387 }
388 root.map(|r| self.view_from(r, &rots, &adms, &revoked)).unwrap_or_default()
389 }
390
391 fn view_from(
392 &self,
393 (root_id, root_rot): &(String, &Rotation),
394 rots: &[(String, &Rotation)],
395 adms: &[(String, &Admission)],
396 revoked: &BTreeSet<&str>,
397 ) -> ChainView {
398 let mut view = ChainView { root: Some(root_id.clone()), ..ChainView::default() };
399
400 let members_of = |id: &str, r: &Rotation, admitted: &mut Vec<String>| -> BTreeSet<String> {
401 let mut m: BTreeSet<String> = r.recipients().map(str::to_string).collect();
402 loop {
403 let mut grew = false;
404 for (aid, a) in adms.iter().filter(|(_, a)| a.rotation == id) {
405 if m.contains(&a.by) && !revoked.contains(a.by.as_str()) && !m.contains(&a.peer_id) {
406 m.insert(a.peer_id.clone());
407 admitted.push(aid.clone());
408 grew = true;
409 }
410 }
411 if !grew {
412 return m;
413 }
414 }
415 };
416 let mut admitted = Vec::new();
417 let add = |view: &mut ChainView, id: &str, r: &Rotation, admitted: &mut Vec<String>| {
418 let members = members_of(id, r, admitted);
419 let clean = !members.iter().any(|m| revoked.contains(m.as_str()));
420 view.valid.insert(id.to_string(), ValidRotation { id: id.to_string(), epoch: r.epoch, members, clean });
421 };
422 add(&mut view, root_id, root_rot, &mut admitted);
423 loop {
424 let mut grew = false;
425 for (id, r) in rots {
426 if view.valid.contains_key(id) {
427 continue;
428 }
429 let Some(p) = r.parent.as_ref().and_then(|p| view.valid.get(p)) else { continue };
430 if r.epoch == p.epoch.saturating_add(1) && p.members.contains(&r.by) && r.recipients().any(|x| x == r.by) {
431 add(&mut view, id, r, &mut admitted);
432 grew = true;
433 }
434 }
435 if !grew {
436 break;
437 }
438 }
439 let parent: BTreeMap<&str, Option<&str>> = rots.iter().map(|(id, r)| (id.as_str(), r.parent.as_deref())).collect();
443 let mut keep: BTreeSet<String> = BTreeSet::new();
444 for (id, r) in rots {
445 if !view.valid.contains_key(id) || revoked.contains(r.by.as_str()) {
446 continue;
447 }
448 let mut cur = Some(id.as_str());
449 while let Some(c) = cur {
450 if !keep.insert(c.to_string()) {
451 break;
452 }
453 cur = parent.get(c).copied().flatten();
454 }
455 }
456 view.valid.retain(|id, _| keep.contains(id));
457 if view.valid.is_empty() {
458 return ChainView::default();
459 }
460 let kept_adm: BTreeSet<String> = adms.iter().filter(|(_, a)| view.valid.contains_key(&a.rotation)).map(|(id, _)| id.clone()).collect();
461 admitted.retain(|id| kept_adm.contains(id));
462 view.admissions = admitted;
463 view.head = view
464 .valid
465 .values()
466 .max_by(|a, b| (a.epoch, a.clean, std::cmp::Reverse(&a.id)).cmp(&(b.epoch, b.clean, std::cmp::Reverse(&b.id))))
467 .map(|v| v.id.clone());
468 view
469 }
470
471 pub fn head_id(&self) -> Option<String> {
473 self.chain_view().head
474 }
475}
476
477#[derive(Clone, Default, PartialEq)]
480pub struct EpochKeys {
481 keys: BTreeMap<String, (u32, Key32)>,
482}
483
484impl std::fmt::Debug for EpochKeys {
485 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
486 write!(f, "EpochKeys({} keys)", self.keys.len())
487 }
488}
489
490#[derive(Serialize, Deserialize)]
491struct KeyEntry {
492 id: String,
493 epoch: u32,
494 key: [u8; 32],
495}
496
497impl EpochKeys {
498 pub fn new() -> Self {
499 Self::default()
500 }
501 pub fn get(&self, id: &str) -> Option<&Key32> {
502 self.keys.get(id).map(|(_, k)| k)
503 }
504 pub fn has(&self, id: &str) -> bool {
505 self.keys.contains_key(id)
506 }
507 pub fn insert(&mut self, id: String, epoch: u32, key: Key32) {
508 self.keys.insert(id, (epoch, key));
509 }
510 pub fn len(&self) -> usize {
511 self.keys.len()
512 }
513 pub fn is_empty(&self) -> bool {
514 self.keys.is_empty()
515 }
516 pub fn ids(&self) -> impl Iterator<Item = (&str, u32)> {
517 self.keys.iter().map(|(id, (e, _))| (id.as_str(), *e))
518 }
519 pub fn merge(&mut self, other: &EpochKeys) {
521 for (id, v) in &other.keys {
522 self.keys.entry(id.clone()).or_insert_with(|| v.clone());
523 }
524 }
525
526 fn entries(&self, only: impl Fn(&str) -> bool) -> Zeroizing<Vec<u8>> {
527 let mut list: Vec<KeyEntry> =
528 self.keys.iter().filter(|(id, _)| only(id)).map(|(id, (e, k))| KeyEntry { id: id.clone(), epoch: *e, key: k.0 }).collect();
529 let out = Zeroizing::new(encode(&list).unwrap_or_default());
530 for e in &mut list {
531 e.key.zeroize();
532 }
533 out
534 }
535
536 fn absorb(&mut self, bytes: &[u8], accept: impl Fn(&str, &Key32) -> bool) -> Result<usize> {
537 let mut list: Vec<KeyEntry> = decode(bytes)?;
538 let mut n = 0;
539 for e in &mut list {
540 let key = Key32(e.key);
541 e.key.zeroize();
542 if !self.has(&e.id) && accept(&e.id, &key) {
543 self.keys.insert(e.id.clone(), (e.epoch, key));
544 n += 1;
545 }
546 }
547 Ok(n)
548 }
549
550 pub fn export(&self) -> Zeroizing<Vec<u8>> {
552 self.entries(|_| true)
553 }
554
555 pub fn import(bytes: &[u8]) -> Result<Self> {
556 let mut k = Self::new();
557 k.absorb(bytes, |_, _| true)?;
558 Ok(k)
559 }
560}
561
562fn seal_to(eph: &ExchangeSecret, to: &[u8; 32], transcript: &[u8], plain: &[u8]) -> Result<Sealed> {
563 let shared = eph.agree(to).ok_or_else(|| crypto("low-order device key"))?;
564 let (k, _) = exchange::derive(&shared, transcript, SEAL_KEY, SEAL_SAS)?;
565 Ok(seal(&k, plain, transcript)?)
566}
567
568fn open_from(me: &ExchangeSecret, eph_hex: &str, transcript: &[u8], sealed: &Sealed) -> Result<Zeroizing<Vec<u8>>> {
569 let eph: [u8; 32] = hex::decode(eph_hex).ok().and_then(|b| b.try_into().ok()).ok_or_else(|| crypto("bad ephemeral key"))?;
570 let shared = me.agree(&eph).ok_or_else(|| crypto("low-order ephemeral key"))?;
571 let (k, _) = exchange::derive(&shared, transcript, SEAL_KEY, SEAL_SAS)?;
572 Ok(open(&k, sealed, transcript)?)
573}
574
575#[derive(Debug, Clone, PartialEq, Eq)]
577pub enum KeyStatus {
578 Seed,
580 Current { epoch: u32 },
582 NeedsAdmission,
585 Revoked,
587}
588
589impl SyncState {
590 pub fn publish_device_key(&mut self, at_ms: i64) -> Result<()> {
592 let device = self.device.as_ref().ok_or_else(|| SyncError::Protocol("no device key".into()))?;
593 if self.roster.chain.device(&device.peer_id()).is_none() {
594 let dk = device.device_key(at_ms)?;
595 self.roster.chain.add_device(dk);
596 }
597 Ok(())
598 }
599
600 pub fn key_status(&self) -> KeyStatus {
601 if self.roster.get(&self.our_cert.peer_id).is_some_and(|c| !c.active()) || !self.our_cert.active() {
602 return KeyStatus::Revoked;
603 }
604 let view = self.roster.chain_view();
605 match view.head() {
606 None => KeyStatus::Seed,
607 Some(h) if self.keys.has(&h.id) => KeyStatus::Current { epoch: h.epoch },
608 Some(_) => KeyStatus::NeedsAdmission,
609 }
610 }
611
612 pub fn needs_admission(&self) -> bool {
613 self.key_status() == KeyStatus::NeedsAdmission
614 }
615
616 pub fn devices_without_key(&self) -> Vec<NodeCert> {
620 self.roster.active().filter(|c| self.roster.chain.device(&c.peer_id).is_none_or(|d| !d.verify())).cloned().collect()
621 }
622
623 pub fn first_rotation_due(&self) -> bool {
631 let Some(device) = &self.device else { return false };
632 if self.key_status() != KeyStatus::Seed {
633 return false;
634 }
635 let active: Vec<&NodeCert> = self.roster.active().collect();
636 let me = device.peer_id();
637 active.len() >= 2 && active.iter().any(|c| c.peer_id == me) && self.devices_without_key().is_empty() && active.iter().all(|c| c.peer_id >= me)
638 }
639
640 pub fn rotate_if_first_due(&mut self, at_ms: i64) -> Result<Option<String>> {
642 if self.first_rotation_due() { self.rotate(at_ms).map(Some) } else { Ok(None) }
643 }
644
645 pub fn needs_rotation(&self) -> bool {
647 let view = self.roster.chain_view();
648 self.device.is_some() && view.dirty() && view.head().is_some_and(|h| self.keys.has(&h.id)) && self.key_status() != KeyStatus::Revoked
649 }
650
651 pub fn refresh_keys(&mut self) -> usize {
654 let Some(device) = self.device.clone() else { return 0 };
655 let me = device.peer_id();
656 let Some(my_pub) = self.roster.chain.device(&me).and_then(DeviceKey::public) else { return 0 };
657 let view = self.roster.chain_view();
658 let views = self.roster.all_views();
659 let valid = |id: &str| views.iter().any(|v| v.valid.contains_key(id));
660 let mut n = 0;
661 let checks: BTreeMap<String, String> = self.roster.chain.rotations.iter().map(|r| (r.id(), r.check.clone())).collect();
662 for r in &self.roster.chain.rotations {
663 let id = r.id();
664 if !valid(&id) || self.keys.has(&id) {
665 continue;
666 }
667 let Some(sk) = r.keys.iter().find(|k| k.peer_id == me) else { continue };
668 if let Ok(plain) = open_from(&device.exchange, &r.eph, &r.transcript(&me, &my_pub), &sk.sealed)
669 && let Ok(key) = Key32::from_slice(&plain)
670 && key_check(&key) == r.check
671 {
672 self.keys.insert(id, r.epoch, key);
673 n += 1;
674 }
675 }
676 for a in &self.roster.chain.admissions {
677 if a.peer_id != me || !views.iter().any(|v| v.admissions.contains(&a.id())) {
678 continue;
679 }
680 if let Ok(plain) = open_from(&device.exchange, &a.eph, &a.transcript(&my_pub), &a.sealed) {
681 n += self.keys.absorb(&plain, |id, key| valid(id) && checks.get(id).is_some_and(|c| *c == key_check(key))).unwrap_or(0);
682 }
683 }
684 if self.roster.chain.root.is_none()
685 && let Some(root) = &view.root
686 && view.valid.keys().any(|id| self.keys.has(id))
687 {
688 self.roster.chain.root = Some(root.clone());
689 }
690 if let Some(h) = view.head() {
691 self.roster.epoch = self.roster.epoch.max(h.epoch);
692 }
693 n
694 }
695
696 pub fn rotate(&mut self, at_ms: i64) -> Result<String> {
699 let view = self.roster.chain_view();
700 self.rotate_on(&view, at_ms)
701 }
702
703 fn rotate_on(&mut self, view: &ChainView, at_ms: i64) -> Result<String> {
706 let device = self.device.clone().ok_or_else(|| SyncError::Protocol("no device key".into()))?;
707 let me = device.peer_id();
708 self.publish_device_key(at_ms)?;
709 if self.key_status() == KeyStatus::Revoked {
710 return Err(SyncError::Refused("revoked".into()));
711 }
712 let active: BTreeSet<String> = self.roster.active().map(|c| c.peer_id.clone()).collect();
713 let (parent, epoch, mut candidates): (Option<String>, u32, BTreeSet<String>) = match view.head() {
714 Some(h) if !self.keys.has(&h.id) => return Err(SyncError::Refused("needs-admission".into())),
715 Some(h) => (Some(h.id.clone()), h.epoch.saturating_add(1), h.members.clone()),
716 None => (None, self.roster.epoch.saturating_add(1), active.clone()),
717 };
718 candidates.extend(self.roster.chain.approved.iter().cloned());
719 let key = Key32::random()?;
720 let eph = ExchangeSecret::generate();
721 let mut r = Rotation {
722 epoch,
723 parent,
724 by: me.clone(),
725 at_ms,
726 eph: hex::encode(eph.public()),
727 check: key_check(&key),
728 keys: Vec::new(),
729 sig: Vec::new(),
730 };
731 let mut recipients: Vec<String> = candidates.into_iter().filter(|p| active.contains(p)).collect();
732 if !recipients.contains(&me) {
733 recipients.push(me.clone());
734 }
735 for peer in recipients {
736 let Some(public) = self.roster.chain.device(&peer).and_then(DeviceKey::public) else { continue };
737 let sealed = seal_to(&eph, &public, &r.transcript(&peer, &public), &key.0)?;
738 r.keys.push(SealedKey { peer_id: peer, sealed });
739 }
740 r.sig = device.sign(&r.body())?;
741 let id = r.id();
742 if r.parent.is_none() {
743 self.roster.chain.root = Some(id.clone());
744 }
745 self.roster.chain.rotations.push(r);
746 self.keys.insert(id.clone(), epoch, key);
747 self.roster.epoch = self.roster.epoch.max(epoch);
748 Ok(id)
749 }
750
751 pub fn revoke(&mut self, user: &Keypair, peer_id: &str, at_ms: i64) -> Result<NodeCert> {
754 let before = self.roster.chain_view();
755 let cert = self.roster.revoke(&WEIRDNET, user, peer_id, at_ms)?;
756 if self.device.is_some() {
757 self.rotate_on(&before, at_ms)?;
758 }
759 Ok(cert)
760 }
761
762 pub fn approve(&mut self, cert: NodeCert, at_ms: i64) -> Result<bool> {
766 if !WEIRDNET.verify_cert(&self.user_key, &cert) || !cert.active() || cert.user_id != self.user_id {
767 return Err(SyncError::Refused("wrong-user".into()));
768 }
769 if self.roster.get(&cert.peer_id).is_some_and(|c| !c.active()) {
770 return Err(SyncError::Refused("revoked".into()));
771 }
772 let peer = cert.peer_id.clone();
773 self.roster.upsert(cert);
774 if !self.roster.chain.approved.contains(&peer) {
775 self.roster.chain.approved.push(peer.clone());
776 }
777 Ok(self.admit_approved(at_ms).contains(&peer))
778 }
779
780 pub fn admit_approved(&mut self, at_ms: i64) -> Vec<String> {
785 let mut admitted = Vec::new();
786 if self.roster.chain.approved.is_empty() || self.device.is_none() {
787 return admitted;
788 }
789 for peer in self.roster.chain.approved.clone() {
790 let active = self.roster.get(&peer).is_some_and(|c| c.active());
791 let mut done = active;
792 let mut any = false;
793 for view in self.roster.all_views() {
794 let Some(head) = view.head() else { continue };
795 if !self.keys.has(&head.id) {
796 if view.root == self.roster.chain_view().root {
797 done = false;
798 }
799 continue;
800 }
801 any = true;
802 if !active || head.members.contains(&peer) {
803 continue;
804 }
805 let admitted_now = self.roster.chain.device(&peer).is_some()
806 && self.roster.get(&peer).cloned().is_some_and(|cert| self.admit_to(cert, &view, at_ms).unwrap_or(false));
807 if admitted_now {
808 if !admitted.contains(&peer) {
809 admitted.push(peer.clone());
810 }
811 } else {
812 done = false;
813 }
814 }
815 if !active || (any && done) {
816 self.roster.chain.approved.retain(|p| p != &peer);
817 }
818 }
819 admitted
820 }
821
822 pub fn admit(&mut self, cert: NodeCert, at_ms: i64) -> Result<bool> {
827 if !WEIRDNET.verify_cert(&self.user_key, &cert) || !cert.active() || cert.user_id != self.user_id {
828 return Err(SyncError::Refused("wrong-user".into()));
829 }
830 if self.roster.get(&cert.peer_id).is_some_and(|c| !c.active()) {
831 return Err(SyncError::Refused("revoked".into()));
832 }
833 self.roster.upsert(cert.clone());
834 let view = self.roster.chain_view();
835 self.admit_to(cert, &view, at_ms)
836 }
837
838 fn admit_to(&mut self, cert: NodeCert, view: &ChainView, at_ms: i64) -> Result<bool> {
839 let device = self.device.clone().ok_or_else(|| SyncError::Protocol("no device key".into()))?;
840 let peer = cert.peer_id.clone();
841 let Some(head) = view.head() else { return Ok(false) };
842 if !self.keys.has(&head.id) {
843 return Err(SyncError::Refused("needs-admission".into()));
844 }
845 let public = self
846 .roster
847 .chain
848 .device(&peer)
849 .and_then(DeviceKey::public)
850 .ok_or_else(|| SyncError::Protocol(format!("no device key for {peer} yet")))?;
851 let eph = ExchangeSecret::generate();
852 let mut a = Admission {
853 rotation: head.id.clone(),
854 peer_id: peer,
855 by: device.peer_id(),
856 at_ms,
857 eph: hex::encode(eph.public()),
858 sealed: Sealed { nonce: String::new(), ct: String::new() },
859 sig: Vec::new(),
860 };
861 let plain = self.keys.entries(|id| view.valid.contains_key(id));
862 a.sealed = seal_to(&eph, &public, &a.transcript(&public), &plain)?;
863 a.sig = device.sign(&a.body())?;
864 self.roster.chain.admissions.push(a);
865 Ok(true)
866 }
867}
868
869#[cfg(test)]
870mod tests {
871 use super::*;
872
873 #[test]
874 fn a_device_key_verifies_only_for_its_own_node() {
875 let node = Keypair::generate_ed25519();
876 let d = Device::from_node_key(&node).unwrap();
877 let dk = d.device_key(5).unwrap();
878 assert!(dk.verify());
879 assert_eq!(dk.peer_id, node.public().to_peer_id().to_string());
880 assert_eq!(Device::from_node_key(&node).unwrap().device_key(5).unwrap().exchange, dk.exchange);
882 let other = Device::from_node_key(&Keypair::generate_ed25519()).unwrap().device_key(5).unwrap();
883 assert!(!DeviceKey { exchange: other.exchange.clone(), ..dk.clone() }.verify(), "a swapped exchange key fails");
884 assert!(!DeviceKey { peer_id: other.peer_id.clone(), ..dk.clone() }.verify());
885 assert_eq!(dk.fingerprint().len(), 14);
886 assert!(format!("{d:?}").starts_with("Device(12D3"));
887 }
888
889 #[test]
890 fn epoch_keys_export_and_import() {
891 let mut k = EpochKeys::new();
892 k.insert("a".into(), 1, Key32::random().unwrap());
893 k.insert("b".into(), 2, Key32::random().unwrap());
894 let back = EpochKeys::import(&k.export()).unwrap();
895 assert_eq!(back, k);
896 assert_eq!(format!("{k:?}"), "EpochKeys(2 keys)");
897 }
898
899 #[test]
900 fn a_sealed_copy_opens_only_for_its_recipient() {
901 let a = Device::from_node_key(&Keypair::generate_ed25519()).unwrap();
902 let b = Device::from_node_key(&Keypair::generate_ed25519()).unwrap();
903 let eph = ExchangeSecret::generate();
904 let to = a.exchange.public();
905 let s = seal_to(&eph, &to, b"t", b"key").unwrap();
906 let eph_hex = hex::encode(eph.public());
907 assert_eq!(&open_from(&a.exchange, &eph_hex, b"t", &s).unwrap()[..], b"key");
908 assert!(open_from(&b.exchange, &eph_hex, b"t", &s).is_err());
909 assert!(open_from(&a.exchange, &eph_hex, b"other", &s).is_err());
910 }
911
912 #[test]
913 fn peer_public_round_trips() {
914 let k = Keypair::generate_ed25519();
915 let pid = k.public().to_peer_id().to_string();
916 assert_eq!(peer_public(&pid).unwrap(), k.public());
917 assert!(peer_public("not-a-peer").is_none());
918 }
919}