aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation/party.rs
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-19 18:52:37 +0000
committertv <tv@krebsco.de>2026-11-19 20:12:23 +0100
commitab9d79ba58562bfcd468afe8c2047a1110e34b7c (patch)
tree835ce4e444bcd11ef9d90c8f70f2c297e128cecb /src/federation/party.rs
parent97b9c45e5f8b7eed61dd494b977d27790a9544e2 (diff)
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.
Diffstat (limited to 'src/federation/party.rs')
-rw-r--r--src/federation/party.rs553
1 files changed, 519 insertions, 34 deletions
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<Command> {
+ 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, &current, 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<Vec<String>> {
- 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(&current(&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::<String>("file").expect("required"))?;
- let current = node.current().await?;
+ let counts = node.counts().await?;
+ let current = current(&counts)?;
signer.named_by(&current)?;
+ let version = to_propose(&node, &current, sub).await?;
let proposed = client::backable(&current, &version)
.map_err(|why| anyhow!("not a version a party may back: {why}"))?;
+ if client::described(&current, &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, &current, &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::<String>("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<Id> {
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<Json> {
+ let Some((name, given)) = sub.subcommand() else {
+ return version_in(sub.get_one::<String>("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<Intent> {
+ let one = |arg: &str| given.get_one::<String>(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<Vec<String>> {
+ let mut lines: Vec<String> = 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::<Result<Vec<String>>>()?,
+ };
+ 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<String>) -> Result<Vec<String>> {
+ 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(&current, &proposed)
+ version_lines(counts, &current, &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<String> {
+ 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(&current, &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<JsonValue> {
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<String>,
+ nodes: Vec<String>,
+ },
+ /// 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<String> },
+ /// Names a party's node list anew.
+ Nodes { party: String, nodes: Vec<String> },
+ /// Moves the store to a checkpoint at these heads.
+ Checkpoint(Vec<Id>),
+ /// 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<JsonValue> {
+ 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::<Vec<_>>().into();
+ }
+ Intent::Revision(_) => unreachable!("returned above"),
+ }
+ Ok(next)
+}
+
+/// The rules of the version `json`.
+fn rules_of(json: &mut JsonValue) -> Result<&mut Vec<JsonValue>> {
+ 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<Version> {
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(&current, &intent).unwrap();
+ client::backable(&current, &client::json(&next).unwrap()).unwrap()
+ };
+ let rules = |version: &Version| -> Vec<String> {
+ 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(
+ &current,
+ &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(&current, &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(
+ &current,
+ &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(&current, &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(&current));
+
+ 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() {