//! The federation's events, and its checkpoints, as bytes (`docs/federation.md`, Events, //! Checkpoints): what each holds, and what makes one none. use super::jcs::{self, Json}; use super::keys; use super::store::Id; use super::version::{self, Version}; use crate::access::sshsig::PublicKey; /// The most bytes an event may have. pub(crate) const LARGEST: usize = 256 * 1024; /// Dependencies an event may name. pub(crate) const DEPENDENCIES: usize = 64; /// An event, read from its bytes. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Event { /// What a party signs. Signed(Signed), /// A version event: a version written once its proposal passed, signed by nobody. Version { deps: Vec, version: Id }, } #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Signed { pub(crate) deps: Vec, pub(crate) party: String, /// The key it is signed with, as the event spells it. pub(crate) key: String, pub(crate) does: Does, } /// What a signed event does. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Does { /// A value at a place: `null` empties it. Write { path: Vec, value: Json }, /// The party's key set. Keys(Vec), /// The party's node list. Nodes(Vec), /// A version proposed, taken whatever it holds: whether it is one is asked where a /// version event names it. Its hash is the version's. Proposal { hash: Id, version: Json }, /// A vote on a proposal (`proposal`) on a version (`on`). Vote { on: Id, proposal: Id, yes: bool }, } impl Event { /// The event `bytes` are, where they are one: none where they aren't the JCS encoding /// of the JSON they read as, a field is missing or more, `key` or `sig` doesn't read /// back to itself, the signature doesn't hold, or it is larger than federation 1 /// allows. pub(crate) fn read(bytes: &[u8]) -> Option { Self::parse(bytes, true) } /// The event `bytes` are, as `read` reads them, but for its signature, which isn't /// checked: for bytes a store took already, whose signature held then. pub(crate) fn read_taken(bytes: &[u8]) -> Option { Self::parse(bytes, false) } fn parse(bytes: &[u8], verify: bool) -> Option { if bytes.len() > LARGEST { return None; } let json = jcs::read(bytes)?; let deps = version::ascending_ids(json.get("deps")?)?; if deps.is_empty() || deps.len() > DEPENDENCIES { return None; } let names = json.names(); if names == ["deps", "version"] { let version = Id::from_hex(json.get("version")?.as_str()?)?; return Some(Event::Version { deps, version }); } let does = ["write", "keys", "nodes", "proposal", "vote"] .into_iter() .find(|name| names.contains(name))?; let mut expected = vec!["deps", "key", "party", "sig", does]; expected.sort_by(|a, b| jcs::names_order(a, b)); if names != expected { return None; } let party = json.get("party")?.as_str()?; let key = json.get("key")?.as_str()?; let public = keys::key(key)?; if !version::is_party(party) { return None; } let sig = json.get("sig")?.as_str()?; if verify && !keys::verifies(&public, sig, &json.without("sig").bytes()) { return None; } let what = json.get(does)?; let does = match does { "write" => { if what.names() != ["path", "value"] { return None; } Does::Write { path: version::path(what.get("path")?.as_str()?)?, value: what.get("value")?.clone(), } } "keys" => { let set = strings(what)?; if set.len() > version::KEYS || !set.iter().all(|key| keys::key(key).is_some()) { return None; } Does::Keys(set) } "nodes" => { let list = strings(what)?; if list.len() > version::NODES || !list.iter().all(|id| keys::node_id(id)) { return None; } Does::Nodes(list) } "proposal" => Does::Proposal { hash: Id::of(&what.bytes()), version: what.clone(), }, _ => { if what.names() != ["on", "proposal", "yes"] { return None; } Does::Vote { on: Id::from_hex(what.get("on")?.as_str()?)?, proposal: Id::from_hex(what.get("proposal")?.as_str()?)?, yes: what.get("yes")?.as_bool()?, } } }; Some(Event::Signed(Signed { deps, party: party.to_owned(), key: key.to_owned(), does, })) } pub(crate) fn deps(&self) -> &[Id] { match self { Event::Signed(signed) => &signed.deps, Event::Version { deps, .. } => deps, } } /// The key a signed event is signed with. pub(crate) fn public(signed: &Signed) -> PublicKey { keys::key(&signed.key).expect("an event's key was read as one") } } /// Strings a JSON array holds, where it holds strings only, none twice. fn strings(json: &Json) -> Option> { let items = json .as_array()? .iter() .map(|item| item.as_str().map(str::to_owned)) .collect::>>()?; let mut sorted = items.clone(); sorted.sort(); sorted.dedup(); (sorted.len() == items.len()).then_some(items) } /// A checkpoint, a federation's root and a fork's among them: the heads it is at, the /// events it keeps, and its version. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Checkpoint { pub(crate) at: Vec, pub(crate) keeps: Vec, pub(crate) version: Version, } impl Checkpoint { /// The checkpoint `bytes` are, where they are one: the JCS encoding of /// `{"at": [], "keeps": [], "version": }`, its IDs ascending, its /// version one by itself. pub(crate) fn read(bytes: &[u8]) -> Option { let json = jcs::read(bytes)?; if json.names() != ["at", "keeps", "version"] { return None; } Some(Checkpoint { at: version::ascending_ids(json.get("at")?)?, keeps: version::ascending_ids(json.get("keeps")?)?, version: Version::read(json.get("version")?).ok()?, }) } /// Its bytes. pub(crate) fn bytes(&self) -> Vec { let ids = |ids: &[Id]| Json::Array(ids.iter().map(|id| Json::Str(id.to_string())).collect()); Json::object(vec![ ("at".to_owned(), ids(&self.at)), ("keeps".to_owned(), ids(&self.keeps)), ("version".to_owned(), self.version.json.clone()), ]) .expect("three names") .bytes() } } #[cfg(test)] mod tests { use super::super::harness::{self, Party, Spec}; use super::*; fn tv() -> Party { Party::new("tv", 1) } fn dep() -> Id { Id::of(b"a dependency") } #[test] fn every_kind_of_event_reads_back() { let tv = tv(); let read = |bytes: Vec| match Event::read(&bytes) { Some(Event::Signed(signed)) => signed.does, other => panic!("not a signed event: {other:?}"), }; assert!(matches!( read(tv.write(&[dep()], "home/tv/x", harness::str("1"))), Does::Write { .. } )); assert_eq!( read(tv.keys(&[dep()], &[tv.key_line()])), Does::Keys(vec![tv.key_line()]) ); assert_eq!( read(tv.nodes(&[dep()], &[harness::node_id(1)])), Does::Nodes(vec![harness::node_id(1)]) ); let spec = Spec::first(&[&tv], &[]); assert!(matches!( read(tv.propose(&[dep()], &spec.json())), Does::Proposal { hash, .. } if hash == spec.hash() )); assert_eq!( read(tv.vote(&[dep()], dep(), spec.hash(), true)), Does::Vote { on: dep(), proposal: spec.hash(), yes: true } ); assert_eq!( Event::read(&harness::version_event(&[dep()], spec.hash())), Some(Event::Version { deps: vec![dep()], version: spec.hash() }) ); } #[test] fn an_event_spelled_otherwise_is_none() { let tv = tv(); let value = || { ( "write", harness::object(vec![("path", harness::str("a")), ("value", Json::Null)]), ) }; let none = |bytes: Vec| assert_eq!(Event::read(&bytes), None); // Signed by another key, or its key with a comment. none(tv.signed_as(&Party::new("x", 2).key, &tv.key_line(), &[dep()], value())); none(tv.signed_as(&tv.key, &format!("{} tv", tv.key_line()), &[dep()], value())); // Dependencies: none, or more than federation 1 allows. none(tv.sign(&[], value())); let many: Vec = (0..=DEPENDENCIES) .map(|i| Id::of(&i.to_be_bytes())) .collect(); none(tv.sign(&many, value())); assert!(Event::read(&tv.sign(&many[1..], value())).is_some()); // A party that is no party's name. none(Party::new("t v", 1).sign(&[dep()], value())); // A field more. let unsigned = harness::object(vec![ ("deps", harness::ids(&[dep()])), ("party", harness::str("tv")), ("key", harness::str(&tv.key_line())), value(), ("more", Json::Null), ]); let sig = keys::sign(&tv.key, &unsigned.bytes()); let Json::Object(mut members) = unsigned else { unreachable!() }; members.push(("sig".to_owned(), Json::Str(sig))); none(Json::object(members).expect("an object").bytes()); // Larger than federation 1 allows. none(tv.write(&[dep()], "a", Json::Str("x".repeat(LARGEST)))); // A node ID or key spelled otherwise, or more keys than a set may hold. none(tv.nodes(&[dep()], &[harness::node_id(1).to_uppercase()])); let keys: Vec = (1..=17).map(harness::key_line).collect(); none(tv.keys(&[dep()], &keys)); assert!(Event::read(&tv.keys(&[dep()], &keys[1..])).is_some()); // Its bytes changed after it was signed. let signed = String::from_utf8(tv.write(&[dep()], "a", harness::str("1"))).expect("UTF-8"); none(signed.replace(r#""1""#, r#""2""#).into_bytes()); } #[test] fn a_checkpoint_reads_back_and_is_no_event() { let spec = Spec::first(&[&tv()], &[]); let checkpoint = Checkpoint { at: Vec::new(), keeps: Vec::new(), version: Version::read(&spec.json()).expect("a version"), }; assert_eq!( Checkpoint::read(&checkpoint.bytes()), Some(checkpoint.clone()) ); assert_eq!(Event::read(&checkpoint.bytes()), None); } }