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, SALT_FILE};
33use fedimint_aead::{encrypted_read, encrypted_write, get_encryption_key};
34use fedimint_api_client::api::net::Connector;
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;
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_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(Parser, Clone)]
213#[command(version)]
214struct Opts {
215 #[arg(long = "data-dir", env = FM_CLIENT_DIR_ENV)]
217 data_dir: Option<PathBuf>,
218
219 #[arg(env = FM_OUR_ID_ENV, long, value_parser = parse_peer_id)]
221 our_id: Option<PeerId>,
222
223 #[arg(long, env = FM_PASSWORD_ENV)]
225 password: Option<String>,
226
227 #[cfg(feature = "tor")]
228 #[arg(long, env = FM_USE_TOR_ENV)]
230 use_tor: bool,
231
232 #[arg(short = 'v', long)]
235 verbose: bool,
236
237 #[clap(subcommand)]
238 command: Command,
239}
240
241impl Opts {
242 fn data_dir(&self) -> CliResult<&PathBuf> {
243 self.data_dir
244 .as_ref()
245 .ok_or_cli_msg("`--data-dir=` argument not set.")
246 }
247
248 async fn data_dir_create(&self) -> CliResult<&PathBuf> {
250 let dir = self.data_dir()?;
251
252 tokio::fs::create_dir_all(&dir).await.map_err_cli()?;
253
254 Ok(dir)
255 }
256
257 async fn admin_client(
258 &self,
259 peer_urls: &BTreeMap<PeerId, SafeUrl>,
260 api_secret: &Option<String>,
261 ) -> CliResult<DynGlobalApi> {
262 let our_id = self.our_id.ok_or_cli_msg("Admin client needs our-id set")?;
263
264 DynGlobalApi::new_admin(
265 our_id,
266 peer_urls
267 .get(&our_id)
268 .cloned()
269 .context("Our peer URL not found in config")
270 .map_err_cli()?,
271 api_secret,
272 )
273 .await
274 .map_err(|e| CliError {
275 error: e.to_string(),
276 })
277 }
278
279 fn auth(&self) -> CliResult<ApiAuth> {
280 let password = self
281 .password
282 .clone()
283 .ok_or_cli_msg("CLI needs password set")?;
284 Ok(ApiAuth(password))
285 }
286
287 async fn load_rocks_db(&self) -> CliResult<Database> {
288 debug!(target: LOG_CLIENT, "Loading client database");
289 let db_path = self.data_dir_create().await?.join("client.db");
290 Ok(fedimint_rocksdb::RocksDb::open(db_path)
291 .await
292 .map_err_cli_msg("could not open database")?
293 .into())
294 }
295
296 #[allow(clippy::unused_self)]
297 fn connector(&self) -> Connector {
298 #[cfg(feature = "tor")]
299 if self.use_tor {
300 Connector::tor()
301 } else {
302 Connector::default()
303 }
304 #[cfg(not(feature = "tor"))]
305 Connector::default()
306 }
307}
308
309async fn load_or_generate_mnemonic(db: &Database) -> Result<Mnemonic, CliError> {
310 Ok(
311 if let Ok(entropy) = Client::load_decodable_client_secret::<Vec<u8>>(db).await {
312 Mnemonic::from_entropy(&entropy).map_err_cli()?
313 } else {
314 debug!(
315 target: LOG_CLIENT,
316 "Generating mnemonic and writing entropy to client storage"
317 );
318 let mnemonic = Bip39RootSecretStrategy::<12>::random(&mut thread_rng());
319 Client::store_encodable_client_secret(db, mnemonic.to_entropy())
320 .await
321 .map_err_cli()?;
322 mnemonic
323 },
324 )
325}
326
327#[derive(Subcommand, Clone)]
328enum Command {
329 VersionHash,
331
332 #[clap(flatten)]
333 Client(client::ClientCmd),
334
335 #[clap(subcommand)]
336 Admin(AdminCmd),
337
338 #[clap(subcommand)]
339 Dev(DevCmd),
340
341 InviteCode {
343 peer: PeerId,
344 },
345
346 JoinFederation {
348 invite_code: String,
349 },
350
351 Completion {
352 shell: clap_complete::Shell,
353 },
354}
355
356#[allow(clippy::large_enum_variant)]
357#[derive(Debug, Clone, Subcommand)]
358enum AdminCmd {
359 Status,
361
362 Audit,
364
365 GuardianConfigBackup,
367
368 Setup(SetupAdminArgs),
369 SignApiAnnouncement {
372 api_url: SafeUrl,
374 #[clap(long)]
377 override_url: Option<SafeUrl>,
378 },
379 Shutdown {
381 session_idx: u64,
383 },
384 BackupStatistics,
386}
387
388#[derive(Debug, Clone, Args)]
389struct SetupAdminArgs {
390 endpoint: SafeUrl,
391
392 #[clap(subcommand)]
393 subcommand: SetupAdminCmd,
394}
395
396#[derive(Debug, Clone, Subcommand)]
397enum SetupAdminCmd {
398 Status,
399 SetLocalParams {
400 name: String,
401 #[clap(long)]
402 federation_name: Option<String>,
403 },
404 AddPeer {
405 info: String,
406 },
407 StartDkg,
408}
409
410#[derive(Debug, Clone, Subcommand)]
411enum DecodeType {
412 InviteCode { invite_code: InviteCode },
414 #[group(required = true, multiple = false)]
416 Notes {
417 notes: Option<OOBNotes>,
419 #[arg(long)]
421 file: Option<PathBuf>,
422 },
423 Transaction { hex_string: String },
425 SetupCode { setup_code: String },
428}
429
430#[derive(Debug, Clone, Deserialize, Serialize)]
431struct OOBNotesJson {
432 federation_id_prefix: String,
433 notes: TieredMulti<SpendableNote>,
434}
435
436#[derive(Debug, Clone, Subcommand)]
437enum EncodeType {
438 InviteCode {
440 #[clap(long)]
441 url: SafeUrl,
442 #[clap(long = "federation_id")]
443 federation_id: FederationId,
444 #[clap(long = "peer")]
445 peer: PeerId,
446 #[arg(env = FM_API_SECRET_ENV)]
447 api_secret: Option<String>,
448 },
449
450 Notes { notes_json: String },
452}
453
454#[derive(Debug, Clone, Subcommand)]
455enum DevCmd {
456 #[command(after_long_help = r#"
460Examples:
461
462 fedimint-cli dev api --peer-id 0 config '"fed114znk7uk7ppugdjuytr8venqf2tkywd65cqvg3u93um64tu5cw4yr0n3fvn7qmwvm4g48cpndgnm4gqq4waen5te0xyerwt3s9cczuvf6xyurzde597s7crdvsk2vmyarjw9gwyqjdzj"'
463 "#)]
464 Api {
465 method: String,
467 #[clap(default_value = "null")]
472 params: String,
473 #[clap(long = "peer-id")]
475 peer_id: Option<u16>,
476
477 #[clap(long = "module")]
479 module: Option<ModuleSelector>,
480
481 #[clap(long, requires = "peer_id")]
484 password: Option<String>,
485 },
486
487 ApiAnnouncements,
488
489 AdvanceNoteIdx {
491 #[clap(long, default_value = "1")]
492 count: usize,
493
494 #[clap(long)]
495 amount: Amount,
496 },
497
498 WaitBlockCount {
500 count: u64,
501 },
502
503 Wait {
505 seconds: Option<f32>,
507 },
508
509 WaitComplete,
511
512 Decode {
514 #[clap(subcommand)]
515 decode_type: DecodeType,
516 },
517
518 Encode {
520 #[clap(subcommand)]
521 encode_type: EncodeType,
522 },
523
524 SessionCount,
526
527 ConfigDecrypt {
528 #[arg(long = "in-file")]
530 in_file: PathBuf,
531 #[arg(long = "out-file")]
533 out_file: PathBuf,
534 #[arg(long = "salt-file")]
537 salt_file: Option<PathBuf>,
538 #[arg(env = FM_PASSWORD_ENV)]
540 password: String,
541 },
542
543 ConfigEncrypt {
544 #[arg(long = "in-file")]
546 in_file: PathBuf,
547 #[arg(long = "out-file")]
549 out_file: PathBuf,
550 #[arg(long = "salt-file")]
553 salt_file: Option<PathBuf>,
554 #[arg(env = FM_PASSWORD_ENV)]
556 password: String,
557 },
558
559 ListOperationStates {
562 operation_id: OperationId,
563 },
564 MetaFields,
568 PeerVersion {
570 #[clap(long)]
571 peer_id: u16,
572 },
573 ShowEventLog {
575 #[arg(long)]
576 pos: Option<EventLogId>,
577 #[arg(long, default_value = "10")]
578 limit: u64,
579 },
580 SubmitTransaction {
585 transaction: String,
587 },
588}
589
590#[derive(Debug, Serialize, Deserialize)]
591#[serde(rename_all = "snake_case")]
592struct PayRequest {
593 notes: TieredMulti<SpendableNote>,
594 invoice: lightning_invoice::Bolt11Invoice,
595}
596
597pub struct FedimintCli {
598 module_inits: ClientModuleInitRegistry,
599 cli_args: Opts,
600}
601
602impl FedimintCli {
603 pub fn new(version_hash: &str) -> anyhow::Result<FedimintCli> {
605 assert_eq!(
606 fedimint_build_code_version_env!().len(),
607 version_hash.len(),
608 "version_hash must have an expected length"
609 );
610
611 handle_version_hash_command(version_hash);
612
613 let cli_args = Opts::parse();
614 let base_level = if cli_args.verbose { "debug" } else { "info" };
615 TracingSetup::default()
616 .with_base_level(base_level)
617 .init()
618 .expect("tracing initializes");
619
620 let version = env!("CARGO_PKG_VERSION");
621 debug!(target: LOG_CLIENT, "Starting fedimint-cli (version: {version} version_hash: {version_hash})");
622
623 Ok(Self {
624 module_inits: ClientModuleInitRegistry::new(),
625 cli_args,
626 })
627 }
628
629 pub fn with_module<T>(mut self, r#gen: T) -> Self
630 where
631 T: ClientModuleInit + 'static + Send + Sync,
632 {
633 self.module_inits.attach(r#gen);
634 self
635 }
636
637 pub fn with_default_modules(self) -> Self {
638 self.with_module(LightningClientInit::default())
639 .with_module(MintClientInit)
640 .with_module(WalletClientInit::default())
641 .with_module(MetaClientInit)
642 .with_module(fedimint_lnv2_client::LightningClientInit::default())
643 }
644
645 pub async fn run(&mut self) {
646 match self.handle_command(self.cli_args.clone()).await {
647 Ok(output) => {
648 let _ = writeln!(std::io::stdout(), "{output}");
650 }
651 Err(err) => {
652 debug!(target: LOG_CLIENT, err = %err.error.as_str(), "Command failed");
653 let _ = writeln!(std::io::stdout(), "{err}");
654 exit(1);
655 }
656 }
657 }
658
659 async fn make_client_builder(&self, cli: &Opts) -> CliResult<ClientBuilder> {
660 let db = cli.load_rocks_db().await?;
661 let mut client_builder = Client::builder(db).await.map_err_cli()?;
662 client_builder.with_module_inits(self.module_inits.clone());
663 client_builder.with_primary_module_kind(fedimint_mint_client::KIND);
664
665 client_builder.with_connector(cli.connector());
666
667 Ok(client_builder)
668 }
669
670 async fn client_join(
671 &mut self,
672 cli: &Opts,
673 invite_code: InviteCode,
674 ) -> CliResult<ClientHandleArc> {
675 let client_builder = self.make_client_builder(cli).await?;
676
677 let mnemonic = load_or_generate_mnemonic(client_builder.db_no_decoders()).await?;
678
679 let client = client_builder
680 .preview(&invite_code)
681 .await
682 .map_err_cli()?
683 .join(RootSecret::LegacyDoubleDerive(
684 Bip39RootSecretStrategy::<12>::to_root_secret(&mnemonic),
685 ))
686 .await
687 .map(Arc::new)
688 .map_err_cli()?;
689
690 print_welcome_message(&client).await;
691 log_expiration_notice(&client).await;
692
693 Ok(client)
694 }
695
696 async fn client_open(&self, cli: &Opts) -> CliResult<ClientHandleArc> {
697 let mut client_builder = self.make_client_builder(cli).await?;
698
699 if let Some(our_id) = cli.our_id {
700 client_builder.set_admin_creds(AdminCreds {
701 peer_id: our_id,
702 auth: cli.auth()?,
703 });
704 }
705
706 let mnemonic = Mnemonic::from_entropy(
707 &Client::load_decodable_client_secret::<Vec<u8>>(client_builder.db_no_decoders())
708 .await
709 .map_err_cli()?,
710 )
711 .map_err_cli()?;
712
713 let client = client_builder
714 .open(RootSecret::LegacyDoubleDerive(
715 Bip39RootSecretStrategy::<12>::to_root_secret(&mnemonic),
716 ))
717 .await
718 .map(Arc::new)
719 .map_err_cli()?;
720
721 log_expiration_notice(&client).await;
722
723 Ok(client)
724 }
725
726 async fn client_recover(
727 &mut self,
728 cli: &Opts,
729 mnemonic: Mnemonic,
730 invite_code: InviteCode,
731 ) -> CliResult<ClientHandleArc> {
732 let builder = self.make_client_builder(cli).await?;
733 match Client::load_decodable_client_secret_opt::<Vec<u8>>(builder.db_no_decoders())
734 .await
735 .map_err_cli()?
736 {
737 Some(existing) => {
738 if existing != mnemonic.to_entropy() {
739 Err(anyhow::anyhow!("Previously set mnemonic does not match")).map_err_cli()?;
740 }
741 }
742 None => {
743 Client::store_encodable_client_secret(
744 builder.db_no_decoders(),
745 mnemonic.to_entropy(),
746 )
747 .await
748 .map_err_cli()?;
749 }
750 }
751
752 let root_secret = RootSecret::LegacyDoubleDerive(
753 Bip39RootSecretStrategy::<12>::to_root_secret(&mnemonic),
754 );
755 let client = builder
756 .preview(&invite_code)
757 .await
758 .map_err_cli()?
759 .recover(root_secret, None)
760 .await
761 .map(Arc::new)
762 .map_err_cli()?;
763
764 print_welcome_message(&client).await;
765 log_expiration_notice(&client).await;
766
767 Ok(client)
768 }
769
770 async fn handle_command(&mut self, cli: Opts) -> CliOutputResult {
771 match cli.command.clone() {
772 Command::InviteCode { peer } => {
773 let client = self.client_open(&cli).await?;
774
775 let invite_code = client
776 .invite_code(peer)
777 .await
778 .ok_or_cli_msg("peer not found")?;
779
780 Ok(CliOutput::InviteCode { invite_code })
781 }
782 Command::JoinFederation { invite_code } => {
783 {
784 let invite_code: InviteCode = InviteCode::from_str(&invite_code)
785 .map_err_cli_msg("invalid invite code")?;
786
787 let _client = self.client_join(&cli, invite_code).await?;
789 }
790
791 Ok(CliOutput::JoinFederation {
792 joined: invite_code,
793 })
794 }
795 Command::VersionHash => Ok(CliOutput::VersionHash {
796 hash: fedimint_build_code_version_env!().to_string(),
797 }),
798 Command::Client(ClientCmd::Restore {
799 mnemonic,
800 invite_code,
801 }) => {
802 let invite_code: InviteCode =
803 InviteCode::from_str(&invite_code).map_err_cli_msg("invalid invite code")?;
804 let mnemonic = Mnemonic::from_str(&mnemonic).map_err_cli()?;
805 let client = self.client_recover(&cli, mnemonic, invite_code).await?;
806
807 debug!(target: LOG_CLIENT, "Waiting for mint module recovery to finish");
810 client.wait_for_all_recoveries().await.map_err_cli()?;
811
812 debug!(target: LOG_CLIENT, "Recovery complete");
813
814 Ok(CliOutput::Raw(serde_json::to_value(()).unwrap()))
815 }
816 Command::Client(command) => {
817 let client = self.client_open(&cli).await?;
818 Ok(CliOutput::Raw(
819 client::handle_command(command, client)
820 .await
821 .map_err_cli()?,
822 ))
823 }
824 Command::Admin(AdminCmd::Audit) => {
825 let client = self.client_open(&cli).await?;
826
827 let audit = cli
828 .admin_client(&client.get_peer_urls().await, client.api_secret())
829 .await?
830 .audit(cli.auth()?)
831 .await?;
832 Ok(CliOutput::Raw(
833 serde_json::to_value(audit).map_err_cli_msg("invalid response")?,
834 ))
835 }
836 Command::Admin(AdminCmd::Status) => {
837 let client = self.client_open(&cli).await?;
838
839 let status = cli
840 .admin_client(&client.get_peer_urls().await, client.api_secret())
841 .await?
842 .status()
843 .await?;
844 Ok(CliOutput::Raw(
845 serde_json::to_value(status).map_err_cli_msg("invalid response")?,
846 ))
847 }
848 Command::Admin(AdminCmd::GuardianConfigBackup) => {
849 let client = self.client_open(&cli).await?;
850
851 let guardian_config_backup = cli
852 .admin_client(&client.get_peer_urls().await, client.api_secret())
853 .await?
854 .guardian_config_backup(cli.auth()?)
855 .await?;
856 Ok(CliOutput::Raw(
857 serde_json::to_value(guardian_config_backup)
858 .map_err_cli_msg("invalid response")?,
859 ))
860 }
861 Command::Admin(AdminCmd::Setup(dkg_args)) => self
862 .handle_admin_setup_command(cli, dkg_args)
863 .await
864 .map(CliOutput::Raw)
865 .map_err_cli_msg("Config Gen Error"),
866 Command::Admin(AdminCmd::SignApiAnnouncement {
867 api_url,
868 override_url,
869 }) => {
870 let client = self.client_open(&cli).await?;
871
872 if !["ws", "wss"].contains(&api_url.scheme()) {
873 return Err(CliError {
874 error: format!(
875 "Unsupported URL scheme {}, use ws:// or wss://",
876 api_url.scheme()
877 ),
878 });
879 }
880
881 let announcement = cli
882 .admin_client(
883 &override_url
884 .and_then(|url| Some(vec![(cli.our_id?, url)].into_iter().collect()))
885 .unwrap_or(client.get_peer_urls().await),
886 client.api_secret(),
887 )
888 .await?
889 .sign_api_announcement(api_url, cli.auth()?)
890 .await?;
891
892 Ok(CliOutput::Raw(
893 serde_json::to_value(announcement).map_err_cli_msg("invalid response")?,
894 ))
895 }
896 Command::Admin(AdminCmd::Shutdown { session_idx }) => {
897 let client = self.client_open(&cli).await?;
898
899 cli.admin_client(&client.get_peer_urls().await, client.api_secret())
900 .await?
901 .shutdown(Some(session_idx), cli.auth()?)
902 .await?;
903
904 Ok(CliOutput::Raw(json!(null)))
905 }
906 Command::Admin(AdminCmd::BackupStatistics) => {
907 let client = self.client_open(&cli).await?;
908
909 let backup_statistics = cli
910 .admin_client(&client.get_peer_urls().await, client.api_secret())
911 .await?
912 .backup_statistics(cli.auth()?)
913 .await?;
914
915 Ok(CliOutput::Raw(
916 serde_json::to_value(backup_statistics).expect("Can be encoded"),
917 ))
918 }
919 Command::Dev(DevCmd::Api {
920 method,
921 params,
922 peer_id,
923 password: auth,
924 module,
925 }) => {
926 let params = serde_json::from_str::<Value>(¶ms).unwrap_or_else(|err| {
929 debug!(
930 target: LOG_CLIENT,
931 "Failed to serialize params:{}. Converting it to JSON string",
932 err
933 );
934
935 serde_json::Value::String(params)
936 });
937
938 let mut params = ApiRequestErased::new(params);
939 if let Some(auth) = auth {
940 params = params.with_auth(ApiAuth(auth));
941 }
942 let client = self.client_open(&cli).await?;
943
944 let api = client.api_clone();
945
946 let module_api = match module {
947 Some(selector) => {
948 Some(api.with_module(selector.resolve(&client).map_err_cli()?))
949 }
950 None => None,
951 };
952
953 let response: Value = match (peer_id, module_api) {
954 (Some(peer_id), Some(module_api)) => module_api
955 .request_raw(peer_id.into(), &method, ¶ms)
956 .await
957 .map_err_cli()?,
958 (Some(peer_id), None) => api
959 .request_raw(peer_id.into(), &method, ¶ms)
960 .await
961 .map_err_cli()?,
962 (None, Some(module_api)) => module_api
963 .request_current_consensus(method, params)
964 .await
965 .map_err_cli()?,
966 (None, None) => api
967 .request_current_consensus(method, params)
968 .await
969 .map_err_cli()?,
970 };
971
972 Ok(CliOutput::UntypedApiOutput { value: response })
973 }
974 Command::Dev(DevCmd::AdvanceNoteIdx { count, amount }) => {
975 let client = self.client_open(&cli).await?;
976
977 let mint = client
978 .get_first_module::<MintClientModule>()
979 .map_err_cli_msg("can't get mint module")?;
980
981 for _ in 0..count {
982 mint.advance_note_idx(amount)
983 .await
984 .map_err_cli_msg("failed to advance the note_idx")?;
985 }
986
987 Ok(CliOutput::Raw(serde_json::Value::Null))
988 }
989 Command::Dev(DevCmd::ApiAnnouncements) => {
990 let client = self.client_open(&cli).await?;
991 let announcements = client.get_peer_url_announcements().await;
992 Ok(CliOutput::Raw(
993 serde_json::to_value(announcements).expect("Can be encoded"),
994 ))
995 }
996 Command::Dev(DevCmd::WaitBlockCount { count: target }) => retry(
997 "wait_block_count",
998 backoff_util::custom_backoff(
999 Duration::from_millis(100),
1000 Duration::from_secs(5),
1001 None,
1002 ),
1003 || async {
1004 let client = self.client_open(&cli).await?;
1005 let wallet = client.get_first_module::<WalletClientModule>()?;
1006 let count = client
1007 .api()
1008 .with_module(wallet.id)
1009 .fetch_consensus_block_count()
1010 .await?;
1011 if count >= target {
1012 Ok(CliOutput::WaitBlockCount { reached: count })
1013 } else {
1014 info!(target: LOG_CLIENT, current=count, target, "Block count not reached");
1015 Err(format_err!("target not reached"))
1016 }
1017 },
1018 )
1019 .await
1020 .map_err_cli(),
1021
1022 Command::Dev(DevCmd::WaitComplete) => {
1023 let client = self.client_open(&cli).await?;
1024 client
1025 .wait_for_all_active_state_machines()
1026 .await
1027 .map_err_cli_msg("failed to wait for all active state machines")?;
1028 Ok(CliOutput::Raw(serde_json::Value::Null))
1029 }
1030 Command::Dev(DevCmd::Wait { seconds }) => {
1031 let _client = self.client_open(&cli).await?;
1032 if let Some(secs) = seconds {
1033 runtime::sleep(Duration::from_secs_f32(secs)).await;
1034 } else {
1035 pending::<()>().await;
1036 }
1037 Ok(CliOutput::Raw(serde_json::Value::Null))
1038 }
1039 Command::Dev(DevCmd::Decode { decode_type }) => match decode_type {
1040 DecodeType::InviteCode { invite_code } => Ok(CliOutput::DecodeInviteCode {
1041 url: invite_code.url(),
1042 federation_id: invite_code.federation_id(),
1043 }),
1044 DecodeType::Notes { notes, file } => {
1045 let notes = if let Some(notes) = notes {
1046 notes
1047 } else if let Some(file) = file {
1048 let notes_str =
1049 fs::read_to_string(file).map_err_cli_msg("failed to read file")?;
1050 OOBNotes::from_str(¬es_str).map_err_cli_msg("failed to decode notes")?
1051 } else {
1052 unreachable!("Clap enforces either notes or file being set");
1053 };
1054
1055 let notes_json = notes
1056 .notes_json()
1057 .map_err_cli_msg("failed to decode notes")?;
1058 Ok(CliOutput::Raw(notes_json))
1059 }
1060 DecodeType::Transaction { hex_string } => {
1061 let bytes: Vec<u8> = hex::FromHex::from_hex(&hex_string)
1062 .map_err_cli_msg("failed to decode transaction")?;
1063
1064 let client = self.client_open(&cli).await?;
1065 let tx = fedimint_core::transaction::Transaction::from_bytes(
1066 &bytes,
1067 client.decoders(),
1068 )
1069 .map_err_cli_msg("failed to decode transaction")?;
1070
1071 Ok(CliOutput::DecodeTransaction {
1072 transaction: (format!("{tx:?}")),
1073 })
1074 }
1075 DecodeType::SetupCode { setup_code } => {
1076 let setup_code = PeerSetupCode::decode_base32(&setup_code)
1077 .map_err_cli_msg("failed to decode setup code")?;
1078
1079 Ok(CliOutput::SetupCode { setup_code })
1080 }
1081 },
1082 Command::Dev(DevCmd::Encode { encode_type }) => match encode_type {
1083 EncodeType::InviteCode {
1084 url,
1085 federation_id,
1086 peer,
1087 api_secret,
1088 } => Ok(CliOutput::InviteCode {
1089 invite_code: InviteCode::new(url, peer, federation_id, api_secret),
1090 }),
1091 EncodeType::Notes { notes_json } => {
1092 let notes = serde_json::from_str::<OOBNotesJson>(¬es_json)
1093 .map_err_cli_msg("invalid JSON for notes")?;
1094 let prefix =
1095 FederationIdPrefix::from_str(¬es.federation_id_prefix).map_err_cli()?;
1096 let notes = OOBNotes::new(prefix, notes.notes);
1097 Ok(CliOutput::Raw(notes.to_string().into()))
1098 }
1099 },
1100 Command::Dev(DevCmd::SessionCount) => {
1101 let client = self.client_open(&cli).await?;
1102 let count = client.api().session_count().await?;
1103 Ok(CliOutput::EpochCount { count })
1104 }
1105 Command::Dev(DevCmd::ConfigDecrypt {
1106 in_file,
1107 out_file,
1108 salt_file,
1109 password,
1110 }) => {
1111 let salt_file = salt_file.unwrap_or_else(|| salt_from_file_path(&in_file));
1112 let salt = fs::read_to_string(salt_file).map_err_cli()?;
1113 let key = get_encryption_key(&password, &salt).map_err_cli()?;
1114 let decrypted_bytes = encrypted_read(&key, in_file).map_err_cli()?;
1115
1116 let mut out_file_handle = fs::File::options()
1117 .create_new(true)
1118 .write(true)
1119 .open(out_file)
1120 .expect("Could not create output cfg file");
1121 out_file_handle.write_all(&decrypted_bytes).map_err_cli()?;
1122 Ok(CliOutput::ConfigDecrypt)
1123 }
1124 Command::Dev(DevCmd::ConfigEncrypt {
1125 in_file,
1126 out_file,
1127 salt_file,
1128 password,
1129 }) => {
1130 let mut in_file_handle =
1131 fs::File::open(in_file).expect("Could not create output cfg file");
1132 let mut plaintext_bytes = vec![];
1133 in_file_handle.read_to_end(&mut plaintext_bytes).unwrap();
1134
1135 let salt_file = salt_file.unwrap_or_else(|| salt_from_file_path(&out_file));
1136 let salt = fs::read_to_string(salt_file).map_err_cli()?;
1137 let key = get_encryption_key(&password, &salt).map_err_cli()?;
1138 encrypted_write(plaintext_bytes, &key, out_file).map_err_cli()?;
1139 Ok(CliOutput::ConfigEncrypt)
1140 }
1141 Command::Dev(DevCmd::ListOperationStates { operation_id }) => {
1142 #[derive(Serialize)]
1143 struct ReactorLogState {
1144 active: bool,
1145 module_instance: ModuleInstanceId,
1146 creation_time: String,
1147 #[serde(skip_serializing_if = "Option::is_none")]
1148 end_time: Option<String>,
1149 state: String,
1150 }
1151
1152 let client = self.client_open(&cli).await?;
1153
1154 let (active_states, inactive_states) =
1155 client.executor().get_operation_states(operation_id).await;
1156 let all_states =
1157 active_states
1158 .into_iter()
1159 .map(|(active_state, active_meta)| ReactorLogState {
1160 active: true,
1161 module_instance: active_state.module_instance_id(),
1162 creation_time: crate::client::time_to_iso8601(&active_meta.created_at),
1163 end_time: None,
1164 state: format!("{active_state:?}",),
1165 })
1166 .chain(inactive_states.into_iter().map(
1167 |(inactive_state, inactive_meta)| ReactorLogState {
1168 active: false,
1169 module_instance: inactive_state.module_instance_id(),
1170 creation_time: crate::client::time_to_iso8601(
1171 &inactive_meta.created_at,
1172 ),
1173 end_time: Some(crate::client::time_to_iso8601(
1174 &inactive_meta.exited_at,
1175 )),
1176 state: format!("{inactive_state:?}",),
1177 },
1178 ))
1179 .sorted_by(|a, b| a.creation_time.cmp(&b.creation_time))
1180 .collect::<Vec<_>>();
1181
1182 Ok(CliOutput::Raw(json!({
1183 "states": all_states
1184 })))
1185 }
1186 Command::Dev(DevCmd::MetaFields) => {
1187 let client = self.client_open(&cli).await?;
1188 let source = MetaModuleMetaSourceWithFallback::<LegacyMetaSource>::default();
1189
1190 let meta_fields = source
1191 .fetch(
1192 &client.config().await,
1193 &client.api_clone(),
1194 FetchKind::Initial,
1195 None,
1196 )
1197 .await
1198 .map_err_cli()?;
1199
1200 Ok(CliOutput::Raw(
1201 serde_json::to_value(meta_fields).expect("Can be encoded"),
1202 ))
1203 }
1204 Command::Dev(DevCmd::PeerVersion { peer_id }) => {
1205 let client = self.client_open(&cli).await?;
1206 let version = client
1207 .api()
1208 .fedimintd_version(peer_id.into())
1209 .await
1210 .map_err_cli()?;
1211
1212 Ok(CliOutput::Raw(json!({ "version": version })))
1213 }
1214 Command::Dev(DevCmd::ShowEventLog { pos, limit }) => {
1215 let client = self.client_open(&cli).await?;
1216
1217 let events: Vec<_> = client
1218 .get_event_log(pos, limit)
1219 .await
1220 .into_iter()
1221 .map(|v| {
1222 let module_id = v.module.as_ref().map(|m| m.1);
1223 let module_kind = v.module.map(|m| m.0);
1224 serde_json::json!({
1225 "id": v.event_id,
1226 "kind": v.event_kind,
1227 "module_kind": module_kind,
1228 "module_id": module_id,
1229 "ts": v.timestamp,
1230 "payload": v.value
1231 })
1232 })
1233 .collect();
1234
1235 Ok(CliOutput::Raw(
1236 serde_json::to_value(events).expect("Can be encoded"),
1237 ))
1238 }
1239 Command::Dev(DevCmd::SubmitTransaction { transaction }) => {
1240 let client = self.client_open(&cli).await?;
1241 let tx = Transaction::consensus_decode_hex(&transaction, client.decoders())
1242 .map_err_cli()?;
1243 let tx_outcome = client
1244 .api()
1245 .submit_transaction(tx)
1246 .await
1247 .try_into_inner(client.decoders())
1248 .map_err_cli()?;
1249
1250 Ok(CliOutput::Raw(
1251 serde_json::to_value(tx_outcome.0.map_err_cli()?).expect("Can be encoded"),
1252 ))
1253 }
1254 Command::Completion { shell } => {
1255 let bin_path = PathBuf::from(
1256 std::env::args_os()
1257 .next()
1258 .expect("Binary name is always provided if we get this far"),
1259 );
1260 let bin_name = bin_path
1261 .file_name()
1262 .expect("path has file name")
1263 .to_string_lossy();
1264 clap_complete::generate(
1265 shell,
1266 &mut Opts::command(),
1267 bin_name.as_ref(),
1268 &mut std::io::stdout(),
1269 );
1270 Ok(CliOutput::Raw(serde_json::Value::Bool(true)))
1272 }
1273 }
1274 }
1275
1276 async fn handle_admin_setup_command(
1277 &self,
1278 cli: Opts,
1279 args: SetupAdminArgs,
1280 ) -> anyhow::Result<Value> {
1281 let client = DynGlobalApi::from_setup_endpoint(args.endpoint.clone(), &None).await?;
1282
1283 match &args.subcommand {
1284 SetupAdminCmd::Status => {
1285 let status = client.setup_status(cli.auth()?).await?;
1286
1287 Ok(serde_json::to_value(status).expect("JSON serialization failed"))
1288 }
1289 SetupAdminCmd::SetLocalParams {
1290 name,
1291 federation_name,
1292 } => {
1293 let info = client
1294 .set_local_params(name.clone(), federation_name.clone(), cli.auth()?)
1295 .await?;
1296
1297 Ok(serde_json::to_value(info).expect("JSON serialization failed"))
1298 }
1299 SetupAdminCmd::AddPeer { info } => {
1300 let name = client
1301 .add_peer_connection_info(info.clone(), cli.auth()?)
1302 .await?;
1303
1304 Ok(serde_json::to_value(name).expect("JSON serialization failed"))
1305 }
1306 SetupAdminCmd::StartDkg => {
1307 client.start_dkg(cli.auth()?).await?;
1308
1309 Ok(Value::Null)
1310 }
1311 }
1312 }
1313}
1314
1315async fn log_expiration_notice(client: &Client) {
1316 client.get_meta_expiration_timestamp().await;
1317 if let Some(expiration_time) = client.get_meta_expiration_timestamp().await {
1318 match expiration_time.duration_since(fedimint_core::time::now()) {
1319 Ok(until_expiration) => {
1320 let days = until_expiration.as_secs() / (60 * 60 * 24);
1321
1322 if 90 < days {
1323 debug!(target: LOG_CLIENT, %days, "This federation will expire");
1324 } else if 30 < days {
1325 info!(target: LOG_CLIENT, %days, "This federation will expire");
1326 } else {
1327 warn!(target: LOG_CLIENT, %days, "This federation will expire soon");
1328 }
1329 }
1330 Err(_) => {
1331 tracing::error!(target: LOG_CLIENT, "This federation has expired and might not be safe to use");
1332 }
1333 }
1334 }
1335}
1336async fn print_welcome_message(client: &Client) {
1337 if let Some(welcome_message) = client
1338 .meta_service()
1339 .get_field::<String>(client.db(), "welcome_message")
1340 .await
1341 .and_then(|v| v.value)
1342 {
1343 eprintln!("{welcome_message}");
1344 }
1345}
1346
1347fn salt_from_file_path(file_path: &Path) -> PathBuf {
1348 file_path
1349 .parent()
1350 .expect("File has no parent?!")
1351 .join(SALT_FILE)
1352}
1353
1354fn metadata_from_clap_cli(metadata: Vec<String>) -> Result<BTreeMap<String, String>, CliError> {
1356 let metadata: BTreeMap<String, String> = metadata
1357 .into_iter()
1358 .map(|item| {
1359 match &item
1360 .splitn(2, '=')
1361 .map(ToString::to_string)
1362 .collect::<Vec<String>>()[..]
1363 {
1364 [] => Err(format_err!("Empty metadata argument not allowed")),
1365 [key] => Err(format_err!("Metadata {key} is missing a value")),
1366 [key, val] => Ok((key.clone(), val.clone())),
1367 [..] => unreachable!(),
1368 }
1369 })
1370 .collect::<anyhow::Result<_>>()
1371 .map_err_cli_msg("invalid metadata")?;
1372 Ok(metadata)
1373}
1374
1375#[test]
1376fn metadata_from_clap_cli_test() {
1377 for (args, expected) in [
1378 (
1379 vec!["a=b".to_string()],
1380 BTreeMap::from([("a".into(), "b".into())]),
1381 ),
1382 (
1383 vec!["a=b".to_string(), "c=d".to_string()],
1384 BTreeMap::from([("a".into(), "b".into()), ("c".into(), "d".into())]),
1385 ),
1386 ] {
1387 assert_eq!(metadata_from_clap_cli(args).unwrap(), expected);
1388 }
1389}