aboutsummaryrefslogtreecommitdiffstats
path: root/src/federation/party.rs
blob: 8163fb3e117817c5c875e28a90a880ad0a87846d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! `continuum-party`: a party's client of a federation (`docs/federation.md`). It signs its
//! party's events with one of its keys (an OpenSSH private key file, `--key`), puts them
//! through a node's API (`--node`, its user and password in the URL, or `--token`), and
//! keeps its party's record (`--record`, `client::Record`), by which it votes, written
//! before a vote is sent.
//!
//! * `init PARTY`: begins a record of `PARTY`, on the version current now;
//! * `write PATH VALUE`: writes `VALUE` (JSON) at `PATH`;
//! * `keys KEY...`, `nodes NODE...`: writes the party's key set (`authorized_keys` lines)
//!   or node list (node IDs);
//! * `propose FILE`: proposes the version `FILE` holds (JSON);
//! * `vote PROPOSAL yes|no`: votes on the proposal of hash `PROPOSAL` on the current
//!   version, by the record;
//! * `again`: signs again what a move refused;
//! * `twice RECORD...`: names, from the records of parties' clients, a party that voted
//!   twice.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, anyhow, bail};
use clap::{Arg, ArgAction, ArgMatches, Command};
use ed25519_dalek::SigningKey;
use serde_json::Value as JsonValue;

use super::client::{self, Record};
use super::event::{self, Does, Event, Signed};
use super::jcs::Json;
use super::store::Id;
use super::version::Version;
use crate::access::sshsig::PublicKey;

fn command() -> Command {
    let id = |name: &'static str| Arg::new(name).required(true);
    Command::new("continuum-party")
        .about("A party's client of a federation: signs its events, and votes by its record")
        .arg(
            Arg::new("node")
                .long("node")
                .value_name("URL")
                .default_value("http://localhost:3000")
                .help(
                    "The node whose API it puts events through; its user and password in the URL",
                ),
        )
        .arg(
            Arg::new("token")
                .long("token")
                .value_name("TOKEN")
                .help("A token the node issued, instead of a password"),
        )
        .arg(
            Arg::new("key")
                .long("key")
                .value_name("FILE")
                .help("The party's key it signs with: an OpenSSH private key file, unencrypted"),
        )
        .arg(
            Arg::new("record")
                .long("record")
                .value_name("FILE")
                .help("The party's record of its votes, written before each vote is sent"),
        )
        .subcommand_required(true)
        .subcommand(
            Command::new("init")
                .about("Begins a record")
                .arg(id("party")),
        )
        .subcommand(
            Command::new("write")
                .about("Writes a value (JSON) at a path")
                .arg(id("path"))
                .arg(id("value")),
        )
        .subcommand(
            Command::new("keys")
                .about("Writes the party's key set")
                .arg(Arg::new("keys").num_args(1..).required(true)),
        )
        .subcommand(
            Command::new("nodes")
                .about("Writes the party's node list")
                .arg(Arg::new("nodes").num_args(0..)),
        )
        .subcommand(
            Command::new("propose")
                .about("Proposes the version a file holds (JSON)")
                .arg(id("file")),
        )
        .subcommand(
            Command::new("vote")
                .about("Votes on a proposal on the current version, by its hash")
                .arg(id("proposal"))
                .arg(Arg::new("yes").required(true).value_parser(["yes", "no"])),
        )
        .subcommand(Command::new("again").about("Signs again what a move refused"))
        .subcommand(
            Command::new("twice")
                .about("Names, from records, a party that voted twice")
                .arg(
                    Arg::new("records")
                        .num_args(1..)
                        .required(true)
                        .action(ArgAction::Append),
                ),
        )
}

