aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md5
-rw-r--r--docs/guides/federation/getting-started.md12
-rw-r--r--src/federation/party.rs229
3 files changed, 232 insertions, 14 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84a9469..7757bf6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,11 @@ it from the release before ([`docs/operations.md`](docs/operations.md),
## Unreleased
+* `continuum-party found` writes a federation's first version from its parties' keys,
+ node lists and rules
+ ([`docs/guides/federation/getting-started.md`](docs/guides/federation/getting-started.md);
+ [`src/federation/party.rs`](src/federation/party.rs)).
+
* `continuum node-id FILE` prints the node ID of a node key, `--create` making it, without
starting a node ([`docs/lifecycle.md`](docs/lifecycle.md); [`src/config/mod.rs`](src/config/mod.rs)).
diff --git a/docs/guides/federation/getting-started.md b/docs/guides/federation/getting-started.md
index d148672..dc0eb25 100644
--- a/docs/guides/federation/getting-started.md
+++ b/docs/guides/federation/getting-started.md
@@ -44,7 +44,15 @@ printf '%s' 'secret' | argon2 "$(openssl rand -hex 16)" -id -e | sed 's/^/tv:/'
## The first version
-The founders write the first version together, as a file:
+The founders agree on the first version, as a file. `continuum-party found` writes it
+from each party's keys (`PARTY=` an `authorized_keys` line, or a file of them), its node
+list, and the rules in order (`--rule PATH=WRITER`), each party writing in its namespace
+where no rule is given:
+
+```sh
+continuum-party found tv=tv.key.pub lass=lass.key.pub \
+ --nodes tv=continuum:5be1… --nodes lass=continuum:9c07… > first.json
+```
```json
{ "federation": 1, "number": 0, "changes": null,
@@ -57,6 +65,8 @@ The founders write the first version together, as a file:
Each party writes in its namespace (`home/tv/…`), and nowhere else: no other rule gives
a place. Every change of the version takes two thirds of its parties: of two, both.
+`--revision FEATURE` starts it on a later revision of the federation
+([`upgrades.md`](upgrades.md)).
## The root
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,
@@ -184,6 +186,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)")
.arg(id("file")),
@@ -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::<String>("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<JsonValue> {
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<Revision> {
+ 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<JsonValue> {
+ let mut keys: std::collections::BTreeMap<String, Vec<String>> = 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<String, Vec<String>> = 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<JsonValue> = 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::<Result<_>>()?
+ };
+ let given = |lists: &std::collections::BTreeMap<String, Vec<String>>, what: &str| {
+ lists
+ .iter()
+ .map(|(party, items)| (party.clone(), serde_json::json!({"since": 0, what: items})))
+ .collect::<serde_json::Map<String, JsonValue>>()
+ };
+ 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::<String>("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<Version> {
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() {