Skip to main content

krust/commands/
delegate.rs

1//! Delegated identifiers, delegate side.
2//!
3//! Order (as keripy 1.2+ `Anchorer`, whose delegators only take a fully
4//! witnessed event as delegable): the delegate's witnesses receipt the
5//! `dip`/`drt` first, then it goes to the delegator's mailbox, then a local
6//! watcher follows the delegator's KEL through the delegator's witnesses
7//! until a fully witnessed event anchors the delegate's seal. Only then is
8//! the delegated event completed (source seal couple stored) and published,
9//! with the delegator's KEL, to the delegate's witnesses. Neither side
10//! writes approval state for the other.
11
12use std::time::Duration;
13
14use anyhow::{Context, Result};
15use libkeri::Habery;
16use libkeri_watcher::{http::wait_for_approval, DelegationWatch};
17
18use super::hab::witness_url;
19
20/// Send own delegated event `sn` of `alias` to its delegator's mailbox at one
21/// of the delegator's witnesses, wrapped in a `/fwd` from `sender` (keripy
22/// `Poster.forwardToWitness`). `sender` must be an identifier the delegator's
23/// witness can verify: a proxy for an inception, as keripy requires.
24pub async fn send_to_delegator(hby: &mut Habery, alias: &str, sender: &str, sn: u64) -> Result<()> {
25    let (pre, _) = delegated(hby, alias)?;
26    let msg = hby.db().clone_evt_msg_at(&pre, sn)?;
27    forward_to_delegator(hby, alias, sender, &msg).await?;
28    println!("Sent {} event {} to its delegator", pre, sn);
29    Ok(())
30}
31
32/// Forward `msg` to the delegator of `alias` through the delegator's mailbox
33/// at one of its witnesses, as a `/fwd` from local identifier `sender`.
34async fn forward_to_delegator(hby: &mut Habery, alias: &str, sender: &str, msg: &[u8]) -> Result<()> {
35    let (_, delpre) = delegated(hby, alias)?;
36    let dwits = hby
37        .kevers()
38        .get(&delpre)
39        .map(|k| k.wits())
40        .with_context(|| format!("Delegator {} unknown - resolve its OOBI first", delpre))?;
41    // keripy picks one of the delegator's witnesses at random; any with a
42    // known URL will do.
43    let (mbx, url) = dwits
44        .iter()
45        .find_map(|w| witness_url(hby, w).ok().map(|u| (w.clone(), u)))
46        .with_context(|| format!("No URL for any witness of delegator {}", delpre))?;
47    let fwd = hby
48        .hab_by_name(sender)
49        .with_context(|| format!("Sender identifier '{}' not found", sender))?
50        .forward(&delpre, "delegate", msg, &mbx)?;
51    libkeri_http::Client::new()
52        .send(&url, &mbx, &fwd)
53        .await
54        .with_context(|| format!("Failed to forward to delegator's mailbox at {} ({})", mbx, url))?;
55    Ok(())
56}
57
58/// Watch the delegator's witnesses until the delegator has approved own
59/// event `sn`, then publish the approved event and the delegator's KEL to
60/// own witnesses (keripy `Anchorer.processUnanchoredEscrow` +
61/// `publishDelegator`), and send the approved event, now with its source
62/// seal couple, back to the delegator (keripy `Poster.sendEventToDelegator`):
63/// a keripy delegator accepts the delegated event from that.
64pub async fn wait_and_complete(
65    hby: &mut Habery,
66    alias: &str,
67    sender: &str,
68    sn: u64,
69    timeout: Duration,
70) -> Result<()> {
71    let (pre, delpre) = delegated(hby, alias)?;
72    let mut watch = DelegationWatch::new(hby, &pre, sn)?;
73    let client = libkeri_http::Client::new();
74    println!("Waiting for delegator {} to approve {} event {}...", delpre, pre, sn);
75    let approved = wait_for_approval(&client, hby, &mut watch, Duration::from_secs(1), timeout).await?;
76    println!("Delegator {} approved {} event {}", delpre, pre, sn);
77
78    let (dkel, wits) = {
79        let hab = hby.hab_by_name(alias)?;
80        (hab.replay(Some(&delpre), None)?, hab.kever()?.wits())
81    };
82    for wit in &wits {
83        let url = witness_url(hby, wit)?;
84        client
85            .send(&url, wit, &dkel)
86            .await
87            .with_context(|| format!("Failed to publish delegator KEL to {}", wit))?;
88        client
89            .send(&url, wit, &approved)
90            .await
91            .with_context(|| format!("Failed to publish approved event to {}", wit))?;
92    }
93    forward_to_delegator(hby, alias, sender, &approved).await?;
94    Ok(())
95}
96
97fn delegated(hby: &mut Habery, alias: &str) -> Result<(String, String)> {
98    let hab = hby.hab_by_name(alias)?;
99    let pre = hab.pre.clone().unwrap_or_default();
100    let delpre = hab
101        .kever()?
102        .delpre()
103        .with_context(|| format!("'{}' is not a delegated identifier", alias))?;
104    Ok((pre, delpre))
105}
106
107/// `krust delegate confirm` (kli `delegate confirm`): approve delegated events
108/// waiting for the local delegator `alias`.
109///
110/// A delegated event reaches the delegator in its delegable or misfit escrow.
111/// krust has no mailbox yet, so instead of reading one it can watch the
112/// delegate's witness OOBIs (`--oobi`): keripy 1.2+ delegates have their
113/// witnesses receipt the event before asking for approval, so the witnesses
114/// serve it. Each approval anchors the event's seal in a new interaction (or
115/// rotation) event, which the delegator's witnesses then receipt so the
116/// delegate's watcher (or keripy's query) finds it fully witnessed.
117pub async fn handle_confirm(name: &str, alias: &str, rotate: bool, oobis: &[String], timeout: u64) -> Result<()> {
118    let mut hby = super::hab::open(name, None)?;
119    let client = libkeri_http::Client::new();
120    let deadline = tokio::time::Instant::now() + Duration::from_secs(timeout);
121    let pending = loop {
122        for url in oobis {
123            if let Ok(stream) = client.get_oobi(url).await {
124                // Events for the local delegator land in its escrows.
125                hby.ingest(&stream, false).ok();
126            }
127        }
128        let pending = hby.pending_delegations()?;
129        if !pending.is_empty() {
130            break pending;
131        }
132        if tokio::time::Instant::now() >= deadline {
133            anyhow::bail!("No delegated event to approve after {}s", timeout);
134        }
135        tokio::time::sleep(Duration::from_secs(1)).await;
136    };
137
138    for (pre, sn, said) in pending {
139        hby.approve_delegation(alias, &pre, sn, rotate)
140            .with_context(|| format!("Failed to approve {} event {} ({})", pre, sn, said))?;
141        let dsn = hby
142            .hab_by_name(alias)?
143            .kever()?
144            .sner()
145            .map(|n| n.sn() as u64)
146            .unwrap_or(0);
147        let wits = hby.hab_by_name(alias)?.kever()?.wits();
148        if !wits.is_empty() {
149            let n = super::hab::collect_receipts(&mut hby, alias, dsn).await?;
150            println!("Anchor at sn {} receipted by {} of {} witnesses", dsn, n, wits.len());
151        }
152        println!("Approved delegate {} event {} ({}), anchored at sn {}", pre, sn, said, dsn);
153    }
154    Ok(())
155}