Skip to main content

fedimint_cli/
lib.rs

1#![deny(clippy::pedantic, clippy::unwrap_used)]
2#![allow(clippy::doc_markdown)]
3#![allow(clippy::missing_errors_doc)]
4#![allow(clippy::missing_panics_doc)]
5#![allow(clippy::module_name_repetitions)]
6#![allow(clippy::must_use_candidate)]
7#![allow(clippy::ref_option)]
8#![allow(clippy::return_self_not_must_use)]
9#![allow(clippy::too_many_lines)]
10#![allow(clippy::large_futures)]
11
12mod api_request;
13mod cli;
14mod client;
15mod command_encoding;
16mod command_wait;
17mod db;
18pub mod envs;
19mod event_output;
20mod secret_input;
21mod utils;
22mod visualize;
23
24#[cfg(test)]
25mod command_tests;
26
27use core::fmt;
28use std::collections::{BTreeMap, BTreeSet};
29use std::fmt::Debug;
30use std::io::{IsTerminal, Read, Write};
31use std::net::IpAddr;
32use std::path::{Path, PathBuf};
33use std::process::exit;
34use std::str::FromStr;
35use std::sync::Arc;
36use std::time::Duration;
37use std::{fs, result};
38
39use anyhow::{Context, format_err};
40use api_request::ApiRequest;
41use clap::{CommandFactory, Parser};
42use cli::{
43    AdminCmd, Command, DatabaseBackend, DevCmd, Opts, SetupAdminArgs, SetupAdminCmd, VisualizeCmd,
44};
45use envs::SALT_FILE;
46use fedimint_aead::{encrypted_read, encrypted_write, get_encryption_key};
47use fedimint_api_client::api::{DynGlobalApi, FederationApiExt, FederationError};
48use fedimint_api_client::download_from_invite_code;
49use fedimint_bip39::{Bip39RootSecretStrategy, Mnemonic};
50use fedimint_client::db::ApiSecretKey;
51use fedimint_client::module::meta::{FetchKind, LegacyMetaSource, MetaSource};
52use fedimint_client::module::module::init::ClientModuleInit;
53use fedimint_client::module_init::ClientModuleInitRegistry;
54use fedimint_client::secret::RootSecretStrategy;
55use fedimint_client::{AdminCreds, Client, ClientBuilder, ClientHandleArc, RootSecret};
56use fedimint_connectors::{Connectivity, ConnectorRegistry};
57use fedimint_core::config::FederationId;
58use fedimint_core::core::ModuleInstanceId;
59use fedimint_core::db::{Database, IDatabaseTransactionOpsCoreTyped as _};
60use fedimint_core::encoding::Decodable;
61use fedimint_core::invite_code::InviteCode;
62use fedimint_core::module::registry::ModuleRegistry;
63use fedimint_core::module::{ApiAuth, ApiRequestErased};
64use fedimint_core::setup_code::PeerSetupCode;
65use fedimint_core::transaction::Transaction;
66use fedimint_core::util::{SafeUrl, handle_version_hash_command};
67use fedimint_core::{PeerId, fedimint_build_code_version_env, runtime};
68use fedimint_derive_secret::DerivableSecret;
69use fedimint_eventlog::EventLogTrimableId;
70use fedimint_ln_client::LightningClientInit;
71use fedimint_logging::{LOG_CLIENT, TracingSetup};
72use fedimint_meta_client::{MetaClientInit, MetaModuleMetaSourceWithFallback};
73use fedimint_mint_client::{MintClientInit, MintClientModule};
74use fedimint_wallet_client::WalletClientInit;
75use futures::future::join_all;
76use itertools::Itertools;
77use rand::thread_rng;
78use serde::{Deserialize, Serialize};
79use serde_json::{Value, json};
80use thiserror::Error;
81use tracing::{debug, info, warn};
82
83use crate::client::ClientCmd;
84use crate::db::{StoredAdminCreds, load_admin_creds, store_admin_creds};
85
86/// Type of output the cli produces
87#[derive(Serialize)]
88#[serde(rename_all = "snake_case")]
89#[serde(untagged)]
90enum CliOutput {
91    VersionHash {
92        hash: String,
93    },
94
95    UntypedApiOutput {
96        value: Value,
97    },
98
99    WaitBlockCount {
100        reached: u64,
101    },
102
103    InviteCode {
104        invite_code: InviteCode,
105    },
106
107    DecodeInviteCode {
108        url: SafeUrl,
109        federation_id: FederationId,
110    },
111
112    Join {
113        joined: String,
114    },
115
116    DecodeTransaction {
117        transaction: String,
118    },
119
120    EpochCount {
121        count: u64,
122    },
123
124    ConfigDecrypt,
125
126    ConfigEncrypt,
127
128    SetupCode {
129        setup_code: PeerSetupCode,
130    },
131
132    Raw(serde_json::Value),
133}
134
135impl fmt::Display for CliOutput {
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        write!(
138            f,
139            "{}",
140            serde_json::to_string_pretty(self).expect("CliOutput is serializable")
141        )
142    }
143}
144
145#[derive(Debug, Serialize)]
146struct FederationPrivacyReport {
147    federation_id: FederationId,
148    guardians: BTreeMap<String, GuardianPrivacyReport>,
149    summary: FederationPrivacySummary,
150}
151
152#[derive(Debug, Serialize)]
153struct GuardianPrivacyReport {
154    name: String,
155    api_url: SafeUrl,
156    addresses: BTreeMap<String, IpInfoReport>,
157    iroh: Option<IrohConnectionReport>,
158    error: Option<String>,
159}
160
161#[derive(Debug, Serialize)]
162struct IrohConnectionReport {
163    node_id: String,
164    connectivity: &'static str,
165    direct_addr: Option<String>,
166    relay_url: Option<String>,
167}
168
169#[derive(Debug, Clone, Default, Serialize)]
170struct IpInfoReport {
171    address_type: &'static str,
172    #[serde(skip_serializing_if = "Option::is_none")]
173    country: Option<String>,
174    #[serde(skip_serializing_if = "Option::is_none")]
175    asn: Option<String>,
176    #[serde(skip_serializing_if = "Option::is_none")]
177    as_name: Option<String>,
178    #[serde(skip_serializing_if = "Option::is_none")]
179    org: Option<String>,
180    #[serde(skip_serializing_if = "Option::is_none")]
181    error: Option<String>,
182}
183
184#[derive(Debug, Serialize)]
185struct FederationPrivacySummary {
186    guardian_count: usize,
187    iroh_guardian_count: usize,
188    resolved_guardian_count: usize,
189    iroh_direct_guardian_count: usize,
190    iroh_relayed_guardian_count: usize,
191    public_ip_count: usize,
192    countries: BTreeMap<String, usize>,
193    autonomous_systems: BTreeMap<String, usize>,
194}
195
196#[derive(Debug, Deserialize)]
197struct IpWhoResponse {
198    success: Option<bool>,
199    message: Option<String>,
200    country_code: Option<String>,
201    country: Option<String>,
202    connection: Option<IpWhoConnection>,
203}
204
205#[derive(Debug, Deserialize)]
206struct IpWhoConnection {
207    asn: Option<u64>,
208    org: Option<String>,
209    isp: Option<String>,
210}
211
212const IP_LOOKUP_TIMEOUT: Duration = Duration::from_secs(5);
213
214/// `Result` with `CliError` as `Error`
215type CliResult<E> = Result<E, CliError>;
216
217/// `Result` with `CliError` as `Error` and `CliOutput` as `Ok`
218type CliOutputResult = Result<CliOutput, CliError>;
219
220/// Cli error
221#[derive(Serialize, Error)]
222#[serde(tag = "error", rename_all(serialize = "snake_case"))]
223struct CliError {
224    error: String,
225}
226
227/// Extension trait making turning Results/Errors into
228/// [`CliError`]/[`CliOutputResult`] easier
229trait CliResultExt<O, E> {
230    /// Map error into `CliError` wrapping the original error message
231    fn map_err_cli(self) -> Result<O, CliError>;
232    /// Map error into `CliError` using custom error message `msg`
233    fn map_err_cli_msg(self, msg: impl fmt::Display + Send + Sync + 'static)
234    -> Result<O, CliError>;
235}
236
237impl<O, E> CliResultExt<O, E> for result::Result<O, E>
238where
239    E: Into<anyhow::Error>,
240{
241    fn map_err_cli(self) -> Result<O, CliError> {
242        self.map_err(|e| {
243            let e = e.into();
244            CliError {
245                error: format!("{e:#}"),
246            }
247        })
248    }
249
250    fn map_err_cli_msg(
251        self,
252        msg: impl fmt::Display + Send + Sync + 'static,
253    ) -> Result<O, CliError> {
254        self.map_err(|e| Into::<anyhow::Error>::into(e))
255            .context(msg)
256            .map_err(|e| CliError {
257                error: format!("{e:#}"),
258            })
259    }
260}
261
262/// Extension trait to make turning `Option`s into
263/// [`CliError`]/[`CliOutputResult`] easier
264trait CliOptionExt<O> {
265    fn ok_or_cli_msg(self, msg: impl Into<String>) -> Result<O, CliError>;
266}
267
268impl<O> CliOptionExt<O> for Option<O> {
269    fn ok_or_cli_msg(self, msg: impl Into<String>) -> Result<O, CliError> {
270        self.ok_or_else(|| CliError { error: msg.into() })
271    }
272}
273
274// TODO: Refactor federation API errors to just delegate to this
275impl From<FederationError> for CliError {
276    fn from(e: FederationError) -> Self {
277        CliError {
278            error: e.to_string(),
279        }
280    }
281}
282
283impl Debug for CliError {
284    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285        f.debug_struct("CliError")
286            .field("error", &self.error)
287            .finish()
288    }
289}
290
291impl fmt::Display for CliError {
292    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
293        let json = serde_json::to_value(self).expect("CliError is valid json");
294        let json_as_string =
295            serde_json::to_string_pretty(&json).expect("valid json is serializable");
296        write!(f, "{json_as_string}")
297    }
298}
299
300impl Opts {
301    fn data_dir(&self) -> CliResult<&PathBuf> {
302        self.data_dir
303            .as_ref()
304            .ok_or_cli_msg("`--data-dir=` argument not set.")
305    }
306
307    /// Get and create if doesn't exist the data dir
308    async fn data_dir_create(&self) -> CliResult<&PathBuf> {
309        let dir = self.data_dir()?;
310
311        tokio::fs::create_dir_all(&dir).await.map_err_cli()?;
312
313        Ok(dir)
314    }
315    fn iroh_enable_dht(&self) -> bool {
316        self.iroh_enable_dht.unwrap_or(true)
317    }
318
319    fn use_tor(&self) -> bool {
320        #[cfg(feature = "tor")]
321        return self.use_tor;
322        #[cfg(not(feature = "tor"))]
323        false
324    }
325
326    async fn admin_client(
327        &self,
328        peer_urls: &BTreeMap<PeerId, SafeUrl>,
329        api_secret: Option<&str>,
330    ) -> CliResult<DynGlobalApi> {
331        self.admin_client_with_db(peer_urls, api_secret, None).await
332    }
333
334    async fn admin_client_with_db(
335        &self,
336        peer_urls: &BTreeMap<PeerId, SafeUrl>,
337        api_secret: Option<&str>,
338        db: Option<&Database>,
339    ) -> CliResult<DynGlobalApi> {
340        // First try CLI argument, then stored credentials
341        let our_id = if let Some(id) = self.our_id {
342            id
343        } else if let Some(db) = db {
344            if let Some(stored_creds) = load_admin_creds(db).await {
345                stored_creds.peer_id
346            } else {
347                return Err(CliError {
348                    error: "Admin client needs our-id set (no stored credentials found)"
349                        .to_string(),
350                });
351            }
352        } else {
353            return Err(CliError {
354                error: "Admin client needs our-id set".to_string(),
355            });
356        };
357
358        Ok(DynGlobalApi::new_admin(
359            self.make_endpoints().await.map_err(|e| CliError {
360                error: e.to_string(),
361            })?,
362            our_id,
363            peer_urls
364                .get(&our_id)
365                .cloned()
366                .context("Our peer URL not found in config")
367                .map_err_cli()?,
368            api_secret,
369        ))
370    }
371
372    async fn make_endpoints(&self) -> Result<ConnectorRegistry, anyhow::Error> {
373        Ok(ConnectorRegistry::build_from_client_defaults()
374            .iroh_pkarr_dht(self.iroh_enable_dht())
375            .ws_force_tor(self.use_tor())
376            .bind()
377            .await)
378    }
379
380    fn auth(&self) -> CliResult<ApiAuth> {
381        let password = self
382            .password
383            .clone()
384            .ok_or_cli_msg("CLI needs password set")?;
385        Ok(ApiAuth::new(password))
386    }
387
388    async fn load_database(&self) -> CliResult<Database> {
389        debug!(target: LOG_CLIENT, "Loading client database");
390        let db_path = self.data_dir_create().await?.join("client.db");
391        match self.db_backend {
392            DatabaseBackend::RocksDb => {
393                debug!(target: LOG_CLIENT, "Using RocksDB database backend");
394                Ok(fedimint_rocksdb::RocksDb::build(db_path)
395                    .open()
396                    .await
397                    .map_err_cli_msg("could not open rocksdb database")?
398                    .into())
399            }
400            DatabaseBackend::CursedRedb => {
401                debug!(target: LOG_CLIENT, "Using CursedRedb database backend");
402                Ok(fedimint_cursed_redb::MemAndRedb::new(db_path)
403                    .await
404                    .map_err_cli_msg("could not open cursed redb database")?
405                    .into())
406            }
407        }
408    }
409}
410
411fn decode_federation_secret_hex(federation_secret_hex: &str) -> CliResult<DerivableSecret> {
412    <DerivableSecret as Decodable>::consensus_decode_hex(
413        federation_secret_hex,
414        &ModuleRegistry::default(),
415    )
416    .map_err(|_| CliError {
417        error: "Invalid federation secret hex".to_owned(),
418    })
419}
420
421enum RecoverySecret {
422    Mnemonic(Mnemonic),
423    FederationSecret(DerivableSecret),
424}
425
426fn root_secret_from_mnemonic(mnemonic: &Mnemonic) -> RootSecret {
427    RootSecret::StandardDoubleDerive(Bip39RootSecretStrategy::<12>::to_root_secret(mnemonic))
428}
429
430async fn load_or_generate_mnemonic(db: &Database) -> Result<Mnemonic, CliError> {
431    Ok(
432        if let Ok(entropy) = Client::load_decodable_client_secret::<Vec<u8>>(db).await {
433            Mnemonic::from_entropy(&entropy).map_err_cli()?
434        } else {
435            debug!(
436                target: LOG_CLIENT,
437                "Generating mnemonic and writing entropy to client storage"
438            );
439            let mnemonic = Bip39RootSecretStrategy::<12>::random(&mut thread_rng());
440            Client::store_encodable_client_secret(db, mnemonic.to_entropy())
441                .await
442                .map_err_cli()?;
443            mnemonic
444        },
445    )
446}
447
448async fn query_guardian_addresses(
449    connectors: &ConnectorRegistry,
450    endpoints: &BTreeMap<PeerId, fedimint_core::config::PeerUrl>,
451    path_timeout: Duration,
452) -> Vec<(PeerId, GuardianPrivacyReport)> {
453    join_all(endpoints.iter().map(|(peer_id, peer_url)| async move {
454        let mut report = GuardianPrivacyReport {
455            name: peer_url.name.clone(),
456            api_url: peer_url.url.clone(),
457            addresses: BTreeMap::new(),
458            iroh: None,
459            error: None,
460        };
461
462        if peer_url.url.scheme() == "iroh" {
463            match connectors.iroh_peer_info(&peer_url.url, path_timeout).await {
464                Ok(Some(iroh_info)) => {
465                    let direct_addr = iroh_info.direct_addr;
466                    let known_direct_addrs = iroh_info.known_direct_addrs;
467                    let known_direct_ips = known_direct_addrs
468                        .iter()
469                        .chain(direct_addr.iter())
470                        .map(std::net::SocketAddr::ip)
471                        .collect::<BTreeSet<_>>();
472
473                    report.addresses = ip_info_map_from_ips(known_direct_ips);
474                    report.iroh = Some(IrohConnectionReport {
475                        node_id: iroh_info.node_id,
476                        connectivity: connectivity_name(iroh_info.connectivity),
477                        direct_addr: direct_addr.map(|addr| addr.to_string()),
478                        relay_url: iroh_info.relay_url,
479                    });
480                }
481                Ok(None) => {}
482                Err(error) => {
483                    report.error = Some(error.to_string());
484                }
485            }
486        } else {
487            match resolve_endpoint_ips(&peer_url.url).await {
488                Ok(ips) => {
489                    report.addresses = ip_info_map_from_ips(ips);
490                }
491                Err(error) => {
492                    report.error = Some(error.to_string());
493                }
494            }
495        }
496
497        (*peer_id, report)
498    }))
499    .await
500}
501
502fn ip_info_map_from_ips(ips: BTreeSet<IpAddr>) -> BTreeMap<String, IpInfoReport> {
503    ips.into_iter()
504        .map(|ip| {
505            (
506                ip.to_string(),
507                IpInfoReport {
508                    address_type: ip_address_type(ip),
509                    ..IpInfoReport::default()
510                },
511            )
512        })
513        .collect()
514}
515
516async fn resolve_endpoint_ips(url: &SafeUrl) -> anyhow::Result<BTreeSet<IpAddr>> {
517    let host = url
518        .host_str()
519        .context("endpoint URL does not contain a host")?;
520    if let Ok(ip) = IpAddr::from_str(host) {
521        return Ok(BTreeSet::from([ip]));
522    }
523
524    let port = endpoint_resolution_port(url).ok_or_else(|| {
525        format_err!(
526            "endpoint URL scheme {} does not have a known resolution port",
527            url.scheme()
528        )
529    })?;
530
531    let addresses = tokio::net::lookup_host((host, port))
532        .await
533        .with_context(|| format!("failed to resolve endpoint host {host}"))?
534        .map(|addr| addr.ip())
535        .collect();
536
537    Ok(addresses)
538}
539
540fn endpoint_resolution_port(url: &SafeUrl) -> Option<u16> {
541    url.port_or_known_default().or(match url.scheme() {
542        "http" | "ws" => Some(80),
543        "https" | "wss" => Some(443),
544        _ => None,
545    })
546}
547
548fn all_iroh_guardians_direct(reports: &[(PeerId, GuardianPrivacyReport)]) -> bool {
549    reports
550        .iter()
551        .filter(|(_, report)| report.api_url.scheme() == "iroh")
552        .all(|(_, report)| {
553            report
554                .iroh
555                .as_ref()
556                .is_some_and(|iroh| matches!(iroh.connectivity, "direct" | "mixed"))
557        })
558}
559
560async fn enrich_guardian_ip_info(reports: &mut [(PeerId, GuardianPrivacyReport)]) {
561    let http_client = reqwest::Client::builder()
562        .timeout(IP_LOOKUP_TIMEOUT)
563        .build()
564        .expect("IP lookup HTTP client config is valid");
565    let unique_ips = reports
566        .iter()
567        .flat_map(|(_, report)| {
568            report
569                .addresses
570                .iter()
571                .filter(|(_, ip_info)| ip_info.address_type == "public")
572                .filter_map(|(ip, _)| IpAddr::from_str(ip).ok())
573        })
574        .collect::<BTreeSet<_>>();
575
576    let lookup_cache = join_all(unique_ips.into_iter().map(|ip| {
577        let http_client = http_client.clone();
578        async move { (ip.to_string(), lookup_ip_info(&http_client, ip).await) }
579    }))
580    .await
581    .into_iter()
582    .collect::<BTreeMap<_, _>>();
583
584    for (_, report) in reports {
585        for (ip, ip_info) in &mut report.addresses {
586            if let Some(lookup) = lookup_cache.get(ip) {
587                *ip_info = IpInfoReport {
588                    address_type: ip_info.address_type,
589                    ..lookup.clone()
590                };
591            }
592        }
593    }
594}
595
596async fn lookup_ip_info(http_client: &reqwest::Client, ip: IpAddr) -> IpInfoReport {
597    let url = format!("https://ipwho.is/{ip}");
598    let response = http_client
599        .get(url)
600        .send()
601        .await
602        .and_then(reqwest::Response::error_for_status);
603
604    let response = match response {
605        Ok(response) => response,
606        Err(error) => {
607            return IpInfoReport {
608                address_type: "public",
609                country: None,
610                asn: None,
611                as_name: None,
612                org: None,
613                error: Some(error.to_string()),
614            };
615        }
616    };
617
618    match response.json::<IpWhoResponse>().await {
619        Ok(body) if body.success.unwrap_or(true) => {
620            let connection = body.connection;
621            let asn = connection
622                .as_ref()
623                .and_then(|connection| connection.asn)
624                .map(|asn| format!("AS{asn}"));
625            let org = connection
626                .as_ref()
627                .and_then(|connection| connection.org.clone());
628            let as_name = org
629                .clone()
630                .or_else(|| connection.and_then(|connection| connection.isp));
631
632            IpInfoReport {
633                address_type: "public",
634                country: body.country_code.or(body.country),
635                asn,
636                as_name,
637                org,
638                error: None,
639            }
640        }
641        Ok(body) => IpInfoReport {
642            address_type: "public",
643            country: None,
644            asn: None,
645            as_name: None,
646            org: None,
647            error: Some(
648                body.message
649                    .unwrap_or_else(|| "IP lookup service returned an error".to_owned()),
650            ),
651        },
652        Err(error) => IpInfoReport {
653            address_type: "public",
654            country: None,
655            asn: None,
656            as_name: None,
657            org: None,
658            error: Some(error.to_string()),
659        },
660    }
661}
662
663fn summarize_privacy_report<'a>(
664    reports: impl IntoIterator<Item = &'a GuardianPrivacyReport>,
665) -> FederationPrivacySummary {
666    let mut countries = BTreeMap::new();
667    let mut autonomous_systems = BTreeMap::new();
668    let mut unique_public_ips = BTreeSet::new();
669    let reports = reports.into_iter().collect::<Vec<_>>();
670
671    for report in &reports {
672        let mut guardian_countries = BTreeSet::new();
673        let mut guardian_autonomous_systems = BTreeSet::new();
674
675        unique_public_ips.extend(
676            report
677                .addresses
678                .iter()
679                .filter(|(_, ip_info)| ip_info.address_type == "public")
680                .map(|(ip, _)| ip.clone()),
681        );
682
683        for ip_info in report
684            .addresses
685            .values()
686            .filter(|ip_info| ip_info.address_type == "public")
687        {
688            if let Some(country) = &ip_info.country {
689                guardian_countries.insert(country.clone());
690            }
691            let as_label = match (&ip_info.asn, &ip_info.as_name) {
692                (Some(asn), Some(as_name)) => Some(format!("{asn} {as_name}")),
693                (Some(asn), None) => Some(asn.clone()),
694                (None, Some(as_name)) => Some(as_name.clone()),
695                (None, None) => None,
696            };
697            if let Some(as_label) = as_label {
698                guardian_autonomous_systems.insert(as_label);
699            }
700        }
701
702        for country in guardian_countries {
703            *countries.entry(country).or_insert(0) += 1;
704        }
705        for autonomous_system in guardian_autonomous_systems {
706            *autonomous_systems.entry(autonomous_system).or_insert(0) += 1;
707        }
708    }
709
710    FederationPrivacySummary {
711        guardian_count: reports.len(),
712        iroh_guardian_count: reports
713            .iter()
714            .filter(|report| report.api_url.scheme() == "iroh")
715            .count(),
716        resolved_guardian_count: reports
717            .iter()
718            .filter(|report| !report.addresses.is_empty())
719            .count(),
720        iroh_direct_guardian_count: reports
721            .iter()
722            .filter(|report| {
723                report
724                    .iroh
725                    .as_ref()
726                    .is_some_and(|iroh| matches!(iroh.connectivity, "direct" | "mixed"))
727            })
728            .count(),
729        iroh_relayed_guardian_count: reports
730            .iter()
731            .filter(|report| {
732                report
733                    .iroh
734                    .as_ref()
735                    .is_some_and(|iroh| iroh.connectivity == "relay")
736            })
737            .count(),
738        public_ip_count: unique_public_ips.len(),
739        countries,
740        autonomous_systems,
741    }
742}
743
744fn connectivity_name(connectivity: Connectivity) -> &'static str {
745    match connectivity {
746        Connectivity::Direct => "direct",
747        Connectivity::Relay => "relay",
748        Connectivity::Mixed => "mixed",
749        Connectivity::Tor => "tor",
750        Connectivity::Unknown => "unknown",
751    }
752}
753
754fn ip_address_type(ip: IpAddr) -> &'static str {
755    match ip {
756        IpAddr::V4(ip) => {
757            if ip.is_private() {
758                "private"
759            } else if ip.is_loopback() {
760                "loopback"
761            } else if ip.is_link_local() {
762                "link_local"
763            } else if ip.is_broadcast() {
764                "broadcast"
765            } else if matches!(
766                ip.octets(),
767                [192, 0, 2, _] | [198, 51, 100, _] | [203, 0, 113, _]
768            ) {
769                "documentation"
770            } else if matches!(ip.octets(), [100, second, _, _] if (64..=127).contains(&second)) {
771                "shared"
772            } else if matches!(ip.octets(), [198, 18 | 19, _, _]) {
773                "benchmark"
774            } else if ip.is_multicast() {
775                "multicast"
776            } else if ip.is_unspecified() {
777                "unspecified"
778            } else {
779                "public"
780            }
781        }
782        IpAddr::V6(ip) => {
783            if ip.is_loopback() {
784                "loopback"
785            } else if ip.is_unspecified() {
786                "unspecified"
787            } else if ip.is_unique_local() {
788                "unique_local"
789            } else if ip.is_unicast_link_local() {
790                "link_local"
791            } else if ip.segments()[0] == 0x2001 && ip.segments()[1] == 0x0db8 {
792                "documentation"
793            } else if ip.is_multicast() {
794                "multicast"
795            } else {
796                "public"
797            }
798        }
799    }
800}
801
802pub struct FedimintCli {
803    module_inits: ClientModuleInitRegistry,
804    cli_args: Opts,
805}
806
807impl FedimintCli {
808    /// Build a new `fedimintd` with a custom version hash
809    pub fn new(version_hash: &str) -> anyhow::Result<FedimintCli> {
810        assert_eq!(
811            fedimint_build_code_version_env!().len(),
812            version_hash.len(),
813            "version_hash must have an expected length"
814        );
815
816        handle_version_hash_command(version_hash);
817
818        let mut cli_args = Opts::parse();
819        secret_input::check_module_stdin(&cli_args)?;
820        cli_args.resolve_secret_inputs()?;
821        let base_level = if cli_args.verbose { "debug" } else { "info" };
822        TracingSetup::default()
823            .with_base_level(base_level)
824            .init()
825            .map_err(anyhow::Error::from)
826            .expect("tracing initializes");
827
828        let version = env!("CARGO_PKG_VERSION");
829        debug!(target: LOG_CLIENT, "Starting fedimint-cli (version: {version} version_hash: {version_hash})");
830
831        Ok(Self {
832            module_inits: ClientModuleInitRegistry::new(),
833            cli_args,
834        })
835    }
836
837    pub fn with_module<T>(mut self, r#gen: T) -> Self
838    where
839        T: ClientModuleInit + 'static + Send + Sync,
840    {
841        self.module_inits.attach(r#gen);
842        self
843    }
844
845    pub fn with_default_modules(self) -> Self {
846        self.with_module(LightningClientInit::default())
847            .with_module(MintClientInit)
848            .with_module(fedimint_mintv2_client::MintClientInit)
849            .with_module(WalletClientInit::default())
850            .with_module(MetaClientInit)
851            .with_module(fedimint_lnv2_client::LightningClientInit::default())
852            .with_module(fedimint_walletv2_client::WalletClientInit)
853    }
854
855    pub async fn run(&mut self) {
856        match self.handle_command(self.cli_args.clone()).await {
857            Ok(output) => {
858                // ignore if there's anyone reading the stuff we're writing out
859                let _ = writeln!(std::io::stdout(), "{output}");
860            }
861            Err(err) => {
862                debug!(target: LOG_CLIENT, err = %err.error.as_str(), "Command failed");
863                let _ = writeln!(std::io::stdout(), "{err}");
864                exit(1);
865            }
866        }
867    }
868
869    async fn make_client_builder(&self, cli: &Opts) -> CliResult<(ClientBuilder, Database)> {
870        let mut client_builder = Client::builder()
871            .await
872            .with_iroh_enable_dht(cli.iroh_enable_dht());
873        client_builder.with_module_inits(self.module_inits.clone());
874
875        let db = cli.load_database().await?;
876        Ok((client_builder, db))
877    }
878
879    async fn client_join(
880        &mut self,
881        cli: &Opts,
882        invite_code: InviteCode,
883    ) -> CliResult<ClientHandleArc> {
884        let (client_builder, db) = self.make_client_builder(cli).await?;
885
886        let mnemonic = load_or_generate_mnemonic(&db).await?;
887
888        let client = client_builder
889            .preview(cli.make_endpoints().await.map_err_cli()?, &invite_code)
890            .await
891            .map_err_cli()?
892            .join(db, root_secret_from_mnemonic(&mnemonic))
893            .await
894            .map(Arc::new)
895            .map_err_cli()?;
896
897        print_welcome_message(&client).await;
898        log_expiration_notice(&client).await;
899
900        Ok(client)
901    }
902
903    async fn client_open(&self, cli: &Opts) -> CliResult<ClientHandleArc> {
904        let (mut client_builder, db) = self.make_client_builder(cli).await?;
905
906        // Use CLI args if provided, otherwise try to load stored credentials
907        if let Some(our_id) = cli.our_id {
908            client_builder.set_admin_creds(AdminCreds {
909                peer_id: our_id,
910                auth: cli.auth()?,
911            });
912        } else if let Some(stored_creds) = load_admin_creds(&db).await {
913            debug!(target: LOG_CLIENT, "Using stored admin credentials");
914            client_builder.set_admin_creds(AdminCreds {
915                peer_id: stored_creds.peer_id,
916                auth: ApiAuth::new(stored_creds.auth),
917            });
918        }
919
920        let existing_mnemonic = Client::load_decodable_client_secret_opt::<Vec<u8>>(&db)
921            .await
922            .map_err_cli()?;
923
924        let root_secret = match (cli.federation_secret_hex.as_deref(), existing_mnemonic) {
925            (Some(_), Some(_)) => {
926                return Err(CliError {
927                    error: "client secret is already set in DB; --federation-secret-hex open requires a client DB without any stored secret".to_owned(),
928                });
929            }
930            (Some(federation_secret_hex), None) => {
931                RootSecret::Custom(decode_federation_secret_hex(federation_secret_hex)?)
932            }
933            (None, Some(entropy)) => {
934                let mnemonic = Mnemonic::from_entropy(&entropy).map_err_cli()?;
935                root_secret_from_mnemonic(&mnemonic)
936            }
937            (None, None) => {
938                return Err(CliError {
939                    error: "Encoded client secret not present in DB".to_owned(),
940                });
941            }
942        };
943
944        let client = client_builder
945            .open(cli.make_endpoints().await.map_err_cli()?, db, root_secret)
946            .await
947            .map(Arc::new)
948            .map_err_cli()?;
949
950        log_expiration_notice(&client).await;
951
952        Ok(client)
953    }
954
955    async fn federation_ip_query(
956        &self,
957        cli: &Opts,
958        invite_code: &InviteCode,
959        path_timeout: Duration,
960        require_direct: bool,
961    ) -> CliResult<FederationPrivacyReport> {
962        let connectors = cli.make_endpoints().await.map_err_cli()?;
963        let (config, _api) = download_from_invite_code(&connectors, invite_code)
964            .await
965            .map_err_cli_msg("failed to download federation config from invite code")?;
966
967        let federation_id = config.calculate_federation_id();
968        let endpoints = config.global.api_endpoints;
969        if require_direct
970            && !endpoints
971                .values()
972                .any(|peer_url| peer_url.url.scheme() == "iroh")
973        {
974            return Err(CliError {
975                error: "--require-direct requires at least one iroh guardian endpoint".to_owned(),
976            });
977        }
978        let report_timeout = if require_direct {
979            Duration::ZERO
980        } else {
981            path_timeout
982        };
983        let mut guardian_reports =
984            query_guardian_addresses(&connectors, &endpoints, report_timeout).await;
985
986        if require_direct {
987            let deadline = fedimint_core::time::now() + path_timeout;
988            while !all_iroh_guardians_direct(&guardian_reports)
989                && fedimint_core::time::now() < deadline
990            {
991                runtime::sleep(Duration::from_millis(250)).await;
992                guardian_reports =
993                    query_guardian_addresses(&connectors, &endpoints, Duration::ZERO).await;
994            }
995
996            if !all_iroh_guardians_direct(&guardian_reports) {
997                let not_direct = guardian_reports
998                    .iter()
999                    .filter(|(_, report)| {
1000                        report.api_url.scheme() == "iroh"
1001                            && !report
1002                                .iroh
1003                                .as_ref()
1004                                .is_some_and(|iroh| matches!(iroh.connectivity, "direct" | "mixed"))
1005                    })
1006                    .map(|(peer_id, _)| peer_id.to_string())
1007                    .join(", ");
1008                return Err(CliError {
1009                    error: format!(
1010                        "not all iroh guardians reached a direct path within {path_timeout:?}; pending peers: {not_direct}"
1011                    ),
1012                });
1013            }
1014        }
1015
1016        enrich_guardian_ip_info(&mut guardian_reports).await;
1017        let summary = summarize_privacy_report(guardian_reports.iter().map(|(_, report)| report));
1018        let guardians = guardian_reports
1019            .into_iter()
1020            .map(|(peer_id, report)| (peer_id.to_string(), report))
1021            .collect();
1022
1023        Ok(FederationPrivacyReport {
1024            federation_id,
1025            guardians,
1026            summary,
1027        })
1028    }
1029
1030    async fn client_recover(
1031        &mut self,
1032        cli: &Opts,
1033        recovery_secret: RecoverySecret,
1034        invite_code: InviteCode,
1035    ) -> CliResult<ClientHandleArc> {
1036        let (builder, db) = self.make_client_builder(cli).await?;
1037        let existing_mnemonic = Client::load_decodable_client_secret_opt::<Vec<u8>>(&db)
1038            .await
1039            .map_err_cli()?;
1040
1041        let root_secret = match (recovery_secret, existing_mnemonic) {
1042            (RecoverySecret::Mnemonic(mnemonic), Some(existing)) => {
1043                if existing != mnemonic.to_entropy() {
1044                    Err(anyhow::anyhow!("Previously set mnemonic does not match")).map_err_cli()?;
1045                }
1046
1047                root_secret_from_mnemonic(&mnemonic)
1048            }
1049            (RecoverySecret::Mnemonic(mnemonic), None) => {
1050                Client::store_encodable_client_secret(&db, mnemonic.to_entropy())
1051                    .await
1052                    .map_err_cli()?;
1053                root_secret_from_mnemonic(&mnemonic)
1054            }
1055            (RecoverySecret::FederationSecret(federation_secret), None) => {
1056                RootSecret::Custom(federation_secret)
1057            }
1058            (RecoverySecret::FederationSecret(_), Some(_)) => {
1059                return Err(CliError {
1060                    error: "client secret is already set in DB; --federation-secret-hex restore requires a client DB without any stored secret".to_owned(),
1061                });
1062            }
1063        };
1064
1065        let preview = builder
1066            .preview(cli.make_endpoints().await.map_err_cli()?, &invite_code)
1067            .await
1068            .map_err_cli()?;
1069
1070        #[allow(deprecated)]
1071        let backup = preview
1072            .download_backup_from_federation(root_secret.clone())
1073            .await
1074            .map_err_cli()?;
1075
1076        let client = preview
1077            .recover(db, root_secret, backup)
1078            .await
1079            .map(Arc::new)
1080            .map_err_cli()?;
1081
1082        print_welcome_message(&client).await;
1083        log_expiration_notice(&client).await;
1084
1085        Ok(client)
1086    }
1087
1088    async fn handle_command(&mut self, cli: Opts) -> CliOutputResult {
1089        if cli.federation_secret_hex.is_some() && matches!(&cli.command, Command::Join { .. }) {
1090            return Err(CliError {
1091                error: "--federation-secret-hex cannot be used with join".to_owned(),
1092            });
1093        }
1094
1095        match cli.command.clone() {
1096            Command::InviteCode { peer } => {
1097                let client = self.client_open(&cli).await?;
1098
1099                let invite_code = client
1100                    .invite_code(peer)
1101                    .await
1102                    .ok_or_cli_msg("peer not found")?;
1103
1104                Ok(CliOutput::InviteCode { invite_code })
1105            }
1106            Command::Join { invite_code, .. } => {
1107                let invite_code = invite_code.expect("secret inputs were resolved");
1108                {
1109                    let invite_code: InviteCode =
1110                        InviteCode::from_str(&invite_code).map_err(|_| CliError {
1111                            error: "Invalid invite code".to_owned(),
1112                        })?;
1113
1114                    // Build client and store config in DB
1115                    let _client = self.client_join(&cli, invite_code).await?;
1116                }
1117
1118                Ok(CliOutput::Join {
1119                    joined: invite_code,
1120                })
1121            }
1122            Command::VersionHash => Ok(CliOutput::VersionHash {
1123                hash: fedimint_build_code_version_env!().to_string(),
1124            }),
1125            Command::Client(ClientCmd::Restore {
1126                mnemonic,
1127                invite_code,
1128                ..
1129            }) => {
1130                let invite_code = invite_code.expect("secret inputs were resolved");
1131                let invite_code: InviteCode =
1132                    InviteCode::from_str(&invite_code).map_err(|_| CliError {
1133                        error: "Invalid invite code".to_owned(),
1134                    })?;
1135                let recovery_secret = match (
1136                    mnemonic.as_deref(),
1137                    cli.federation_secret_hex.as_deref(),
1138                ) {
1139                    (Some(_), Some(_)) => {
1140                        return Err(CliError {
1141                            error: "restore accepts either --mnemonic or --federation-secret-hex, not both".to_owned(),
1142                        });
1143                    }
1144                    (Some(mnemonic), None) => {
1145                        let mnemonic = Mnemonic::from_str(mnemonic).map_err(|_| CliError {
1146                            error: "Invalid mnemonic".to_owned(),
1147                        })?;
1148                        RecoverySecret::Mnemonic(mnemonic)
1149                    }
1150                    (None, Some(federation_secret_hex)) => {
1151                        let federation_secret =
1152                            decode_federation_secret_hex(federation_secret_hex)?;
1153                        RecoverySecret::FederationSecret(federation_secret)
1154                    }
1155                    (None, None) => {
1156                        return Err(CliError {
1157                            error: "restore requires either --mnemonic or --federation-secret-hex"
1158                                .to_owned(),
1159                        });
1160                    }
1161                };
1162                let client = self
1163                    .client_recover(&cli, recovery_secret, invite_code)
1164                    .await?;
1165
1166                // TODO: until we implement recovery for other modules we can't really wait
1167                // for more than this one
1168                debug!(target: LOG_CLIENT, "Waiting for mint module recovery to finish");
1169                client.wait_for_all_recoveries().await.map_err_cli()?;
1170
1171                debug!(target: LOG_CLIENT, "Recovery complete");
1172
1173                Ok(CliOutput::Raw(
1174                    serde_json::to_value(()).expect("unit type is serializable"),
1175                ))
1176            }
1177            Command::Client(command) => {
1178                let client = self.client_open(&cli).await?;
1179                Ok(CliOutput::Raw(
1180                    client::handle_command(command, client)
1181                        .await
1182                        .map_err_cli()?,
1183                ))
1184            }
1185            Command::Admin(command) => self.handle_admin_command(cli, command).await,
1186            Command::Dev(command) => self.handle_dev_command(cli, command).await,
1187            Command::Completion { shell } => {
1188                let bin_path = PathBuf::from(
1189                    std::env::args_os()
1190                        .next()
1191                        .expect("Binary name is always provided if we get this far"),
1192                );
1193                let bin_name = bin_path
1194                    .file_name()
1195                    .expect("path has file name")
1196                    .to_string_lossy();
1197                clap_complete::generate(
1198                    shell,
1199                    &mut Opts::command(),
1200                    bin_name.as_ref(),
1201                    &mut std::io::stdout(),
1202                );
1203                // HACK: prints true to stdout which is fine for shells
1204                Ok(CliOutput::Raw(serde_json::Value::Bool(true)))
1205            }
1206        }
1207    }
1208
1209    /// Verify a guardian's credentials before storing them in the client
1210    /// database.
1211    async fn handle_admin_auth(
1212        &self,
1213        cli: &Opts,
1214        peer_id: u16,
1215        password: String,
1216        no_verify: bool,
1217        force: bool,
1218    ) -> CliOutputResult {
1219        let db = cli.load_database().await?;
1220        let peer_id = PeerId::from(peer_id);
1221        let auth = ApiAuth::new(password);
1222
1223        // Check if credentials already exist
1224        if !force {
1225            let existing = load_admin_creds(&db).await;
1226            if existing.is_some() {
1227                return Err(CliError {
1228                    error: "Admin credentials already stored. Use --force to overwrite."
1229                        .to_string(),
1230                });
1231            }
1232        }
1233
1234        // Load client config to get peer endpoints
1235        let config = Client::get_config_from_db(&db)
1236            .await
1237            .ok_or_cli_msg("Client not initialized. Please join a federation first.")?;
1238
1239        // Get the endpoint for the specified peer
1240        let peer_url = config
1241            .global
1242            .api_endpoints
1243            .get(&peer_id)
1244            .ok_or_else(|| CliError {
1245                error: format!(
1246                    "Peer ID {} not found in federation. Valid peer IDs are: {:?}",
1247                    peer_id,
1248                    config.global.api_endpoints.keys().collect::<Vec<_>>()
1249                ),
1250            })?;
1251
1252        // Interactive verification unless --no-verify is set
1253        if !no_verify {
1254            // Check if stdin is a terminal for interactive prompts
1255            if !std::io::stdin().is_terminal() {
1256                return Err(CliError {
1257                    error: "Interactive verification requires a terminal. Use --no-verify to skip."
1258                        .to_string(),
1259                });
1260            }
1261
1262            eprintln!("Guardian endpoint for peer {}: {}", peer_id, peer_url.url);
1263            eprint!("Does this look correct? (y/N): ");
1264            std::io::stderr().flush().map_err_cli()?;
1265
1266            let mut input = String::new();
1267            std::io::stdin().read_line(&mut input).map_err_cli()?;
1268            let input = input.trim().to_lowercase();
1269
1270            if input != "y" && input != "yes" {
1271                return Err(CliError {
1272                    error: "Endpoint verification cancelled by user.".to_string(),
1273                });
1274            }
1275        }
1276
1277        // Verify credentials by making an authenticated API call
1278        eprintln!("Verifying credentials...");
1279        let admin_api = DynGlobalApi::new_admin(
1280            cli.make_endpoints().await.map_err_cli()?,
1281            peer_id,
1282            peer_url.url.clone(),
1283            db.begin_transaction_nc()
1284                .await
1285                .get_value(&ApiSecretKey)
1286                .await
1287                .as_deref(),
1288        );
1289
1290        // Use the `auth` endpoint to verify credentials
1291        admin_api.auth(auth.clone()).await.map_err(|e| CliError {
1292            error: format!(
1293                "Failed to verify credentials: {e}. Please check your peer ID and password."
1294            ),
1295        })?;
1296
1297        // Store the credentials in the database
1298        store_admin_creds(
1299            &db,
1300            &StoredAdminCreds {
1301                peer_id,
1302                auth: auth.as_str().to_string(),
1303            },
1304        )
1305        .await;
1306
1307        eprintln!("Admin credentials verified and saved successfully.");
1308        Ok(CliOutput::Raw(json!({
1309            "peer_id": peer_id,
1310            "endpoint": peer_url.url.to_string(),
1311            "status": "saved"
1312        })))
1313    }
1314
1315    /// Dispatch guardian administration without opening a client for setup or
1316    /// auth.
1317    async fn handle_admin_command(&mut self, cli: Opts, command: AdminCmd) -> CliOutputResult {
1318        match command {
1319            AdminCmd::Auth {
1320                peer_id,
1321                password,
1322                no_verify,
1323                force,
1324                ..
1325            } => {
1326                self.handle_admin_auth(
1327                    &cli,
1328                    peer_id,
1329                    password.expect("secret inputs were resolved"),
1330                    no_verify,
1331                    force,
1332                )
1333                .await
1334            }
1335            AdminCmd::Audit => {
1336                let client = self.client_open(&cli).await?;
1337
1338                let audit = cli
1339                    .admin_client(
1340                        &client.get_peer_urls().await,
1341                        client.api_secret().as_deref(),
1342                    )
1343                    .await?
1344                    .audit(cli.auth()?)
1345                    .await?;
1346                Ok(CliOutput::Raw(
1347                    serde_json::to_value(audit).map_err_cli_msg("invalid response")?,
1348                ))
1349            }
1350            AdminCmd::Status => {
1351                let client = self.client_open(&cli).await?;
1352
1353                let status = cli
1354                    .admin_client_with_db(
1355                        &client.get_peer_urls().await,
1356                        client.api_secret().as_deref(),
1357                        Some(client.db()),
1358                    )
1359                    .await?
1360                    .status()
1361                    .await?;
1362                Ok(CliOutput::Raw(
1363                    serde_json::to_value(status).map_err_cli_msg("invalid response")?,
1364                ))
1365            }
1366            AdminCmd::ResetPeerAvailability { peer_id } => {
1367                let client = self.client_open(&cli).await?;
1368                cli.admin_client(
1369                    &client.get_peer_urls().await,
1370                    client.api_secret().as_deref(),
1371                )
1372                .await?
1373                .reset_peer_availability(
1374                    fedimint_core::peer_availability::ResetPeerAvailabilityRequest { peer_id },
1375                    cli.auth()?,
1376                )
1377                .await?;
1378                Ok(CliOutput::Raw(serde_json::Value::Null))
1379            }
1380            AdminCmd::GuardianConfigBackup => {
1381                let client = self.client_open(&cli).await?;
1382
1383                let guardian_config_backup = cli
1384                    .admin_client(
1385                        &client.get_peer_urls().await,
1386                        client.api_secret().as_deref(),
1387                    )
1388                    .await?
1389                    .guardian_config_backup(cli.auth()?)
1390                    .await?;
1391                Ok(CliOutput::Raw(
1392                    serde_json::to_value(guardian_config_backup)
1393                        .map_err_cli_msg("invalid response")?,
1394                ))
1395            }
1396            AdminCmd::Setup(dkg_args) => self
1397                .handle_admin_setup_command(cli, dkg_args)
1398                .await
1399                .map(CliOutput::Raw)
1400                .map_err_cli_msg("Config Gen Error"),
1401            AdminCmd::SignApiAnnouncement {
1402                api_url,
1403                override_url,
1404            } => {
1405                let client = self.client_open(&cli).await?;
1406
1407                if !["ws", "wss"].contains(&api_url.scheme()) {
1408                    return Err(CliError {
1409                        error: format!(
1410                            "Unsupported URL scheme {}, use ws:// or wss://",
1411                            api_url.scheme()
1412                        ),
1413                    });
1414                }
1415
1416                let announcement = cli
1417                    .admin_client(
1418                        &override_url
1419                            .and_then(|url| Some(vec![(cli.our_id?, url)].into_iter().collect()))
1420                            .unwrap_or(client.get_peer_urls().await),
1421                        client.api_secret().as_deref(),
1422                    )
1423                    .await?
1424                    .sign_api_announcement(api_url, cli.auth()?)
1425                    .await?;
1426
1427                Ok(CliOutput::Raw(
1428                    serde_json::to_value(announcement).map_err_cli_msg("invalid response")?,
1429                ))
1430            }
1431            AdminCmd::SignGuardianMetadata { api_urls, pkarr_id } => {
1432                let client = self.client_open(&cli).await?;
1433
1434                let metadata = fedimint_core::net::guardian_metadata::GuardianMetadata::new(
1435                    api_urls,
1436                    pkarr_id,
1437                    fedimint_core::time::duration_since_epoch().as_secs(),
1438                );
1439
1440                let signed_metadata = cli
1441                    .admin_client(
1442                        &client.get_peer_urls().await,
1443                        client.api_secret().as_deref(),
1444                    )
1445                    .await?
1446                    .sign_guardian_metadata(metadata, cli.auth()?)
1447                    .await?;
1448
1449                Ok(CliOutput::Raw(
1450                    serde_json::to_value(signed_metadata).map_err_cli_msg("invalid response")?,
1451                ))
1452            }
1453            AdminCmd::Shutdown { session_idx } => {
1454                let client = self.client_open(&cli).await?;
1455
1456                cli.admin_client(
1457                    &client.get_peer_urls().await,
1458                    client.api_secret().as_deref(),
1459                )
1460                .await?
1461                .shutdown(Some(session_idx), cli.auth()?)
1462                .await?;
1463
1464                Ok(CliOutput::Raw(json!(null)))
1465            }
1466            AdminCmd::BackupStatistics => {
1467                let client = self.client_open(&cli).await?;
1468
1469                let backup_statistics = cli
1470                    .admin_client(
1471                        &client.get_peer_urls().await,
1472                        client.api_secret().as_deref(),
1473                    )
1474                    .await?
1475                    .backup_statistics(cli.auth()?)
1476                    .await?;
1477
1478                Ok(CliOutput::Raw(
1479                    serde_json::to_value(backup_statistics).expect("Can be encoded"),
1480                ))
1481            }
1482        }
1483    }
1484
1485    /// Submit a raw API request, preserving authenticated and federation-wide
1486    /// routing.
1487    async fn handle_api_request(&mut self, cli: &Opts, request: ApiRequest) -> CliOutputResult {
1488        let ApiRequest {
1489            method,
1490            params,
1491            peer_id,
1492            auth,
1493            module,
1494        } = request;
1495        //Parse params to JSON.
1496        //If fails, convert to JSON string.
1497        let params = serde_json::from_str::<Value>(&params).unwrap_or_else(|_| {
1498            debug!(
1499                target: LOG_CLIENT,
1500                "Failed to parse params. Converting it to JSON string"
1501            );
1502
1503            serde_json::Value::String(params)
1504        });
1505
1506        let mut params = ApiRequestErased::new(params);
1507        if let Some(auth) = auth {
1508            params = params.with_auth(ApiAuth::new(auth));
1509        }
1510        let client = self.client_open(cli).await?;
1511
1512        let api = client.api_clone();
1513
1514        let module_api = match module {
1515            Some(selector) => Some(api.with_module(selector.resolve(&client).map_err_cli()?)),
1516            None => None,
1517        };
1518
1519        let response: Value = match (peer_id, module_api) {
1520            (Some(peer_id), Some(module_api)) => module_api
1521                .request_raw(peer_id.into(), &method, &params)
1522                .await
1523                .map_err_cli()?,
1524            (Some(peer_id), None) => api
1525                .request_raw(peer_id.into(), &method, &params)
1526                .await
1527                .map_err_cli()?,
1528            (None, Some(module_api)) => module_api
1529                .request_current_consensus(method, params)
1530                .await
1531                .map_err_cli()?,
1532            (None, None) => api
1533                .request_current_consensus(method, params)
1534                .await
1535                .map_err_cli()?,
1536        };
1537
1538        Ok(CliOutput::UntypedApiOutput { value: response })
1539    }
1540
1541    /// Submit a transaction using the client's module decoders for both
1542    /// directions.
1543    async fn submit_transaction(&self, cli: &Opts, transaction: &str) -> CliOutputResult {
1544        let client = self.client_open(cli).await?;
1545        let tx = Transaction::consensus_decode_hex(transaction, client.decoders()).map_err_cli()?;
1546        let tx_outcome = client
1547            .api()
1548            .submit_transaction(tx)
1549            .await
1550            .try_into_inner(client.decoders())
1551            .map_err_cli()?;
1552        Ok(CliOutput::Raw(
1553            serde_json::to_value(tx_outcome.0.map_err_cli()?).expect("Can be encoded"),
1554        ))
1555    }
1556
1557    /// Render one requested client visualization.
1558    async fn handle_visualize(&self, cli: &Opts, visualize_type: VisualizeCmd) -> CliOutputResult {
1559        let client = self.client_open(cli).await?;
1560        match visualize_type {
1561            VisualizeCmd::Notes { limit } => {
1562                visualize::cmd_notes(&client, limit).await?;
1563            }
1564            VisualizeCmd::Transactions {
1565                operation_id,
1566                limit,
1567            } => {
1568                visualize::cmd_transactions(&client, operation_id, limit).await?;
1569            }
1570            VisualizeCmd::Operations {
1571                operation_id,
1572                limit,
1573            } => {
1574                visualize::cmd_operations(&client, operation_id, limit).await?;
1575            }
1576        }
1577        Ok(CliOutput::Raw(json!({})))
1578    }
1579
1580    /// Fetch metadata using the module source and legacy fallback.
1581    async fn fetch_meta_fields(&self, cli: &Opts) -> CliOutputResult {
1582        let client = self.client_open(cli).await?;
1583        let source = MetaModuleMetaSourceWithFallback::<LegacyMetaSource>::default();
1584        let meta_fields = source
1585            .fetch(
1586                &client.config().await,
1587                &client.api_clone(),
1588                FetchKind::Initial,
1589                None,
1590            )
1591            .await
1592            .map_err_cli()?;
1593        Ok(CliOutput::Raw(
1594            serde_json::to_value(meta_fields).expect("Can be encoded"),
1595        ))
1596    }
1597
1598    /// Dispatch developer commands, opening the client only where required.
1599    async fn handle_dev_command(&mut self, cli: Opts, command: DevCmd) -> CliOutputResult {
1600        match command {
1601            DevCmd::Api {
1602                method,
1603                params,
1604                peer_id,
1605                password: auth,
1606                module,
1607                ..
1608            } => {
1609                self.handle_api_request(
1610                    &cli,
1611                    ApiRequest {
1612                        method,
1613                        params: params.unwrap_or_else(|| "null".to_owned()),
1614                        peer_id,
1615                        auth,
1616                        module,
1617                    },
1618                )
1619                .await
1620            }
1621            DevCmd::AdvanceNoteIdx { count, amount } => {
1622                let client = self.client_open(&cli).await?;
1623
1624                let mint = client
1625                    .get_first_module::<MintClientModule>()
1626                    .map_err_cli_msg("can't get mint module")?;
1627
1628                for _ in 0..count {
1629                    mint.advance_note_idx(amount).await;
1630                }
1631
1632                Ok(CliOutput::Raw(serde_json::Value::Null))
1633            }
1634            DevCmd::ApiAnnouncements => {
1635                let client = self.client_open(&cli).await?;
1636                let announcements = client.get_peer_url_announcements().await;
1637                Ok(CliOutput::Raw(
1638                    serde_json::to_value(announcements).expect("Can be encoded"),
1639                ))
1640            }
1641            DevCmd::GuardianMetadata => {
1642                let client = self.client_open(&cli).await?;
1643                let metadata = client.get_guardian_metadata().await;
1644                Ok(CliOutput::Raw(
1645                    serde_json::to_value(metadata).expect("Can be encoded"),
1646                ))
1647            }
1648            DevCmd::WaitBlockCount { count: target } => self.wait_block_count(&cli, target).await,
1649
1650            DevCmd::WaitComplete => {
1651                let client = self.client_open(&cli).await?;
1652                client.wait_for_all_active_state_machines().await;
1653                Ok(CliOutput::Raw(serde_json::Value::Null))
1654            }
1655            DevCmd::Wait { seconds } => self.wait_with_networking(&cli, seconds).await,
1656            DevCmd::Decode { decode_type } => self.handle_decode(&cli, decode_type).await,
1657            DevCmd::Encode { encode_type } => command_encoding::handle_encode(encode_type),
1658            DevCmd::SessionCount => {
1659                let client = self.client_open(&cli).await?;
1660                let count = client.api().session_count().await?;
1661                Ok(CliOutput::EpochCount { count })
1662            }
1663            DevCmd::QueryFederationIps {
1664                invite_code,
1665                path_timeout_seconds,
1666                require_direct,
1667                ..
1668            } => {
1669                let invite_code =
1670                    InviteCode::from_str(&invite_code.expect("secret inputs were resolved"))
1671                        .map_err(|_| CliError {
1672                            error: "Invalid invite code".to_owned(),
1673                        })?;
1674                let report = self
1675                    .federation_ip_query(
1676                        &cli,
1677                        &invite_code,
1678                        Duration::from_secs(path_timeout_seconds),
1679                        require_direct,
1680                    )
1681                    .await?;
1682                Ok(CliOutput::Raw(
1683                    serde_json::to_value(report).expect("privacy report is serializable"),
1684                ))
1685            }
1686            DevCmd::Config => {
1687                let client = self.client_open(&cli).await?;
1688                let config = client.get_config_json().await;
1689                Ok(CliOutput::Raw(
1690                    serde_json::to_value(config).expect("Client config is serializable"),
1691                ))
1692            }
1693            DevCmd::ConfigDecrypt {
1694                in_file,
1695                out_file,
1696                salt_file,
1697                password,
1698                ..
1699            } => decrypt_config(
1700                in_file,
1701                out_file,
1702                salt_file,
1703                &password.expect("secret inputs were resolved"),
1704            ),
1705            DevCmd::ConfigEncrypt {
1706                in_file,
1707                out_file,
1708                salt_file,
1709                password,
1710                ..
1711            } => encrypt_config(
1712                in_file,
1713                out_file,
1714                salt_file,
1715                &password.expect("secret inputs were resolved"),
1716            ),
1717            DevCmd::ListOperationStates { operation_id } => {
1718                #[derive(Serialize)]
1719                struct ReactorLogState {
1720                    active: bool,
1721                    module_instance: ModuleInstanceId,
1722                    creation_time: String,
1723                    #[serde(skip_serializing_if = "Option::is_none")]
1724                    end_time: Option<String>,
1725                    state: String,
1726                }
1727
1728                let client = self.client_open(&cli).await?;
1729
1730                let (active_states, inactive_states) =
1731                    client.executor().get_operation_states(operation_id).await;
1732                let all_states =
1733                    active_states
1734                        .into_iter()
1735                        .map(|(active_state, active_meta)| ReactorLogState {
1736                            active: true,
1737                            module_instance: active_state.module_instance_id(),
1738                            creation_time: crate::client::time_to_iso8601(&active_meta.created_at),
1739                            end_time: None,
1740                            state: format!("{active_state:?}",),
1741                        })
1742                        .chain(inactive_states.into_iter().map(
1743                            |(inactive_state, inactive_meta)| ReactorLogState {
1744                                active: false,
1745                                module_instance: inactive_state.module_instance_id(),
1746                                creation_time: crate::client::time_to_iso8601(
1747                                    &inactive_meta.created_at,
1748                                ),
1749                                end_time: Some(crate::client::time_to_iso8601(
1750                                    &inactive_meta.exited_at,
1751                                )),
1752                                state: format!("{inactive_state:?}",),
1753                            },
1754                        ))
1755                        .sorted_by(|a, b| a.creation_time.cmp(&b.creation_time))
1756                        .collect::<Vec<_>>();
1757
1758                Ok(CliOutput::Raw(json!({
1759                    "states": all_states
1760                })))
1761            }
1762            DevCmd::MetaFields => self.fetch_meta_fields(&cli).await,
1763            DevCmd::PeerVersion { peer_id } => {
1764                let client = self.client_open(&cli).await?;
1765                let version = client
1766                    .api()
1767                    .fedimintd_version(peer_id.into())
1768                    .await
1769                    .map_err_cli()?;
1770
1771                Ok(CliOutput::Raw(json!({ "version": version })))
1772            }
1773            DevCmd::ShowEventLog { pos, limit } => {
1774                let client = self.client_open(&cli).await?;
1775
1776                let events: Vec<_> = client
1777                    .get_event_log(pos, limit)
1778                    .await
1779                    .into_iter()
1780                    .map(|v| event_output::event_to_json(v.id(), v.as_raw()))
1781                    .collect();
1782
1783                Ok(CliOutput::Raw(
1784                    serde_json::to_value(events).expect("Can be encoded"),
1785                ))
1786            }
1787            DevCmd::ShowEventLogTrimable { pos, limit } => {
1788                let client = self.client_open(&cli).await?;
1789
1790                let events: Vec<_> = client
1791                    .get_event_log_trimable(
1792                        pos.map(|id| EventLogTrimableId::from(u64::from(id))),
1793                        limit,
1794                    )
1795                    .await
1796                    .into_iter()
1797                    .map(|v| event_output::event_to_json(v.id(), v.as_raw()))
1798                    .collect();
1799
1800                Ok(CliOutput::Raw(
1801                    serde_json::to_value(events).expect("Can be encoded"),
1802                ))
1803            }
1804            DevCmd::NextEventLogId => {
1805                let client = self.client_open(&cli).await?;
1806
1807                let id = client.get_next_event_log_id().await;
1808
1809                Ok(CliOutput::Raw(
1810                    serde_json::to_value(id).expect("Can be encoded"),
1811                ))
1812            }
1813            DevCmd::SubmitTransaction { transaction } => {
1814                self.submit_transaction(&cli, &transaction).await
1815            }
1816            DevCmd::TestEventLogHandling => {
1817                let client = self.client_open(&cli).await?;
1818
1819                client
1820                    .handle_events(
1821                        client.built_in_application_event_log_tracker(),
1822                        move |_dbtx, event| {
1823                            Box::pin(async move {
1824                                info!(target: LOG_CLIENT, "{event:?}");
1825
1826                                Ok::<(), std::convert::Infallible>(())
1827                            })
1828                        },
1829                    )
1830                    .await
1831                    .map_err_cli()?;
1832                unreachable!(
1833                    "handle_events exits only if client shuts down, which we don't do here"
1834                )
1835            }
1836            DevCmd::Panic => {
1837                panic!("This panic is intentional for testing backtrace handling");
1838            }
1839            DevCmd::ChainId => {
1840                let client = self.client_open(&cli).await?;
1841                let chain_id = client
1842                    .db()
1843                    .begin_transaction_nc()
1844                    .await
1845                    .get_value(&fedimint_client::db::ChainIdKey)
1846                    .await
1847                    .ok_or_cli_msg("Chain ID not cached in client database")?;
1848
1849                Ok(CliOutput::Raw(serde_json::json!({
1850                    "chain_id": chain_id.to_string()
1851                })))
1852            }
1853            DevCmd::Visualize { visualize_type } => {
1854                self.handle_visualize(&cli, visualize_type).await
1855            }
1856            DevCmd::RefreshApiVersions => {
1857                let client = self.client_open(&cli).await?;
1858                let versions = client.refresh_api_versions().await.map_err_cli()?;
1859                Ok(CliOutput::Raw(json!({ "versions": versions })))
1860            }
1861        }
1862    }
1863
1864    async fn handle_admin_setup_command(
1865        &self,
1866        cli: Opts,
1867        args: SetupAdminArgs,
1868    ) -> anyhow::Result<Value> {
1869        let client =
1870            DynGlobalApi::new_admin_setup(cli.make_endpoints().await?, args.endpoint.clone());
1871
1872        match &args.subcommand {
1873            SetupAdminCmd::Status => {
1874                let status = client.setup_status(cli.auth()?).await?;
1875
1876                Ok(serde_json::to_value(status).expect("JSON serialization failed"))
1877            }
1878            SetupAdminCmd::SetLocalParams {
1879                name,
1880                federation_name,
1881                federation_size,
1882            } => {
1883                let info = client
1884                    .set_local_params(
1885                        name.clone(),
1886                        federation_name.clone(),
1887                        None,
1888                        None,
1889                        *federation_size,
1890                        cli.auth()?,
1891                    )
1892                    .await?;
1893
1894                Ok(serde_json::to_value(info).expect("JSON serialization failed"))
1895            }
1896            SetupAdminCmd::AddPeer { info } => {
1897                let name = client
1898                    .add_peer_connection_info(info.clone(), cli.auth()?)
1899                    .await?;
1900
1901                Ok(serde_json::to_value(name).expect("JSON serialization failed"))
1902            }
1903            SetupAdminCmd::StartDkg => {
1904                client.start_dkg(cli.auth()?).await?;
1905
1906                Ok(Value::Null)
1907            }
1908        }
1909    }
1910}
1911
1912async fn log_expiration_notice(client: &Client) {
1913    client.get_meta_expiration_timestamp().await;
1914    if let Some(expiration_time) = client.get_meta_expiration_timestamp().await {
1915        match expiration_time.duration_since(fedimint_core::time::now()) {
1916            Ok(until_expiration) => {
1917                let days = until_expiration.as_secs() / (60 * 60 * 24);
1918
1919                if 90 < days {
1920                    debug!(target: LOG_CLIENT, %days, "This federation will expire");
1921                } else if 30 < days {
1922                    info!(target: LOG_CLIENT, %days, "This federation will expire");
1923                } else {
1924                    warn!(target: LOG_CLIENT, %days, "This federation will expire soon");
1925                }
1926            }
1927            Err(_) => {
1928                tracing::error!(target: LOG_CLIENT, "This federation has expired and might not be safe to use");
1929            }
1930        }
1931    }
1932}
1933async fn print_welcome_message(client: &Client) {
1934    if let Some(welcome_message) = client
1935        .meta_service()
1936        .get_field::<String>(client.db(), "welcome_message")
1937        .await
1938        .and_then(|v| v.value)
1939    {
1940        eprintln!("{welcome_message}");
1941    }
1942}
1943
1944/// Decrypt a configuration without overwriting an existing output file.
1945fn decrypt_config(
1946    in_file: PathBuf,
1947    out_file: PathBuf,
1948    salt_file: Option<PathBuf>,
1949    password: &str,
1950) -> CliOutputResult {
1951    let salt_file = salt_file.unwrap_or_else(|| salt_from_file_path(&in_file));
1952    let salt = fs::read_to_string(salt_file).map_err_cli()?;
1953    let key = get_encryption_key(password, &salt).map_err_cli()?;
1954    let decrypted_bytes = encrypted_read(&key, in_file).map_err_cli()?;
1955    let mut out_file_handle = fs::File::options()
1956        .create_new(true)
1957        .write(true)
1958        .open(out_file)
1959        .expect("Could not create output cfg file");
1960    out_file_handle.write_all(&decrypted_bytes).map_err_cli()?;
1961    Ok(CliOutput::ConfigDecrypt)
1962}
1963
1964/// Encrypt a configuration using the salt next to the output unless overridden.
1965fn encrypt_config(
1966    in_file: PathBuf,
1967    out_file: PathBuf,
1968    salt_file: Option<PathBuf>,
1969    password: &str,
1970) -> CliOutputResult {
1971    let mut in_file_handle = fs::File::open(in_file).expect("Could not create output cfg file");
1972    let mut plaintext_bytes = vec![];
1973    in_file_handle
1974        .read_to_end(&mut plaintext_bytes)
1975        .expect("Could not read input cfg file");
1976    let salt_file = salt_file.unwrap_or_else(|| salt_from_file_path(&out_file));
1977    let salt = fs::read_to_string(salt_file).map_err_cli()?;
1978    let key = get_encryption_key(password, &salt).map_err_cli()?;
1979    encrypted_write(plaintext_bytes, &key, out_file).map_err_cli()?;
1980    Ok(CliOutput::ConfigEncrypt)
1981}
1982
1983fn salt_from_file_path(file_path: &Path) -> PathBuf {
1984    file_path
1985        .parent()
1986        .expect("File has no parent?!")
1987        .join(SALT_FILE)
1988}
1989
1990/// Convert clap arguments to backup metadata
1991fn metadata_from_clap_cli(metadata: Vec<String>) -> Result<BTreeMap<String, String>, CliError> {
1992    let metadata: BTreeMap<String, String> = metadata
1993        .into_iter()
1994        .map(|item| {
1995            match &item
1996                .splitn(2, '=')
1997                .map(ToString::to_string)
1998                .collect::<Vec<String>>()[..]
1999            {
2000                [] => Err(format_err!("Empty metadata argument not allowed")),
2001                [key] => Err(format_err!("Metadata {key} is missing a value")),
2002                [key, val] => Ok((key.clone(), val.clone())),
2003                [..] => unreachable!(),
2004            }
2005        })
2006        .collect::<anyhow::Result<_>>()
2007        .map_err_cli_msg("invalid metadata")?;
2008    Ok(metadata)
2009}
2010
2011#[test]
2012#[allow(clippy::unwrap_used)]
2013fn metadata_from_clap_cli_test() {
2014    for (args, expected) in [
2015        (
2016            vec!["a=b".to_string()],
2017            BTreeMap::from([("a".into(), "b".into())]),
2018        ),
2019        (
2020            vec!["a=b".to_string(), "c=d".to_string()],
2021            BTreeMap::from([("a".into(), "b".into()), ("c".into(), "d".into())]),
2022        ),
2023    ] {
2024        assert_eq!(metadata_from_clap_cli(args).unwrap(), expected);
2025    }
2026}