Skip to main content

weirdnet_sync/
plan.rs

1//! Plans (since 0.8): one signed, versioned document per name, written by a lease holder and
2//! ordered by `(term, version)`, never by wall clock or HLC, so a stale holder whose clock
3//! runs ahead can't override a newer holder's plan.
4//!
5//! Each plan is signed by the writing device's node key over the user, record type, name and
6//! body, so a device that relays the page can't alter or move it, and it only counts while the
7//! signer's certificate is active. Stored as a normal record (configure the type
8//! `RecordOptions::sealed` to seal it).
9use serde::{Deserialize, Serialize};
10
11use crate::error::{Result, SyncError};
12use crate::hlc::Hlc;
13use crate::lease::{LeaseHandle, Term};
14use crate::net::SyncState;
15use crate::protocol::{decode, encode};
16use crate::rotation::peer_public;
17
18const PLAN_DOMAIN: &[u8] = b"weirdnet-sync/v1/plan\n";
19
20/// A body signed by a device's node key, bound to where it is stored.
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub(crate) struct SignedDoc {
23    pub signer: String,
24    #[serde(with = "crate::bytes")]
25    pub body: Vec<u8>,
26    #[serde(with = "crate::bytes")]
27    pub sig: Vec<u8>,
28}
29
30fn doc_bytes(domain: &[u8], user_id: &str, typ: &str, record_id: &str, body: &[u8]) -> Vec<u8> {
31    let mut b = domain.to_vec();
32    for part in [user_id, typ, record_id] {
33        b.extend_from_slice(part.as_bytes());
34        b.push(b'\n');
35    }
36    b.extend_from_slice(body);
37    b
38}
39
40impl SyncState {
41    pub(crate) fn sign_doc(&self, domain: &[u8], typ: &str, record_id: &str, body: Vec<u8>) -> Result<SignedDoc> {
42        let device = self.device.as_ref().ok_or_else(|| SyncError::NotPermitted("signing needs this device's node key".into()))?;
43        let sig = device.sign(&doc_bytes(domain, &self.user_id, typ, record_id, &body))?;
44        Ok(SignedDoc { signer: device.peer_id(), body, sig })
45    }
46
47    /// The signed docs under `typ`/`record_id` whose signature verifies and whose signer is an
48    /// active device, with each entry's HLC.
49    pub(crate) fn signed_docs(&self, domain: &[u8], typ: &str, record_id: &str) -> Vec<(SignedDoc, Hlc)> {
50        let mut out = Vec::new();
51        for e in self.log.iter().filter(|e| e.typ == typ && e.record_id == record_id) {
52            let Some(bytes) = self.read(e).ok().and_then(|v| v.ready()) else { continue };
53            let Ok(doc) = decode::<SignedDoc>(&bytes) else { continue };
54            let Some(key) = peer_public(&doc.signer) else { continue };
55            if !self.roster.get(&doc.signer).is_some_and(|c| c.active()) {
56                continue;
57            }
58            if key.verify(&doc_bytes(domain, &self.user_id, typ, record_id, &doc.body), &doc.sig) {
59                out.push((doc, e.hlc.clone()));
60            }
61        }
62        out
63    }
64}
65
66#[derive(Serialize, Deserialize)]
67struct PlanBody {
68    term: Term,
69    version: u64,
70    #[serde(with = "crate::bytes")]
71    body: Vec<u8>,
72}
73
74/// A plan as read back: the newest by `(term, version)` among valid ones.
75#[derive(Debug, Clone, PartialEq, Eq)]
76#[non_exhaustive]
77pub struct Plan {
78    pub name: String,
79    pub term: Term,
80    pub version: u64,
81    pub body: Vec<u8>,
82    /// The device that wrote it.
83    pub signer: String,
84    pub hlc: Hlc,
85}
86
87impl SyncState {
88    /// Write the plan `name` under `typ` (for example `ymir.plan`) while holding `lease`.
89    /// The version is the previous one of the same term plus one, or 1 on a new term.
90    pub fn publish_plan(&mut self, now_ms: u64, typ: &str, name: &str, lease: &LeaseHandle, body: &[u8]) -> Result<Plan> {
91        if !lease.is_valid() {
92            return Err(SyncError::NotPermitted("the lease is no longer valid".into()));
93        }
94        if lease.holder() != self.our_cert.peer_id {
95            return Err(SyncError::NotPermitted("the lease is another device's".into()));
96        }
97        let version = match self.current_plan(typ, name) {
98            Some(p) if p.term > lease.term() => return Err(SyncError::NotPermitted(format!("a newer term ({}) has published", p.term))),
99            Some(p) if p.term == lease.term() => p.version + 1,
100            _ => 1,
101        };
102        let inner = encode(&PlanBody { term: lease.term(), version, body: body.to_vec() })?;
103        let doc = self.sign_doc(PLAN_DOMAIN, typ, name, inner)?;
104        let signer = doc.signer.clone();
105        self.write(now_ms, typ, name, &encode(&doc)?)?;
106        let hlc = self.clock.clone().ok_or_else(|| SyncError::Protocol("no clock after a write".into()))?;
107        Ok(Plan { name: name.into(), term: lease.term(), version, body: body.to_vec(), signer, hlc })
108    }
109
110    /// The current plan `name`: the highest `(term, version)` whose signature verifies and whose
111    /// signer has an active certificate. HLC only breaks exact ties.
112    pub fn current_plan(&self, typ: &str, name: &str) -> Option<Plan> {
113        self.current_plan_where(typ, name, |_| true)
114    }
115
116    /// [`current_plan`](Self::current_plan) counting only signers `signer_ok` accepts (for
117    /// example `|p| roster.has_role(p, "ymir.inference")`).
118    pub fn current_plan_where(&self, typ: &str, name: &str, signer_ok: impl Fn(&str) -> bool) -> Option<Plan> {
119        self.signed_docs(PLAN_DOMAIN, typ, name)
120            .into_iter()
121            .filter(|(d, _)| signer_ok(&d.signer))
122            .filter_map(|(d, hlc)| {
123                let b: PlanBody = decode(&d.body).ok()?;
124                Some(Plan { name: name.into(), term: b.term, version: b.version, body: b.body, signer: d.signer, hlc })
125            })
126            .max_by(|a, b| (a.term, a.version).cmp(&(b.term, b.version)).then_with(|| a.hlc.cmp_total(&b.hlc)))
127    }
128}