summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/federation/judge.rs192
-rw-r--r--src/federation/mod.rs1
-rw-r--r--src/federation/party.rs12
3 files changed, 205 insertions, 0 deletions
diff --git a/src/federation/judge.rs b/src/federation/judge.rs
new file mode 100644
index 0000000..4fc4ce8
--- /dev/null
+++ b/src/federation/judge.rs
@@ -0,0 +1,192 @@
+//! What a store makes of histories, in a format every release of continuum keeps
+//! (`continuum-party judge`; `docs/federation-tests.md`, Against released revisions), so
+//! that a release judges the same histories as an earlier one, under every revision that
+//! one knows. Never change the format: an earlier release prints it too.
+//!
+//! In, a history after another: `case <label>`, `root <hex>`, the bytes of its root, then
+//! `event <hex>` for each of its events, in the order offered.
+//!
+//! Out, for each: `case <label>`; then `root none` where the root reads as none here, as
+//! one of a revision this continuum doesn't know; else `became <ID> <kind>` for each event
+//! in the order offered, what became of it by kind (never a refusal's words, which may
+//! change), and `reads <JSON>`, what the store reads after: its checkpoint's ID, the
+//! current version's hash, the values at places, the members, and the event it stopped
+//! at.
+
+use std::collections::BTreeMap;
+use std::fmt::Write as _;
+
+use super::fold::Federation;
+use super::store::Id;
+use super::store::memory::{Refusal, Store};
+
+/// A history: its label, its root, and its events in the order offered.
+pub(crate) struct History {
+ pub(crate) label: String,
+ pub(crate) root: Vec<u8>,
+ pub(crate) events: Vec<Vec<u8>>,
+}
+
+/// `histories` as `judge` reads them.
+pub(crate) fn spelled(histories: &[History]) -> String {
+ let mut text = String::new();
+ for history in histories {
+ let _ = writeln!(text, "case {}", history.label);
+ let _ = writeln!(text, "root {}", hex(&history.root));
+ for event in &history.events {
+ let _ = writeln!(text, "event {}", hex(event));
+ }
+ }
+ text
+}
+
+/// The histories `text` spells (`spelled`).
+pub(crate) fn read(text: &str) -> Result<Vec<History>, String> {
+ let mut histories: Vec<History> = Vec::new();
+ for line in text.lines() {
+ let (word, rest) = line.split_once(' ').unwrap_or((line, ""));
+ let bytes = || unhex(rest).ok_or_else(|| format!("no hex: {line:?}"));
+ match (word, histories.last_mut()) {
+ ("case", _) => histories.push(History {
+ label: rest.to_owned(),
+ root: Vec::new(),
+ events: Vec::new(),
+ }),
+ ("root", Some(history)) => history.root = bytes()?,
+ ("event", Some(history)) => history.events.push(bytes()?),
+ _ => return Err(format!("no line of a history: {line:?}")),
+ }
+ }
+ Ok(histories)
+}
+
+fn hex(bytes: &[u8]) -> String {
+ bytes.iter().map(|byte| format!("{byte:02x}")).collect()
+}
+
+fn unhex(text: &str) -> Option<Vec<u8>> {
+ if !text.len().is_multiple_of(2) || !text.bytes().all(|byte| byte.is_ascii_hexdigit()) {
+ return None;
+ }
+ (0..text.len())
+ .step_by(2)
+ .map(|at| u8::from_str_radix(text.get(at..at + 2)?, 16).ok())
+ .collect()
+}
+
+/// What a store makes of `histories`, as the format says.
+pub(crate) fn judge(histories: &[History]) -> String {
+ let mut text = String::new();
+ for history in histories {
+ let _ = writeln!(text, "case {}", history.label);
+ let Ok(mut store) = Store::<Federation>::new(history.root.clone(), Vec::new()) else {
+ text.push_str("root none\n");
+ continue;
+ };
+ for event in &history.events {
+ store.offer(event.clone());
+ }
+ for event in &history.events {
+ let id = Id::of(event);
+ let _ = writeln!(text, "became {id} {}", became(&store, &id));
+ }
+ let _ = writeln!(text, "reads {}", reads(&store));
+ }
+ text
+}
+
+/// What became of `id` in `store`, by kind.
+fn became(store: &Store<Federation>, id: &Id) -> &'static str {
+ if store.stopped().is_some_and(|(at, ..)| at == id) {
+ return "stopped at";
+ }
+ if store.held_back().iter().any(|(held, _)| held == id) {
+ return "held back";
+ }
+ if store.holds(id) {
+ return "taken";
+ }
+ if store.get(id).is_some() {
+ return "kept";
+ }
+ match store.refusal(id) {
+ Some(Refusal::None) => "refused: none",
+ Some(Refusal::Judged(_)) => "refused: judged",
+ Some(Refusal::BuiltOn(_)) => "refused: built on a refused one",
+ Some(Refusal::NotAbove) => "refused: not above the checkpoint",
+ Some(Refusal::Own) => "refused: its own",
+ Some(Refusal::Dropped) => "refused: dropped",
+ None if store.is_waiting(id) => "waiting",
+ None => "gone with a move",
+ }
+}
+
+/// What `store` reads, a line of JSON.
+fn reads(store: &Store<Federation>) -> String {
+ let state = store.state();
+ let values: BTreeMap<String, String> = state
+ .values()
+ .into_iter()
+ .map(|(path, value)| (path, String::from_utf8_lossy(&value.bytes()).into_owned()))
+ .collect();
+ serde_json::json!({
+ "checkpoint": Id::of(store.checkpoint()).to_string(),
+ "current": state.current().hash.to_string(),
+ "values": values,
+ "members": state.members(),
+ "stopped": store.stopped().map(|(id, ..)| id.to_string()),
+ })
+ .to_string()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::federation::harness::{self, Party, Spec};
+
+ /// Histories read back as spelled, and judged as the format says: an event taken, one
+ /// refused, and a root of a revision this continuum doesn't know read as none.
+ #[test]
+ fn histories_are_judged_as_the_format_says() {
+ let tv = Party::new("tv", 1);
+ let first = Spec::first(&[&tv, &Party::new("lass", 2)], &[]);
+ let root = first.root();
+ let write = tv.write(&[Id::of(&root)], "home/tv/a", harness::str("1"));
+ let unknown = String::from_utf8(root.clone()).expect("UTF-8").replacen(
+ r#""rules":"#,
+ &format!(r#""revision":"{}","rules":"#, Id::of(b"elsewhere")),
+ 1,
+ );
+ let histories = vec![
+ History {
+ label: "one".to_owned(),
+ root: root.clone(),
+ events: vec![write.clone(), b"not an event".to_vec()],
+ },
+ History {
+ label: "unknown".to_owned(),
+ root: unknown.into_bytes(),
+ events: vec![write.clone()],
+ },
+ ];
+ let again = read(&spelled(&histories)).expect("as spelled");
+ assert_eq!(again.len(), 2);
+ assert_eq!(again[0].events, histories[0].events);
+ let judged = judge(&again);
+ let lines: Vec<&str> = judged.lines().collect();
+ assert_eq!(lines[0], "case one");
+ assert_eq!(lines[1], format!("became {} taken", Id::of(&write)));
+ assert_eq!(
+ lines[2],
+ format!("became {} refused: none", Id::of(b"not an event"))
+ );
+ assert!(
+ lines[3].starts_with(r#"reads {"checkpoint":"#),
+ "{}",
+ lines[3]
+ );
+ assert!(lines[3].contains(r#""home/tv/a":"\"1\"""#), "{}", lines[3]);
+ assert_eq!(&lines[4..], ["case unknown", "root none"]);
+ assert!(read("nothing").is_err());
+ }
+}
diff --git a/src/federation/mod.rs b/src/federation/mod.rs
index 9444712..18fc70d 100644
--- a/src/federation/mod.rs
+++ b/src/federation/mod.rs
@@ -20,6 +20,7 @@ pub(crate) mod fork;
pub(crate) mod harness;
pub(crate) mod held;
pub(crate) mod jcs;
+pub(crate) mod judge;
pub(crate) mod keys;
#[cfg(test)]
mod model;
diff --git a/src/federation/party.rs b/src/federation/party.rs
index 148bd20..a12dc7f 100644
--- a/src/federation/party.rs
+++ b/src/federation/party.rs
@@ -53,6 +53,7 @@ use super::client::{self, Record};
use super::event::{self, Does, Event, Signed};
use super::fold::Federation;
use super::jcs::Json;
+use super::judge;
use super::keys::{self, Key};
use super::revision::{FEATURES, Revision};
use super::store::Id;
@@ -175,6 +176,10 @@ fn command() -> Command {
.about("What the node finds of the fork whose root a file holds")
.arg(id("file")),
)
+ .subcommand(Command::new("judge").about(
+ "What a store makes of the histories its input spells, in a format every release \
+ keeps (federation-tests.md, Against released revisions)",
+ ))
.subcommand(Command::new("proposals").about(
"The proposals on the current version: whether each passed or is dead, who voted \
what, and what it changes",
@@ -277,6 +282,13 @@ pub(crate) async fn main() -> Result<()> {
}
return out(&super::fork::root_file(&root, &[]));
}
+ if name == "judge" {
+ let mut input = String::new();
+ std::io::Read::read_to_string(&mut std::io::stdin(), &mut input)?;
+ let histories = judge::read(&input).map_err(|why| anyhow!(why))?;
+ print!("{}", judge::judge(&histories));
+ return Ok(());
+ }
let node = Node::new(&options)?;
if name == "proposals" {
return proposals(&node).await;