Skip to main content

libkeri_watcher/
lib.rs

1//! Local KEL watcher for libkeri.
2//!
3//! A watcher follows another identifier's KEL as that identifier's witnesses
4//! serve it, and tells its owner when the KEL reaches a state the owner is
5//! waiting for. Its first use is delegation approval: a delegate waits for its
6//! delegator to anchor the delegate's seal in a fully witnessed event, then
7//! completes the delegated event ([`Habery::complete_delegation`]).
8//!
9//! This replaces both approaches keripy has used. In keripy 1.1 (`Sealer`)
10//! the delegate asked the delegator before going to its witnesses; in 1.2 and
11//! later (`Anchorer`) the delegate witnesses first and the delegator writes
12//! the authorizer seal into its own database when it confirms. Here neither
13//! side writes approval state for the other. The delegate trusts only the
14//! delegator's KEL as the delegator's witnesses serve it.
15//!
16//! The core is sans-IO, following libkeri's memory model (no threads, locks
17//! or async). [`DelegationWatch::next_request`] says what to fetch, the owner
18//! fetches it however it likes and hands the body to
19//! [`DelegationWatch::feed`] together with its `Habery`. The `http` feature
20//! adds an async driver on libkeri-http ([`http::wait_for_approval`]).
21
22use libkeri::{Habery, KERIError};
23
24#[cfg(feature = "http")]
25pub mod http;
26
27#[derive(Debug, thiserror::Error)]
28pub enum WatchError {
29    #[error(transparent)]
30    Keri(#[from] KERIError),
31    #[error("{0} is not a local delegated identifier")]
32    NotDelegated(String),
33    #[error("no witness of {aid} has a known URL; resolve its OOBI first")]
34    NoSources { aid: String },
35    #[error("transport: {0}")]
36    Transport(String),
37    #[error("timed out after {polls} polls waiting for {what}")]
38    Timeout { what: String, polls: u64 },
39}
40
41/// One witness of the watched identifier and the URL it was resolved at.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Source {
44    pub wit: String,
45    pub url: String,
46}
47
48/// A fetch the owner should perform: an HTTP GET of `url`.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct Request {
51    pub wit: String,
52    pub url: String,
53}
54
55/// What a fed response changed.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum Outcome {
58    /// The delegator has approved: the delegated event with its source seal
59    /// couple (`-G`) attached, ready for the delegate's witnesses.
60    Approved(Vec<u8>),
61    /// Not approved yet; poll again.
62    Pending,
63}
64
65/// The witnesses of `aid` as this Habery knows them: the witness list from
66/// `aid`'s current key state, each with the `http` URL learned from its OOBI.
67/// Witnesses without a known URL are skipped.
68pub fn witness_sources(hby: &Habery, aid: &str) -> Result<Vec<Source>, WatchError> {
69    let Some(kever) = hby.kevers().get(aid) else {
70        return Ok(Vec::new());
71    };
72    let mut sources = Vec::new();
73    for wit in kever.wits() {
74        let loc = hby
75            .db()
76            .locs
77            .get(&[wit.as_bytes(), b"http".as_slice()])
78            .map_err(|e| KERIError::DatabaseError(format!("locs: {}", e)))?;
79        if let Some(loc) = loc {
80            sources.push(Source { wit, url: loc.url });
81        }
82    }
83    Ok(sources)
84}
85
86/// The witness OOBI URL for `aid` at witness `wit` served from `base`
87/// (`{base}/oobi/{aid}/witness/{wit}`). keripy (1.1, 1.2, main) and
88/// libkeri-witness serve the full KEL there once its last event is fully
89/// witnessed.
90pub fn witness_oobi_url(base: &str, aid: &str, wit: &str) -> String {
91    format!("{}/oobi/{}/witness/{}", base.trim_end_matches('/'), aid, wit)
92}
93
94/// Waits for the delegator of a local delegated identifier to approve its
95/// event at `sn`, by following the delegator's KEL through the delegator's
96/// witnesses (keripy: app/delegating.py Anchorer.processUnanchoredEscrow, but
97/// without the delegator or delegate writing the seal for the other).
98#[derive(Debug, Clone)]
99pub struct DelegationWatch {
100    delegate: String,
101    sn: u64,
102    delpre: String,
103    sources: Vec<Source>,
104    next: usize,
105    polls: u64,
106}
107
108impl DelegationWatch {
109    /// Watch for approval of `delegate`'s event at `sn`. The delegator and
110    /// its witnesses come from `hby`: the delegator's KEL and its witnesses'
111    /// OOBIs must have been resolved.
112    pub fn new(hby: &Habery, delegate: &str, sn: u64) -> Result<Self, WatchError> {
113        let delpre = hby
114            .kevers()
115            .get(delegate)
116            .and_then(|k| k.delpre())
117            .ok_or_else(|| WatchError::NotDelegated(delegate.to_string()))?;
118        let sources = witness_sources(hby, &delpre)?;
119        if sources.is_empty() {
120            return Err(WatchError::NoSources { aid: delpre });
121        }
122        Ok(Self::with_sources(delegate, sn, &delpre, sources))
123    }
124
125    /// Watch with an explicit list of the delegator's witnesses.
126    pub fn with_sources(delegate: &str, sn: u64, delpre: &str, sources: Vec<Source>) -> Self {
127        Self {
128            delegate: delegate.to_string(),
129            sn,
130            delpre: delpre.to_string(),
131            sources,
132            next: 0,
133            polls: 0,
134        }
135    }
136
137    pub fn delegate(&self) -> &str {
138        &self.delegate
139    }
140
141    pub fn delpre(&self) -> &str {
142        &self.delpre
143    }
144
145    pub fn sn(&self) -> u64 {
146        self.sn
147    }
148
149    /// Responses fed so far.
150    pub fn polls(&self) -> u64 {
151        self.polls
152    }
153
154    /// Check `hby` as it stands, without fetching anything.
155    pub fn check(&self, hby: &mut Habery) -> Result<Outcome, WatchError> {
156        Ok(match hby.complete_delegation(&self.delegate, self.sn)? {
157            Some(msg) => Outcome::Approved(msg),
158            None => Outcome::Pending,
159        })
160    }
161
162    /// The next fetch: the delegator's KEL from one of its witnesses, taking
163    /// them in turn so one unreachable witness doesn't stall the watch. The
164    /// witness list is refreshed from `hby` first, since the delegator may
165    /// have rotated witnesses.
166    pub fn next_request(&mut self, hby: &Habery) -> Result<Request, WatchError> {
167        let fresh = witness_sources(hby, &self.delpre)?;
168        if !fresh.is_empty() {
169            self.sources = fresh;
170        }
171        if self.sources.is_empty() {
172            return Err(WatchError::NoSources { aid: self.delpre.clone() });
173        }
174        let source = &self.sources[self.next % self.sources.len()];
175        self.next = self.next.wrapping_add(1);
176        Ok(Request {
177            wit: source.wit.clone(),
178            url: witness_oobi_url(&source.url, &self.delpre, &source.wit),
179        })
180    }
181
182    /// Ingest a fetched response (the delegator's KEL and replies, as a
183    /// witness OOBI serves it) and check for approval.
184    pub fn feed(&mut self, hby: &mut Habery, body: &[u8]) -> Result<Outcome, WatchError> {
185        self.polls += 1;
186        if !body.is_empty() {
187            hby.ingest(body, false)?;
188        }
189        self.check(hby)
190    }
191}