From ab9d79ba58562bfcd468afe8c2047a1110e34b7c Mon Sep 17 00:00:00 2001 From: tv Date: Thu, 19 Nov 2026 18:52:37 +0000 Subject: continuum-party: propose admit, remove, give, take, keys, nodes, checkpoint, revision The changes made most no longer go through `next`, jq and a file: each is a subcommand of `propose`, which writes the next version changed so (Intent, intended) and proposes it. * admit PARTY --keys KEY|FILE... [--nodes NODE...]: its keys and node list named anew since the new number; a party already, or no party's name, refused. * remove PARTY: its keys, node list and the rules giving it places go. * give PATH PARTY|{party}: a rule first; one of that path before goes. * take PATH: the rule of that path goes, and where another rule may still give one of its places (overlaps), a rule giving them to nobody goes first. * keys PARTY KEY|FILE..., nodes PARTY NODE...: named anew. * checkpoint: at the heads the node shows. * revision FEATURE: as `next --revision`. Keys are authorized_keys lines, or files of them. Every proposal, a file's too, now says what its version does first (version_lines, shared with `show`) and asks on a terminal; with --yes the one question covers the vote, which then says and asks nothing more. A version changing only its number isn't proposed. --print writes the version instead, to change by hand and propose as a file. --- CHANGELOG.md | 7 + docs/guides/federation/common-changes.md | 119 ++++-- docs/guides/federation/proposing-and-voting.md | 23 +- src/federation/party.rs | 553 +++++++++++++++++++++++-- 4 files changed, 621 insertions(+), 81 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76bc09a..b2664b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ it from the release before ([`docs/operations.md`](docs/operations.md), ## Unreleased +* `continuum-party propose` takes the changes made most by what they are for: `admit`, + `remove`, `give`, `take`, `keys`, `nodes`, `checkpoint` and `revision` write the next + version so and propose it. Every proposal says first what it does, and asks on a + terminal; `--print` writes the version instead + ([`docs/guides/federation/common-changes.md`](docs/guides/federation/common-changes.md); + [`src/federation/party.rs`](src/federation/party.rs)). + * `scripts/wire-check` runs a swarm of the last release's nodes and this tree's on one host, and checks they talk where their wire versions meet, and say so where they don't; `scripts/release` runs it ([`docs/development.md`](docs/development.md), diff --git a/docs/guides/federation/common-changes.md b/docs/guides/federation/common-changes.md index a18d863..8a31080 100644 --- a/docs/guides/federation/common-changes.md +++ b/docs/guides/federation/common-changes.md @@ -1,91 +1,121 @@ # Common changes -Recipes for the changes a federation makes most, each a version to propose and vote on -([`proposing-and-voting.md`](proposing-and-voting.md)), and a few a party makes by itself. +The changes a federation makes most, each a version proposed by a command of its own and +voted on ([`proposing-and-voting.md`](proposing-and-voting.md)), and a few a party makes +by itself. The rules are the design's ([`federation.md`](../../federation.md), [The policy](../../federation.md#the-policy), [Keys](../../federation.md#keys), [Nodes](../../federation.md#nodes)). -## The next version +## How -Every change below begins from the current version: the next number, the current one's -hash as `changes`, and no `checkpoint` (a version names one only to move the store -on, and the current version's heads are behind): +Each change below is a subcommand of `propose`: the client writes the next version, the +current one with the next number, its hash as `changes`, no `checkpoint`, and the change; +says what it does; asks on a terminal; and proposes it. `--yes` votes `true` on it too. +The client's options are as everywhere (`--node`, `--key`, `--record`, or a federation's +directory, [`configuration.md`](../../configuration.md), +[The party's client](../../configuration.md#the-partys-client)), left out below: ```sh -continuum-party --node http://tv:secret@localhost:3000 next > next.json +continuum-party propose admit makefu --keys makefu.key.pub --nodes continuum:e2a8… --yes +# version 2 on 1: +# lets makefu in: 1 key (ssh-ed25519 SHA256:2kq…); 1 node (continuum:e2a8…) +# Propose it, and vote `true` on it? [y/N] y +# c41e… taken +# proposal 8d02… +# 5a77… taken ``` -Each recipe is a `jq` filter on that file; then propose the result, and vote. +The other parties vote as on any proposal (`continuum-party vote 8d02 yes`). ## Letting a party in -Name its keys and its node list anew, `since` the new version's number: - -```sh -jq --arg key "$(cut -d' ' -f1,2 makefu.key.pub)" --arg node continuum:e2a8… ' - .keys.makefu = {since: .number, keys: [$key]} - | .nodes.makefu = {since: .number, nodes: [$node]}' next.json -``` - -A party let in without nodes has an empty list (`nodes: []`) and writes through any node -that takes its events. It begins its record before it votes: from the root, as it never -voted ([`proposing-and-voting.md`](proposing-and-voting.md), +`propose admit PARTY --keys KEY… [--nodes NODE…]`: its keys, each an `authorized_keys` +line as one argument or a file of them (`makefu.key.pub`), and its node list, by node ID, +named anew, `since` the new version's number. A party let in without nodes has an empty +list and writes through any node that takes its events. It begins its record before it +votes: from the root, as it never voted +([`proposing-and-voting.md`](proposing-and-voting.md), [Voting](proposing-and-voting.md#voting)). ## Taking a party out -Leave out its keys and its node list, and the rules giving it places: - -```sh -jq 'del(.keys.lass, .nodes.lass) | .rules |= map(select(.writer != "lass"))' next.json -``` - +`propose remove PARTY`: its keys and node list left out, and the rules giving it places. What it wrote counts no more, nor its key set and node list: its nodes are members no more. To come back, the parties let it in anew. ## Giving a place, taking it back A place goes to a party by a rule before any other that matches its path; the first -match decides: +match decides. `propose give PATH PARTY` adds that rule first, and drops one of the same +path that came before: ```sh -jq '.rules = [{path: "names/r/wiki", writer: "lass"}] + .rules' next.json +continuum-party propose give names/r/wiki lass ``` -To give it to another, change the rule's writer; to take it back, remove the rule or -make its writer `false`. What the former writer signed there counts no more; given back -later, it shows again, unless something replaced it or a checkpoint left it out. +`propose take PATH` gives the places the path matches to nobody: it drops the rule of +that path, and where another rule still gives one of them, adds a rule giving them to +nobody (`"writer": false`) first. What the former writer signed there counts no more; +given back later, it shows again, unless something replaced it or a checkpoint left it +out. ## Zones and blocks -A rule a party holds by its name gives it a zone without a vote for each name in it: +A rule a party holds by its name gives it a zone without a vote for each name in it, a +rule for the name and one for what lies under it: ```sh -jq '.rules += [{path: "names/r/{party}", writer: "{party}"}, - {path: "names/r/{party}/**", writer: "{party}"}]' next.json +continuum-party propose give 'names/r/{party}' '{party}' +continuum-party propose give 'names/r/{party}/**' '{party}' ``` and a block of addresses by its parts, to one party: ```sh -jq '.rules += [{path: "ip4/10/243/7/*", writer: "tv"}]' next.json +continuum-party propose give 'ip4/10/243/7/*' tv ``` Then a new host in the zone or the block is a write, no vote -([`designing-rules.md`](designing-rules.md)). +([`designing-rules.md`](designing-rules.md)). Each `propose` is a version of its own: +the second of two proposed at once lapses when the first passes, so propose the next once +one passed, or write both rules in one version by hand ([By hand](#by-hand)). -## Keys named anew +## Keys and node lists named anew A party that lost a key its version names, or had one stolen, gets its keys named anew (`since` the new number); every key set it wrote before counts no more, and it writes its set again ([`keys.md`](keys.md)): ```sh -jq --arg key "$(cut -d' ' -f1,2 tv-new.key.pub)" ' - .keys.tv = {since: .number, keys: [$key]}' next.json +continuum-party propose keys tv tv-new.key.pub ``` +`propose nodes PARTY NODE…` names a party's node list anew, likewise: where it can't +write its own. + +## By hand + +Anything else, or several changes in one version, is written by hand from the next +version, the current one with the next number, its hash as `changes`, and no +`checkpoint`: + +```sh +continuum-party next > next.json +``` + +or from what a command above would propose, `--print` writing it instead: + +```sh +continuum-party propose give 'names/r/{party}' '{party}' --print > next.json +jq '.rules = [{path: "names/r/{party}/**", writer: "{party}"}] + .rules' next.json \ + > both.json +continuum-party propose both.json +``` + +What each field holds is in [`proposing-and-voting.md`](proposing-and-voting.md), +[Writing a version](proposing-and-voting.md#writing-a-version). + ## What a party does by itself * **Its node list**, signed with a key its version names, no vote: the list as it counts @@ -111,7 +141,12 @@ jq --arg key "$(cut -d' ' -f1,2 tv-new.key.pub)" ' ## Moving to a checkpoint -A version that only moves the store on changes nothing else: the next version, with -`checkpoint` set to the heads ([`checkpoints.md`](checkpoints.md)). Keep other changes -out of it: a node voting by itself backs no version naming a checkpoint that changes -more. +`propose checkpoint`: a version that only moves the store on, to a checkpoint at the +heads the node shows ([`checkpoints.md`](checkpoints.md)). Keep other changes out of it: +a node voting by itself backs no version naming a checkpoint that changes more. + +## Moving to a revision + +`propose revision FEATURE`: the next version, following the revision that adds the +feature, once every party's nodes run a continuum that knows it +([`upgrades.md`](upgrades.md), [Moving to a revision](upgrades.md#moving-to-a-revision)). diff --git a/docs/guides/federation/proposing-and-voting.md b/docs/guides/federation/proposing-and-voting.md index d8410f6..b58a926 100644 --- a/docs/guides/federation/proposing-and-voting.md +++ b/docs/guides/federation/proposing-and-voting.md @@ -10,8 +10,15 @@ its key set are its own to write, without a vote ## Writing a version -A version is the whole policy, not a change to it. Begin from the current one, as a node -shows it, with `number` and `changes` set and its `checkpoint` left out, as below: +The changes made most have a command each, which writes the version from the current +one and proposes it: `propose admit`, `remove`, `give`, `take`, `keys`, `nodes`, +`checkpoint` and `revision` ([`common-changes.md`](common-changes.md)). With `--print`, +each writes the version to standard output instead, to change further and propose as a +file. + +A version is the whole policy, not a change to it. To write one by hand, begin from the +current one, as a node shows it, with `number` and `changes` set and its `checkpoint` +left out, as below: ```sh continuum-party --node http://tv:secret@localhost:3000 next > next.json @@ -55,13 +62,19 @@ drop it ([`when-things-go-wrong.md`](when-things-go-wrong.md), ```sh continuum-party --node http://tv:secret@localhost:3000 --key tv.key --record tv.record \ propose next.json +# version 4 on 3: +# adds rule 1: names/r/wiki -> lass +# Propose it? [y/N] y # c41e… taken # proposal 8d02… ``` -With `--yes`, the client votes `true` on it too, as `vote 8d02… yes` does -([Voting](#voting), below): a party whose node votes for it by itself votes through that -node instead. +The client says what the version does to the current one, as `show` says it of a +proposal ([Following a vote](#following-a-vote)), and asks before it signs, where its +input and its errors are a terminal; asked nothing, as in a script, it goes on. It +proposes nothing that changes the current version only by its number. With `--yes`, it +votes `true` on it too, as `vote 8d02… yes` does ([Voting](#voting), below), asking once +for both: a party whose node votes for it by itself votes through that node instead. The client proposes only a version it would back: one changing the current one as a version must (its `number`, `changes`, and each `since`), whose checkpoint, where it names diff --git a/src/federation/party.rs b/src/federation/party.rs index 35d791e..3dfd951 100644 --- a/src/federation/party.rs +++ b/src/federation/party.rs @@ -17,8 +17,11 @@ //! * `next`: the version after the current one, to change and propose: the current one //! numbered on, naming its hash, without its checkpoint (JSON), to standard output; //! * `propose FILE`: proposes the version `FILE` holds (JSON), where a party may back it -//! (`client::backable`), and says the proposal's hash; with `--yes`, votes `true` on it -//! too, as `vote` does; +//! (`client::backable`), saying first what it does and asking on a terminal, and says +//! the proposal's hash; with `--yes`, votes `true` on it too, as `vote` does; with +//! `--print`, writes the version to standard output instead. `propose admit`, `remove`, +//! `give`, `take`, `keys`, `nodes`, `checkpoint` and `revision` propose the next +//! version changed as they say (`Intent`), likewise; //! * `vote PROPOSAL yes|no`: votes on the proposal of hash `PROPOSAL` on the current //! version, by the record; with `--through`, through the node that votes for the //! party by itself and keeps its record, as such a party votes by hand; @@ -150,14 +153,15 @@ fn command() -> Command { ) .subcommand( Command::new("propose") - .about("Proposes the version a file holds (JSON), and says the proposal's hash") - .arg(id("file")) - .arg( - Arg::new("yes") - .long("yes") - .action(ArgAction::SetTrue) - .help("Votes true on it too, by the record, as vote does"), - ), + .about( + "Proposes a version, saying what it does and asking first on a terminal: the \ + version a file holds (JSON), or the next one changed as a subcommand says", + ) + .arg(id("file").help("A file holding the version (JSON)")) + .args(proposing()) + .args_conflicts_with_subcommands(true) + .subcommand_negates_reqs(true) + .subcommands(intents().into_iter().map(|intent| intent.args(proposing()))), ) .subcommand( Command::new("vote") @@ -216,6 +220,78 @@ fn command() -> Command { ) } +/// `propose`'s own options, and each of its subcommands'. +fn proposing() -> [Arg; 2] { + [ + Arg::new("yes") + .long("yes") + .action(ArgAction::SetTrue) + .help("Votes true on it too, by the record, as vote does"), + Arg::new("print") + .long("print") + .action(ArgAction::SetTrue) + .help("Writes the version to standard output (JSON) instead, to change and propose"), + ] +} + +/// The changes `propose` makes by what they are for (`Intent`), a subcommand each. +fn intents() -> Vec { + let required = |name: &'static str| Arg::new(name).required(true); + let keys = || { + Arg::new("keys") + .value_name("KEY|FILE") + .num_args(1..) + .action(ArgAction::Append) + .help("Keys, each an authorized_keys line, one argument, or a file of such lines") + }; + let nodes = || { + Arg::new("nodes") + .value_name("NODE") + .num_args(0..) + .action(ArgAction::Append) + .help("Node IDs (continuum:…), as `continuum node-id` says them") + }; + vec![ + Command::new("admit") + .about("Lets a party in, naming its keys and its node list") + .arg(required("party")) + .arg(keys().long("keys").required(true)) + .arg(nodes().long("nodes")), + Command::new("remove") + .about("Takes a party out, with the rules giving it places") + .arg(required("party")), + Command::new("give") + .about( + "Gives the places a path matches to a party, or each to the party it names \ + ({party}), by a rule before every other", + ) + .arg(required("path")) + .arg(required("writer").value_name("PARTY|{party}")), + Command::new("take") + .about( + "Gives the places a path matches to nobody: its rule goes, and another \ + still giving one of them is overruled", + ) + .arg(required("path")), + Command::new("keys") + .about("Names a party's keys anew: every key set it wrote before counts no more") + .arg(required("party")) + .arg(keys().required(true)), + Command::new("nodes") + .about("Names a party's node list anew: every node list it wrote before counts no more") + .arg(required("party")) + .arg(nodes()), + Command::new("checkpoint") + .about("Moves the store to a checkpoint at the heads the node shows"), + Command::new("revision") + .about( + "Follows the revision that adds a feature (federation.md, Changing the \ + federation): once every party's nodes run a continuum that knows it", + ) + .arg(required("feature")), + ] +} + /// What lists or changes the party's key set or node list (`whole`), of `items` named /// `value`: `--list`, as it counts, what the command does given none of the others; /// `--add` and `--remove`, changing it as it counts; `--set`, setting it whole; `--force`, @@ -428,6 +504,13 @@ pub(crate) async fn main() -> Result<()> { return Ok(()); } let node = Node::new(&options)?; + if name == "propose" && proposing_flags(sub).get_flag("print") { + let current = node.current().await?; + let version = to_propose(&node, ¤t, sub).await?; + let version: JsonValue = serde_json::from_slice(&version.bytes())?; + println!("{}", serde_json::to_string_pretty(&version)?); + return Ok(()); + } if name == "proposals" { return proposals(&node).await; } @@ -641,13 +724,7 @@ pub(crate) async fn main() -> Result<()> { sign(&node, &signer, &mut record, &path, event::keys(&keys)).await } ("nodes", sub) => { - let given = |name: &str| -> Result> { - let nodes = strings(sub, name); - match nodes.iter().find(|id| !keys::node_id(id)) { - Some(none) => bail!("{none:?} isn't a node ID"), - None => Ok(nodes), - } - }; + let given = |name: &str| node_ids(strings(sub, name)); let counts = node.counts().await?; signer.named_by(¤t(&counts)?)?; let party = &signer.party; @@ -663,11 +740,33 @@ pub(crate) async fn main() -> Result<()> { sign(&node, &signer, &mut record, &path, event::nodes(&nodes)).await } ("propose", sub) => { - let version = version_in(sub.get_one::("file").expect("required"))?; - let current = node.current().await?; + let counts = node.counts().await?; + let current = current(&counts)?; signer.named_by(¤t)?; + let version = to_propose(&node, ¤t, sub).await?; let proposed = client::backable(¤t, &version) .map_err(|why| anyhow!("not a version a party may back: {why}"))?; + if client::described(¤t, &proposed).is_empty() { + bail!( + "it changes nothing of version {} but its number", + current.number + ); + } + // What it proposes, said before anything is signed. + println!("version {} on {}:", proposed.number, current.number); + for line in version_lines(&counts, ¤t, &proposed) { + println!(" {line}"); + } + let yes = proposing_flags(sub).get_flag("yes"); + let question = if yes { + "Propose it, and vote `true` on it?" + } else { + "Propose it?" + }; + if !confirmed(question)? { + println!("nothing proposed"); + return Ok(()); + } sign( &node, &signer, @@ -681,15 +780,24 @@ pub(crate) async fn main() -> Result<()> { "proposal {}", marked(&proposed.hash.to_string(), &proposal_hashes(&counts)) ); - if sub.get_flag("yes") { - vote(&node, &signer, &mut record, &path, proposed.hash, true).await?; + if yes { + vote( + &node, + &signer, + &mut record, + &path, + proposed.hash, + true, + false, + ) + .await?; } Ok(()) } ("vote", sub) => { let proposal = proposal_named(&node.counts().await?, sub)?; let yes = sub.get_one::("yes").map(String::as_str) == Some("yes"); - vote(&node, &signer, &mut record, &path, proposal, yes).await + vote(&node, &signer, &mut record, &path, proposal, yes, true).await } ("again", _) => again(&node, &signer, &mut record, &path).await, _ => unreachable!("every subcommand handled"), @@ -715,6 +823,93 @@ fn proposal_named(counts: &JsonValue, sub: &ArgMatches) -> Result { client::named(given, &hashes, "proposal").map_err(|why| anyhow!(why)) } +/// The matches of `propose` holding `--yes` and `--print`: its subcommand's, where it has +/// one. +fn proposing_flags(sub: &ArgMatches) -> &ArgMatches { + sub.subcommand().map_or(sub, |(_, intent)| intent) +} + +/// What `propose` proposes: the version its file holds, or the version after `current` +/// changed as its subcommand says (`Intent`, `intended`). +async fn to_propose(node: &Node, current: &Version, sub: &ArgMatches) -> Result { + let Some((name, given)) = sub.subcommand() else { + return version_in(sub.get_one::("file").expect("required")); + }; + let intent = intent_of(node, name, given).await?; + client::json(&intended(current, &intent)?).map_err(|why| anyhow!(why)) +} + +/// The change an intent's subcommand `name` asks for, with its arguments `given` +/// (`intents`); of a checkpoint, at the heads `node` shows. +async fn intent_of(node: &Node, name: &str, given: &ArgMatches) -> Result { + let one = |arg: &str| given.get_one::(arg).expect("required").clone(); + Ok(match name { + "admit" => Intent::Admit { + party: one("party"), + keys: key_lines(&strings(given, "keys"))?, + nodes: node_ids(strings(given, "nodes"))?, + }, + "remove" => Intent::Remove(one("party")), + "give" => Intent::Give { + path: one("path"), + writer: one("writer"), + }, + "take" => Intent::Take(one("path")), + "keys" => Intent::Keys { + party: one("party"), + keys: key_lines(&strings(given, "keys"))?, + }, + "nodes" => Intent::Nodes { + party: one("party"), + nodes: node_ids(strings(given, "nodes"))?, + }, + "checkpoint" => Intent::Checkpoint(node.summary().await?.1), + "revision" => Intent::Revision(one("feature")), + _ => unreachable!("every intent handled"), + }) +} + +/// The keys `given` names, as the federation spells them (without comments): each an +/// `authorized_keys` line itself, or a file of such lines, blank ones and `#` comments +/// left out; none twice. +fn key_lines(given: &[String]) -> Result> { + let mut lines: Vec = Vec::new(); + for item in given { + let found = match Key::parse(item) { + Ok(key) => vec![key.line()], + Err(itself) => std::fs::read_to_string(item) + .map_err(|error| anyhow!("{item}: no key ({itself}), nor a file ({error})"))? + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .map(|line| { + Key::parse(line) + .map(|key| key.line()) + .map_err(|why| anyhow!("{item}: {line:?}: {why}")) + }) + .collect::>>()?, + }; + for line in found { + if lines.contains(&line) { + bail!("{} given twice", client::fingerprint(&line)); + } + lines.push(line); + } + } + if lines.is_empty() { + bail!("no key given: a party signs with the keys a version names"); + } + Ok(lines) +} + +/// `given`, where each is a node ID. +fn node_ids(given: Vec) -> Result> { + match given.iter().find(|id| !keys::node_id(id)) { + Some(none) => bail!("{none:?} isn't a node ID"), + None => Ok(given), + } +} + /// `hash`, its shortest prefix that no other of `among` starts with marked, as bold, where /// it goes to a terminal and `NO_COLOR` is unset: the part that names it to the client. fn marked(hash: &str, among: &[String]) -> String { @@ -952,7 +1147,8 @@ async fn sign( node.put(&event).await } -/// A vote, by the record: written to it before it is sent. +/// A vote, by the record: written to it before it is sent. With `ask`, what it votes on is +/// said first, and asked about on a terminal (`confirmed`); without, that was done. async fn vote( node: &Node, signer: &Signer, @@ -960,6 +1156,7 @@ async fn vote( path: &Path, proposal: Id, yes: bool, + ask: bool, ) -> Result<()> { let counts = node.counts().await?; let current = current(&counts)?; @@ -989,8 +1186,10 @@ async fn vote( }; // What it votes on, said before anything is cast. let hashes = proposal_hashes(&counts); - for line in preview(node, &counts, &proposal.to_string(), &hashes).await? { - println!("{line}"); + if ask { + for line in preview(node, &counts, &proposal.to_string(), &hashes).await? { + println!("{line}"); + } } // A later revision: the node knows it, or it stops at the version once it passes; and // so does every other node not known to know it. @@ -1065,10 +1264,12 @@ async fn vote( } let on = client::building(proposing, checkpoint, &kept).map_err(|why| anyhow!(why))?; let word = if yes { "`true`" } else { "`false`" }; - if !confirmed(&format!( - "Vote {word} on {}?", - marked(&proposal.to_string(), &hashes) - ))? { + if ask + && !confirmed(&format!( + "Vote {word} on {}?", + marked(&proposal.to_string(), &hashes) + ))? + { println!("nothing cast"); return Ok(()); } @@ -1207,7 +1408,7 @@ async fn preview( proposed.number, current.number )); lines.extend( - client::described(¤t, &proposed) + version_lines(counts, ¤t, &proposed) .into_iter() .map(|line| format!(" {line}")), ); @@ -1221,6 +1422,14 @@ async fn preview( ), }); } + Ok(lines) +} + +/// What `proposed` does to `current`, in words, a line each: what its version does +/// (`client::described`), the places holding a value in `counts` whose writer it moves, +/// and the nodes not known to know its revision. +fn version_lines(counts: &JsonValue, current: &Version, proposed: &Version) -> Vec { + let mut lines = client::described(current, proposed); let places: Vec<&str> = counts["values"] .as_object() .into_iter() @@ -1228,18 +1437,18 @@ async fn preview( .map(|(place, _)| place.as_str()) .collect(); lines.extend( - client::writers(¤t, &proposed, places) + client::writers(current, proposed, places) .into_iter() - .map(|line| format!(" who writes {line}")), + .map(|line| format!("who writes {line}")), ); if proposed.revision != current.revision { lines.extend( client::unready(counts, proposed.revision) .into_iter() - .map(|line| format!(" not known to know {}: {line}", proposed.revision)), + .map(|line| format!("not known to know {}: {line}", proposed.revision)), ); } - Ok(lines) + lines } /// Whether the user, asked `question` where both its input and the client's errors are a @@ -1296,6 +1505,139 @@ fn next(current: &Version, feature: Option<&str>) -> Result { Ok(next) } +/// A change to a version by what it is for, as `propose` and `fork` take it: the version +/// after the current one, changed so (`intended`). +#[derive(Debug)] +enum Intent { + /// Lets a party in, naming its keys and node list. + Admit { + party: String, + keys: Vec, + nodes: Vec, + }, + /// Takes a party out, with the rules giving it places. + Remove(String), + /// Gives the places a path matches to `writer`, a party or `{party}`, by a rule before + /// every other; a rule of that path before goes. + Give { path: String, writer: String }, + /// Gives the places a path matches to nobody: the rules of that path go, and where + /// another may still give one of them, a rule giving them to nobody goes first. + Take(String), + /// Names a party's keys anew. + Keys { party: String, keys: Vec }, + /// Names a party's node list anew. + Nodes { party: String, nodes: Vec }, + /// Moves the store to a checkpoint at these heads. + Checkpoint(Vec), + /// Follows the revision that adds this feature (`next`). + Revision(String), +} + +/// The version after `current` (`next`), changed as `intent` says: checked here where the +/// change needs `current` (the party it names is one, or isn't yet), and otherwise when it +/// is proposed (`client::backable`). +fn intended(current: &Version, intent: &Intent) -> Result { + if let Intent::Revision(feature) = intent { + return next(current, Some(feature)); + } + let mut next = next(current, None)?; + let number = next["number"].clone(); + let of = |party: &str| -> Result<()> { + if !current.parties.contains_key(party) { + bail!("{party} is no party of version {}", current.number); + } + Ok(()) + }; + match intent { + Intent::Admit { party, keys, nodes } => { + if current.parties.contains_key(party) { + bail!("{party} is a party of version {} already", current.number); + } + if !super::version::is_party(party) { + bail!("{party:?} is no party's name: 1 to 64 of A-Z a-z 0-9 . _ @ -"); + } + next["keys"][party.as_str()] = serde_json::json!({"since": number, "keys": keys}); + next["nodes"][party.as_str()] = serde_json::json!({"since": number, "nodes": nodes}); + } + Intent::Remove(party) => { + of(party)?; + for field in ["keys", "nodes"] { + if let Some(given) = next[field].as_object_mut() { + given.remove(party); + } + } + rules_of(&mut next)?.retain(|rule| rule["writer"].as_str() != Some(party.as_str())); + } + Intent::Give { path, writer } => { + if writer != "{party}" { + of(writer)?; + } + let rules = rules_of(&mut next)?; + rules.retain(|rule| rule["path"].as_str() != Some(path.as_str())); + rules.insert(0, serde_json::json!({"path": path, "writer": writer})); + } + Intent::Take(path) => { + let segments = + super::version::path(path).with_context(|| format!("{path:?} is no path"))?; + let rules = rules_of(&mut next)?; + let before = rules.len(); + rules.retain(|rule| rule["path"].as_str() != Some(path.as_str())); + let dropped = rules.len() < before; + let still = rules.iter().any(|rule| { + rule["writer"] != JsonValue::Bool(false) + && rule["path"] + .as_str() + .and_then(super::version::path) + .is_some_and(|other| overlaps(&segments, &other)) + }); + if still { + rules.insert(0, serde_json::json!({"path": path, "writer": false})); + } else if !dropped { + bail!("nobody writes at {path}: no rule gives a place there"); + } + } + Intent::Keys { party, keys } => { + of(party)?; + next["keys"][party.as_str()] = serde_json::json!({"since": number, "keys": keys}); + } + Intent::Nodes { party, nodes } => { + of(party)?; + next["nodes"][party.as_str()] = serde_json::json!({"since": number, "nodes": nodes}); + } + Intent::Checkpoint(heads) => { + let mut heads = heads.clone(); + heads.sort(); + heads.dedup(); + next["checkpoint"] = heads.iter().map(Id::to_string).collect::>().into(); + } + Intent::Revision(_) => unreachable!("returned above"), + } + Ok(next) +} + +/// The rules of the version `json`. +fn rules_of(json: &mut JsonValue) -> Result<&mut Vec> { + json["rules"] + .as_array_mut() + .context("a version whose rules are no list") +} + +/// Whether some path matches both the rule paths `a` and `b`, as rules spell them (`*` any +/// one segment, `**` last, one or more, `{party}` a party's name): where unsure, as of +/// `{party}` and a name, yes. +fn overlaps(a: &[String], b: &[String]) -> bool { + match (a.split_first(), b.split_first()) { + (None, None) => true, + (Some((first, _)), _) if first.as_str() == "**" => !b.is_empty(), + (_, Some((first, _))) if first.as_str() == "**" => !a.is_empty(), + (Some((x, a)), Some((y, b))) => { + let any = |segment: &str| matches!(segment, "*" | "{party}"); + (any(x) || any(y) || x == y) && overlaps(a, b) + } + _ => false, + } +} + /// 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))?; @@ -1630,6 +1972,149 @@ mod tests { assert_ne!(revised.revision, Revision::default()); } + /// A change by what it is for makes the next version so: a party let in or taken out + /// (its rules with it), a place given (first, the rule of its path before gone) or + /// taken (to nobody, where another rule still gives it), keys and nodes named anew + /// `since` its number, a checkpoint at heads, a revision; each a version the parties + /// may pass, and a party named that isn't one, or one let in that is, refused. + #[test] + fn a_change_by_what_it_is_for() { + use super::{Intent, intended}; + use crate::federation::client; + use crate::federation::harness::{Party, Spec, node_id, str}; + use crate::federation::store::Id; + use crate::federation::version::Version; + let (tv, lass, makefu) = ( + Party::new("tv", 1), + Party::new("lass", 2), + Party::new("makefu", 3), + ); + let current = Version::read( + &Spec::first( + &[&tv, &lass], + &[ + ("names/r/wiki", str("lass")), + ("home/{party}/**", str("{party}")), + ("names/**", str("tv")), + ], + ) + .json(), + ) + .unwrap(); + let made = |intent: Intent| -> Version { + let next = intended(¤t, &intent).unwrap(); + client::backable(¤t, &client::json(&next).unwrap()).unwrap() + }; + let rules = |version: &Version| -> Vec { + let json: serde_json::Value = serde_json::from_slice(&version.json.bytes()).unwrap(); + json["rules"] + .as_array() + .unwrap() + .iter() + .map(|rule| format!("{} {}", rule["path"].as_str().unwrap(), rule["writer"])) + .collect() + }; + + let admitted = made(Intent::Admit { + party: "makefu".to_owned(), + keys: vec![makefu.key_line()], + nodes: vec![node_id(3)], + }); + let given = &admitted.parties["makefu"]; + assert_eq!((given.keys_since, given.nodes_since), (1, 1)); + assert_eq!(given.nodes, [node_id(3)]); + assert!( + intended( + ¤t, + &Intent::Admit { + party: "tv".to_owned(), + keys: vec![tv.key_line()], + nodes: Vec::new(), + }, + ) + .is_err() + ); + + let removed = made(Intent::Remove("lass".to_owned())); + assert!(!removed.parties.contains_key("lass")); + assert!(!rules(&removed).iter().any(|rule| rule.contains("\"lass\""))); + assert!(intended(¤t, &Intent::Remove("makefu".to_owned())).is_err()); + + let given = made(Intent::Give { + path: "names/r/wiki".to_owned(), + writer: "tv".to_owned(), + }); + assert_eq!(rules(&given)[0], r#"names/r/wiki "tv""#); + assert_eq!(rules(&given).len(), 3); + let zone = made(Intent::Give { + path: "names/r/{party}".to_owned(), + writer: "{party}".to_owned(), + }); + assert_eq!(rules(&zone)[0], r#"names/r/{party} "{party}""#); + assert!( + intended( + ¤t, + &Intent::Give { + path: "x".to_owned(), + writer: "makefu".to_owned() + } + ) + .is_err() + ); + + // names/** still gives names/r/wiki once its rule goes: to nobody, first. + let taken = made(Intent::Take("names/r/wiki".to_owned())); + assert_eq!(rules(&taken)[0], "names/r/wiki false"); + assert_eq!( + taken.writer(&["names".into(), "r".into(), "wiki".into()]), + None + ); + // Every place names/** matches, lass's wiki among them. + let taken = made(Intent::Take("names/**".to_owned())); + assert_eq!(rules(&taken)[0], "names/** false"); + assert_eq!(rules(&taken).len(), 3); + // Given by its own rule alone: that rule goes. + let taken = made(Intent::Take("home/{party}/**".to_owned())); + assert_eq!(rules(&taken).len(), 2); + assert!(intended(¤t, &Intent::Take("ip4/10".to_owned())).is_err()); + + let keys = made(Intent::Keys { + party: "tv".to_owned(), + keys: vec![makefu.key_line()], + }); + assert_eq!(keys.parties["tv"].keys, [makefu.key_line()]); + assert_eq!(keys.parties["tv"].keys_since, 1); + let nodes = made(Intent::Nodes { + party: "lass".to_owned(), + nodes: vec![node_id(5)], + }); + assert_eq!(nodes.parties["lass"].nodes_since, 1); + + let (a, b) = (Id::of(b"a"), Id::of(b"b")); + let moved = made(Intent::Checkpoint(vec![b, a, b])); + let mut heads = vec![a, b]; + heads.sort(); + assert_eq!(moved.checkpoint, Some(heads)); + assert!(moved.only_moves_on(¤t)); + + let revised = made(Intent::Revision("merge-events".to_owned())); + assert_ne!(revised.revision, current.revision); + } + + /// Two rule paths overlap where some path matches both. + #[test] + fn rule_paths_overlap() { + let path = |text: &str| crate::federation::version::path(text).unwrap(); + let overlaps = |a: &str, b: &str| super::overlaps(&path(a), &path(b)); + assert!(overlaps("names/r/wiki", "names/**")); + assert!(overlaps("names/r/*", "names/r/wiki")); + assert!(overlaps("home/{party}/**", "home/tv/motd")); + assert!(!overlaps("names/r/wiki", "names/r/wiki/x")); + assert!(!overlaps("names/**", "names")); + assert!(!overlaps("names/r/wiki", "home/**")); + assert!(overlaps("a/**", "a/b/**")); + } + /// Its options come from configuration files as the node's do, arguments winning. #[test] fn its_options_come_from_configuration_files_and_arguments() { -- cgit v1.3.1