From 8a6474557ad9df0b29e7f6fe9f2c231fc9900588 Mon Sep 17 00:00:00 2001 From: tv Date: Thu, 19 Nov 2026 19:01:55 +0000 Subject: continuum-party found: a federation's first version from its parties The founders wrote the first version as JSON by hand. `found PARTY=KEY|FILE...` writes it: each party with its keys, an authorized_keys line or a file of them, again for more, since 0; --nodes PARTY=NODE,... their node lists, empty where not given; --rule PATH=WRITER the rules in order, `nobody` for false, and without any, each party writing under home/{party}/; --revision FEATURE a later revision. It is checked as a first version (Version::read, changes_validly), and goes to standard output, for `root` to make the root of. The feature lookup is shared with `next` (adding). --- src/federation/party.rs | 229 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 216 insertions(+), 13 deletions(-) (limited to 'src/federation/party.rs') diff --git a/src/federation/party.rs b/src/federation/party.rs index 9a77829..55ad5a5 100644 --- a/src/federation/party.rs +++ b/src/federation/party.rs @@ -33,6 +33,8 @@ //! * `status`: the store, its version and parties, the party's keys and nodes, the node, //! the proposals, the versions the node refused of its own, what to sign again; //! * `values [PATH]`: the values that count, all or under `PATH`, with who writes there; +//! * `found PARTY=KEY|FILE...`: the first version of a federation, from its parties' keys, +//! node lists (`--nodes`) and rules (`--rule`), to standard output; //! * `root FILE`: the root of the federation whose first version `FILE` holds (JSON), //! the file its founders start its swarm from (`--store-root`), to standard output; //! * `fork FILE [HEAD...]`: the root of the fork at the heads named (those the node shows, @@ -183,6 +185,48 @@ fn command() -> Command { ), ) .subcommand(Command::new("again").about("Signs again what a move refused")) + .subcommand( + Command::new("found") + .about( + "The first version of a federation (JSON), to standard output, from its \ + parties' keys, node lists and rules: what root makes the root of", + ) + .arg( + Arg::new("parties") + .value_name("PARTY=KEY|FILE") + .num_args(1..) + .required(true) + .action(ArgAction::Append) + .help( + "A party and its keys: an authorized_keys line, one argument, or a \ + file of them; again for more keys of it", + ), + ) + .arg( + Arg::new("nodes") + .long("nodes") + .value_name("PARTY=NODE,…") + .action(ArgAction::Append) + .help("A party's node list, by node IDs (continuum node-id): none where not given"), + ) + .arg( + Arg::new("rule") + .long("rule") + .value_name("PATH=WRITER") + .action(ArgAction::Append) + .help( + "A rule, in order: the places PATH matches to WRITER, a party, \ + {party} or nobody. Without any, each party writes under \ + home/{party}/", + ), + ) + .arg( + Arg::new("revision") + .long("revision") + .value_name("FEATURE") + .help("Following the revision that adds FEATURE, as next --revision"), + ), + ) .subcommand( Command::new("root") .about("The root of the federation whose first version a file holds (JSON)") @@ -502,7 +546,7 @@ pub(crate) async fn main() -> Result<()> { let matches = command().get_matches(); let (name, sub) = matches.subcommand().expect("a subcommand is required"); // Those that use no options read no federation's. - let dir = if matches!(name, "twice" | "root" | "judge") { + let dir = if matches!(name, "twice" | "root" | "judge" | "found") { None } else { federation(&matches, federations().as_deref())? @@ -546,6 +590,10 @@ pub(crate) async fn main() -> Result<()> { } return Ok(()); } + if name == "found" { + println!("{}", serde_json::to_string_pretty(&founded(sub)?)?); + return Ok(()); + } if name == "root" { let version = version_in(sub.get_one::("file").expect("required"))?; let version = Version::read(&version).map_err(|why| anyhow!("no version: {why}"))?; @@ -1825,18 +1873,7 @@ fn next(current: &Version, feature: Option<&str>) -> Result { fields.insert("changes".to_owned(), current.hash.to_string().into()); fields.remove("checkpoint"); if let Some(name) = feature { - let Some(feature) = FEATURES.iter().find(|feature| feature.name() == name) else { - let names: Vec<&str> = FEATURES.iter().map(|feature| feature.name()).collect(); - bail!( - "no feature {name:?} this continuum knows: it knows {}", - if names.is_empty() { - "none".to_owned() - } else { - names.join(", ") - } - ); - }; - let revision = feature.revision(); + let revision = adding(name)?; if revision < current.revision { bail!( "the current version follows {}, later than {revision}: a version never \ @@ -1982,6 +2019,105 @@ fn overlaps(a: &[String], b: &[String]) -> bool { } } +/// The revision that adds the feature `name`. +fn adding(name: &str) -> Result { + let Some(feature) = FEATURES.iter().find(|feature| feature.name() == name) else { + let names: Vec<&str> = FEATURES.iter().map(|feature| feature.name()).collect(); + bail!( + "no feature {name:?} this continuum knows: it knows {}", + if names.is_empty() { + "none".to_owned() + } else { + names.join(", ") + } + ); + }; + Ok(feature.revision()) +} + +/// The first version of a federation, as `found`'s arguments `sub` say: its parties, each +/// with its keys (`PARTY=KEY|FILE`, again for more), `since` 0; their node lists +/// (`--nodes PARTY=NODE,…`), empty where not given; its rules in order (`--rule +/// PATH=WRITER`, `nobody` writing `false`), each party writing under `home/{party}/` where +/// none is given; and its revision (`--revision`). Checked as a first version. +fn founded(sub: &ArgMatches) -> Result { + let mut keys: std::collections::BTreeMap> = Default::default(); + for item in strings(sub, "parties") { + let (party, given) = item + .split_once('=') + .with_context(|| format!("{item:?}: PARTY=KEY or PARTY=FILE it is"))?; + let held = keys.entry(party.to_owned()).or_default(); + for line in key_lines(&[given.to_owned()])? { + if held.contains(&line) { + bail!("{party}: {} given twice", client::fingerprint(&line)); + } + held.push(line); + } + } + let mut nodes: std::collections::BTreeMap> = keys + .keys() + .map(|party| (party.clone(), Vec::new())) + .collect(); + for item in strings(sub, "nodes") { + let (party, given) = item + .split_once('=') + .with_context(|| format!("--nodes {item:?}: PARTY=NODE,… it is"))?; + let Some(list) = nodes.get_mut(party) else { + bail!("--nodes {party}: no party given keys"); + }; + list.extend(node_ids( + given + .split(',') + .filter(|node| !node.is_empty()) + .map(str::to_owned) + .collect(), + )?); + } + let given = strings(sub, "rule"); + let rules: Vec = if given.is_empty() { + vec![serde_json::json!({"path": "home/{party}/**", "writer": "{party}"})] + } else { + given + .iter() + .map(|rule| { + let (path, writer) = rule + .rsplit_once('=') + .with_context(|| format!("--rule {rule:?}: PATH=WRITER it is"))?; + let writer = match writer { + "nobody" => JsonValue::Bool(false), + writer => writer.into(), + }; + Ok(serde_json::json!({"path": path, "writer": writer})) + }) + .collect::>()? + }; + let given = |lists: &std::collections::BTreeMap>, what: &str| { + lists + .iter() + .map(|(party, items)| (party.clone(), serde_json::json!({"since": 0, what: items}))) + .collect::>() + }; + let mut version = serde_json::json!({ + "federation": super::version::FEDERATION, + "number": 0, + "changes": null, + "keys": given(&keys, "keys"), + "nodes": given(&nodes, "nodes"), + "rules": rules, + }); + if let Some(name) = sub.get_one::("revision") { + let revision = adding(name)?; + if revision != Revision::default() { + version["revision"] = revision.id().to_string().into(); + } + } + let read = Version::read(&client::json(&version).map_err(|why| anyhow!(why))?) + .map_err(|why| anyhow!("no first version: {why}"))?; + read.changes_validly(None) + .map_err(|why| anyhow!("no first version: {why}"))?; + Ok(version) +} + /// The current version, as `counts` names it, checked: its hash its own. fn current(counts: &JsonValue) -> Result { let json = client::json(&counts["version"]["version"]).map_err(|why| anyhow!(why))?; @@ -2534,6 +2670,73 @@ mod tests { assert_ne!(revised.revision, current.revision); } + /// `found` writes a first version from the parties' keys, node lists and rules: each + /// party writing under `home/{party}/` where no rule is given; one rooting a + /// federation, as `root` takes it. + #[test] + fn a_first_version_founded() { + use crate::federation::harness::{Party, node_id}; + use crate::federation::version::Version; + let (tv, lass) = (Party::new("tv", 1), Party::new("lass", 2)); + let dir = crate::files::scratch_dir("party-found"); + let lass_file = dir.join("lass.pub"); + std::fs::write(&lass_file, format!("{} lass@host\n", lass.key_line())).unwrap(); + let founded = |args: &[String]| { + let matches = super::command() + .try_get_matches_from( + ["continuum-party", "found"] + .into_iter() + .map(str::to_owned) + .chain(args.iter().cloned()), + ) + .unwrap(); + let (_, found) = matches.subcommand().unwrap(); + super::founded(found) + }; + let tv_key = format!("tv={}", tv.key_line()); + let lass_key = format!("lass={}", lass_file.display()); + let version = founded(&[ + tv_key.clone(), + lass_key.clone(), + "--nodes".to_owned(), + format!("tv={},{}", node_id(1), node_id(2)), + ]) + .unwrap(); + assert_eq!(version["number"], 0); + assert_eq!(version["keys"]["lass"]["keys"][0], lass.key_line().as_str()); + assert_eq!(version["nodes"]["tv"]["nodes"][1], node_id(2).as_str()); + assert_eq!(version["nodes"]["lass"]["nodes"], serde_json::json!([])); + assert_eq!( + version["rules"], + serde_json::json!([{"path": "home/{party}/**", "writer": "{party}"}]) + ); + let json = crate::federation::client::json(&version).unwrap(); + Version::read(&json).unwrap().changes_validly(None).unwrap(); + + let ruled = founded(&[ + tv_key.clone(), + "--rule".to_owned(), + "names/r/wiki=tv".to_owned(), + "--rule".to_owned(), + "names/**=nobody".to_owned(), + "--revision".to_owned(), + "merge-events".to_owned(), + ]) + .unwrap(); + assert_eq!(ruled["rules"][1]["writer"], false); + assert!(ruled.get("revision").is_some()); + assert!(founded(&[tv_key.clone(), tv_key.clone()]).is_err()); + assert!( + founded(&[ + tv_key.clone(), + "--nodes".to_owned(), + format!("lass={}", node_id(2)) + ]) + .is_err() + ); + assert!(founded(&[tv_key, "--rule".to_owned(), "names/r/wiki=lass".to_owned()]).is_err()); + } + /// `values` shows a place and those under it, not those beside it. #[test] fn places_under_a_path() { -- cgit v1.3.1