aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/federation/party.rs116
1 files changed, 110 insertions, 6 deletions
diff --git a/src/federation/party.rs b/src/federation/party.rs
index d5fcb2c..d7880c2 100644
--- a/src/federation/party.rs
+++ b/src/federation/party.rs
@@ -14,7 +14,15 @@
//! party by itself and keeps its record, as such a party votes by hand;
//! * `again`: signs again what a move refused;
//! * `twice RECORD...`: names, from the records of parties' clients, a party that voted
-//! twice.
+//! twice;
+//! * `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 by the version `FILE`
+//! holds, as the node builds it, with the events it keeps: the file the fork's founders
+//! start its swarm from, to standard output;
+//! * `check FILE`: what the node finds of the fork whose root `FILE` holds: whether it
+//! builds it, what it holds that its heads lack, and the parties whose keys it gives
+//! otherwise.
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
@@ -26,8 +34,10 @@ use serde_json::Value as JsonValue;
use super::client::{self, Record};
use super::event::{self, Does, Event, Signed};
+use super::fold::Federation;
use super::jcs::Json;
use super::store::Id;
+use super::store::memory::Store;
use super::version::Version;
use crate::access::sshsig::PublicKey;
@@ -103,6 +113,22 @@ fn command() -> Command {
)
.subcommand(Command::new("again").about("Signs again what a move refused"))
.subcommand(
+ Command::new("root")
+ .about("The root of the federation whose first version a file holds (JSON)")
+ .arg(id("file")),
+ )
+ .subcommand(
+ Command::new("fork")
+ .about("The root of the fork at heads by the version a file holds, as the node builds it")
+ .arg(id("file"))
+ .arg(Arg::new("heads").num_args(1..).required(true)),
+ )
+ .subcommand(
+ Command::new("check")
+ .about("What the node finds of the fork whose root a file holds")
+ .arg(id("file")),
+ )
+ .subcommand(
Command::new("twice")
.about("Names, from records, a party that voted twice")
.arg(
@@ -130,7 +156,51 @@ pub(crate) async fn main() -> Result<()> {
}
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}"))?;
+ let root = event::Checkpoint {
+ at: Vec::new(),
+ keeps: Vec::new(),
+ version,
+ }
+ .bytes();
+ if let Err(refused) = Store::<Federation>::new(root.clone(), Vec::new()) {
+ bail!("no federation's root: {}", refused.0);
+ }
+ return out(&super::fork::root_file(&root, &[]));
+ }
let node = Node::new(&matches)?;
+ if name == "fork" {
+ let version = version_in(sub.get_one::<String>("file").expect("required"))?;
+ let heads = strings(sub, "heads");
+ let body = serde_json::json!({
+ "heads": heads,
+ "version": serde_json::from_slice::<JsonValue>(&version.bytes())?,
+ });
+ return out(&node.post_for_bytes("/admin/events/fork", &body).await?);
+ }
+ if name == "check" {
+ let file = sub.get_one::<String>("file").expect("required");
+ let bytes = std::fs::read(file).with_context(|| format!("Reading {file}"))?;
+ let check = node.post_bytes("/events/fork", bytes).await?;
+ let fork = check["fork"].as_str().unwrap_or_default();
+ match (check["builds"].as_bool(), check["why"].as_str()) {
+ (Some(true), _) => println!("{fork}: built here, byte for byte"),
+ (_, Some(why)) => println!("{fork}: not built here: {why}"),
+ _ => println!("{fork}: not built here: another root at its heads"),
+ }
+ for id in check["lacking"].as_array().into_iter().flatten() {
+ println!("its heads lack {}", id.as_str().unwrap_or_default());
+ }
+ for (party, keys) in check["keys"].as_object().into_iter().flatten() {
+ println!(
+ "{party}'s keys: {} here, {} in the fork",
+ keys["there"], keys["fork"]
+ );
+ }
+ return Ok(());
+ }
// 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");
@@ -191,11 +261,7 @@ pub(crate) async fn main() -> Result<()> {
sign(&node, &signer, &mut record, &path, event::nodes(&nodes)).await
}
("propose", sub) => {
- let file = sub.get_one::<String>("file").expect("required");
- let text = std::fs::read_to_string(file).with_context(|| format!("Reading {file}"))?;
- let version: JsonValue =
- serde_json::from_str(&text).with_context(|| format!("{file} isn't JSON"))?;
- let version = client::json(&version).map_err(|why| anyhow!(why))?;
+ let version = version_in(sub.get_one::<String>("file").expect("required"))?;
sign(
&node,
&signer,
@@ -216,6 +282,23 @@ pub(crate) async fn main() -> Result<()> {
}
}
+/// The version the file `file` holds, as JSON the federation takes.
+fn version_in(file: &str) -> Result<Json> {
+ let text = std::fs::read_to_string(file).with_context(|| format!("Reading {file}"))?;
+ let version: JsonValue =
+ serde_json::from_str(&text).with_context(|| format!("{file} isn't JSON"))?;
+ client::json(&version).map_err(|why| anyhow!(why))
+}
+
+/// `bytes`, to standard output.
+fn out(bytes: &[u8]) -> Result<()> {
+ use std::io::Write;
+ let mut stdout = std::io::stdout().lock();
+ stdout.write_all(bytes)?;
+ stdout.flush()?;
+ Ok(())
+}
+
fn strings(matches: &ArgMatches, name: &str) -> Vec<String> {
matches
.get_many::<String>(name)
@@ -462,6 +545,27 @@ impl Node {
Ok(Self::answer(response).await?.json().await?)
}
+ /// What the node answers to `body`, as bytes.
+ async fn post_for_bytes(&self, path: &str, body: &JsonValue) -> Result<Vec<u8>> {
+ let response = self
+ .request(reqwest::Method::POST, path)?
+ .json(body)
+ .send()
+ .await?;
+ Ok(Self::answer(response).await?.bytes().await?.to_vec())
+ }
+
+ /// What the node answers to the bytes `body`.
+ async fn post_bytes(&self, path: &str, body: Vec<u8>) -> Result<JsonValue> {
+ let response = self
+ .request(reqwest::Method::POST, path)?
+ .header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
+ .body(body)
+ .send()
+ .await?;
+ Ok(Self::answer(response).await?.json().await?)
+ }
+
async fn put(&self, event: &[u8]) -> Result<()> {
let response = self
.request(reqwest::Method::POST, "/events")?