/// Runs the client, as its arguments say.
pub(crate) async fn main() -> Result<()> {
    let matches = command().get_matches();
    let (name, sub) = matches.subcommand().expect("a subcommand is required");
    if name == "twice" {
        let records = sub
            .get_many::<String>("records")
            .into_iter()
            .flatten()
            .map(|path| Record::load(Path::new(path)).map_err(|why| anyhow!(why)))
            .collect::<Result<Vec<_>>>()?;
        for (version, party, why) in client::voted_twice(&records) {
            println!("{party} voted twice on version {version}: {why}");
        }
        return Ok(());
    }
    let node = Node::new(&matches)?;
    let path = PathBuf::from(
        matches
            .get_one::<String>("record")
            .context("--record names the party's record")?,
    );
    if name == "init" {
        if path.exists() {
            bail!("{} holds a record already", path.display());
        }
        let party = sub.get_one::<String>("party").expect("required");
        let (store, _) = node.summary().await?;
        let record = Record::begin(store, party, &node.current().await?);
        record.save(&path).map_err(|why| anyhow!(why))?;
        println!("began a record of {party}, of the store {store}");
        return Ok(());
    }
    let mut record = Record::load(&path).map_err(|why| anyhow!(why))?;
    let key = signing_key(&matches)?;
    let signer = Signer {
        key,
        party: record.party.clone(),
    };
    match (name, sub) {
        ("write", sub) => {
            let path_to = sub.get_one::<String>("path").expect("required");
            let value: JsonValue =
                serde_json::from_str(sub.get_one::<String>("value").expect("required"))
                    .context("the value isn't JSON")?;
            let value = client::json(&value).map_err(|why| anyhow!(why))?;
            sign(
                &node,
                &signer,
                &mut record,
                &path,
                event::write(path_to, value),
            )
            .await
        }
        ("keys", sub) => {
            let keys: Vec<String> = strings(sub, "keys");
            sign(&node, &signer, &mut record, &path, event::keys(&keys)).await
        }
        ("nodes", sub) => {
            let nodes: Vec<String> = strings(sub, "nodes");
            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))?;
            sign(
                &node,
                &signer,
                &mut record,
                &path,
                event::proposal(&version),
            )
            .await
        }
        ("vote", sub) => {
            let proposal = Id::from_hex(sub.get_one::<String>("proposal").expect("required"))
                .context("not a proposal's hash")?;
            let yes = sub.get_one::<String>("yes").map(String::as_str) == Some("yes");
            vote(&node, &signer, &mut record, &path, proposal, yes).await
        }
        ("again", _) => again(&node, &signer, &mut record, &path).await,
        _ => unreachable!("every subcommand handled"),
    }
}

fn strings(matches: &ArgMatches, name: &str) -> Vec<String> {
    matches
        .get_many::<String>(name)
        .into_iter()
        .flatten()
        .cloned()
        .collect()
}

fn signing_key(matches: &ArgMatches) -> Result<SigningKey> {
    let file = matches
        .get_one::<String>("key")
        .context("--key names the party's key")?;
    let text = std::fs::read_to_string(file).with_context(|| format!("Reading {file}"))?;
    client::signing_key(&text).map_err(|why| anyhow!("{file}: {why}"))
}

/// Who signs: the party, with one of its keys.
struct Signer {
    key: SigningKey,
    party: String,
}

impl Signer {
    fn sign(&self, deps: &[Id], does: (&str, Json)) -> Vec<u8> {
        let line = PublicKey(self.key.verifying_key().to_bytes()).line();
        event::signed(&self.key, &self.party, &line, deps, does)
    }
}

/// An event signed on the node's heads, recorded, and put.
async fn sign(
    node: &Node,
    signer: &Signer,
    record: &mut Record,
    path: &Path,
    does: (&str, Json),
) -> Result<()> {
    let (_, heads) = node.summary().await?;
    let event = signer.sign(&heads, does);
    record.signed(&event);
    record.save(path).map_err(|why| anyhow!(why))?;
    node.put(&event).await
}

/// A vote, by the record: written to it before it is sent.
async fn vote(
    node: &Node,
    signer: &Signer,
    record: &mut Record,
    path: &Path,
    proposal: Id,
    yes: bool,
) -> Result<()> {
    let counts = node.counts().await?;
    let current = current(&counts)?;
    let ballots = &counts["proposals"];
    let ids = |hash: &Id, what: &str| -> Vec<Id> {
        ballots[hash.to_string()][what]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|id| id.as_str().and_then(Id::from_hex))
            .collect()
    };
    let Some(proposing) = ids(&proposal, "proposals").first().copied() else {
        bail!("no proposal of hash {proposal} on the current version, as the node reads it");
    };
    let proposed = match Event::read(&node.event(&proposing).await?) {
        Some(Event::Signed(Signed {
            does: Does::Proposal { hash, version },
            ..
        })) if hash == proposal => version,
        _ => bail!("the node's {proposing} isn't the proposal it names"),
    };
    // The votes on its party's earlier proposals it backed, for the nays among them.
    let mut nays = Vec::new();
    let backed: BTreeSet<Id> = record
        .votes
        .iter()
        .filter_map(|text| match Event::read_taken(text.as_bytes()) {
            Some(Event::Signed(Signed {
                does:
                    Does::Vote {
                        on,
                        proposal,
                        yes: true,
                    },
                ..
            })) if on == current.hash => Some(proposal),
            _ => None,
        })
        .collect();
    for earlier in &backed {
        for id in ids(earlier, "votes") {
            nays.push(node.event(&id).await?);
        }
    }
    let kept = record
        .may_vote(&current, proposal, &proposed, yes, &nays)
        .map_err(|why| anyhow!(why))?;
    let (_, heads) = node.summary().await?;
    let cast = signer.sign(&heads, event::vote(current.hash, proposal, yes));
    record.cast(&current, &cast, kept);
    record.save(path).map_err(|why| anyhow!(why))?;
    node.put(&cast).await
}

