From fdfe968d7abb6470e65253a720f87b82f5d5e388 Mon Sep 17 00:00:00 2001 From: tv Date: Wed, 25 Nov 2026 19:21:13 +0000 Subject: federation: properties of nodes voting by themselves getting on The properties were all of safety. Three of getting on, over generated histories gone on with (gone_on): nodes vote by themselves, time passing for them, parties vote by hand, some proposing a checkpoint at heads no version may name, or again beside its heads, and backing it there, and after each step a node writes what passed. * What a node's rules cast, its own store takes, and it backs the checkpoint it proposes. * What its rules back is written once it passes by votes a version event may be written on. * Where some votes make a version event a store takes, State::version_event returns one it takes: every choice of a true of each party is tried. Each fails where vote::decide asks no vote::builds_on, where vote::backs_checkpoint asks no State::may_name, or where State::version_event takes votes beside a checkpoint's heads. --- src/federation/properties.rs | 674 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 670 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/federation/properties.rs b/src/federation/properties.rs index dce0984..9f7f975 100644 --- a/src/federation/properties.rs +++ b/src/federation/properties.rs @@ -3,15 +3,18 @@ //! versions and checkpoints, vote, and write the versions that pass, each on what it last //! caught up with, and their nodes merge; an adversary signs with its keys or stolen ones whatever it likes. The //! store is checked against the model, which reads every history anew, against itself in -//! other orders, and read from a document against itself given the events alone. A -//! failing history is cut down, events taken out with what builds on them for as long as -//! it still fails, and printed. +//! other orders, and read from a document against itself given the events alone. And +//! nodes voting by themselves get on: a history is gone on with by them and by parties +//! voting by hand (`gone_on`), and what they cast is taken, what they back is written once +//! it passes, and what some votes can write, a node writes. A failing history is cut down, +//! events taken out with what builds on them for as long as it still fails, and printed. use std::collections::{BTreeMap, BTreeSet}; use ed25519_dalek::SigningKey; -use super::event::{Checkpoint, Does, Event}; +use super::client::Record; +use super::event::{Checkpoint, Does, Event, Signed}; use super::fold::Federation; use super::harness::{self, Party, Spec}; use super::held::Holding; @@ -21,6 +24,7 @@ use super::revision::{Feature, Revision}; use super::store::memory::{Offered, Refusal, Store}; use super::store::{Fold, Id}; use super::version::Version; +use super::vote::{self, Act, Rules, Seen}; use crate::access::sshsig::PublicKey; use crate::document::events; use crate::testrand::{Rng, for_seeds}; @@ -801,3 +805,665 @@ fn a_fork_keeps_what_counts_at_its_heads_and_takes_nothing_of_the_other() { }, ); } + +/// The parties of a history, with the keys its first version names: those sign its +/// votes and proposals throughout, as no generated version changes them. +fn parties(history: &History) -> Vec { + let first = Checkpoint::read(&history.root).expect("a root").version; + (0..first.parties.len()) + .map(|i| Party::new(&format!("p{i}"), i as u8 + 1)) + .collect() +} + +/// What the node voting by itself for a party sees and goes by: which events it held for +/// a while, which when it started, and its operator's rules. +struct Voting { + party: Party, + rules: Rules, + long: BTreeSet, + from_start: BTreeSet, +} + +impl Voting { + /// A node voting for `party`, following the others, as it may see `history`: each + /// event held for a while or new, more often than not held when it started or none. + fn new(rng: &mut Rng, history: &History, party: &Party, others: &[Party]) -> Voting { + let ids = || history.events.iter().map(|event| Id::of(event)); + let old = rng.next_f64(); + let started = if rng.chance(0.5) { rng.next_f64() } else { 0.0 }; + Voting { + party: Party::new(&party.name, party.key.to_bytes()[0]), + rules: Rules { + follow: others + .iter() + .filter(|other| other.name != party.name && rng.chance(0.7)) + .map(|other| other.name.clone()) + .collect(), + follow_any: rng.chance(0.5), + propose_events: Some(1), + held_for: std::time::Duration::from_secs(60), + ..Rules::default() + }, + long: ids().filter(|_| rng.chance(old)).collect(), + from_start: ids().filter(|_| rng.chance(started)).collect(), + } + } + + /// Its party's record, as restored from `store`: its votes on the current version, and + /// the events proposing on it that it signed. + fn record(&self, store: &Store) -> Record { + let state = store.state(); + let current = state.current(); + let mut record = Record::before(store.id(), &self.party.name); + for ballot in state.ballots(¤t.hash).values() { + let votes: Vec> = ballot + .votes + .iter() + .filter_map(|id| store.get(id).map(<[u8]>::to_vec)) + .collect(); + record.restore(current, &votes); + for bytes in ballot.proposals.iter().filter_map(|id| store.get(id)) { + if let Some(Event::Signed(signed)) = Event::read_taken(bytes) + && signed.party == self.party.name + { + record.signed(bytes); + } + } + } + record + } + + /// What it signs now, as `Holding::sign` does: its votes on what `vote::builds_on` + /// says, a checkpoint's proposal on the heads it names. An error where a vote its rules + /// cast builds on nothing its store takes it on. + fn signs(&self, store: &Store, record: &Record) -> Result>, String> { + let hour = std::time::Duration::from_secs(3600); + let held = |id: &Id| { + Some(if self.long.contains(id) { + hour + } else { + std::time::Duration::ZERO + }) + }; + let from_start = |id: &Id| self.from_start.contains(id); + let seen = Seen { + store, + held: &held, + from_start: &from_start, + since_move: hour, + }; + let current = store.state().current().hash; + let mut signed = Vec::new(); + for act in vote::decide(&seen, &self.rules, record) { + match act { + Act::Vote { + proposal, + yes, + nays, + } => { + let on = vote::builds_on(store, &self.party.name, &proposal, yes, &nays) + .map_err(|why| { + format!( + "{}'s node casts {yes} on {proposal}, and builds it on nothing: \ + {why}", + self.party.name + ) + })?; + signed.push(self.party.vote(&on, current, proposal, yes)); + } + Act::Propose(version) => { + let at = Version::read(&version) + .ok() + .and_then(|version| version.checkpoint) + .unwrap_or_else(|| store.building_on()); + signed.push(self.party.propose(&at, &version)); + } + } + } + Ok(signed) + } + + /// Signs as `signs`, and offers it to `store`: the proposals it backs with a `true` + /// then, its own, proposed now, among them, which it backs next. An error where the + /// store takes one not, or where it backs its own proposal not. + fn acts(&self, store: &mut Store) -> Result, String> { + let name = &self.party.name; + let mut backs = Vec::new(); + let mut proposed = None; + for round in 0..2 { + let record = self.record(store); + for bytes in self.signs(store, &record)? { + let id = Id::of(&bytes); + let offered = store.offer(bytes.clone()); + if !matches!(offered, Offered::Taken(_)) { + return Err(format!( + "{name}'s node casts {}, and its store says {offered:?}", + String::from_utf8_lossy(&bytes) + )); + } + match Event::read_taken(&bytes) { + Some(Event::Signed(Signed { + does: Does::Proposal { hash, .. }, + .. + })) => proposed = Some(hash), + Some(Event::Signed(Signed { + does: + Does::Vote { + proposal, + yes: true, + .. + }, + .. + })) => backs.push(proposal), + _ => return Err(format!("{name}'s node signs {id}, no vote or proposal")), + } + } + match proposed { + Some(hash) if round == 1 && !backs.contains(&hash) => { + return Err(format!("{name}'s node proposes {hash}, and backs it not")); + } + Some(_) => {} + None => break, + } + } + Ok(backs) + } +} + +/// A version changing `current`: naming `checkpoint`, with a rule giving `rule`'s path to +/// its party, or both. +fn next(current: &Version, checkpoint: Option<&[Id]>, rule: Option<(&str, &str)>) -> Option { + let Json::Object(mut members) = current + .json + .without("number") + .without("changes") + .without("checkpoint") + else { + return None; + }; + members.push(("number".to_owned(), Json::Int(current.number as i64 + 1))); + members.push(("changes".to_owned(), Json::Str(current.hash.to_string()))); + if let Some(heads) = checkpoint { + members.push(("checkpoint".to_owned(), harness::ids(heads))); + } + if let Some((path, writer)) = rule { + let mut rules = current + .json + .get("rules") + .and_then(Json::as_array) + .map(<[Json]>::to_vec) + .unwrap_or_default(); + rules.push(harness::object(vec![ + ("path", harness::str(path)), + ("writer", harness::str(writer)), + ])); + members.retain(|(name, _)| name != "rules"); + members.push(("rules".to_owned(), Json::Array(rules))); + } + Json::object(members) +} + +/// The parties that haven't yet back the proposal of hash `backed`, on the version +/// current in `store`, by hand: as many as their records and the store let, each on what +/// `vote::builds_on` says, their votes added to `events`. An error where the store takes +/// such a vote not. +fn backed_by_the_rest( + store: &mut Store, + nodes: &[Voting], + backed: Id, + events: &mut Vec>, +) -> Result<(), String> { + let current = store.state().current().clone(); + for other in nodes { + let state = store.state(); + let Some(json) = state.proposal(&backed).cloned() else { + continue; + }; + let nays: Vec> = state + .ballots(¤t.hash) + .values() + .flat_map(|ballot| &ballot.votes) + .filter_map(|id| store.get(id).map(<[u8]>::to_vec)) + .collect(); + let name = &other.party.name; + let Ok(kept) = other + .record(store) + .may_vote(¤t, backed, &json, true, &nays) + else { + continue; + }; + let Ok(on) = vote::builds_on(store, name, &backed, true, &kept) else { + continue; + }; + let bytes = other.party.vote(&on, current.hash, backed, true); + events.push(bytes.clone()); + let offered = store.offer(bytes); + if !matches!(offered, Offered::Taken(_)) { + return Err(format!( + "{name} backs {backed} as its node says, and the store says {offered:?}" + )); + } + } + Ok(()) +} + +/// Writes the proposal of hash `proposal`, on the version current in `store`, as a node +/// does, by the event `State::version_event` gives, added to `events`: whether the store +/// takes it. An error where it is taken and the version isn't current then; or where none +/// is given, or the store takes it not, and some votes make a version event it takes: +/// every choice of a `true` of each party is tried, as many as pass it or more. +fn one_is_written( + store: &mut Store, + proposal: Id, + events: &mut Vec>, +) -> Result { + let state = store.state(); + let current = state.current().clone(); + let needed = (2 * current.parties.len()).div_ceil(3); + let written = state.version_event(&proposal); + // Each party's `true`s on it. + let mut yes: BTreeMap> = BTreeMap::new(); + for id in state + .ballots(¤t.hash) + .get(&proposal) + .map(|ballot| ballot.votes.clone()) + .unwrap_or_default() + { + if let Some(Event::Signed(Signed { + party, + does: Does::Vote { yes: true, .. }, + .. + })) = store.get(&id).and_then(Event::read_taken) + { + yes.entry(party).or_default().push(id); + } + } + if let Some(bytes) = &written { + events.push(bytes.clone()); + if matches!(store.offer(bytes.clone()), Offered::Taken(_)) { + return if store.state().current().hash == proposal { + Ok(true) + } else { + Err(format!("{proposal} is written, and isn't current")) + }; + } + } + if yes.len() < needed { + return Ok(false); + } + // Every choice: of each party none of its votes, or one. + let mut choices: Vec> = vec![Vec::new()]; + for votes in yes.values() { + choices = choices + .into_iter() + .flat_map(|chosen| { + std::iter::once(chosen.clone()).chain(votes.iter().map(move |vote| { + let mut with = chosen.clone(); + with.push(*vote); + with + })) + }) + .collect(); + } + for mut deps in choices { + deps.sort_unstable(); + if deps.len() >= needed + && matches!( + store.offer(harness::version_event(&deps, proposal)), + Offered::Taken(_) + ) + { + return Err(match &written { + None => format!( + "a version event on {deps:?} writes {proposal}, and `version_event` \ + returns none" + ), + Some(bytes) => format!( + "a version event on {deps:?} writes {proposal}, and the store refuses \ + the one `version_event` returns, {}", + Id::of(bytes) + ), + }); + } + } + Ok(false) +} + +/// The most steps a history is gone on with. +const STEPS: usize = 24; + +/// A history gone on with, and how its nodes got on: the first of each that came up. +struct Went { + history: History, + nodes: Vec, + /// How many of the history's events it was gone on with after: all, or none. + kept: usize, + /// A node cast by itself what its store took not. + cast: Result<(), String>, + /// What a node backed by itself passed, by votes on events a vote may build on, and + /// no version event the store takes writes it. + backed: Result<(), String>, + /// Some votes make a version event the store takes, and `State::version_event` + /// returns none it takes. + written: Result<(), String>, +} + +/// A history gone on with, seeded by its bytes, half the time from its root alone, where +/// no party is bound by a vote yet. Step by step: a party's node votes by itself, time +/// passing for it now and then; or a party, by hand, proposes a checkpoint at heads of its +/// choosing, some no version may name, on them or beside them, backing it more often than +/// not, another party proposing it again now and then where it writes, and backing it +/// there; proposes a change; proposes again what is proposed; votes as its record lets, +/// on any event proposing what it votes on; or writes. Now and then the parties that +/// haven't yet back what was backed too (`backed_by_the_rest`). After each step, a node +/// writes what passed (`one_is_written`). +fn gone_on(base: &History) -> Went { + let parties = parties(base); + let all: Vec = std::iter::once(&base.root) + .chain(&base.events) + .flatten() + .copied() + .collect(); + let seed = u64::from_str_radix(&Id::of(&all).to_string()[..16], 16).unwrap_or_default(); + let mut rng = Rng::new(seed); + // Half from the root alone, where no party is bound by a vote yet. + let base = &History { + root: base.root.clone(), + events: if rng.chance(0.5) { + Vec::new() + } else { + base.events.clone() + }, + }; + let kept = base.events.len(); + let mut nodes: Vec = parties + .iter() + .map(|party| Voting::new(&mut rng, base, party, &parties)) + .collect(); + let mut history = base.clone(); + let (mut store, _) = base.store(&base.written()); + let (mut cast, mut backed, mut written) = (Ok(()), Ok(()), Ok(())); + // The proposals a node backed by itself; and those with a `true` on an event proposing + // them that a vote may not build on, which counts for passing, and no version event + // is written on. + let mut by_nodes = BTreeSet::new(); + let mut beside = BTreeSet::new(); + 'steps: for step in 0..rng.between(4, STEPS) { + let w = rng.below(parties.len()); + let party = &parties[w]; + let current = store.state().current().clone(); + let taken = store.taken().to_vec(); + let ballots = store.state().ballots(¤t.hash); + let nays: Vec> = ballots + .values() + .flat_map(|ballot| &ballot.votes) + .filter_map(|id| store.get(id).map(<[u8]>::to_vec)) + .collect(); + let roll = rng.below(100); + let by_node = roll < 35; + let signed: Vec> = if by_node { + if rng.chance(0.5) { + nodes[w].long.extend(taken.iter().copied()); + } + let record = nodes[w].record(&store); + match nodes[w].signs(&store, &record) { + Ok(signed) => signed, + Err(why) => { + cast = Err(why); + break; + } + } + } else if roll < 58 && !taken.is_empty() { + let mut heads = if rng.chance(0.4) { + store.heads() + } else { + vec![*rng.pick(&taken)] + }; + if rng.chance(0.2) { + heads.push(*rng.pick(&taken)); + } + heads.sort_unstable(); + heads.dedup(); + let on = if rng.chance(0.7) { + heads.clone() + } else { + store.building_on() + }; + // Its proposer backs it, more often than not, where its record lets; and now + // and then another party proposes it again where it writes, beside the heads, + // say, and backs it there. + let backs = rng.chance(0.7); + let again = rng.chance(0.5).then(|| rng.below(parties.len())); + let beside = store.building_on(); + next(¤t, Some(&heads), None) + .map(|version| { + let hash = Id::of(&version.bytes()); + let mut signed = Vec::new(); + let mut propose = |by: usize, on: &[Id], backs: bool| { + let proposing = parties[by].propose(on, &version); + let vote = nodes[by] + .record(&store) + .may_vote(¤t, hash, &version, true, &nays) + .ok() + .filter(|_| backs) + .map(|_| { + parties[by].vote(&[Id::of(&proposing)], current.hash, hash, true) + }); + signed.push(proposing); + signed.extend(vote); + }; + propose(w, &on, backs); + if let Some(other) = again.filter(|other| *other != w) { + propose(other, &beside, true); + } + signed + }) + .unwrap_or_default() + } else if roll < 63 { + next( + ¤t, + None, + Some((&format!("names/w{step}"), &party.name)), + ) + .map(|version| party.propose(&store.building_on(), &version)) + .into_iter() + .collect() + } else if roll < 68 && !ballots.is_empty() { + // Proposed again, where the party writes now: beside a checkpoint's heads, say. + let hashes: Vec = ballots.keys().copied().collect(); + store + .state() + .proposal(rng.pick(&hashes)) + .map(|version| party.propose(&store.building_on(), version)) + .into_iter() + .collect() + } else if roll < 87 && !ballots.is_empty() { + let hashes: Vec = ballots.keys().copied().collect(); + let hash = *rng.pick(&hashes); + let yes = rng.chance(0.6); + let json = store.state().proposal(&hash).cloned(); + let checkpoint = json + .as_ref() + .and_then(|json| Version::read(json).ok()) + .is_some_and(|version| version.checkpoint.is_some()); + let kept = json.and_then(|json| { + nodes[w] + .record(&store) + .may_vote(¤t, hash, &json, yes, &nays) + .ok() + }); + match (kept, ballots[&hash].proposals.as_slice()) { + (Some(kept), proposing) if !proposing.is_empty() => { + super::client::building(*rng.pick(proposing), checkpoint, &kept) + .map(|on| party.vote(&on, current.hash, hash, yes)) + .into_iter() + .collect() + } + _ => Vec::new(), + } + } else if roll < 94 { + let deps = if taken.is_empty() || rng.chance(0.6) { + store.building_on() + } else { + vec![*rng.pick(&taken)] + }; + vec![party.write( + &deps, + &format!("home/{}/w", party.name), + harness::str(&step.to_string()), + )] + } else { + ballots + .keys() + .filter_map(|hash| store.state().version_event(hash)) + .collect() + }; + let mut by_hand = Vec::new(); + for bytes in signed { + let offered = store.offer(bytes.clone()); + let vote = match Event::read_taken(&bytes) { + Some(Event::Signed(Signed { + deps, + does: + Does::Vote { + proposal, + yes: true, + .. + }, + .. + })) => Some((proposal, deps)), + _ => None, + }; + history.events.push(bytes.clone()); + if !by_node { + by_hand.extend(vote); + continue; + } + if !matches!(offered, Offered::Taken(_)) { + cast = Err(format!( + "{}'s node casts {}, and its store says {offered:?}", + party.name, + String::from_utf8_lossy(&bytes) + )); + break 'steps; + } + if let Some((proposal, _)) = vote { + by_nodes.insert(proposal); + if rng.chance(0.5) + && let Err(why) = + backed_by_the_rest(&mut store, &nodes, proposal, &mut history.events) + { + backed = Err(why); + break 'steps; + } + } + } + // Now and then the rest back by hand what a party backed by hand. + if let Some((proposal, _)) = by_hand.first() + && rng.chance(0.3) + && let Err(why) = backed_by_the_rest(&mut store, &nodes, *proposal, &mut history.events) + { + backed = Err(why); + break 'steps; + } + if store.state().current().hash != current.hash { + continue; + } + for (proposal, deps) in by_hand { + let proposing = store.state().proposing(¤t.hash, &proposal); + if !deps.iter().any(|dep| proposing.contains(dep)) { + beside.insert(proposal); + } + } + for proposal in store.state().ballots(¤t.hash).into_keys() { + match one_is_written(&mut store, proposal, &mut history.events) { + Err(why) => { + written = Err(why); + break 'steps; + } + Ok(true) => break, + Ok(false) => { + if by_nodes.contains(&proposal) + && !beside.contains(&proposal) + && store.state().tally(¤t, &proposal).passed + { + backed = Err(format!( + "{proposal}, which a node backs by itself, passed, and no version \ + event the store takes writes it" + )); + break 'steps; + } + } + } + } + } + Went { + history, + nodes, + kept, + cast, + backed, + written, + } +} + +/// Checks on the histories of `cases` seeds, with an adversary and without, each gone on +/// with (`gone_on`), what `got_on` says of how its nodes got on; a failing history is cut +/// down and printed, with what it was gone on with. +fn check_going_on(cases: u64, got_on: impl Fn(&Went) -> Result<(), String>) { + for adversary in [false, true] { + check( + cases, + Kind { + adversary, + checkpoints: true, + unread: false, + }, + |base| { + let went = gone_on(base); + got_on(&went).map_err(|why| { + let after: Vec = went.history.events[went.kept..] + .iter() + .map(|event| { + format!("{} {}", Id::of(event), String::from_utf8_lossy(event)) + }) + .collect(); + format!( + "{why}; gone on with\n{}\nafter the first {} events of", + after.join("\n"), + went.kept + ) + }) + }, + ); + } +} + +/// What a node's rules cast, its own store takes: a vote or a proposal it signs by itself +/// that its store refuses binds its party by its record, and counts nowhere. And it backs +/// the checkpoint it proposes. +#[test] +fn what_a_node_casts_by_itself_its_store_takes() { + check_going_on(32, |went| { + went.cast.clone()?; + // And after: one of the nodes, each history another's. + let node = &went.nodes[went.history.events.len() % went.nodes.len()]; + let (mut store, _) = went.history.store(&went.history.written()); + node.acts(&mut store).map(|_| ()) + }); +} + +/// What a node's rules back, a version event can name: where the parties that may back it +/// too, each on an event a vote may build on, and it passes, a node writes it, by the +/// event `State::version_event` gives, which the store takes. +#[test] +fn what_a_node_backs_by_itself_is_written_once_it_passes() { + check_going_on(32, |went| went.backed.clone()); +} + +/// Where some votes make a version event a store takes, `State::version_event` returns +/// one it takes, and the version it writes is current. +#[test] +fn where_votes_make_a_version_event_one_is_written() { + check_going_on(32, |went| went.written.clone()); +} -- cgit v1.3.1