1#![deny(clippy::pedantic)]
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 client;
13pub mod envs;
14mod utils;
15
16use core::fmt;
17use std::collections::BTreeMap;
18use std::fmt::Debug;
19use std::io::{Read, Write};
20use std::path::{Path, PathBuf};
21use std::process::exit;
22use std::str::FromStr;
23use std::sync::Arc;
24use std::time::Duration;
25use std::{fs, result};
26
27use anyhow::{Context, format_err};
28use clap::{Args, CommandFactory, Parser, Subcommand};
29use client::ModuleSelector;
30#[cfg(feature = "tor")]
31use envs::FM_USE_TOR_ENV;
32use envs::{FM_API_SECRET_ENV, FM_DB_BACKEND_ENV, FM_IROH_ENABLE_DHT_ENV, SALT_FILE};
33use fedimint_aead::{encrypted_read, encrypted_write, get_encryption_key};
34use fedimint_api_client::api::net::ConnectorType;
35use fedimint_api_client::api::{DynGlobalApi, FederationApiExt, FederationError};
36use fedimint_bip39::{Bip39RootSecretStrategy, Mnemonic};
37use fedimint_client::module::meta::{FetchKind, LegacyMetaSource, MetaSource};
38use fedimint_client::module::module::init::ClientModuleInit;
39use fedimint_client::module_init::ClientModuleInitRegistry;
40use fedimint_client::secret::RootSecretStrategy;
41use fedimint_client::{AdminCreds, Client, ClientBuilder, ClientHandleArc, RootSecret};
42use fedimint_core::config::{FederationId, FederationIdPrefix};
43use fedimint_core::core::{ModuleInstanceId, OperationId};
44use fedimint_core::db::{Database, DatabaseValue};
45use fedimint_core::encoding::Decodable;
46use fedimint_core::invite_code::InviteCode;
47use fedimint_core::module::{ApiAuth, ApiRequestErased};
48use fedimint_core::setup_code::PeerSetupCode;
49use fedimint_core::transaction::Transaction;
50use fedimint_core::util::{SafeUrl, backoff_util, handle_version_hash_command, retry};
51use fedimint_core::{Amount, PeerId, TieredMulti, fedimint_build_code_version_env, runtime};
52use fedimint_eventlog::{EventLogId, EventLogTrimableId};
53use fedimint_ln_client::LightningClientInit;
54use fedimint_logging::{LOG_CLIENT, TracingSetup};
55use fedimint_meta_client::{MetaClientInit, MetaModuleMetaSourceWithFallback};
56use fedimint_mint_client::{MintClientInit, MintClientModule, OOBNotes, SpendableNote};
57use fedimint_wallet_client::api::WalletFederationApi;
58use fedimint_wallet_client::{WalletClientInit, WalletClientModule};
59use futures::future::pending;
60use itertools::Itertools;
61use rand::thread_rng;
62use serde::{Deserialize, Serialize};
63use serde_json::{Value, json};
64use thiserror::Error;
65use tracing::{debug, info, warn};
66use utils::parse_peer_id;
67
68use crate::client::ClientCmd;
69use crate::envs::{FM_CLIENT_DIR_ENV, FM_IROH_ENABLE_NEXT_ENV, FM_OUR_ID_ENV, FM_PASSWORD_ENV};
70
71#[derive(Serialize)]
73#[serde(rename_all = "snake_case")]
74#[serde(untagged)]
75enum CliOutput {
76 VersionHash {
77 hash: String,
78 },
79
80 UntypedApiOutput {
81 value: Value,
82 },
83
84 WaitBlockCount {
85 reached: u64,
86 },
87
88 InviteCode {
89 invite_code: InviteCode,
90 },
91
92 DecodeInviteCode {
93 url: SafeUrl,
94 federation_id: FederationId,
95 },
96
97 JoinFederation {
98 joined: String,
99 },
100
101 DecodeTransaction {
102 transaction: String,
103 },
104
105 EpochCount {
106 count: u64,
107 },
108
109 ConfigDecrypt,
110
111 ConfigEncrypt,
112
113 SetupCode {
114 setup_code: PeerSetupCode,
115 },
116
117 Raw(serde_json::Value),
118}
119
120impl fmt::Display for CliOutput {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 write!(f, "{}", serde_json::to_string_pretty(self).unwrap())
123 }
124}
125
126type CliResult<E> = Result<E, CliError>;
128
129type CliOutputResult = Result<CliOutput, CliError>;
131
132#[derive(Serialize, Error)]
134#[serde(tag = "error", rename_all(serialize = "snake_case"))]
135struct CliError {
136 error: String,
137}
138
139trait CliResultExt<O, E> {
142 fn map_err_cli(self) -> Result<O, CliError>;
144 fn map_err_cli_msg(self, msg: impl fmt::Display + Send + Sync + 'static)
146 -> Result<O, CliError>;
147}
148
149impl<O, E> CliResultExt<O, E> for result::Result<O, E>
150where
151 E: Into<anyhow::Error>,
152{
153 fn map_err_cli(self) -> Result<O, CliError> {
154 self.map_err(|e| {
155 let e = e.into();
156 CliError {
157 error: format!("{e:#}"),
158 }
159 })
160 }
161
162 fn map_err_cli_msg(
163 self,
164 msg: impl fmt::Display + Send + Sync + 'static,
165 ) -> Result<O, CliError> {
166 self.map_err(|e| Into::<anyhow::Error>::into(e))
167 .context(msg)
168 .map_err(|e| CliError {
169 error: format!("{e:#}"),
170 })
171 }
172}
173
174trait CliOptionExt<O> {
177 fn ok_or_cli_msg(self, msg: impl Into<String>) -> Result<O, CliError>;
178}
179
180impl<O> CliOptionExt<O> for Option<O> {
181 fn ok_or_cli_msg(self, msg: impl Into<String>) -> Result<O, CliError> {
182 self.ok_or_else(|| CliError { error: msg.into() })
183 }
184}
185
186impl From<FederationError> for CliError {
188 fn from(e: FederationError) -> Self {
189 CliError {
190 error: e.to_string(),
191 }
192 }
193}
194
195impl Debug for CliError {
196 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197 f.debug_struct("CliError")
198 .field("error", &self.error)
199 .finish()
200 }
201}
202
203impl fmt::Display for CliError {
204 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
205 let json = serde_json::to_value(self).expect("CliError is valid json");
206 let json_as_string =
207 serde_json::to_string_pretty(&json).expect("valid json is serializable");
208 write!(f, "{json_as_string}")
209 }
210}
211
212#[derive(Debug, Clone, Copy, clap::ValueEnum)]
213enum DatabaseBackend {
214 #[value(name = "rocksdb")]
216 RocksDb,
217 #[value(name = "cursed-redb")]
219 CursedRedb,
220}
221
222#[derive(Parser, Clone)]
223#[command(version)]
224struct Opts {
225 #[arg(long = "data-dir", env = FM_CLIENT_DIR_ENV)]
227 data_dir: Option<PathBuf>,
228
229 #[arg(env = FM_OUR_ID_ENV, long, value_parser = parse_peer_id)]
231 our_id: Option<PeerId>,
232
233 #[arg(long, env = FM_PASSWORD_ENV)]
235 password: Option<String>,
236
237 #[cfg(feature = "tor")]
238 #[arg(long, env = FM_USE_TOR_ENV)]
240 use_tor: bool,
241
242 #[arg(long, env = FM_IROH_ENABLE_DHT_ENV)]
244 iroh_enable_dht: Option<bool>,
245
246 #[arg(long, env = FM_IROH_ENABLE_NEXT_ENV)]
248 iroh_enable_next: Option<bool>,
249
250 #[arg(long, env = FM_DB_BACKEND_ENV, value_enum, default_value = "rocksdb")]
252 db_backend: DatabaseBackend,
253
254 #[arg(short = 'v', long)]
257 verbose: bool,
258
259 #[clap(subcommand)]
260 command: Command,
261}
262
263impl Opts {
264 fn data_dir(&self) -> CliResult<&PathBuf> {
265 self.data_dir
266 .as_ref()
267 .ok_or_cli_msg("`--data-dir=` argument not set.")
268 }
269
270 async fn data_dir_create(&self) -> CliResult<&PathBuf> {
272 let dir = self.data_dir()?;
273
274 tokio::fs::create_dir_all(&dir).await.map_err_cli()?;
275
276 Ok(dir)
277 }
278 fn iroh_enable_dht(&self) -> bool {
279 self.iroh_enable_dht.unwrap_or(true)
280 }
281
282 fn iroh_enable_next(&self) -> bool {
283 self.iroh_enable_next.unwrap_or(true)
284 }
285
286 async fn admin_client(
287 &self,
288 peer_urls: &BTreeMap<PeerId, SafeUrl>,
289 api_secret: &Option<String>,
290 ) -> CliResult<DynGlobalApi> {
291 let our_id = self.our_id.ok_or_cli_msg("Admin client needs our-id set")?;
292
293 DynGlobalApi::new_admin(
294 our_id,
295 peer_urls
296 .get(&our_id)
297 .cloned()
298 .context("Our peer URL not found in config")
299 .map_err_cli()?,
300 api_secret,
301 self.iroh_enable_dht(),
302 self.iroh_enable_next(),
303 )
304 .await
305 .map_err(|e| CliError {
306 error: e.to_string(),
307 })
308 }
309
310 fn auth(&self) -> CliResult<ApiAuth> {
311 let password = self
312 .password
313 .clone()
314 .ok_or_cli_msg("CLI needs password set")?;
315 Ok(ApiAuth(password))
316 }
317
318 async fn load_database(&self) -> CliResult<Database> {
319 debug!(target: LOG_CLIENT, "Loading client database");
320 let db_path = self.data_dir_create().await?.join("client.db");
321 match self.db_backend {
322 DatabaseBackend::RocksDb => {
323 debug!(target: LOG_CLIENT, "Using RocksDB database backend");
324 Ok(fedimint_rocksdb::RocksDb::open(db_path)
325 .await
326 .map_err_cli_msg("could not open rocksdb database")?
327 .into())
328 }
329 DatabaseBackend::CursedRedb => {
330 debug!(target: LOG_CLIENT, "Using CursedRedb database backend");
331 Ok(fedimint_cursed_redb::MemAndRedb::new(db_path)
332 .await
333 .map_err_cli_msg("could not open cursed redb database")?
334 .into())
335 }
336 }
337 }
338
339 #[allow(clippy::unused_self)]
340 fn connector(&self) -> ConnectorType {
341 #[cfg(feature = "tor")]
342 if self.use_tor {
343 ConnectorType::tor()
344 } else {
345 ConnectorType::default()
346 }
347 #[cfg(not(feature = "tor"))]
348 ConnectorType::default()
349 }
350}
351
352async fn load_or_generate_mnemonic(db: &Database) -> Result<Mnemonic, CliError> {
353 Ok(
354 if let Ok(entropy) = Client::load_decodable_client_secret::<Vec<u8>>(db).await {
355 Mnemonic::from_entropy(&entropy).map_err_cli()?
356 } else {
357 debug!(
358 target: LOG_CLIENT,
359 "Generating mnemonic and writing entropy to client storage"
360 );
361 let mnemonic = Bip39RootSecretStrategy::<12>::random(&mut thread_rng());
362 Client::store_encodable_client_secret(db, mnemonic.to_entropy())
363 .await
364 .map_err_cli()?;
365 mnemonic
366 },
367 )
368}
369
370#[derive(Subcommand, Clone)]
371enum Command {
372 VersionHash,
374
375 #[clap(flatten)]
376 Client(client::ClientCmd),
377
378 #[clap(subcommand)]
379 Admin(AdminCmd),
380
381 #[clap(subcommand)]
382 Dev(DevCmd),
383
384 InviteCode {
386 peer: PeerId,
387 },
388
389 JoinFederation {
391 invite_code: String,
392 },
393
394 Completion {
395 shell: clap_complete::Shell,
396 },
397}
398
399#[allow(clippy::large_enum_variant)]
400#[derive(Debug, Clone, Subcommand)]
401enum AdminCmd {
402 Status,
404
405 Audit,
407
408 GuardianConfigBackup,
410
411 Setup(SetupAdminArgs),
412 SignApiAnnouncement {
415 api_url: SafeUrl,
417 #[clap(long)]
420 override_url: Option<SafeUrl>,
421 },
422 Shutdown {
424 session_idx: u64,
426 },
427 BackupStatistics,
429 ChangePassword {
432 new_password: String,
434 },
435}
436
437#[derive(Debug, Clone, Args)]
438struct SetupAdminArgs {
439 endpoint: SafeUrl,
440
441 #[clap(subcommand)]
442 subcommand: SetupAdminCmd,
443}
444
445#[derive(Debug, Clone, Subcommand)]
446enum SetupAdminCmd {
447 Status,
448 SetLocalParams {
449 name: String,
450 #[clap(long)]
451 federation_name: Option<String>,
452 },
453 AddPeer {
454 info: String,
455 },
456 StartDkg,
457}
458
459#[derive(Debug, Clone, Subcommand)]
460enum DecodeType {
461 InviteCode { invite_code: InviteCode },
463 #[group(required = true, multiple = false)]
465 Notes {
466 notes: Option<OOBNotes>,
468 #[arg(long)]
470 file: Option<PathBuf>,
471 },
472 Transaction { hex_string: String },
474 SetupCode { setup_code: String },
477}
478
479#[derive(Debug, Clone, Deserialize, Serialize)]
480struct OOBNotesJson {
481 federation_id_prefix: String,
482 notes: TieredMulti<SpendableNote>,
483}
484
485#[derive(Debug, Clone, Subcommand)]
486enum EncodeType {
487 InviteCode {
489 #[clap(long)]
490 url: SafeUrl,
491 #[clap(long = "federation_id")]
492 federation_id: FederationId,
493 #[clap(long = "peer")]
494 peer: PeerId,
495 #[arg(env = FM_API_SECRET_ENV)]
496 api_secret: Option<String>,
497 },
498
499 Notes { notes_json: String },
501}
502
503#[derive(Debug, Clone, Subcommand)]
504enum DevCmd {
505 #[command(after_long_help = r#"
509Examples:
510
511 fedimint-cli dev api --peer-id 0 config '"fed114znk7uk7ppugdjuytr8venqf2tkywd65cqvg3u93um64tu5cw4yr0n3fvn7qmwvm4g48cpndgnm4gqq4waen5te0xyerwt3s9cczuvf6xyurzde597s7crdvsk2vmyarjw9gwyqjdzj"'
512 "#)]
513 Api {
514 method: String,
516 #[clap(default_value = "null")]
521 params: String,
522 #[clap(long = "peer-id")]
524 peer_id: Option<u16>,
525
526 #[clap(long = "module")]
528 module: Option<ModuleSelector>,
529
530 #[clap(long, requires = "peer_id")]
533 password: Option<String>,
534 },
535
536 ApiAnnouncements,
537
538 AdvanceNoteIdx {
540 #[clap(long, default_value = "1")]
541 count: usize,
542
543 #[clap(long)]
544 amount: Amount,
545 },
546
547 WaitBlockCount {
549 count: u64,
550 },
551
552 Wait {
554 seconds: Option<f32>,
556 },
557
558 WaitComplete,
560
561 Decode {
563 #[clap(subcommand)]
564 decode_type: DecodeType,
565 },
566
567 Encode {
569 #[clap(subcommand)]
570 encode_type: EncodeType,
571 },
572
573 SessionCount,
575
576 ConfigDecrypt {
577 #[arg(long = "in-file")]
579 in_file: PathBuf,
580 #[arg(long = "out-file")]
582 out_file: PathBuf,
583 #[arg(long = "salt-file")]
586 salt_file: Option<PathBuf>,
587 #[arg(env = FM_PASSWORD_ENV)]
589 password: String,
590 },
591
592 ConfigEncrypt {
593 #[arg(long = "in-file")]
595 in_file: PathBuf,
596 #[arg(long = "out-file")]
598 out_file: PathBuf,
599 #[arg(long = "salt-file")]
602 salt_file: Option<PathBuf>,
603 #[arg(env = FM_PASSWORD_ENV)]
605 password: String,
606 },
607
608 ListOperationStates {
611 operation_id: OperationId,
612 },
613 MetaFields,
617 PeerVersion {
619 #[clap(long)]
620 peer_id: u16,
621 },
622 ShowEventLog {
624 #[arg(long)]
625 pos: Option<EventLogId>,
626 #[arg(long, default_value = "10")]
627 limit: u64,
628 },
629 ShowEventLogTrimable {
631 #[arg(long)]
632 pos: Option<EventLogId>,
633 #[arg(long, default_value = "10")]
634 limit: u64,
635 },
636 SubmitTransaction {
641 transaction: String,
643 },
644}
645
646#[derive(Debug, Serialize, Deserialize)]
647#[serde(rename_all = "snake_case")]
648struct PayRequest {
649 notes: TieredMulti<SpendableNote>,
650 invoice: lightning_invoice::Bolt11Invoice,
651}
652
653pub struct FedimintCli {
654 module_inits: ClientModuleInitRegistry,
655 cli_args: Opts,
656}
657
658impl FedimintCli {
659 pub fn new(version_hash: &str) -> anyhow::Result<FedimintCli> {
661 assert_eq!(
662 fedimint_build_code_version_env!().len(),
663 version_hash.len(),
664 "version_hash must have an expected length"
665 );
666
667 handle_version_hash_command(version_hash);
668
669 let cli_args = Opts::parse();
670 let base_level = if cli_args.verbose { "debug" } else { "info" };
671 TracingSetup::default()
672 .with_base_level(base_level)
673 .init()
674 .expect("tracing initializes");
675
676 let version = env!("CARGO_PKG_VERSION");
677 debug!(target: LOG_CLIENT, "Starting fedimint-cli (version: {version} version_hash: {version_hash})");
678
679 Ok(Self {
680 module_inits: ClientModuleInitRegistry::new(),
681 cli_args,
682 })
683 }
684
685 pub fn with_module<T>(mut self, r#gen: T) -> Self
686 where
687 T: ClientModuleInit + 'static + Send + Sync,
688 {
689 self.module_inits.attach(r#gen);
690 self
691 }
692
693 pub fn with_default_modules(self) -> Self {
694 self.with_module(LightningClientInit::default())
695 .with_module(MintClientInit)
696 .with_module(WalletClientInit::default())
697 .with_module(MetaClientInit)
698 .with_module(fedimint_lnv2_client::LightningClientInit::default())
699 }
700
701 pub async fn run(&mut self) {
702 match self.handle_command(self.cli_args.clone()).await {
703 Ok(output) => {
704 let _ = writeln!(std::io::stdout(), "{output}");
706 }
707 Err(err) => {
708 debug!(target: LOG_CLIENT, err = %err.error.as_str(), "Command failed");
709 let _ = writeln!(std::io::stdout(), "{err}");
710 exit(1);
711 }
712 }
713 }
714
715 async fn make_client_builder(&self, cli: &Opts) -> CliResult<(ClientBuilder, Database)> {
716 let mut client_builder = Client::builder()
717 .await
718 .map_err_cli()?
719 .with_iroh_enable_dht(cli.iroh_enable_dht())
720 .with_iroh_enable_next(cli.iroh_enable_next());
721 client_builder.with_module_inits(self.module_inits.clone());
722
723 client_builder.with_connector(cli.connector());
724
725 let db = cli.load_database().await?;
726 Ok((client_builder, db))
727 }
728
729 async fn client_join(
730 &mut self,
731 cli: &Opts,
732 invite_code: InviteCode,
733 ) -> CliResult<ClientHandleArc> {
734 let (client_builder, db) = self.make_client_builder(cli).await?;
735
736 let mnemonic = load_or_generate_mnemonic(&db).await?;
737
738 let client = client_builder
739 .preview(&invite_code)
740 .await
741 .map_err_cli()?
742 .join(
743 db,
744 RootSecret::StandardDoubleDerive(Bip39RootSecretStrategy::<12>::to_root_secret(
745 &mnemonic,
746 )),
747 )
748 .await
749 .map(Arc::new)
750 .map_err_cli()?;
751
752 print_welcome_message(&client).await;
753 log_expiration_notice(&client).await;
754
755 Ok(client)
756 }
757
758 async fn client_open(&self, cli: &Opts) -> CliResult<ClientHandleArc> {
759 let (mut client_builder, db) = self.make_client_builder(cli).await?;
760
761 if let Some(our_id) = cli.our_id {
762 client_builder.set_admin_creds(AdminCreds {
763 peer_id: our_id,
764 auth: cli.auth()?,
765 });
766 }
767
768 let mnemonic = Mnemonic::from_entropy(
769 &Client::load_decodable_client_secret::<Vec<u8>>(&db)
770 .await
771 .map_err_cli()?,
772 )
773 .map_err_cli()?;
774
775 let client = client_builder
776 .open(
777 db,
778 RootSecret::StandardDoubleDerive(Bip39RootSecretStrategy::<12>::to_root_secret(
779 &mnemonic,
780 )),
781 )
782 .await
783 .map(Arc::new)
784 .map_err_cli()?;
785
786 log_expiration_notice(&client).await;
787
788 Ok(client)
789 }
790
791 async fn client_recover(
792 &mut self,
793 cli: &Opts,
794 mnemonic: Mnemonic,
795 invite_code: InviteCode,
796 ) -> CliResult<ClientHandleArc> {
797 let (builder, db) = self.make_client_builder(cli).await?;
798 match Client::load_decodable_client_secret_opt::<Vec<u8>>(&db)
799 .await
800 .map_err_cli()?
801 {
802 Some(existing) => {
803 if existing != mnemonic.to_entropy() {
804 Err(anyhow::anyhow!("Previously set mnemonic does not match")).map_err_cli()?;
805 }
806 }
807 None => {
808 Client::store_encodable_client_secret(&db, mnemonic.to_entropy())
809 .await
810 .map_err_cli()?;
811 }
812 }
813
814 let root_secret = RootSecret::StandardDoubleDerive(
815 Bip39RootSecretStrategy::<12>::to_root_secret(&mnemonic),
816 );
817 let client = builder
818 .preview(&invite_code)
819 .await
820 .map_err_cli()?
821 .recover(db, root_secret, None)
822 .await
823 .map(Arc::new)
824 .map_err_cli()?;
825
826 print_welcome_message(&client).await;
827 log_expiration_notice(&client).await;
828
829 Ok(client)
830 }
831
832 async fn handle_command(&mut self, cli: Opts) -> CliOutputResult {
833 match cli.command.clone() {
834 Command::InviteCode { peer } => {
835 let client = self.client_open(&cli).await?;
836
837 let invite_code = client
838 .invite_code(peer)
839 .await
840 .ok_or_cli_msg("peer not found")?;
841
842 Ok(CliOutput::InviteCode { invite_code })
843 }
844 Command::JoinFederation { invite_code } => {
845 {
846 let invite_code: InviteCode = InviteCode::from_str(&invite_code)
847 .map_err_cli_msg("invalid invite code")?;
848
849 let _client = self.client_join(&cli, invite_code).await?;
851 }
852
853 Ok(CliOutput::JoinFederation {
854 joined: invite_code,
855 })
856 }
857 Command::VersionHash => Ok(CliOutput::VersionHash {
858 hash: fedimint_build_code_version_env!().to_string(),
859 }),
860 Command::Client(ClientCmd::Restore {
861 mnemonic,
862 invite_code,
863 }) => {
864 let invite_code: InviteCode =
865 InviteCode::from_str(&invite_code).map_err_cli_msg("invalid invite code")?;
866 let mnemonic = Mnemonic::from_str(&mnemonic).map_err_cli()?;
867 let client = self.client_recover(&cli, mnemonic, invite_code).await?;
868
869 debug!(target: LOG_CLIENT, "Waiting for mint module recovery to finish");
872 client.wait_for_all_recoveries().await.map_err_cli()?;
873
874 debug!(target: LOG_CLIENT, "Recovery complete");
875
876 Ok(CliOutput::Raw(serde_json::to_value(()).unwrap()))
877 }
878 Command::Client(command) => {
879 let client = self.client_open(&cli).await?;
880 Ok(CliOutput::Raw(
881 client::handle_command(command, client)
882 .await
883 .map_err_cli()?,
884 ))
885 }
886 Command::Admin(AdminCmd::Audit) => {
887 let client = self.client_open(&cli).await?;
888
889 let audit = cli
890 .admin_client(&client.get_peer_urls().await, client.api_secret())
891 .await?
892 .audit(cli.auth()?)
893 .await?;
894 Ok(CliOutput::Raw(
895 serde_json::to_value(audit).map_err_cli_msg("invalid response")?,
896 ))
897 }
898 Command::Admin(AdminCmd::Status) => {
899 let client = self.client_open(&cli).await?;
900
901 let status = cli
902 .admin_client(&client.get_peer_urls().await, client.api_secret())
903 .await?
904 .status()
905 .await?;
906 Ok(CliOutput::Raw(
907 serde_json::to_value(status).map_err_cli_msg("invalid response")?,
908 ))
909 }
910 Command::Admin(AdminCmd::GuardianConfigBackup) => {
911 let client = self.client_open(&cli).await?;
912
913 let guardian_config_backup = cli
914 .admin_client(&client.get_peer_urls().await, client.api_secret())
915 .await?
916 .guardian_config_backup(cli.auth()?)
917 .await?;
918 Ok(CliOutput::Raw(
919 serde_json::to_value(guardian_config_backup)
920 .map_err_cli_msg("invalid response")?,
921 ))
922 }
923 Command::Admin(AdminCmd::Setup(dkg_args)) => self
924 .handle_admin_setup_command(cli, dkg_args)
925 .await
926 .map(CliOutput::Raw)
927 .map_err_cli_msg("Config Gen Error"),
928 Command::Admin(AdminCmd::SignApiAnnouncement {
929 api_url,
930 override_url,
931 }) => {
932 let client = self.client_open(&cli).await?;
933
934 if !["ws", "wss"].contains(&api_url.scheme()) {
935 return Err(CliError {
936 error: format!(
937 "Unsupported URL scheme {}, use ws:// or wss://",
938 api_url.scheme()
939 ),
940 });
941 }
942
943 let announcement = cli
944 .admin_client(
945 &override_url
946 .and_then(|url| Some(vec![(cli.our_id?, url)].into_iter().collect()))
947 .unwrap_or(client.get_peer_urls().await),
948 client.api_secret(),
949 )
950 .await?
951 .sign_api_announcement(api_url, cli.auth()?)
952 .await?;
953
954 Ok(CliOutput::Raw(
955 serde_json::to_value(announcement).map_err_cli_msg("invalid response")?,
956 ))
957 }
958 Command::Admin(AdminCmd::Shutdown { session_idx }) => {
959 let client = self.client_open(&cli).await?;
960
961 cli.admin_client(&client.get_peer_urls().await, client.api_secret())
962 .await?
963 .shutdown(Some(session_idx), cli.auth()?)
964 .await?;
965
966 Ok(CliOutput::Raw(json!(null)))
967 }
968 Command::Admin(AdminCmd::BackupStatistics) => {
969 let client = self.client_open(&cli).await?;
970
971 let backup_statistics = cli
972 .admin_client(&client.get_peer_urls().await, client.api_secret())
973 .await?
974 .backup_statistics(cli.auth()?)
975 .await?;
976
977 Ok(CliOutput::Raw(
978 serde_json::to_value(backup_statistics).expect("Can be encoded"),
979 ))
980 }
981 Command::Admin(AdminCmd::ChangePassword { new_password }) => {
982 let client = self.client_open(&cli).await?;
983
984 cli.admin_client(&client.get_peer_urls().await, client.api_secret())
985 .await?
986 .change_password(cli.auth()?, &new_password)
987 .await?;
988
989 warn!(target: LOG_CLIENT, "Password changed, please restart fedimintd manually");
990
991 Ok(CliOutput::Raw(json!(null)))
992 }
993 Command::Dev(DevCmd::Api {
994 method,
995 params,
996 peer_id,
997 password: auth,
998 module,
999 }) => {
1000 let params = serde_json::from_str::<Value>(¶ms).unwrap_or_else(|err| {
1003 debug!(
1004 target: LOG_CLIENT,
1005 "Failed to serialize params:{}. Converting it to JSON string",
1006 err
1007 );
1008
1009 serde_json::Value::String(params)
1010 });
1011
1012 let mut params = ApiRequestErased::new(params);
1013 if let Some(auth) = auth {
1014 params = params.with_auth(ApiAuth(auth));
1015 }
1016 let client = self.client_open(&cli).await?;
1017
1018 let api = client.api_clone();
1019
1020 let module_api = match module {
1021 Some(selector) => {
1022 Some(api.with_module(selector.resolve(&client).map_err_cli()?))
1023 }
1024 None => None,
1025 };
1026
1027 let response: Value = match (peer_id, module_api) {
1028 (Some(peer_id), Some(module_api)) => module_api
1029 .request_raw(peer_id.into(), &method, ¶ms)
1030 .await
1031 .map_err_cli()?,
1032 (Some(peer_id), None) => api
1033 .request_raw(peer_id.into(), &method, ¶ms)
1034 .await
1035 .map_err_cli()?,
1036 (None, Some(module_api)) => module_api
1037 .request_current_consensus(method, params)
1038 .await
1039 .map_err_cli()?,
1040 (None, None) => api
1041 .request_current_consensus(method, params)
1042 .await
1043 .map_err_cli()?,
1044 };
1045
1046 Ok(CliOutput::UntypedApiOutput { value: response })
1047 }
1048 Command::Dev(DevCmd::AdvanceNoteIdx { count, amount }) => {
1049 let client = self.client_open(&cli).await?;
1050
1051 let mint = client
1052 .get_first_module::<MintClientModule>()
1053 .map_err_cli_msg("can't get mint module")?;
1054
1055 for _ in 0..count {
1056 mint.advance_note_idx(amount)
1057 .await
1058 .map_err_cli_msg("failed to advance the note_idx")?;
1059 }
1060
1061 Ok(CliOutput::Raw(serde_json::Value::Null))
1062 }
1063 Command::Dev(DevCmd::ApiAnnouncements) => {
1064 let client = self.client_open(&cli).await?;
1065 let announcements = client.get_peer_url_announcements().await;
1066 Ok(CliOutput::Raw(
1067 serde_json::to_value(announcements).expect("Can be encoded"),
1068 ))
1069 }
1070 Command::Dev(DevCmd::WaitBlockCount { count: target }) => retry(
1071 "wait_block_count",
1072 backoff_util::custom_backoff(
1073 Duration::from_millis(100),
1074 Duration::from_secs(5),
1075 None,
1076 ),
1077 || async {
1078 let client = self.client_open(&cli).await?;
1079 let wallet = client.get_first_module::<WalletClientModule>()?;
1080 let count = client
1081 .api()
1082 .with_module(wallet.id)
1083 .fetch_consensus_block_count()
1084 .await?;
1085 if count >= target {
1086 Ok(CliOutput::WaitBlockCount { reached: count })
1087 } else {
1088 info!(target: LOG_CLIENT, current=count, target, "Block count not reached");
1089 Err(format_err!("target not reached"))
1090 }
1091 },
1092 )
1093 .await
1094 .map_err_cli(),
1095
1096 Command::Dev(DevCmd::WaitComplete) => {
1097 let client = self.client_open(&cli).await?;
1098 client
1099 .wait_for_all_active_state_machines()
1100 .await
1101 .map_err_cli_msg("failed to wait for all active state machines")?;
1102 Ok(CliOutput::Raw(serde_json::Value::Null))
1103 }
1104 Command::Dev(DevCmd::Wait { seconds }) => {
1105 let _client = self.client_open(&cli).await?;
1106 if let Some(secs) = seconds {
1107 runtime::sleep(Duration::from_secs_f32(secs)).await;
1108 } else {
1109 pending::<()>().await;
1110 }
1111 Ok(CliOutput::Raw(serde_json::Value::Null))
1112 }
1113 Command::Dev(DevCmd::Decode { decode_type }) => match decode_type {
1114 DecodeType::InviteCode { invite_code } => Ok(CliOutput::DecodeInviteCode {
1115 url: invite_code.url(),
1116 federation_id: invite_code.federation_id(),
1117 }),
1118 DecodeType::Notes { notes, file } => {
1119 let notes = if let Some(notes) = notes {
1120 notes
1121 } else if let Some(file) = file {
1122 let notes_str =
1123 fs::read_to_string(file).map_err_cli_msg("failed to read file")?;
1124 OOBNotes::from_str(¬es_str).map_err_cli_msg("failed to decode notes")?
1125 } else {
1126 unreachable!("Clap enforces either notes or file being set");
1127 };
1128
1129 let notes_json = notes
1130 .notes_json()
1131 .map_err_cli_msg("failed to decode notes")?;
1132 Ok(CliOutput::Raw(notes_json))
1133 }
1134 DecodeType::Transaction { hex_string } => {
1135 let bytes: Vec<u8> = hex::FromHex::from_hex(&hex_string)
1136 .map_err_cli_msg("failed to decode transaction")?;
1137
1138 let client = self.client_open(&cli).await?;
1139 let tx = fedimint_core::transaction::Transaction::from_bytes(
1140 &bytes,
1141 client.decoders(),
1142 )
1143 .map_err_cli_msg("failed to decode transaction")?;
1144
1145 Ok(CliOutput::DecodeTransaction {
1146 transaction: (format!("{tx:?}")),
1147 })
1148 }
1149 DecodeType::SetupCode { setup_code } => {
1150 let setup_code = PeerSetupCode::decode_base32(&setup_code)
1151 .map_err_cli_msg("failed to decode setup code")?;
1152
1153 Ok(CliOutput::SetupCode { setup_code })
1154 }
1155 },
1156 Command::Dev(DevCmd::Encode { encode_type }) => match encode_type {
1157 EncodeType::InviteCode {
1158 url,
1159 federation_id,
1160 peer,
1161 api_secret,
1162 } => Ok(CliOutput::InviteCode {
1163 invite_code: InviteCode::new(url, peer, federation_id, api_secret),
1164 }),
1165 EncodeType::Notes { notes_json } => {
1166 let notes = serde_json::from_str::<OOBNotesJson>(¬es_json)
1167 .map_err_cli_msg("invalid JSON for notes")?;
1168 let prefix =
1169 FederationIdPrefix::from_str(¬es.federation_id_prefix).map_err_cli()?;
1170 let notes = OOBNotes::new(prefix, notes.notes);
1171 Ok(CliOutput::Raw(notes.to_string().into()))
1172 }
1173 },
1174 Command::Dev(DevCmd::SessionCount) => {
1175 let client = self.client_open(&cli).await?;
1176 let count = client.api().session_count().await?;
1177 Ok(CliOutput::EpochCount { count })
1178 }
1179 Command::Dev(DevCmd::ConfigDecrypt {
1180 in_file,
1181 out_file,
1182 salt_file,
1183 password,
1184 }) => {
1185 let salt_file = salt_file.unwrap_or_else(|| salt_from_file_path(&in_file));
1186 let salt = fs::read_to_string(salt_file).map_err_cli()?;
1187 let key = get_encryption_key(&password, &salt).map_err_cli()?;
1188 let decrypted_bytes = encrypted_read(&key, in_file).map_err_cli()?;
1189
1190 let mut out_file_handle = fs::File::options()
1191 .create_new(true)
1192 .write(true)
1193 .open(out_file)
1194 .expect("Could not create output cfg file");
1195 out_file_handle.write_all(&decrypted_bytes).map_err_cli()?;
1196 Ok(CliOutput::ConfigDecrypt)
1197 }
1198 Command::Dev(DevCmd::ConfigEncrypt {
1199 in_file,
1200 out_file,
1201 salt_file,
1202 password,
1203 }) => {
1204 let mut in_file_handle =
1205 fs::File::open(in_file).expect("Could not create output cfg file");
1206 let mut plaintext_bytes = vec![];
1207 in_file_handle.read_to_end(&mut plaintext_bytes).unwrap();
1208
1209 let salt_file = salt_file.unwrap_or_else(|| salt_from_file_path(&out_file));
1210 let salt = fs::read_to_string(salt_file).map_err_cli()?;
1211 let key = get_encryption_key(&password, &salt).map_err_cli()?;
1212 encrypted_write(plaintext_bytes, &key, out_file).map_err_cli()?;
1213 Ok(CliOutput::ConfigEncrypt)
1214 }
1215 Command::Dev(DevCmd::ListOperationStates { operation_id }) => {
1216 #[derive(Serialize)]
1217 struct ReactorLogState {
1218 active: bool,
1219 module_instance: ModuleInstanceId,
1220 creation_time: String,
1221 #[serde(skip_serializing_if = "Option::is_none")]
1222 end_time: Option<String>,
1223 state: String,
1224 }
1225
1226 let client = self.client_open(&cli).await?;
1227
1228 let (active_states, inactive_states) =
1229 client.executor().get_operation_states(operation_id).await;
1230 let all_states =
1231 active_states
1232 .into_iter()
1233 .map(|(active_state, active_meta)| ReactorLogState {
1234 active: true,
1235 module_instance: active_state.module_instance_id(),
1236 creation_time: crate::client::time_to_iso8601(&active_meta.created_at),
1237 end_time: None,
1238 state: format!("{active_state:?}",),
1239 })
1240 .chain(inactive_states.into_iter().map(
1241 |(inactive_state, inactive_meta)| ReactorLogState {
1242 active: false,
1243 module_instance: inactive_state.module_instance_id(),
1244 creation_time: crate::client::time_to_iso8601(
1245 &inactive_meta.created_at,
1246 ),
1247 end_time: Some(crate::client::time_to_iso8601(
1248 &inactive_meta.exited_at,
1249 )),
1250 state: format!("{inactive_state:?}",),
1251 },
1252 ))
1253 .sorted_by(|a, b| a.creation_time.cmp(&b.creation_time))
1254 .collect::<Vec<_>>();
1255
1256 Ok(CliOutput::Raw(json!({
1257 "states": all_states
1258 })))
1259 }
1260 Command::Dev(DevCmd::MetaFields) => {
1261 let client = self.client_open(&cli).await?;
1262 let source = MetaModuleMetaSourceWithFallback::<LegacyMetaSource>::default();
1263
1264 let meta_fields = source
1265 .fetch(
1266 &client.config().await,
1267 &client.api_clone(),
1268 FetchKind::Initial,
1269 None,
1270 )
1271 .await
1272 .map_err_cli()?;
1273
1274 Ok(CliOutput::Raw(
1275 serde_json::to_value(meta_fields).expect("Can be encoded"),
1276 ))
1277 }
1278 Command::Dev(DevCmd::PeerVersion { peer_id }) => {
1279 let client = self.client_open(&cli).await?;
1280 let version = client
1281 .api()
1282 .fedimintd_version(peer_id.into())
1283 .await
1284 .map_err_cli()?;
1285
1286 Ok(CliOutput::Raw(json!({ "version": version })))
1287 }
1288 Command::Dev(DevCmd::ShowEventLog { pos, limit }) => {
1289 let client = self.client_open(&cli).await?;
1290
1291 let events: Vec<_> = client
1292 .get_event_log(pos, limit)
1293 .await
1294 .into_iter()
1295 .map(|v| {
1296 let module_id = v.module.as_ref().map(|m| m.1);
1297 let module_kind = v.module.map(|m| m.0);
1298 serde_json::json!({
1299 "id": v.event_id,
1300 "kind": v.event_kind,
1301 "module_kind": module_kind,
1302 "module_id": module_id,
1303 "ts": v.timestamp,
1304 "payload": v.value
1305 })
1306 })
1307 .collect();
1308
1309 Ok(CliOutput::Raw(
1310 serde_json::to_value(events).expect("Can be encoded"),
1311 ))
1312 }
1313 Command::Dev(DevCmd::ShowEventLogTrimable { pos, limit }) => {
1314 let client = self.client_open(&cli).await?;
1315
1316 let events: Vec<_> = client
1317 .get_event_log_trimable(
1318 pos.map(|id| EventLogTrimableId::from(u64::from(id))),
1319 limit,
1320 )
1321 .await
1322 .into_iter()
1323 .map(|v| {
1324 let module_id = v.module.as_ref().map(|m| m.1);
1325 let module_kind = v.module.map(|m| m.0);
1326 serde_json::json!({
1327 "id": v.event_id,
1328 "kind": v.event_kind,
1329 "module_kind": module_kind,
1330 "module_id": module_id,
1331 "ts": v.timestamp,
1332 "payload": v.value
1333 })
1334 })
1335 .collect();
1336
1337 Ok(CliOutput::Raw(
1338 serde_json::to_value(events).expect("Can be encoded"),
1339 ))
1340 }
1341 Command::Dev(DevCmd::SubmitTransaction { transaction }) => {
1342 let client = self.client_open(&cli).await?;
1343 let tx = Transaction::consensus_decode_hex(&transaction, client.decoders())
1344 .map_err_cli()?;
1345 let tx_outcome = client
1346 .api()
1347 .submit_transaction(tx)
1348 .await
1349 .try_into_inner(client.decoders())
1350 .map_err_cli()?;
1351
1352 Ok(CliOutput::Raw(
1353 serde_json::to_value(tx_outcome.0.map_err_cli()?).expect("Can be encoded"),
1354 ))
1355 }
1356 Command::Completion { shell } => {
1357 let bin_path = PathBuf::from(
1358 std::env::args_os()
1359 .next()
1360 .expect("Binary name is always provided if we get this far"),
1361 );
1362 let bin_name = bin_path
1363 .file_name()
1364 .expect("path has file name")
1365 .to_string_lossy();
1366 clap_complete::generate(
1367 shell,
1368 &mut Opts::command(),
1369 bin_name.as_ref(),
1370 &mut std::io::stdout(),
1371 );
1372 Ok(CliOutput::Raw(serde_json::Value::Bool(true)))
1374 }
1375 }
1376 }
1377
1378 async fn handle_admin_setup_command(
1379 &self,
1380 cli: Opts,
1381 args: SetupAdminArgs,
1382 ) -> anyhow::Result<Value> {
1383 let client = DynGlobalApi::from_setup_endpoint(
1384 args.endpoint.clone(),
1385 &None,
1386 cli.iroh_enable_dht(),
1387 cli.iroh_enable_next(),
1388 )
1389 .await?;
1390
1391 match &args.subcommand {
1392 SetupAdminCmd::Status => {
1393 let status = client.setup_status(cli.auth()?).await?;
1394
1395 Ok(serde_json::to_value(status).expect("JSON serialization failed"))
1396 }
1397 SetupAdminCmd::SetLocalParams {
1398 name,
1399 federation_name,
1400 } => {
1401 let info = client
1402 .set_local_params(name.clone(), federation_name.clone(), None, cli.auth()?)
1403 .await?;
1404
1405 Ok(serde_json::to_value(info).expect("JSON serialization failed"))
1406 }
1407 SetupAdminCmd::AddPeer { info } => {
1408 let name = client
1409 .add_peer_connection_info(info.clone(), cli.auth()?)
1410 .await?;
1411
1412 Ok(serde_json::to_value(name).expect("JSON serialization failed"))
1413 }
1414 SetupAdminCmd::StartDkg => {
1415 client.start_dkg(cli.auth()?).await?;
1416
1417 Ok(Value::Null)
1418 }
1419 }
1420 }
1421}
1422
1423async fn log_expiration_notice(client: &Client) {
1424 client.get_meta_expiration_timestamp().await;
1425 if let Some(expiration_time) = client.get_meta_expiration_timestamp().await {
1426 match expiration_time.duration_since(fedimint_core::time::now()) {
1427 Ok(until_expiration) => {
1428 let days = until_expiration.as_secs() / (60 * 60 * 24);
1429
1430 if 90 < days {
1431 debug!(target: LOG_CLIENT, %days, "This federation will expire");
1432 } else if 30 < days {
1433 info!(target: LOG_CLIENT, %days, "This federation will expire");
1434 } else {
1435 warn!(target: LOG_CLIENT, %days, "This federation will expire soon");
1436 }
1437 }
1438 Err(_) => {
1439 tracing::error!(target: LOG_CLIENT, "This federation has expired and might not be safe to use");
1440 }
1441 }
1442 }
1443}
1444async fn print_welcome_message(client: &Client) {
1445 if let Some(welcome_message) = client
1446 .meta_service()
1447 .get_field::<String>(client.db(), "welcome_message")
1448 .await
1449 .and_then(|v| v.value)
1450 {
1451 eprintln!("{welcome_message}");
1452 }
1453}
1454
1455fn salt_from_file_path(file_path: &Path) -> PathBuf {
1456 file_path
1457 .parent()
1458 .expect("File has no parent?!")
1459 .join(SALT_FILE)
1460}
1461
1462fn metadata_from_clap_cli(metadata: Vec<String>) -> Result<BTreeMap<String, String>, CliError> {
1464 let metadata: BTreeMap<String, String> = metadata
1465 .into_iter()
1466 .map(|item| {
1467 match &item
1468 .splitn(2, '=')
1469 .map(ToString::to_string)
1470 .collect::<Vec<String>>()[..]
1471 {
1472 [] => Err(format_err!("Empty metadata argument not allowed")),
1473 [key] => Err(format_err!("Metadata {key} is missing a value")),
1474 [key, val] => Ok((key.clone(), val.clone())),
1475 [..] => unreachable!(),
1476 }
1477 })
1478 .collect::<anyhow::Result<_>>()
1479 .map_err_cli_msg("invalid metadata")?;
1480 Ok(metadata)
1481}
1482
1483#[test]
1484fn metadata_from_clap_cli_test() {
1485 for (args, expected) in [
1486 (
1487 vec!["a=b".to_string()],
1488 BTreeMap::from([("a".into(), "b".into())]),
1489 ),
1490 (
1491 vec!["a=b".to_string(), "c=d".to_string()],
1492 BTreeMap::from([("a".into(), "b".into()), ("c".into(), "d".into())]),
1493 ),
1494 ] {
1495 assert_eq!(metadata_from_clap_cli(args).unwrap(), expected);
1496 }
1497}