Skip to main content

fedimint_mintv2_client/
cli.rs

1use std::path::PathBuf;
2use std::{ffi, iter};
3
4use clap::{Parser, Subcommand};
5use fedimint_client_module::error::OperationLookupError;
6use fedimint_core::Amount;
7use fedimint_core::base32::{self, FEDIMINT_PREFIX, PrefixedDecodeError};
8use fedimint_core::core::Account;
9use serde::Serialize;
10use serde_json::Value;
11
12use crate::{ECash, MintClientModule, ReceiveECashError, SendECashError, SpendableNote};
13
14#[derive(Parser, Serialize)]
15enum Opts {
16    /// Count the `ECash` notes an account holds by denomination.
17    Count {
18        #[clap(long, default_value_t = Account::Primary)]
19        account: Account,
20    },
21    /// Send `ECash` for the given amount.
22    Send {
23        amount: Amount,
24        #[clap(long, default_value_t = Account::Primary)]
25        account: Account,
26        /// Embed the federation's invite code in the serialized ecash so a
27        /// recipient that hasn't joined the federation can do so from it.
28        #[clap(long)]
29        include_invite: bool,
30    },
31    /// Hand out everything an account holds as one bundle. Receive it into
32    /// another account to move a balance across.
33    SendMax {
34        #[clap(long, default_value_t = Account::Primary)]
35        account: Account,
36        #[clap(long)]
37        include_invite: bool,
38    },
39    /// Receive the `ECash` by reissuing the notes and return the amount.
40    Receive {
41        ecash: Option<String>,
42        /// Read serialized e-cash from a file, or '-' for stdin.
43        #[clap(long)]
44        ecash_file: Option<PathBuf>,
45        #[clap(long, default_value_t = Account::Primary)]
46        account: Account,
47    },
48    /// Developer and debugging commands.
49    Dev {
50        #[clap(subcommand)]
51        command: DevOpts,
52    },
53}
54
55#[derive(Subcommand, Serialize)]
56enum DevOpts {
57    /// Decode an `ECash` string into a JSON representation without receiving
58    /// it.
59    Decode { ecash: String },
60}
61
62fn resolve_ecash(ecash: Option<String>, file: Option<PathBuf>) -> Result<ECash, CliCommandError> {
63    match (ecash, file) {
64        (Some(ecash), None) => Ok(base32::decode_prefixed(FEDIMINT_PREFIX, &ecash)?),
65        (None, Some(file)) => {
66            #[cfg(not(target_family = "wasm"))]
67            {
68                let encoded = fedimint_core::util::read_secret_file(&file, 16 * 1024 * 1024)?;
69                base32::decode_prefixed(FEDIMINT_PREFIX, &encoded)
70                    .map_err(|_| CliCommandError::InvalidSecretEcash)
71            }
72            #[cfg(target_family = "wasm")]
73            {
74                let _ = file;
75                Err(CliCommandError::UnsupportedSecretInput)
76            }
77        }
78        (Some(_), Some(_)) => Err(CliCommandError::ConflictingEcash),
79        (None, None) => Err(CliCommandError::MissingEcash),
80    }
81}
82
83pub(crate) async fn handle_cli_command(
84    mint: &MintClientModule,
85    args: &[ffi::OsString],
86) -> Result<Value, CliCommandError> {
87    let opts = Opts::parse_from(iter::once(&ffi::OsString::from("mintv2")).chain(args.iter()));
88
89    match opts {
90        Opts::Count { account } => Ok(json(mint.get_count_by_denomination(account).await)),
91        Opts::Send {
92            amount,
93            account,
94            include_invite,
95        } => {
96            let (_, ecash) = mint
97                .send(account, amount, Value::Null, include_invite)
98                .await?;
99            let ecash = base32::encode_prefixed(FEDIMINT_PREFIX, &ecash);
100
101            Ok(json(ecash))
102        }
103        Opts::SendMax {
104            account,
105            include_invite,
106        } => {
107            let ecash = mint
108                .send_max(account, Value::Null, include_invite)
109                .await
110                .map(|(_, ecash)| base32::encode_prefixed(FEDIMINT_PREFIX, &ecash));
111
112            Ok(json(ecash))
113        }
114        Opts::Receive {
115            ecash,
116            ecash_file,
117            account,
118        } => {
119            let ecash = resolve_ecash(ecash, ecash_file)?;
120
121            let operation_id = mint.receive(account, ecash, Value::Null).await?;
122
123            let state = mint
124                .await_final_receive_operation_state(operation_id)
125                .await?;
126
127            Ok(json(state))
128        }
129        Opts::Dev {
130            command: DevOpts::Decode { ecash },
131        } => {
132            let ecash: ECash = base32::decode_prefixed(FEDIMINT_PREFIX, &ecash)?;
133            let notes = ecash.notes();
134
135            Ok(serde_json::json!({
136                "federation_id": ecash.mint(),
137                "unit": ecash.unit(),
138                "amount": ecash.amount(),
139                "note_count": notes.len(),
140                "notes": notes.iter().map(SpendableNote::note).collect::<Vec<_>>(),
141                "invite": ecash.federation_invite(),
142            }))
143        }
144    }
145}
146
147fn json<T: Serialize>(value: T) -> Value {
148    serde_json::to_value(value).expect("JSON serialization failed")
149}
150
151/// A failure of a `mintv2` module command.
152#[derive(Debug, thiserror::Error)]
153pub(crate) enum CliCommandError {
154    #[error("Provide either positional e-cash or --ecash-file, not both")]
155    ConflictingEcash,
156    #[error("Provide positional e-cash or --ecash-file")]
157    MissingEcash,
158    #[cfg(not(target_family = "wasm"))]
159    #[error("Invalid e-cash in secret input")]
160    InvalidSecretEcash,
161    #[cfg(not(target_family = "wasm"))]
162    #[error(transparent)]
163    SecretInput(#[from] fedimint_core::util::SecretInputError),
164    #[cfg(target_family = "wasm")]
165    #[error("Secret file input is not supported on this platform")]
166    UnsupportedSecretInput,
167    /// The e-cash could not be sent.
168    #[error(transparent)]
169    Send(#[from] SendECashError),
170
171    /// The e-cash string is not valid.
172    #[error(transparent)]
173    Decode(#[from] PrefixedDecodeError),
174
175    /// The e-cash could not be received.
176    #[error(transparent)]
177    Receive(#[from] ReceiveECashError),
178
179    /// The receive operation could not be looked up.
180    #[error(transparent)]
181    OperationLookup(#[from] OperationLookupError),
182}
183
184#[cfg(test)]
185mod tests;