/// Signs again what a move refused: of the latest event it signed at each place, its key
/// set and its node list, those the node refuses as not above its checkpoint's heads, or
/// as built on one it refuses.
async fn again(node: &Node, signer: &Signer, record: &mut Record, path: &Path) -> Result<()> {
    let refused = node.get("/events/refused").await?;
    let moved: BTreeSet<Id> = refused["refused"]
        .as_array()
        .into_iter()
        .flatten()
        .filter(|entry| matches!(entry["kind"].as_str(), Some("notAbove" | "builtOn")))
        .filter_map(|entry| entry["id"].as_str().and_then(Id::from_hex))
        .collect();
    let again = record.again(|id| moved.contains(id));
    if again.is_empty() {
        println!("nothing to sign again");
    }
    for (refused, does) in again {
        let does = match does {
            Does::Write { path, value } => event::write(&path.join("/"), value),
            Does::Keys(keys) => event::keys(&keys),
            Does::Nodes(nodes) => event::nodes(&nodes),
            Does::Proposal { .. } | Does::Vote { .. } => continue,
        };
        println!("signing again {refused}");
        sign(node, signer, record, path, does).await?;
    }
    Ok(())
}

/// 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))?;
    let version =
        Version::read(&json).map_err(|why| anyhow!("the node's current version: {why}"))?;
    if Some(version.hash.to_string().as_str()) != counts["version"]["hash"].as_str() {
        bail!("the node's current version isn't of the hash it names");
    }
    Ok(version)
}

/// A node's API.
struct Node {
    url: reqwest::Url,
    http: reqwest::Client,
    password: Option<(String, Option<String>)>,
    token: Option<String>,
}

impl Node {
    fn new(matches: &ArgMatches) -> Result<Self> {
        let _ = rustls::crypto::ring::default_provider().install_default();
        let mut url: reqwest::Url = matches
            .get_one::<String>("node")
            .expect("defaulted")
            .parse()
            .context("--node isn't a URL")?;
        let password = (!url.username().is_empty())
            .then(|| (url.username().to_owned(), url.password().map(str::to_owned)));
        let _ = url.set_username("");
        let _ = url.set_password(None);
        Ok(Node {
            url,
            http: reqwest::Client::new(),
            password,
            token: matches.get_one::<String>("token").cloned(),
        })
    }

    fn request(&self, method: reqwest::Method, path: &str) -> Result<reqwest::RequestBuilder> {
        let url = self.url.join(path).context("a path of the node's API")?;
        let request = self.http.request(method, url);
        Ok(match (&self.token, &self.password) {
            (Some(token), _) => request.bearer_auth(token),
            (None, Some((user, password))) => request.basic_auth(user, password.as_ref()),
            (None, None) => request,
        })
    }

    async fn answer(response: reqwest::Response) -> Result<reqwest::Response> {
        let status = response.status();
        if status.is_success() {
            return Ok(response);
        }
        let body = response.text().await.unwrap_or_default();
        bail!("the node answers {status}: {body}")
    }

    async fn get(&self, path: &str) -> Result<JsonValue> {
        let response = self.request(reqwest::Method::GET, path)?.send().await?;
        Ok(Self::answer(response).await?.json().await?)
    }

    /// The store's ID, and its heads.
    async fn summary(&self) -> Result<(Id, Vec<Id>)> {
        let summary = self.get("/events").await?;
        let store = summary["store"]
            .as_str()
            .and_then(Id::from_hex)
            .context("the node names no store")?;
        let heads = summary["heads"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|id| id.as_str().and_then(Id::from_hex))
            .collect();
        Ok((store, heads))
    }

    async fn counts(&self) -> Result<JsonValue> {
        self.get("/events/counts").await
    }

    async fn current(&self) -> Result<Version> {
        current(&self.counts().await?)
    }

    /// The bytes of an event the node's store holds.
    async fn event(&self, id: &Id) -> Result<Vec<u8>> {
        let response = self
            .request(reqwest::Method::GET, &format!("/events/{id}"))?
            .send()
            .await?;
        let bytes = Self::answer(response).await?.bytes().await?.to_vec();
        if Id::of(&bytes) != *id {
            bail!("the node's event {id} isn't of that ID");
        }
        Ok(bytes)
    }

    async fn put(&self, event: &[u8]) -> Result<()> {
        let response = self
            .request(reqwest::Method::POST, "/events")?
            .header(reqwest::header::CONTENT_TYPE, "application/json")
            .body(event.to_vec())
            .send()
            .await?;
        let answer: JsonValue = Self::answer(response).await?.json().await?;
        println!(
            "{} {}",
            answer["id"].as_str().unwrap_or_default(),
            answer["event"].as_str().unwrap_or_default()
        );
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn its_arguments_are_well_formed() {
        super::command().debug_assert();
    }
}