diff options
| author | tv <tv@krebsco.de> | 2026-11-19 16:15:42 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-19 17:36:10 +0100 |
| commit | 9d3350f996ddba2a8e4636dd3705d9bd1c7aa4fb (patch) | |
| tree | eda545027a286d7f5359e4e1f55140ff82e31d30 /src | |
| parent | 866c6a402e65f9102e63cebdf5a50c0a3f526260 (diff) | |
continuum-party: hashes named by their prefixes, the shortest marked
The guides wrote `vote 8d02… yes`, and the client took a whole hash
only. It takes a proposal's hash by a prefix of four digits or more that
no other proposal on the current version starts with (`client::named`),
and says which proposals a prefix names where it names several; a whole
hash is itself, as before. Heads given to `fork` are named so too, among
the heads the node shows. Four digits at least, so that a prefix read a
moment ago doesn't come to name a proposal made since, as one or two
soon would.
Where it shows a proposal's hash (`proposals`, `propose`), the client
marks the shortest prefix that names it, in bold, on a terminal unless
NO_COLOR is set; elsewhere the hash is printed as it was.
Diffstat (limited to 'src')
| -rw-r--r-- | src/federation/client.rs | 86 | ||||
| -rw-r--r-- | src/federation/party.rs | 65 |
2 files changed, 144 insertions, 7 deletions
diff --git a/src/federation/client.rs b/src/federation/client.rs index 57e20e1..ddbc9bb 100644 --- a/src/federation/client.rs +++ b/src/federation/client.rs @@ -395,6 +395,63 @@ pub(crate) fn backable(current: &Version, proposed: &Json) -> Result<Version, St Ok(version) } +/// The fewest hex digits that name a hash in part: fewer would too soon name another, +/// proposed since the part was read. +pub(crate) const PREFIX: usize = 4; + +/// Of each of `ids`, the length of its shortest prefix that no other of them starts with, +/// `PREFIX` digits at least: the part that names it among them. +pub(crate) fn prefixes(ids: &[&str]) -> Vec<usize> { + ids.iter() + .map(|id| { + let shared = ids + .iter() + .filter(|other| *other != id) + .map(|other| { + id.bytes() + .zip(other.bytes()) + .take_while(|(a, b)| a == b) + .count() + }) + .max() + .unwrap_or(0); + (shared + 1).max(PREFIX).min(id.len()) + }) + .collect() +} + +/// The hash `given` names among `ids`: the one it is a prefix of, of `PREFIX` digits at +/// least; or a whole hash, itself, whether among them or not. Why none, where it names +/// none or several, `what` naming what `ids` are. +pub(crate) fn named(given: &str, ids: &[&str], what: &str) -> Result<Id, String> { + let given = given.trim_end_matches('…').to_ascii_lowercase(); + if !given.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(format!("{given:?}: a {what} is named by hex digits")); + } + if let Some(id) = Id::from_hex(&given) { + return Ok(id); + } + if given.len() < PREFIX { + return Err(format!( + "{given}: name a {what} by {PREFIX} digits or more of its hash" + )); + } + let matching: Vec<&str> = ids + .iter() + .copied() + .filter(|id| id.starts_with(&given)) + .collect(); + match matching.as_slice() { + [] => Err(format!("no {what} starts with {given}")), + [one] => Id::from_hex(one).ok_or_else(|| format!("{one}: no hash")), + several => Err(format!( + "{given} names {} of them: {}", + several.len(), + several.join(", ") + )), + } +} + /// What a vote on a proposal builds on: `proposing`, an event proposing it (of a /// checkpoint, one above the heads it names, so that a version event may be written on /// the vote); and, but for a checkpoint (`checkpoint`), the nays that freed its party @@ -1002,6 +1059,35 @@ mod tests { ); } + /// Each hash is named by its shortest prefix no other has, of four digits at least, and + /// found by any prefix it alone has; a whole hash is itself, a short or shared prefix + /// none. + #[test] + fn hashes_are_named_by_their_prefixes() { + let a = "8d02".to_owned() + &"0".repeat(60); + let b = "8d0f".to_owned() + &"1".repeat(60); + let c = "1234".to_owned() + &"2".repeat(60); + let d = "8d02a".to_owned() + &"3".repeat(59); + let ids = [a.as_str(), b.as_str(), c.as_str()]; + assert_eq!(prefixes(&ids), [4, 4, 4]); + assert_eq!(prefixes(&[a.as_str(), d.as_str()]), [5, 5]); + assert_eq!(prefixes(&[a.as_str()]), [4]); + assert_eq!( + named("8d02", &ids, "proposal"), + Ok(Id::from_hex(&a).unwrap()) + ); + assert_eq!( + named("8D0F…", &ids, "proposal"), + Ok(Id::from_hex(&b).unwrap()) + ); + assert_eq!(named(&c, &[], "proposal"), Ok(Id::from_hex(&c).unwrap())); + assert!(named("8d0", &ids, "proposal").is_err()); + assert!(named("8d0x", &ids, "proposal").is_err()); + assert!(named("9999", &ids, "proposal").is_err()); + let shared = named("8d02", &[a.as_str(), d.as_str()], "proposal").unwrap_err(); + assert!(shared.contains("2 of them"), "{shared}"); + } + /// Row 74 (`docs/federation.md`): a party backs X, and Y is proposed at a history /// holding that `true`; X dies after. Its `true` on Y built on Y's proposal alone is /// refused, X being alive at its history; built as a vote builds (`building`), on the diff --git a/src/federation/party.rs b/src/federation/party.rs index a544155..78c31e2 100644 --- a/src/federation/party.rs +++ b/src/federation/party.rs @@ -331,7 +331,18 @@ pub(crate) async fn main() -> Result<()> { } if name == "fork" { let version = version_in(sub.get_one::<String>("file").expect("required"))?; - let heads = strings(sub, "heads"); + // Each head by its ID, or a prefix of one of the heads the node shows. + let (_, shown) = node.summary().await?; + let shown: Vec<String> = shown.iter().map(Id::to_string).collect(); + let shown: Vec<&str> = shown.iter().map(String::as_str).collect(); + let heads = strings(sub, "heads") + .iter() + .map(|head| { + client::named(head, &shown, "head") + .map(|id| id.to_string()) + .map_err(|why| anyhow!(why)) + }) + .collect::<Result<Vec<String>>>()?; let body = serde_json::json!({ "heads": heads, "version": serde_json::from_slice::<JsonValue>(&version.bytes())?, @@ -376,12 +387,12 @@ pub(crate) async fn main() -> Result<()> { } // A party that has a node vote by itself votes by hand only through it. if name == "vote" && sub.get_flag("through") { - let proposal = sub.get_one::<String>("proposal").expect("required"); + let proposal = proposal_named(&node.counts().await?, sub)?; let yes = sub.get_one::<String>("yes").map(String::as_str) == Some("yes"); let answer = node .post( "/admin/events/vote", - &serde_json::json!({"proposal": proposal, "yes": yes}), + &serde_json::json!({"proposal": proposal.to_string(), "yes": yes}), ) .await?; println!("{} cast", answer["id"].as_str().unwrap_or_default()); @@ -507,15 +518,18 @@ pub(crate) async fn main() -> Result<()> { event::proposal(&version), ) .await?; - println!("proposal {}", proposed.hash); + let counts = node.counts().await?; + println!( + "proposal {}", + marked(&proposed.hash.to_string(), &proposal_hashes(&counts)) + ); if sub.get_flag("yes") { vote(&node, &signer, &mut record, &path, proposed.hash, true).await?; } Ok(()) } ("vote", sub) => { - let proposal = Id::from_hex(sub.get_one::<String>("proposal").expect("required")) - .context("not a proposal's hash")?; + 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 } @@ -524,6 +538,41 @@ pub(crate) async fn main() -> Result<()> { } } +/// The hashes of the proposals on the current version, as `counts` names them. +fn proposal_hashes(counts: &JsonValue) -> Vec<String> { + counts["proposals"] + .as_object() + .into_iter() + .flatten() + .map(|(hash, _)| hash.clone()) + .collect() +} + +/// The proposal the argument `proposal` names: by its hash, or a prefix of the hash of one +/// on the current version (`client::named`). +fn proposal_named(counts: &JsonValue, sub: &ArgMatches) -> Result<Id> { + let given = sub.get_one::<String>("proposal").expect("required"); + let hashes = proposal_hashes(counts); + let hashes: Vec<&str> = hashes.iter().map(String::as_str).collect(); + client::named(given, &hashes, "proposal").map_err(|why| anyhow!(why)) +} + +/// `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 { + use std::io::IsTerminal; + if !std::io::stdout().is_terminal() || std::env::var_os("NO_COLOR").is_some() { + return hash.to_owned(); + } + let mut ids: Vec<&str> = among.iter().map(String::as_str).collect(); + if !ids.contains(&hash) { + ids.push(hash); + } + let at = ids.iter().position(|id| *id == hash).expect("among them"); + let length = client::prefixes(&ids)[at]; + format!("\x1b[1m{}\x1b[0m{}", &hash[..length], &hash[length..]) +} + /// The party's keys or nodes (`what`) as they count, as `counts` names them. fn listed(counts: &JsonValue, party: &str, what: &str) -> Vec<String> { counts["parties"][party][what] @@ -928,6 +977,7 @@ async fn proposals(node: &Node) -> Result<()> { names.join(", ") } }; + let hashes = proposal_hashes(&counts); for (hash, proposal) in counts["proposals"].as_object().into_iter().flatten() { let standing = match (proposal["passed"].as_bool(), proposal["dead"].as_bool()) { (Some(true), _) => "passed", @@ -935,7 +985,8 @@ async fn proposals(node: &Node) -> Result<()> { _ => "can still pass", }; println!( - "{hash}: {standing}; true: {}; false: {}", + "{}: {standing}; true: {}; false: {}", + marked(hash, &hashes), parties(&proposal["yes"]), parties(&proposal["no"]) ); |
