Skip to main content

gateway_cli/
general_commands.rs

1use std::time::{Duration, UNIX_EPOCH};
2
3use clap::Subcommand;
4use fedimint_connectors::error::ServerError;
5use fedimint_core::config::FederationId;
6use fedimint_core::fedimint_build_code_version_env;
7use fedimint_core::time::now;
8use fedimint_core::util::SafeUrl;
9use fedimint_eventlog::{EventKind, EventLogId};
10use fedimint_gateway_client::{
11    connect_federation, get_balances, get_info, get_invite_codes, get_mnemonic, leave_federation,
12    payment_log, payment_summary, stop,
13};
14use fedimint_gateway_common::{
15    ConnectFedPayload, LeaveFedPayload, PaymentLogPayload, PaymentSummaryPayload,
16};
17use fedimint_ln_common::client::GatewayApi;
18
19use crate::{CliOutput, CliOutputResult};
20
21/// General federation management commands including info, connecting, or
22/// leaving a federation.
23#[derive(Subcommand)]
24pub enum GeneralCommands {
25    /// Display the version hash of the CLI.
26    VersionHash,
27    /// Display high-level information about the gateway.
28    Info,
29    /// Get the total on-chain, lightning, and eCash balances of the gateway.
30    GetBalances,
31    /// Register the gateway with a federation.
32    ConnectFed {
33        /// Invite code (may contain an API secret). Prefer --invite-code-file.
34        #[clap(required_unless_present = "invite_code_file")]
35        invite_code: Option<String>,
36        /// Read the invite code from a file, or '-' for stdin
37        #[clap(long)]
38        invite_code_file: Option<std::path::PathBuf>,
39        /// Include the Tor preference in the federation connection request.
40        #[cfg(feature = "tor")]
41        use_tor: Option<bool>,
42        /// Include the Tor preference in the federation connection request.
43        /// Do not combine with the positional boolean.
44        #[cfg(feature = "tor")]
45        #[clap(long = "use-tor")]
46        use_tor_option: Option<bool>,
47        /// Indicates if the client should be recovered from a mnemonic
48        #[clap(long)]
49        recover: Option<bool>,
50    },
51    /// Leave a federation.
52    LeaveFed {
53        #[clap(long)]
54        federation_id: FederationId,
55    },
56    /// Prints the seed phrase for the gateway
57    Seed,
58    /// Safely stop the gateway
59    Stop,
60    /// List the fedimint transactions that the gateway has processed
61    PaymentLog {
62        #[clap(long)]
63        end_position: Option<EventLogId>,
64
65        #[clap(long, default_value_t = 25)]
66        pagination_size: usize,
67
68        #[clap(long)]
69        federation_id: FederationId,
70
71        #[clap(long)]
72        event_kinds: Vec<EventKind>,
73    },
74    /// Create a bcrypt hash of a password, for use in gateway deployment
75    CreatePasswordHash {
76        /// Password in process arguments (discouraged). Prefer --password-file.
77        #[clap(required_unless_present = "password_file")]
78        password: Option<String>,
79        /// Read the password from a file, or '-' for stdin
80        #[clap(long)]
81        password_file: Option<std::path::PathBuf>,
82
83        /// The bcrypt cost factor to use when hashing the password
84        #[clap(long)]
85        cost: Option<u32>,
86    },
87    /// List a payment summary for the last day
88    PaymentSummary {
89        #[clap(long)]
90        start: Option<u64>,
91
92        #[clap(long)]
93        end: Option<u64>,
94    },
95    /// List all invite codes of each federation the gateway has joined
96    InviteCodes,
97}
98
99impl GeneralCommands {
100    #[allow(clippy::too_many_lines)]
101    pub async fn handle(self, client: &GatewayApi, base_url: &SafeUrl) -> CliOutputResult {
102        match self {
103            Self::VersionHash => {
104                // Keep version-hash as raw string output for backward compatibility
105                println!("{}", fedimint_build_code_version_env!());
106                Ok(CliOutput::Empty)
107            }
108            Self::Info => {
109                let response = get_info(client, base_url).await?;
110                Ok(CliOutput::Info(response))
111            }
112            Self::GetBalances => {
113                let response = get_balances(client, base_url).await?;
114                Ok(CliOutput::Balances(response))
115            }
116            Self::ConnectFed {
117                invite_code,
118                #[cfg(feature = "tor")]
119                use_tor,
120                #[cfg(feature = "tor")]
121                use_tor_option,
122                recover,
123                ..
124            } => {
125                let invite_code =
126                    invite_code.expect("required invite code source resolved before handling");
127                let response = connect_federation(
128                    client,
129                    base_url,
130                    ConnectFedPayload {
131                        invite_code,
132                        #[cfg(feature = "tor")]
133                        use_tor: use_tor_option.or(use_tor),
134                        #[cfg(not(feature = "tor"))]
135                        use_tor: None,
136                        recover,
137                    },
138                )
139                .await?;
140
141                Ok(CliOutput::Federation(response))
142            }
143            Self::LeaveFed { federation_id } => {
144                let response =
145                    leave_federation(client, base_url, LeaveFedPayload { federation_id }).await?;
146                Ok(CliOutput::Federation(response))
147            }
148            Self::Seed => {
149                let response = get_mnemonic(client, base_url).await?;
150                Ok(CliOutput::Mnemonic(response))
151            }
152            Self::Stop => {
153                stop(client, base_url).await?;
154                Ok(CliOutput::Empty)
155            }
156            Self::PaymentLog {
157                end_position,
158                pagination_size,
159                federation_id,
160                event_kinds,
161            } => {
162                let payment_log = payment_log(
163                    client,
164                    base_url,
165                    PaymentLogPayload {
166                        end_position,
167                        pagination_size,
168                        federation_id,
169                        event_kinds,
170                    },
171                )
172                .await?;
173                Ok(CliOutput::PaymentLog(payment_log))
174            }
175            Self::CreatePasswordHash { password, cost, .. } => {
176                let password = password.expect("required password source resolved before handling");
177                let hash =
178                    bcrypt::hash(password, cost.unwrap_or(bcrypt::DEFAULT_COST)).map_err(|_| {
179                        ServerError::InvalidRequest("Unable to hash password".to_owned())
180                    })?;
181                Ok(CliOutput::PasswordHash(hash))
182            }
183            Self::PaymentSummary { start, end } => {
184                let now = now();
185                let now_millis: u64 = now
186                    .duration_since(UNIX_EPOCH)
187                    .expect("Before unix epoch")
188                    .as_millis()
189                    .try_into()
190                    .map_err(|e| ServerError::InternalClientError(format!("{e}")))?;
191                let one_day_ago = now
192                    .checked_sub(Duration::from_hours(24))
193                    .expect("Before unix epoch");
194                let one_day_ago_millis: u64 = one_day_ago
195                    .duration_since(UNIX_EPOCH)
196                    .expect("Before unix epoch")
197                    .as_millis()
198                    .try_into()
199                    .map_err(|e| ServerError::InternalClientError(format!("{e}")))?;
200                let end_millis = end.unwrap_or(now_millis);
201                let start_millis = start.unwrap_or(one_day_ago_millis);
202                let payment_summary = payment_summary(
203                    client,
204                    base_url,
205                    PaymentSummaryPayload {
206                        start_millis,
207                        end_millis,
208                    },
209                )
210                .await?;
211                Ok(CliOutput::PaymentSummary(payment_summary))
212            }
213            Self::InviteCodes => {
214                let invite_codes = get_invite_codes(client, base_url).await?;
215                Ok(CliOutput::InviteCodes(invite_codes))
216            }
217        }
218    }
219}