1#![deny(clippy::pedantic, clippy::nursery)]
2
3mod config_commands;
4mod ecash_commands;
5mod general_commands;
6mod lightning_commands;
7mod onchain_commands;
8
9use std::collections::BTreeMap;
10use std::path::PathBuf;
11
12use bitcoin::Txid;
13use bitcoin::address::NetworkUnchecked;
14use clap::{CommandFactory, Parser, Subcommand};
15use config_commands::ConfigCommands;
16use ecash_commands::EcashCommands;
17use fedimint_connectors::ConnectorRegistry;
18use fedimint_connectors::error::ServerError;
19use fedimint_core::PeerId;
20use fedimint_core::config::FederationId;
21use fedimint_core::invite_code::InviteCode;
22use fedimint_core::util::SafeUrl;
23use fedimint_gateway_common::{
24 ChannelInfo, CloseChannelsWithPeerResponse, CreateOfferResponse, FederationConfig,
25 FederationInfo, GatewayBalances, GatewayFedConfig, GatewayInfo, GetInvoiceResponse,
26 ListTransactionsResponse, MnemonicResponse, PayOfferResponse, PaymentLogResponse,
27 PaymentSummaryResponse, ReceiveEcashResponse, SpendEcashResponse, WithdrawResponse,
28};
29use fedimint_ln_common::client::GatewayApi;
30use fedimint_logging::TracingSetup;
31use general_commands::GeneralCommands;
32use lightning_commands::LightningCommands;
33use onchain_commands::OnchainCommands;
34use serde::Serialize;
35
36#[derive(Serialize)]
42#[serde(untagged)]
43pub enum CliOutput {
44 Info(GatewayInfo),
46 Balances(GatewayBalances),
47 Federation(FederationInfo),
48 Mnemonic(MnemonicResponse),
49 PaymentLog(PaymentLogResponse),
50 PaymentSummary(PaymentSummaryResponse),
51 InviteCodes(BTreeMap<FederationId, BTreeMap<PeerId, (String, InviteCode)>>),
52 PasswordHash(String),
53
54 Invoice {
56 invoice: String,
57 },
58 Preimage {
59 preimage: String,
60 },
61 FundingTxid {
62 funding_txid: Txid,
63 },
64 Channels(Vec<ChannelInfo>),
65 CloseChannels(CloseChannelsWithPeerResponse),
66 InvoiceDetails(Option<GetInvoiceResponse>),
67 Transactions(ListTransactionsResponse),
68 Offer(CreateOfferResponse),
69 OfferPayment(PayOfferResponse),
70
71 DepositAddress {
73 address: bitcoin::Address<NetworkUnchecked>,
74 },
75 DepositRecheck(serde_json::Value),
76 PeginTxid {
77 txid: Txid,
78 },
79 Withdraw(WithdrawResponse),
80 SpendEcash(SpendEcashResponse),
81 ReceiveEcash(ReceiveEcashResponse),
82
83 OnchainAddress {
85 address: String,
86 },
87 SendOnchainTxid {
88 txid: Txid,
89 },
90
91 Config(GatewayFedConfig),
93 FederationConfigs(Vec<FederationConfig>),
94
95 #[serde(skip)]
97 Empty,
98}
99
100pub type CliOutputResult = Result<CliOutput, ServerError>;
103
104#[derive(Debug, Clone, Copy, Serialize)]
109#[serde(rename_all = "snake_case")]
110pub enum ErrorCode {
111 AuthFailed,
113 ConnectionFailed,
115 InvalidInput,
117 NotFound,
119 InvalidState,
121 Timeout,
123 Internal,
125 Unknown,
127}
128
129#[derive(Debug, Clone, Copy)]
134#[repr(i32)]
135pub enum ExitCode {
136 Success = 0,
137 GeneralError = 1,
138 ConnectionError = 2,
139 AuthError = 3,
140 InvalidInput = 4,
141 NotFound = 5,
142 Timeout = 6,
143}
144
145impl From<ErrorCode> for ExitCode {
146 fn from(code: ErrorCode) -> Self {
147 match code {
148 ErrorCode::AuthFailed => Self::AuthError,
149 ErrorCode::ConnectionFailed => Self::ConnectionError,
150 ErrorCode::InvalidInput => Self::InvalidInput,
151 ErrorCode::NotFound => Self::NotFound,
152 ErrorCode::Timeout => Self::Timeout,
153 ErrorCode::InvalidState | ErrorCode::Internal | ErrorCode::Unknown => {
154 Self::GeneralError
155 }
156 }
157 }
158}
159
160#[derive(Debug, Serialize)]
165pub struct CliError {
166 pub error: String,
168
169 pub code: ErrorCode,
171
172 #[serde(skip_serializing_if = "Option::is_none")]
174 pub cause: Option<String>,
175}
176
177impl CliError {
178 fn from_server_error(err: &ServerError) -> Self {
183 let error = err.to_string();
184 let code = Self::classify_server_error(err);
185 let cause = std::error::Error::source(err).map(ToString::to_string);
186
187 Self { error, code, cause }
188 }
189
190 const fn classify_server_error(err: &ServerError) -> ErrorCode {
192 match err {
193 ServerError::Connection(_) | ServerError::Transport(_) => ErrorCode::ConnectionFailed,
195
196 ServerError::InvalidPeerId { .. }
198 | ServerError::InvalidPeerUrl { .. }
199 | ServerError::InvalidEndpoint(_)
200 | ServerError::InvalidRpcId(_) => ErrorCode::InvalidInput,
201
202 ServerError::InvalidRequest(_)
204 | ServerError::ResponseDeserialization(_)
205 | ServerError::InvalidResponse(_)
206 | ServerError::ServerError(_)
207 | ServerError::InternalClientError(_) => ErrorCode::Internal,
208
209 ServerError::ConditionFailed(_) => ErrorCode::NotFound,
211
212 _ => ErrorCode::Unknown,
214 }
215 }
216}
217
218#[derive(Parser)]
219#[command(version)]
220struct Cli {
221 #[clap(long, short, default_value = "http://127.0.0.1:80")]
223 address: SafeUrl,
224
225 #[command(subcommand)]
227 command: Commands,
228
229 #[clap(long)]
232 rpcpassword: Option<String>,
233
234 #[clap(long)]
236 rpcpassword_file: Option<PathBuf>,
237}
238
239#[derive(Subcommand)]
240enum Commands {
241 #[command(flatten)]
242 General(GeneralCommands),
243 #[command(subcommand)]
244 Lightning(LightningCommands),
245 #[command(subcommand)]
246 Ecash(EcashCommands),
247 #[command(subcommand)]
248 Onchain(OnchainCommands),
249 #[command(subcommand)]
250 Cfg(ConfigCommands),
251 Completion {
252 shell: clap_complete::Shell,
253 },
254}
255
256#[tokio::main]
257async fn main() {
258 if let Err(err) = TracingSetup::default().init() {
259 let cli_err = CliError {
260 error: format!("Failed to initialize logging: {err}"),
261 code: ErrorCode::Internal,
262 cause: None,
263 };
264 print_response(&cli_err);
265 std::process::exit(ExitCode::GeneralError as i32);
266 }
267
268 if let Err(err) = run().await {
269 let cli_err = CliError::from_server_error(&err);
270 let exit_code = ExitCode::from(cli_err.code);
271 print_response(&cli_err);
272 std::process::exit(exit_code as i32);
273 }
274}
275
276async fn run() -> CliOutputResult {
277 let mut cli = Cli::parse();
278 cli.resolve_secret_inputs()?;
279 let connector_registry = ConnectorRegistry::build_from_client_defaults()
280 .with_env_var_overrides()
281 .bind()
282 .await;
283 let client = GatewayApi::new(cli.rpcpassword, connector_registry);
284
285 let output = match cli.command {
286 Commands::General(general_command) => general_command.handle(&client, &cli.address).await?,
287 Commands::Lightning(lightning_command) => {
288 lightning_command.handle(&client, &cli.address).await?
289 }
290 Commands::Ecash(ecash_command) => ecash_command.handle(&client, &cli.address).await?,
291 Commands::Onchain(onchain_command) => onchain_command.handle(&client, &cli.address).await?,
292 Commands::Cfg(config_commands) => config_commands.handle(&client, &cli.address).await?,
293 Commands::Completion { shell } => {
294 clap_complete::generate(
295 shell,
296 &mut Cli::command(),
297 "gateway-cli",
298 &mut std::io::stdout(),
299 );
300 return Ok(CliOutput::Empty);
301 }
302 };
303
304 if !matches!(output, CliOutput::Empty) {
306 print_response(&output);
307 }
308
309 Ok(output)
310}
311
312impl Cli {
313 fn resolve_secret_inputs(&mut self) -> Result<(), ServerError> {
315 #[cfg(feature = "tor")]
316 if let Commands::General(GeneralCommands::ConnectFed {
317 use_tor: Some(_),
318 use_tor_option: Some(_),
319 ..
320 }) = &self.command
321 {
322 return Err(ServerError::InvalidRequest(
323 "Specify Tor selection either positionally or with --use-tor, not both".to_owned(),
324 ));
325 }
326 let command_limit = if matches!(
327 &self.command,
328 Commands::Ecash(EcashCommands::Receive { .. })
329 ) {
330 16 * 1024 * 1024
331 } else {
332 1024 * 1024
333 };
334 let command_source = match &mut self.command {
335 Commands::General(GeneralCommands::CreatePasswordHash {
336 password,
337 password_file,
338 ..
339 }) => Some((password, password_file)),
340 Commands::General(GeneralCommands::ConnectFed {
341 invite_code,
342 invite_code_file,
343 ..
344 }) => Some((invite_code, invite_code_file)),
345 Commands::Cfg(ConfigCommands::SetMnemonic { words, words_file }) => {
346 Some((words, words_file))
347 }
348 Commands::Ecash(EcashCommands::Receive { notes, notes_file }) => {
349 Some((notes, notes_file))
350 }
351 _ => None,
352 };
353 let mut sources = vec![(
354 &mut self.rpcpassword,
355 &mut self.rpcpassword_file,
356 1024 * 1024,
357 )];
358 sources.extend(command_source.map(|(value, file)| (value, file, command_limit)));
359 if sources
360 .iter()
361 .any(|(value, file, _)| value.is_some() && file.is_some())
362 {
363 return Err(ServerError::InvalidRequest(
364 "Specify only one value or file source for each secret".to_owned(),
365 ));
366 }
367 fedimint_core::util::ensure_single_stdin(
368 sources.iter().filter_map(|(_, file, _)| file.as_deref()),
369 )
370 .map_err(|e| ServerError::InvalidRequest(e.to_string()))?;
371 for (value, file, limit) in sources {
372 if let Some(path) = file.take() {
373 *value = Some(
374 fedimint_core::util::read_secret_file(&path, limit)
375 .map_err(|e| ServerError::InvalidRequest(e.to_string()))?,
376 );
377 }
378 }
379 Ok(())
380 }
381}
382
383#[cfg(test)]
384mod secret_input_tests;
385
386fn print_response<T: Serialize>(val: T) {
387 println!(
388 "{}",
389 serde_json::to_string_pretty(&val).expect("Cannot serialize")
390 );
391}