1use serde::{Deserialize, Serialize};
30
31pub const DEFAULT_BASE_URL: &str = "https://api.audit.8333.space";
33
34#[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#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct AuditedMint {
52 pub id: u64,
53 pub url: String,
54 #[serde(default)]
58 pub info: Option<serde_json::Value>,
59}
60
61impl AuditedMint {
62 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 pub fn name(&self) -> Option<String> {
74 self.parsed_info().and_then(|i| i.name)
75 }
76
77 pub fn icon_url(&self) -> Option<String> {
80 self.parsed_info().and_then(|i| i.icon_url)
81 }
82}
83
84#[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 #[serde(default)]
108 pub nuts: Option<serde_json::Value>,
109}
110
111#[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 pub created_at: String,
126 pub time_taken: f64,
128 pub state: String,
129 #[serde(default)]
130 pub error: Option<String>,
131}
132
133impl Swap {
134 pub fn is_ok(&self) -> bool {
136 self.state.eq_ignore_ascii_case("ok")
137 }
138}
139
140#[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#[derive(Debug, Clone, Default)]
154pub struct SwapQuery {
155 pub received: Option<bool>,
158 pub skip: Option<u32>,
159 pub limit: Option<u32>,
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
166pub enum HealthRating {
167 Unknown,
169 Healthy,
171 Degraded,
173 Unreliable,
175}
176
177#[derive(Debug, Clone, Serialize, Deserialize)]
180pub struct MintHealth {
181 pub mint_id: u64,
182 pub sampled_swaps: usize,
184 pub ok: usize,
185 pub failed: usize,
186 pub success_rate: f64,
188 pub last_ok_at: Option<String>,
190 pub last_failure_at: Option<String>,
192 pub avg_settle_ms: Option<f64>,
194 pub recent_errors: Vec<String>,
196}
197
198impl MintHealth {
199 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 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#[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 pub fn new() -> Self {
282 Self::with_base_url(DEFAULT_BASE_URL)
283 }
284
285 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 pub async fn list_mints(&self) -> Result<Vec<AuditedMint>, AuditError> {
305 self.get_json("/mints/").await
306 }
307
308 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 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 pub async fn mint(&self, mint_id: u64) -> Result<AuditedMint, AuditError> {
338 self.get_json(&format!("/mints/{mint_id}")).await
339 }
340
341 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 pub async fn stats(&self) -> Result<AuditorStats, AuditError> {
365 self.get_json("/stats/").await
366 }
367
368 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 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
390fn 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()]); }
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}