Skip to main content

fedimint_cli/
client.rs

1#[cfg(test)]
2mod tests;
3
4use std::collections::BTreeMap;
5use std::ffi;
6use std::path::{Path, PathBuf};
7use std::str::FromStr;
8use std::time::{Duration, SystemTime, UNIX_EPOCH};
9
10use anyhow::{Context, bail};
11use bitcoin::address::NetworkUnchecked;
12use bitcoin::{Network, secp256k1};
13use clap::Subcommand;
14use fedimint_bip39::Mnemonic;
15use fedimint_client::backup::Metadata;
16use fedimint_client::{Client, ClientHandleArc};
17use fedimint_core::config::{ClientModuleConfig, FederationId};
18use fedimint_core::core::{Account, ModuleInstanceId, ModuleKind, OperationId};
19use fedimint_core::encoding::Encodable;
20use fedimint_core::{Amount, BitcoinAmountOrAll, TieredCounts, TieredMulti};
21use fedimint_ln_client::cli::LnInvoiceResponse;
22use fedimint_ln_client::{LightningClientModule, LnReceiveState, OutgoingLightningPayment};
23use fedimint_logging::LOG_CLIENT;
24use fedimint_mint_client::{
25    MintClientModule, OOBNotes, SelectNotesWithAtleastAmount, SelectNotesWithExactAmount,
26};
27use fedimint_wallet_client::{WalletClientModule, WithdrawState};
28use futures::StreamExt;
29use itertools::Itertools;
30use lightning_invoice::{Bolt11InvoiceDescription, Description};
31use serde::{Deserialize, Serialize};
32use serde_json::json;
33use time::OffsetDateTime;
34use time::format_description::well_known::iso8601;
35use tracing::{debug, info, warn};
36
37use crate::metadata_from_clap_cli;
38
39#[derive(Debug, Clone)]
40pub enum ModuleSelector {
41    Id(ModuleInstanceId),
42    Kind(ModuleKind),
43}
44
45impl ModuleSelector {
46    pub fn resolve(&self, client: &Client) -> anyhow::Result<ModuleInstanceId> {
47        Ok(match self {
48            ModuleSelector::Id(id) => {
49                client.get_module_client_dyn(*id)?;
50                *id
51            }
52            ModuleSelector::Kind(kind) => client
53                .get_first_instance(kind)
54                .context("No module with this kind found")?,
55        })
56    }
57}
58#[derive(Debug, Clone, Serialize)]
59pub enum ModuleStatus {
60    Active,
61    UnsupportedByClient,
62}
63
64#[derive(Serialize)]
65struct ModuleInfo {
66    kind: ModuleKind,
67    id: u16,
68    status: ModuleStatus,
69}
70
71impl FromStr for ModuleSelector {
72    type Err = anyhow::Error;
73
74    fn from_str(s: &str) -> Result<Self, Self::Err> {
75        Ok(if s.chars().all(|ch| ch.is_ascii_digit()) {
76            Self::Id(s.parse()?)
77        } else {
78            Self::Kind(ModuleKind::clone_from_str(s))
79        })
80    }
81}
82
83#[derive(Debug, Clone, Subcommand)]
84pub enum ClientCmd {
85    /// Display wallet info (holdings, tiers)
86    Info {
87        /// The account whose holdings to display
88        #[arg(long, default_value_t = Account::Primary)]
89        account: Account,
90    },
91    /// Reissue notes received from a third party to avoid double spends
92    #[clap(hide = true)]
93    Reissue {
94        oob_notes: Option<OOBNotes>,
95        /// Read serialized notes from a file, or '-' for stdin.
96        #[arg(long)]
97        notes_file: Option<PathBuf>,
98        #[arg(long = "no-wait", action = clap::ArgAction::SetFalse)]
99        wait: bool,
100    },
101    /// Prepare notes to send to a third party as a payment
102    #[clap(hide = true)]
103    Spend {
104        /// The amount of e-cash to spend
105        amount: Amount,
106        /// If the exact amount cannot be represented, return e-cash of a higher
107        /// value instead of failing
108        #[clap(long)]
109        allow_overpay: bool,
110        /// After how many seconds we will try to reclaim the e-cash if it
111        /// hasn't been redeemed by the recipient. Defaults to one week.
112        #[clap(long, default_value_t = 60 * 60 * 24 * 7)]
113        timeout: u64,
114        /// If the necessary information to join the federation the e-cash
115        /// belongs to should be included in the serialized notes
116        #[clap(long)]
117        include_invite: bool,
118    },
119    /// Splits a string containing multiple e-cash notes (e.g. from the `spend`
120    /// command) into ones that contain exactly one.
121    #[clap(hide = true)]
122    Split {
123        oob_notes: Option<OOBNotes>,
124        /// Read serialized notes from a file, or '-' for stdin.
125        #[arg(long)]
126        notes_file: Option<PathBuf>,
127    },
128    /// Combines two or more serialized e-cash notes strings
129    #[clap(hide = true)]
130    Combine {
131        oob_notes: Vec<OOBNotes>,
132        /// Read one serialized notes string per file. May be repeated; '-'
133        /// reads stdin once. Cannot be combined with positional notes.
134        #[arg(long)]
135        notes_file: Vec<PathBuf>,
136    },
137    /// Create a lightning invoice to receive payment via gateway
138    #[clap(hide = true)]
139    LnInvoice {
140        #[clap(long)]
141        amount: Amount,
142        #[clap(long, default_value = "")]
143        description: String,
144        #[clap(long)]
145        expiry_time: Option<u64>,
146        #[clap(long)]
147        gateway_id: Option<secp256k1::PublicKey>,
148        #[clap(long, default_value = "false")]
149        force_internal: bool,
150    },
151    /// Wait for incoming invoice to be paid
152    #[clap(hide = true)]
153    AwaitInvoice { operation_id: OperationId },
154    /// Pay a lightning invoice or lnurl via a gateway
155    #[clap(hide = true)]
156    LnPay {
157        /// Lightning invoice or lnurl
158        payment_info: String,
159        /// Amount to pay, used for lnurl
160        #[clap(long)]
161        amount: Option<Amount>,
162        /// Invoice comment/description, used on lnurl
163        #[clap(long)]
164        lnurl_comment: Option<String>,
165        #[clap(long)]
166        gateway_id: Option<secp256k1::PublicKey>,
167        #[clap(long, default_value = "false")]
168        force_internal: bool,
169    },
170    /// Wait for a lightning payment to complete
171    #[clap(hide = true)]
172    AwaitLnPay { operation_id: OperationId },
173    /// List registered gateways
174    #[clap(hide = true)]
175    ListGateways {
176        /// Don't fetch the registered gateways from the federation
177        #[clap(long, default_value = "false")]
178        no_update: bool,
179    },
180    /// Generate a new deposit address, funds sent to it can later be claimed
181    #[clap(hide = true)]
182    DepositAddress,
183    /// Wait for deposit on previously generated address
184    #[clap(hide = true)]
185    AwaitDeposit { operation_id: OperationId },
186    /// Withdraw funds from the federation
187    #[clap(hide = true)]
188    Withdraw {
189        #[clap(long)]
190        amount: BitcoinAmountOrAll,
191        #[clap(long)]
192        address: bitcoin::Address<NetworkUnchecked>,
193    },
194    /// Upload the (encrypted) snapshot of mint notes to federation
195    Backup {
196        #[clap(long = "metadata")]
197        /// Backup metadata, encoded as `key=value` (use `--metadata=key=value`,
198        /// possibly multiple times)
199        // TODO: Can we make it `*Map<String, String>` and avoid custom parsing?
200        metadata: Vec<String>,
201    },
202    /// Discover the common api version to use to communicate with the
203    /// federation
204    #[clap(hide = true)]
205    DiscoverVersion,
206    /// Join federation and restore modules that support it
207    Restore {
208        /// BIP-39 mnemonic used by standard Fedimint CLI clients.
209        ///
210        /// If omitted, use global `--federation-secret-hex` instead.
211        #[clap(long)]
212        mnemonic: Option<String>,
213        /// Read the mnemonic from a protected UTF-8 file (`-` for stdin).
214        #[clap(long)]
215        mnemonic_file: Option<std::path::PathBuf>,
216        #[clap(long)]
217        invite_code: Option<String>,
218        /// Read an invite code from a file (`-` for stdin).
219        #[clap(long)]
220        invite_code_file: Option<std::path::PathBuf>,
221    },
222    /// Print the secret key of the client
223    PrintSecret,
224    ListOperations {
225        #[clap(long, default_value = "10")]
226        limit: usize,
227    },
228    /// Call a module subcommand
229    // Make `--help` be passed to the module handler, not root cli one
230    #[command(disable_help_flag = true)]
231    Module {
232        /// Module selector (either module id or module kind)
233        module: Option<ModuleSelector>,
234        #[arg(allow_hyphen_values = true, trailing_var_arg = true)]
235        args: Vec<ffi::OsString>,
236    },
237    /// Returns the client config
238    #[clap(hide = true)]
239    Config,
240    /// Gets the current fedimint AlephBFT session count
241    #[clap(hide = true)]
242    SessionCount,
243    /// Shows how available each guardian has been, as combined from all
244    /// guardians' views of each other
245    PeerAvailability,
246}
247
248/// Reissue legacy mint notes, optionally waiting for the operation stream.
249async fn reissue_notes(
250    client: &Client,
251    oob_notes: OOBNotes,
252    wait: bool,
253) -> anyhow::Result<serde_json::Value> {
254    warn!(
255        target: LOG_CLIENT,
256        "Command deprecated. Use `fedimint-cli module mint reissue` instead."
257    );
258    let amount = oob_notes.total_amount();
259
260    let mint = client.get_first_module::<MintClientModule>()?;
261
262    let operation_id = mint.reissue_external_notes(oob_notes, ()).await?;
263    if wait {
264        let mut updates = mint
265            .subscribe_reissue_external_notes(operation_id)
266            .await
267            .expect("just created operation can't already be deleted")
268            .into_stream();
269
270        while let Some(update) = updates.next().await {
271            if let fedimint_mint_client::ReissueExternalNotesState::Failed(e) = update {
272                bail!("Reissue failed: {e}");
273            }
274
275            debug!(target: LOG_CLIENT, ?update, "Reissue external notes state update");
276        }
277    }
278
279    Ok(serde_json::to_value(amount).expect("Amount is serializable"))
280}
281
282/// Select and spend legacy notes, preserving overpay and cancellation policy.
283async fn spend_notes(
284    client: &Client,
285    amount: Amount,
286    allow_overpay: bool,
287    timeout: u64,
288    include_invite: bool,
289) -> anyhow::Result<serde_json::Value> {
290    warn!(
291        target: LOG_CLIENT,
292        "Command deprecated. Use `fedimint-cli module mint spend` instead."
293    );
294    warn!(
295        target: LOG_CLIENT,
296        "The client will try to double-spend these notes after the duration specified by the --timeout option to recover any unclaimed e-cash."
297    );
298
299    let mint_module = client.get_first_module::<MintClientModule>()?;
300    let timeout = Duration::from_secs(timeout);
301    let (operation, notes) = if allow_overpay {
302        let (operation, notes) = mint_module
303            .spend_notes_with_selector(
304                &SelectNotesWithAtleastAmount,
305                amount,
306                Some(timeout),
307                include_invite,
308                (),
309            )
310            .await?;
311
312        let overspend_amount = notes.total_amount().saturating_sub(amount);
313        if overspend_amount != Amount::ZERO {
314            warn!(
315                target: LOG_CLIENT,
316                "Selected notes {} worth more than requested",
317                overspend_amount
318            );
319        }
320
321        (operation, notes)
322    } else {
323        mint_module
324            .spend_notes_with_selector(
325                &SelectNotesWithExactAmount,
326                amount,
327                Some(timeout),
328                include_invite,
329                (),
330            )
331            .await?
332    };
333    info!(target: LOG_CLIENT, "Spend e-cash operation: {}", operation.fmt_short());
334
335    Ok(json!({
336        "notes": notes,
337    }))
338}
339
340/// Split legacy notes into individual notes grouped by denomination.
341fn split_notes(oob_notes: &OOBNotes) -> serde_json::Value {
342    warn!(
343        target: LOG_CLIENT,
344        "Command deprecated. Use `fedimint-cli module mint split` instead."
345    );
346    let federation = oob_notes.federation_id_prefix();
347    let notes = oob_notes
348        .notes()
349        .iter()
350        .map(|(amount, notes)| {
351            let notes = notes
352                .iter()
353                .map(|note| {
354                    OOBNotes::new(
355                        federation,
356                        TieredMulti::new(vec![(amount, vec![*note])].into_iter().collect()),
357                    )
358                })
359                .collect::<Vec<_>>();
360            (amount, notes)
361        })
362        .collect::<BTreeMap<_, _>>();
363
364    json!({
365        "notes": notes,
366    })
367}
368
369/// Combine legacy notes only when all inputs belong to the same federation.
370fn combine_notes(oob_notes: &[OOBNotes]) -> anyhow::Result<serde_json::Value> {
371    warn!(
372        target: LOG_CLIENT,
373        "Command deprecated. Use `fedimint-cli module mint combine` instead."
374    );
375    let federation_id_prefix = match oob_notes
376        .iter()
377        .map(OOBNotes::federation_id_prefix)
378        .all_equal_value()
379    {
380        Ok(id) => id,
381        Err(None) => panic!("At least one e-cash notes string expected"),
382        Err(Some((a, b))) => {
383            bail!("Trying to combine e-cash from different federations: {a} and {b}");
384        }
385    };
386
387    let combined_notes = oob_notes
388        .iter()
389        .flat_map(|notes| notes.notes().iter_items().map(|(amt, note)| (amt, *note)))
390        .collect();
391
392    let combined_oob_notes = OOBNotes::new(federation_id_prefix, combined_notes);
393
394    Ok(json!({
395        "notes": combined_oob_notes,
396    }))
397}
398
399/// Create a legacy Lightning invoice through the selected gateway.
400async fn create_invoice(
401    client: &Client,
402    amount: Amount,
403    description: String,
404    expiry_time: Option<u64>,
405    gateway_id: Option<secp256k1::PublicKey>,
406    force_internal: bool,
407) -> anyhow::Result<serde_json::Value> {
408    warn!(
409        target: LOG_CLIENT,
410        "Command deprecated. Use `fedimint-cli module ln invoice` instead."
411    );
412    let lightning_module = client.get_first_module::<LightningClientModule>()?;
413    let ln_gateway = lightning_module
414        .get_gateway(gateway_id, force_internal)
415        .await?;
416
417    let lightning_module = client.get_first_module::<LightningClientModule>()?;
418    let desc = Description::new(description)?;
419    let (operation_id, invoice, _) = lightning_module
420        .create_bolt11_invoice(
421            amount,
422            Bolt11InvoiceDescription::Direct(desc),
423            expiry_time,
424            (),
425            ln_gateway,
426        )
427        .await?;
428    Ok(serde_json::to_value(LnInvoiceResponse {
429        operation_id,
430        invoice: invoice.to_string(),
431    })
432    .expect("LnInvoiceResponse is serializable"))
433}
434
435/// Wait for invoice receipt, preserving terminal stream outcomes.
436async fn await_invoice(
437    client: &ClientHandleArc,
438    operation_id: OperationId,
439) -> anyhow::Result<serde_json::Value> {
440    warn!(
441        target: LOG_CLIENT,
442        "Command deprecated. Use `fedimint-cli module ln await-invoice` instead."
443    );
444    let lightning_module = &client.get_first_module::<LightningClientModule>()?;
445    let mut updates = lightning_module
446        .subscribe_ln_receive(operation_id)
447        .await?
448        .into_stream();
449    while let Some(update) = updates.next().await {
450        match update {
451            LnReceiveState::Claimed => {
452                return get_note_summary(client, Account::Primary).await;
453            }
454            LnReceiveState::Canceled { reason } => {
455                return Err(reason.into());
456            }
457            _ => {}
458        }
459
460        debug!(target: LOG_CLIENT, ?update, "Await invoice state update");
461    }
462
463    Err(anyhow::anyhow!(
464        "Unexpected end of update stream. Lightning receive failed"
465    ))
466}
467
468/// Pay a legacy Lightning invoice or LNURL and wait for its final outcome.
469async fn pay_invoice(
470    client: &Client,
471    payment_info: String,
472    amount: Option<Amount>,
473    lnurl_comment: Option<String>,
474    gateway_id: Option<secp256k1::PublicKey>,
475    force_internal: bool,
476) -> anyhow::Result<serde_json::Value> {
477    warn!(
478        target: LOG_CLIENT,
479        "Command deprecated. Use `fedimint-cli module ln pay` instead."
480    );
481    let bolt11 = fedimint_ln_client::get_invoice(&payment_info, amount, lnurl_comment).await?;
482    info!(target: LOG_CLIENT, "Paying invoice: {bolt11}");
483    let lightning_module = client.get_first_module::<LightningClientModule>()?;
484    let ln_gateway = lightning_module
485        .get_gateway(gateway_id, force_internal)
486        .await?;
487
488    let lightning_module = client.get_first_module::<LightningClientModule>()?;
489    let OutgoingLightningPayment {
490        payment_type,
491        contract_id: _,
492        fee,
493    } = lightning_module
494        .pay_bolt11_invoice(ln_gateway, bolt11, ())
495        .await?;
496    let operation_id = payment_type.operation_id();
497    info!(
498        target: LOG_CLIENT,
499        "Gateway fee: {fee}, payment operation id: {}",
500        operation_id.fmt_short()
501    );
502    let lnv1 = client.get_first_module::<LightningClientModule>()?;
503    let outcome = lnv1.await_outgoing_payment(operation_id).await?;
504    Ok(serde_json::to_value(outcome).expect("Cant fail"))
505}
506
507/// Dispatch client commands using the already-open client.
508impl ClientCmd {
509    /// Secret note files to include in preflight stdin checks.
510    pub fn notes_file_paths(&self) -> Vec<&Path> {
511        match self {
512            Self::Reissue { notes_file, .. } | Self::Split { notes_file, .. } => {
513                notes_file.iter().map(PathBuf::as_path).collect()
514            }
515            Self::Combine { notes_file, .. } => notes_file.iter().map(PathBuf::as_path).collect(),
516            _ => vec![],
517        }
518    }
519
520    /// Check sources before any global credential consumes stdin.
521    pub fn validate_notes_sources(&self) -> anyhow::Result<()> {
522        match self {
523            Self::Reissue {
524                oob_notes,
525                notes_file,
526                ..
527            }
528            | Self::Split {
529                oob_notes,
530                notes_file,
531            } => {
532                validate_notes_sources(oob_notes.is_some(), notes_file.is_some())?;
533            }
534            Self::Combine {
535                oob_notes,
536                notes_file,
537            } => {
538                validate_notes_sources(!oob_notes.is_empty(), !notes_file.is_empty())?;
539            }
540            _ => {}
541        }
542        fedimint_core::util::ensure_single_stdin(self.notes_file_paths())?;
543        Ok(())
544    }
545}
546
547fn validate_notes_sources(has_notes: bool, has_file: bool) -> anyhow::Result<()> {
548    match (has_notes, has_file) {
549        (true, true) => bail!("Provide either positional notes or --notes-file, not both"),
550        (false, false) => bail!("Provide positional notes or --notes-file"),
551        _ => Ok(()),
552    }
553}
554
555fn read_notes_file(path: &Path) -> anyhow::Result<OOBNotes> {
556    fedimint_core::util::read_secret_file(path, 16 * 1024 * 1024)?
557        .parse()
558        .map_err(|_| anyhow::anyhow!("Invalid e-cash notes in secret input"))
559}
560
561fn resolve_notes(notes: Option<OOBNotes>, file: Option<PathBuf>) -> anyhow::Result<OOBNotes> {
562    validate_notes_sources(notes.is_some(), file.is_some())?;
563    match (notes, file) {
564        (Some(notes), None) => Ok(notes),
565        (None, Some(file)) => read_notes_file(&file),
566        _ => unreachable!("Sources validated"),
567    }
568}
569
570fn resolve_notes_list(notes: Vec<OOBNotes>, files: &[PathBuf]) -> anyhow::Result<Vec<OOBNotes>> {
571    validate_notes_sources(!notes.is_empty(), !files.is_empty())?;
572    fedimint_core::util::ensure_single_stdin(files.iter().map(PathBuf::as_path))?;
573    if notes.is_empty() {
574        files.iter().map(|file| read_notes_file(file)).collect()
575    } else {
576        Ok(notes)
577    }
578}
579
580pub async fn handle_command(
581    command: ClientCmd,
582    client: ClientHandleArc,
583) -> anyhow::Result<serde_json::Value> {
584    command.validate_notes_sources()?;
585    match command {
586        ClientCmd::Info { account } => get_note_summary(&client, account).await,
587        ClientCmd::Reissue {
588            oob_notes,
589            notes_file,
590            wait,
591        } => reissue_notes(&client, resolve_notes(oob_notes, notes_file)?, wait).await,
592        ClientCmd::Spend {
593            amount,
594            allow_overpay,
595            timeout,
596            include_invite,
597        } => spend_notes(&client, amount, allow_overpay, timeout, include_invite).await,
598        ClientCmd::Split {
599            oob_notes,
600            notes_file,
601        } => Ok(split_notes(&resolve_notes(oob_notes, notes_file)?)),
602        ClientCmd::Combine {
603            oob_notes,
604            notes_file,
605        } => combine_notes(&resolve_notes_list(oob_notes, &notes_file)?),
606        ClientCmd::LnInvoice {
607            amount,
608            description,
609            expiry_time,
610            gateway_id,
611            force_internal,
612        } => {
613            create_invoice(
614                &client,
615                amount,
616                description,
617                expiry_time,
618                gateway_id,
619                force_internal,
620            )
621            .await
622        }
623        ClientCmd::AwaitInvoice { operation_id } => await_invoice(&client, operation_id).await,
624        ClientCmd::LnPay {
625            payment_info,
626            amount,
627            lnurl_comment,
628            gateway_id,
629            force_internal,
630        } => {
631            pay_invoice(
632                &client,
633                payment_info,
634                amount,
635                lnurl_comment,
636                gateway_id,
637                force_internal,
638            )
639            .await
640        }
641        ClientCmd::AwaitLnPay { operation_id } => {
642            warn!(
643                target: LOG_CLIENT,
644                "Command deprecated. Use `fedimint-cli module ln await-pay` instead."
645            );
646            let lightning_module = client.get_first_module::<LightningClientModule>()?;
647            let outcome = lightning_module
648                .await_outgoing_payment(operation_id)
649                .await?;
650            Ok(serde_json::to_value(outcome).expect("Cant fail"))
651        }
652        ClientCmd::ListGateways { no_update } => {
653            warn!(
654                target: LOG_CLIENT,
655                "Command deprecated. Use `fedimint-cli module ln list-gateways` instead."
656            );
657            let lightning_module = client.get_first_module::<LightningClientModule>()?;
658            if !no_update {
659                lightning_module.update_gateway_cache().await?;
660            }
661            let gateways = lightning_module.list_gateways().await;
662            if gateways.is_empty() {
663                return Ok(
664                    serde_json::to_value(Vec::<String>::new()).expect("empty vec is serializable")
665                );
666            }
667
668            Ok(json!(&gateways))
669        }
670        ClientCmd::DepositAddress => {
671            warn!(
672                target: LOG_CLIENT,
673                "Command deprecated. Use `fedimint-cli module wallet new-deposit-address` instead."
674            );
675            let deposit_address = client
676                .get_first_module::<WalletClientModule>()?
677                .allocate_deposit_address_expert_only(())
678                .await?;
679            Ok(serde_json::json! {
680                {
681                    "address": deposit_address.address,
682                    "operation_id": deposit_address.operation_id,
683                    "idx": deposit_address.tweak_idx.0
684                }
685            })
686        }
687        ClientCmd::AwaitDeposit { operation_id } => {
688            warn!(
689                target: LOG_CLIENT,
690                "Command deprecated. Use `fedimint-cli module wallet await-deposit` instead."
691            );
692            client
693                .get_first_module::<WalletClientModule>()?
694                .await_num_deposits_by_operation_id(operation_id, 1)
695                .await?;
696
697            Ok(serde_json::to_value(()).expect("unit type is serializable"))
698        }
699
700        ClientCmd::Backup { metadata } => {
701            let metadata = metadata_from_clap_cli(metadata)?;
702
703            #[allow(deprecated)]
704            client
705                .backup_to_federation(Metadata::from_json_serialized(metadata))
706                .await?;
707            Ok(serde_json::to_value(()).expect("unit type is serializable"))
708        }
709        ClientCmd::Restore { .. } => {
710            panic!("Has to be handled before initializing client")
711        }
712        ClientCmd::PrintSecret => {
713            let entropy = client.get_decoded_client_secret::<Vec<u8>>().await?;
714            let mnemonic = Mnemonic::from_entropy(&entropy)?;
715
716            Ok(json!({
717                "secret": mnemonic,
718            }))
719        }
720        ClientCmd::ListOperations { limit } => {
721            #[derive(Serialize)]
722            #[serde(rename_all = "snake_case")]
723            struct OperationOutput {
724                id: OperationId,
725                creation_time: String,
726                operation_kind: String,
727                operation_meta: serde_json::Value,
728                #[serde(skip_serializing_if = "Option::is_none")]
729                outcome: Option<serde_json::Value>,
730            }
731
732            let operations = client
733                .operation_log()
734                .paginate_operations_rev(limit, None)
735                .await
736                .into_iter()
737                .map(|(k, v)| {
738                    let creation_time = time_to_iso8601(&k.creation_time);
739
740                    OperationOutput {
741                        id: k.operation_id,
742                        creation_time,
743                        operation_kind: v.operation_module_kind().to_owned(),
744                        operation_meta: v.meta(),
745                        outcome: v.outcome(),
746                    }
747                })
748                .collect::<Vec<_>>();
749
750            Ok(json!({
751                "operations": operations,
752            }))
753        }
754        ClientCmd::Withdraw { amount, address } => withdraw(&client, amount, address).await,
755        ClientCmd::DiscoverVersion => {
756            Ok(json!({ "versions": client.load_and_refresh_common_api_version().await? }))
757        }
758        ClientCmd::Module { module, args } => {
759            if let Some(module) = module {
760                let module_instance_id = module.resolve(&client)?;
761
762                Ok(client
763                    .get_module_client_dyn(module_instance_id)
764                    .context("Module not found")?
765                    .handle_cli_command(&args)
766                    .await?)
767            } else {
768                let module_list: Vec<ModuleInfo> = client
769                    .config()
770                    .await
771                    .modules
772                    .iter()
773                    .map(|(id, ClientModuleConfig { kind, .. })| ModuleInfo {
774                        kind: kind.clone(),
775                        id: *id,
776                        status: if client.has_module(*id) {
777                            ModuleStatus::Active
778                        } else {
779                            ModuleStatus::UnsupportedByClient
780                        },
781                    })
782                    .collect();
783                Ok(json!({
784                    "list": module_list,
785                }))
786            }
787        }
788        ClientCmd::Config => {
789            warn!(
790                target: LOG_CLIENT,
791                "Command deprecated. Use `fedimint-cli dev config` instead."
792            );
793            let config = client.get_config_json().await;
794            Ok(serde_json::to_value(config).expect("Client config is serializable"))
795        }
796        ClientCmd::SessionCount => {
797            warn!(
798                target: LOG_CLIENT,
799                "Command deprecated. Use `fedimint-cli dev session-count` instead."
800            );
801            let count = client.api().session_count().await?;
802            Ok(json!({ "count": count }))
803        }
804        ClientCmd::PeerAvailability => Ok(serde_json::to_value(client.peer_availability().await)
805            .expect("Peer availability is serializable")),
806    }
807}
808
809/// Quote and execute a legacy withdrawal, keeping its amount and fees paired.
810async fn withdraw(
811    client: &Client,
812    amount: BitcoinAmountOrAll,
813    address: bitcoin::Address<NetworkUnchecked>,
814) -> anyhow::Result<serde_json::Value> {
815    warn!(
816        target: LOG_CLIENT,
817        "Command deprecated. Use `fedimint-cli module wallet withdraw` instead."
818    );
819    let wallet_module = client.get_first_module::<WalletClientModule>()?;
820    let address = address.require_network(wallet_module.get_network())?;
821    let (amount, fees) = match amount {
822        // The on-chain fee is only part of the cost of withdrawing
823        // everything: funding the peg-out output also incurs the
824        // federation's per-note fees. The returned fees are quoted at
825        // the returned amount, so they must be used together.
826        BitcoinAmountOrAll::All => {
827            let balance = client.get_balance_for_btc(Account::Primary).await?;
828            wallet_module
829                .max_withdrawable_amount(&address, balance)
830                .await?
831        }
832        BitcoinAmountOrAll::Amount(amount) => (
833            amount,
834            wallet_module.get_withdraw_fees(&address, amount).await?,
835        ),
836    };
837    let absolute_fees = fees.amount();
838    info!(
839        target: LOG_CLIENT,
840        "Attempting withdraw with fees: {fees:?}"
841    );
842    let operation_id = wallet_module.withdraw(&address, amount, fees, ()).await?;
843    let mut updates = wallet_module
844        .subscribe_withdraw_updates(operation_id)
845        .await?
846        .into_stream();
847    while let Some(update) = updates.next().await {
848        debug!(target: LOG_CLIENT, ?update, "Withdraw state update");
849        match update {
850            WithdrawState::Succeeded(txid) => {
851                return Ok(json!({
852                    "txid": txid.consensus_encode_to_hex(),
853                    "fees_sat": absolute_fees.to_sat(),
854                }));
855            }
856            WithdrawState::Failed(e) => bail!("Withdraw failed: {e}"),
857            WithdrawState::Created => {}
858        }
859    }
860    unreachable!("Update stream ended without outcome");
861}
862
863async fn get_note_summary(
864    client: &ClientHandleArc,
865    account: Account,
866) -> anyhow::Result<serde_json::Value> {
867    // Try wallet v1 first, then walletv2
868    let network = if let Ok(wallet_client) = client.get_first_module::<WalletClientModule>() {
869        wallet_client.get_network()
870    } else if let Ok(wallet_client) =
871        client.get_first_module::<fedimint_walletv2_client::WalletClientModule>()
872    {
873        wallet_client.get_network()
874    } else {
875        anyhow::bail!("No wallet module found");
876    };
877
878    let summary = if let Ok(mint_client) = client.get_first_module::<MintClientModule>() {
879        // The legacy mint holds a single balance, so only primary exists.
880        anyhow::ensure!(
881            account == Account::Primary,
882            "The mint module only supports the primary account"
883        );
884
885        let mint_module_id = client
886            .get_first_instance(&fedimint_mint_client::KIND)
887            .context("Mint module not found")?;
888        mint_client
889            .get_note_counts_by_denomination(
890                &mut client
891                    .db()
892                    .begin_transaction_nc()
893                    .await
894                    .to_ref_with_prefix_module_id(mint_module_id)
895                    .0,
896            )
897            .await
898    } else if let Ok(mintv2_client) =
899        client.get_first_module::<fedimint_mintv2_client::MintClientModule>()
900    {
901        let counts = mintv2_client.get_count_by_denomination(account).await;
902        let mut summary = TieredCounts::default();
903        #[allow(clippy::cast_possible_truncation)]
904        for (denomination, count) in counts {
905            summary.inc(denomination.amount(), count as usize);
906        }
907        summary
908    } else {
909        anyhow::bail!("No mint module found");
910    };
911
912    Ok(serde_json::to_value(InfoResponse {
913        federation_id: client.federation_id(),
914        network,
915        meta: client.config().await.global.meta.clone(),
916        total_amount_msat: summary.total_amount(),
917        total_num_notes: summary.count_items(),
918        denominations_msat: summary,
919    })
920    .expect("InfoResponse is serializable"))
921}
922
923#[derive(Debug, Clone, Serialize, Deserialize)]
924#[serde(rename_all = "snake_case")]
925pub struct InfoResponse {
926    federation_id: FederationId,
927    network: Network,
928    meta: BTreeMap<String, String>,
929    total_amount_msat: Amount,
930    total_num_notes: usize,
931    denominations_msat: TieredCounts,
932}
933
934pub(crate) fn time_to_iso8601(time: &SystemTime) -> String {
935    const ISO8601_CONFIG: iso8601::EncodedConfig = iso8601::Config::DEFAULT
936        .set_formatted_components(iso8601::FormattedComponents::DateTime)
937        .encode();
938
939    OffsetDateTime::from_unix_timestamp_nanos(
940        time.duration_since(UNIX_EPOCH)
941            .expect("Couldn't convert time from SystemTime to timestamp")
942            .as_nanos()
943            .try_into()
944            .expect("Time overflowed"),
945    )
946    .expect("Couldn't convert time from SystemTime to OffsetDateTime")
947    .format(&iso8601::Iso8601::<ISO8601_CONFIG>)
948    .expect("Couldn't format OffsetDateTime as ISO8601")
949}