Skip to main content

krust/commands/
hab.rs

1//! Shared keystore access for commands that operate on identifiers.
2//!
3//! Every command opens one `libkeri::Habery` for the keystore, which reloads
4//! identifiers and key state from the database, does its work through a Hab
5//! view, and drops it on exit.
6
7use anyhow::{Context, Result};
8use libkeri::{Habery, HaberyOptions};
9
10/// Open (or create) the keystore `name`. `salt` (qb64) only takes effect when
11/// the keystore is first created.
12pub fn open(name: &str, salt: Option<&str>) -> Result<Habery> {
13    Habery::open(
14        name,
15        HaberyOptions {
16            salt: salt.map(str::to_string),
17            ..Default::default()
18        },
19    )
20    .with_context(|| format!("Failed to open keystore '{}'", name))
21}
22
23/// HTTP URL of witness `wit`, learned by resolving its OOBI.
24pub fn witness_url(hby: &Habery, wit: &str) -> Result<String> {
25    hby.db()
26        .locs
27        .get(&[wit.as_bytes(), b"http".as_slice()])
28        .map_err(|e| anyhow::anyhow!("Failed to look up witness {}: {}", wit, e))?
29        .map(|loc| loc.url)
30        .ok_or_else(|| {
31            anyhow::anyhow!(
32                "No URL for witness {} - resolve its OOBI first (krust oobi resolve)",
33                wit
34            )
35        })
36}
37
38/// Submit own event `sn` of `alias` to each witness's /receipts and store the
39/// receipts (keripy `Receiptor.receipt`, i.e. `kli incept --receipt-endpoint`).
40/// Returns the number of witnesses that receipted.
41pub async fn collect_receipts(hby: &mut Habery, alias: &str, sn: u64) -> Result<usize> {
42    let (event, wits) = {
43        let hab = hby.hab_by_name(alias)?;
44        (hab.make_own_event(sn, false)?, hab.kever()?.wits())
45    };
46    let client = libkeri_http::Client::new();
47    let mut receipted = 0;
48    for wit in &wits {
49        let url = witness_url(hby, wit)?;
50        match client
51            .post_receipt(&url, wit, &event)
52            .await
53            .with_context(|| format!("Witness {} at {} failed", wit, url))?
54        {
55            libkeri_http::ReceiptResponse::Receipted(rct) => {
56                hby.ingest(&rct, false)
57                    .with_context(|| format!("Invalid receipt from witness {}", wit))?;
58                receipted += 1;
59            }
60            libkeri_http::ReceiptResponse::Pending => {
61                eprintln!("Witness {} accepted the event but has not receipted it yet", wit);
62            }
63        }
64    }
65    propagate_receipts(hby, alias, sn, &client).await;
66    Ok(receipted)
67}
68
69/// Send each witness of own event `sn` the other witnesses' receipts (keripy
70/// `Receiptor.receipt` second phase), so every witness holds a fully
71/// witnessed event and can serve it. Failures are reported, not fatal: the
72/// receipts are already collected.
73async fn propagate_receipts(hby: &mut Habery, alias: &str, sn: u64, client: &libkeri_http::Client) {
74    let msgs = match hby.hab_by_name(alias).and_then(|hab| hab.witness_receipt_msgs(sn)) {
75        Ok(msgs) => msgs,
76        Err(e) => {
77            eprintln!("Could not build witness receipt messages: {}", e);
78            return;
79        }
80    };
81    for (wit, msg) in msgs {
82        let sent = match witness_url(hby, &wit) {
83            Ok(url) => client.send(&url, &wit, &msg).await.map_err(anyhow::Error::from),
84            Err(e) => Err(e),
85        };
86        if let Err(e) = sent {
87            eprintln!("Could not send receipts to witness {}: {}", wit, e);
88        }
89    }
90}
91
92/// Send own KEL of `alias` to witnesses `wits` that are new to it (keripy
93/// `Receiptor.catchup`), before they are asked to receipt a rotation that
94/// adds them.
95pub async fn catchup(hby: &mut Habery, alias: &str, wits: &[String]) -> Result<()> {
96    let kel = hby.hab_by_name(alias)?.replay(None, None)?;
97    let client = libkeri_http::Client::new();
98    for wit in wits {
99        let url = witness_url(hby, wit)?;
100        client
101            .send(&url, wit, &kel)
102            .await
103            .with_context(|| format!("Failed to send KEL to new witness {} at {}", wit, url))?;
104    }
105    Ok(())
106}
107
108/// Number of witness signatures stored for own event `sn` of `alias`.
109pub fn receipt_count(hby: &mut Habery, alias: &str, sn: u64) -> Result<usize> {
110    let hab = hby.hab_by_name(alias)?;
111    let pre = hab.pre.clone().unwrap_or_default();
112    let dig = hby
113        .db()
114        .get_ke_last(&libkeri::keri::db::dbing::keys::sn_key(&pre, sn))?
115        .unwrap_or_default();
116    let wigs: Vec<Vec<u8>> = hby
117        .db()
118        .wigs
119        .get(&[&libkeri::keri::db::dbing::keys::dg_key(&pre, dig.as_bytes())])
120        .map_err(|e| anyhow::anyhow!("Failed to read receipts: {}", e))?;
121    Ok(wigs.len())
122}