Skip to main content

cashu_mint_audit/
lib.rs

1//! # cashu-mint-audit
2//!
3//! A tiny async client for the **Cashu mint auditor** ([audit.8333.space]) — the
4//! round-robin auditor by calle that perpetually sends Lightning payments in a
5//! circle between Cashu mints and records which mints pay and which fail.
6//!
7//! This crate wraps its public JSON API (`https://api.audit.8333.space`) and
8//! derives a per-mint **health** summary (success rate, last-seen-good, recent
9//! failures) from the raw swap history, so a wallet can show honest reliability
10//! signal next to a mint before a user trusts it.
11//!
12//! It is deliberately standalone — no wallet, Nostr, or protocol dependencies —
13//! so it can be released and consumed independently.
14//!
15//! ```no_run
16//! # async fn run() -> Result<(), cashu_mint_audit::AuditError> {
17//! let client = cashu_mint_audit::AuditorClient::new();
18//! let mints = client.list_mints().await?;
19//! for m in &mints {
20//!     let health = client.health_for(m.id, 100).await?;
21//!     println!("{} — {:?} ({:.0}% of {} swaps ok)",
22//!         m.url, health.rating(), health.success_rate * 100.0, health.sampled_swaps);
23//! }
24//! # Ok(()) }
25//! ```
26//!
27//! [audit.8333.space]: https://audit.8333.space
28
29use serde::{Deserialize, Serialize};
30
31/// Default base URL of the public auditor API.
32pub const DEFAULT_BASE_URL: &str = "https://api.audit.8333.space";
33
34/// Errors from the auditor client.
35#[derive(Debug, thiserror::Error)]
36pub enum AuditError {
37    #[error("http error: {0}")]
38    Http(#[from] reqwest::Error),
39    #[error("the auditor does not know mint url {0}")]
40    UnknownMint(String),
41    #[error("could not parse auditor response: {0}")]
42    Decode(String),
43}
44
45// ─────────────────────────────── models ───────────────────────────────
46
47/// A mint as tracked by the auditor. `info` is the mint's own NUT-06
48/// `/v1/info` document, captured verbatim by the auditor (as a JSON string on
49/// the wire); use [`AuditedMint::parsed_info`] to decode it.
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct AuditedMint {
52    pub id: u64,
53    pub url: String,
54    /// Raw NUT-06 info as recorded by the auditor. On the wire this is usually a
55    /// JSON *string*; occasionally an object — both are handled by
56    /// [`AuditedMint::parsed_info`].
57    #[serde(default)]
58    pub info: Option<serde_json::Value>,
59}
60
61impl AuditedMint {
62    /// Decode the captured NUT-06 info document, whether it arrived as a string
63    /// or an object. Returns `None` if absent or unparseable.
64    pub fn parsed_info(&self) -> Option<MintInfo> {
65        match &self.info {
66            Some(serde_json::Value::String(s)) => serde_json::from_str(s).ok(),
67            Some(v @ serde_json::Value::Object(_)) => serde_json::from_value(v.clone()).ok(),
68            _ => None,
69        }
70    }
71
72    /// The mint's advertised display name, if any (from NUT-06 info).
73    pub fn name(&self) -> Option<String> {
74        self.parsed_info().and_then(|i| i.name)
75    }
76
77    /// The mint's advertised icon URL, if any (from NUT-06 info). Per the Cashu
78    /// convention, a client should derive a mint's visual identity from this.
79    pub fn icon_url(&self) -> Option<String> {
80        self.parsed_info().and_then(|i| i.icon_url)
81    }
82}
83
84/// A subset of a mint's NUT-06 `/v1/info` document. Unknown fields are ignored;
85/// `nuts` is kept as a raw value since its shape varies by NUT.
86#[derive(Debug, Clone, Default, Serialize, Deserialize)]
87pub struct MintInfo {
88    #[serde(default)]
89    pub name: Option<String>,
90    #[serde(default)]
91    pub pubkey: Option<String>,
92    #[serde(default)]
93    pub version: Option<String>,
94    #[serde(default)]
95    pub description: Option<String>,
96    #[serde(default)]
97    pub description_long: Option<String>,
98    #[serde(default)]
99    pub icon_url: Option<String>,
100    #[serde(default)]
101    pub motd: Option<String>,
102    #[serde(default)]
103    pub tos_url: Option<String>,
104    #[serde(default)]
105    pub time: Option<i64>,
106    /// Supported NUTs, verbatim (shape varies per NUT number).
107    #[serde(default)]
108    pub nuts: Option<serde_json::Value>,
109}
110
111/// One round-robin swap the auditor performed involving a mint. `state == "OK"`
112/// means the swap settled; anything else (with an `error`) is a failure — the
113/// core reliability signal.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Swap {
116    pub id: u64,
117    pub from_id: u64,
118    pub to_id: u64,
119    pub from_url: String,
120    pub to_url: String,
121    pub amount: i64,
122    pub fee: i64,
123    /// ISO-8601 timestamp, e.g. `2026-07-04T15:46:07`. Lexicographically
124    /// sortable, so no date lib is needed to find the most recent.
125    pub created_at: String,
126    /// Milliseconds the swap took.
127    pub time_taken: f64,
128    pub state: String,
129    #[serde(default)]
130    pub error: Option<String>,
131}
132
133impl Swap {
134    /// Whether this swap settled successfully.
135    pub fn is_ok(&self) -> bool {
136        self.state.eq_ignore_ascii_case("ok")
137    }
138}
139
140/// Aggregate auditor statistics.
141#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct AuditorStats {
143    pub total_balance: i64,
144    pub total_swaps: i64,
145    pub total_swaps_24h: i64,
146    pub total_amount_swapped: i64,
147    pub total_amount_swapped_24h: i64,
148    pub average_swap_time: f64,
149    pub average_swap_time_24h: f64,
150}
151
152/// Query filters for [`AuditorClient::swaps`].
153#[derive(Debug, Clone, Default)]
154pub struct SwapQuery {
155    /// `Some(true)` → only swaps the mint *received*; `Some(false)` → only sent;
156    /// `None` → both.
157    pub received: Option<bool>,
158    pub skip: Option<u32>,
159    pub limit: Option<u32>,
160}
161
162// ─────────────────────────────── health ───────────────────────────────
163
164/// A coarse reliability verdict derived from a mint's recent swap history.
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
166pub enum HealthRating {
167    /// No audit swaps in the sample — the auditor has no signal on this mint.
168    Unknown,
169    /// Nearly all recent swaps settled.
170    Healthy,
171    /// A meaningful minority of recent swaps failed.
172    Degraded,
173    /// Recent swaps failed often — treat with caution.
174    Unreliable,
175}
176
177/// A per-mint reliability summary computed from recent audit swaps. This is the
178/// "audit information" a wallet surfaces next to a mint.
179#[derive(Debug, Clone, Serialize, Deserialize)]
180pub struct MintHealth {
181    pub mint_id: u64,
182    /// How many swaps were examined.
183    pub sampled_swaps: usize,
184    pub ok: usize,
185    pub failed: usize,
186    /// `ok / sampled` in `0.0..=1.0`; `0.0` when the sample is empty.
187    pub success_rate: f64,
188    /// `created_at` of the most recent successful swap, if any.
189    pub last_ok_at: Option<String>,
190    /// `created_at` of the most recent failed swap, if any.
191    pub last_failure_at: Option<String>,
192    /// Average settle time (ms) over successful swaps, if any.
193    pub avg_settle_ms: Option<f64>,
194    /// Distinct recent error messages (most-recent-first, deduped, capped).
195    pub recent_errors: Vec<String>,
196}
197
198impl MintHealth {
199    /// Compute a health summary from a slice of swaps (already filtered to one
200    /// mint). Pure — unit-testable without network.
201    pub fn from_swaps(mint_id: u64, swaps: &[Swap]) -> Self {
202        let sampled_swaps = swaps.len();
203        let mut ok = 0usize;
204        let mut failed = 0usize;
205        let mut last_ok_at: Option<String> = None;
206        let mut last_failure_at: Option<String> = None;
207        let mut settle_sum = 0.0f64;
208        let mut recent_errors: Vec<String> = Vec::new();
209
210        for s in swaps {
211            if s.is_ok() {
212                ok += 1;
213                settle_sum += s.time_taken;
214                if last_ok_at.as_deref().map_or(true, |cur| s.created_at.as_str() > cur) {
215                    last_ok_at = Some(s.created_at.clone());
216                }
217            } else {
218                failed += 1;
219                if last_failure_at.as_deref().map_or(true, |cur| s.created_at.as_str() > cur) {
220                    last_failure_at = Some(s.created_at.clone());
221                }
222                if let Some(e) = &s.error {
223                    if !recent_errors.iter().any(|x| x == e) {
224                        recent_errors.push(e.clone());
225                    }
226                }
227            }
228        }
229        recent_errors.truncate(5);
230        let success_rate = if sampled_swaps == 0 {
231            0.0
232        } else {
233            ok as f64 / sampled_swaps as f64
234        };
235        let avg_settle_ms = (ok > 0).then(|| settle_sum / ok as f64);
236
237        MintHealth {
238            mint_id,
239            sampled_swaps,
240            ok,
241            failed,
242            success_rate,
243            last_ok_at,
244            last_failure_at,
245            avg_settle_ms,
246            recent_errors,
247        }
248    }
249
250    /// A coarse verdict. Thresholds are intentionally conservative: with fewer
251    /// than 3 sampled swaps we stay `Unknown` rather than over-claiming.
252    pub fn rating(&self) -> HealthRating {
253        if self.sampled_swaps < 3 {
254            return HealthRating::Unknown;
255        }
256        match self.success_rate {
257            r if r >= 0.98 => HealthRating::Healthy,
258            r if r >= 0.85 => HealthRating::Degraded,
259            _ => HealthRating::Unreliable,
260        }
261    }
262}
263
264// ─────────────────────────────── client ───────────────────────────────
265
266/// Async client for the Cashu mint auditor API.
267#[derive(Debug, Clone)]
268pub struct AuditorClient {
269    base_url: String,
270    http: reqwest::Client,
271}
272
273impl Default for AuditorClient {
274    fn default() -> Self {
275        Self::new()
276    }
277}
278
279impl AuditorClient {
280    /// A client pointed at the public auditor ([`DEFAULT_BASE_URL`]).
281    pub fn new() -> Self {
282        Self::with_base_url(DEFAULT_BASE_URL)
283    }
284
285    /// A client pointed at a custom auditor deployment.
286    pub fn with_base_url(base_url: impl Into<String>) -> Self {
287        let http = reqwest::Client::builder()
288            .user_agent(concat!("cashu-mint-audit/", env!("CARGO_PKG_VERSION")))
289            .build()
290            .unwrap_or_default();
291        Self {
292            base_url: base_url.into().trim_end_matches('/').to_string(),
293            http,
294        }
295    }
296
297    async fn get_json<T: for<'de> Deserialize<'de>>(&self, path: &str) -> Result<T, AuditError> {
298        let url = format!("{}{}", self.base_url, path);
299        let resp = self.http.get(&url).send().await?.error_for_status()?;
300        resp.json::<T>().await.map_err(AuditError::from)
301    }
302
303    /// Every mint the auditor tracks, with its captured NUT-06 info.
304    pub async fn list_mints(&self) -> Result<Vec<AuditedMint>, AuditError> {
305        self.get_json("/mints/").await
306    }
307
308    /// Look a mint up by its URL. Errors [`AuditError::UnknownMint`] if the
309    /// auditor has never seen it.
310    pub async fn mint_by_url(&self, mint_url: &str) -> Result<AuditedMint, AuditError> {
311        let url = format!(
312            "{}/mints/url?url={}",
313            self.base_url,
314            urlencode(mint_url)
315        );
316        let resp = self.http.get(&url).send().await?;
317        if resp.status() == reqwest::StatusCode::NOT_FOUND
318            || resp.status() == reqwest::StatusCode::UNPROCESSABLE_ENTITY
319        {
320            return Err(AuditError::UnknownMint(mint_url.to_string()));
321        }
322        let resp = resp.error_for_status()?;
323        // The endpoint may return a single object or a one-element list.
324        let value: serde_json::Value = resp.json().await?;
325        match value {
326            serde_json::Value::Array(mut arr) => arr
327                .drain(..)
328                .next()
329                .and_then(|v| serde_json::from_value(v).ok())
330                .ok_or_else(|| AuditError::UnknownMint(mint_url.to_string())),
331            other => serde_json::from_value(other)
332                .map_err(|e| AuditError::Decode(e.to_string())),
333        }
334    }
335
336    /// A single mint by its auditor id.
337    pub async fn mint(&self, mint_id: u64) -> Result<AuditedMint, AuditError> {
338        self.get_json(&format!("/mints/{mint_id}")).await
339    }
340
341    /// Swaps involving a mint (most recent first). Use [`SwapQuery`] to filter
342    /// direction / paginate.
343    pub async fn swaps(&self, mint_id: u64, q: &SwapQuery) -> Result<Vec<Swap>, AuditError> {
344        let mut path = format!("/swaps/mint/{mint_id}");
345        let mut sep = '?';
346        if let Some(r) = q.received {
347            path.push(sep);
348            path.push_str(&format!("received={r}"));
349            sep = '&';
350        }
351        if let Some(s) = q.skip {
352            path.push(sep);
353            path.push_str(&format!("skip={s}"));
354            sep = '&';
355        }
356        if let Some(l) = q.limit {
357            path.push(sep);
358            path.push_str(&format!("limit={l}"));
359        }
360        self.get_json(&path).await
361    }
362
363    /// Aggregate auditor statistics.
364    pub async fn stats(&self) -> Result<AuditorStats, AuditError> {
365        self.get_json("/stats/").await
366    }
367
368    /// Fetch up to `sample` recent swaps for a mint and derive its [`MintHealth`].
369    pub async fn health_for(&self, mint_id: u64, sample: u32) -> Result<MintHealth, AuditError> {
370        let swaps = self
371            .swaps(
372                mint_id,
373                &SwapQuery {
374                    received: None,
375                    skip: None,
376                    limit: Some(sample),
377                },
378            )
379            .await?;
380        Ok(MintHealth::from_swaps(mint_id, &swaps))
381    }
382
383    /// Convenience: resolve a mint by URL and compute its health in one call.
384    pub async fn health_for_url(&self, mint_url: &str, sample: u32) -> Result<MintHealth, AuditError> {
385        let mint = self.mint_by_url(mint_url).await?;
386        self.health_for(mint.id, sample).await
387    }
388}
389
390/// Minimal percent-encoding for a query value (enough for mint URLs).
391fn urlencode(s: &str) -> String {
392    let mut out = String::with_capacity(s.len() + 8);
393    for b in s.bytes() {
394        match b {
395            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
396                out.push(b as char)
397            }
398            _ => out.push_str(&format!("%{b:02X}")),
399        }
400    }
401    out
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407
408    fn swap(id: u64, state: &str, ts: &str, err: Option<&str>, ms: f64) -> Swap {
409        Swap {
410            id,
411            from_id: 1,
412            to_id: 2,
413            from_url: "https://a".into(),
414            to_url: "https://b".into(),
415            amount: 10,
416            fee: 1,
417            created_at: ts.into(),
418            time_taken: ms,
419            state: state.into(),
420            error: err.map(|e| e.into()),
421        }
422    }
423
424    #[test]
425    fn health_all_ok_is_healthy() {
426        let swaps = vec![
427            swap(1, "OK", "2026-07-01T10:00:00", None, 2000.0),
428            swap(2, "OK", "2026-07-02T10:00:00", None, 4000.0),
429            swap(3, "OK", "2026-07-03T10:00:00", None, 3000.0),
430        ];
431        let h = MintHealth::from_swaps(1, &swaps);
432        assert_eq!(h.ok, 3);
433        assert_eq!(h.failed, 0);
434        assert_eq!(h.success_rate, 1.0);
435        assert_eq!(h.rating(), HealthRating::Healthy);
436        assert_eq!(h.last_ok_at.as_deref(), Some("2026-07-03T10:00:00"));
437        assert_eq!(h.avg_settle_ms, Some(3000.0));
438    }
439
440    #[test]
441    fn health_mixed_failures_and_last_seen() {
442        let swaps = vec![
443            swap(1, "OK", "2026-07-01T10:00:00", None, 2000.0),
444            swap(2, "FAILED", "2026-07-04T10:00:00", Some("no route"), 0.0),
445            swap(3, "FAILED", "2026-07-02T10:00:00", Some("no route"), 0.0),
446            swap(4, "OK", "2026-07-03T10:00:00", None, 4000.0),
447        ];
448        let h = MintHealth::from_swaps(1, &swaps);
449        assert_eq!(h.ok, 2);
450        assert_eq!(h.failed, 2);
451        assert_eq!(h.success_rate, 0.5);
452        assert_eq!(h.rating(), HealthRating::Unreliable);
453        assert_eq!(h.last_failure_at.as_deref(), Some("2026-07-04T10:00:00"));
454        assert_eq!(h.last_ok_at.as_deref(), Some("2026-07-03T10:00:00"));
455        assert_eq!(h.recent_errors, vec!["no route".to_string()]); // deduped
456    }
457
458    #[test]
459    fn health_small_sample_is_unknown() {
460        let swaps = vec![swap(1, "OK", "2026-07-01T10:00:00", None, 2000.0)];
461        assert_eq!(MintHealth::from_swaps(1, &swaps).rating(), HealthRating::Unknown);
462        assert_eq!(MintHealth::from_swaps(1, &[]).rating(), HealthRating::Unknown);
463    }
464
465    #[test]
466    fn parses_info_string() {
467        let m = AuditedMint {
468            id: 1,
469            url: "https://8333.space:3338".into(),
470            info: Some(serde_json::Value::String(
471                r#"{"name":"Cashu test mint","icon_url":"https://x/i.png","version":"Nutshell/0.20.2"}"#
472                    .into(),
473            )),
474        };
475        assert_eq!(m.name().as_deref(), Some("Cashu test mint"));
476        assert_eq!(m.icon_url().as_deref(), Some("https://x/i.png"));
477    }
478}