Skip to main content

fedimint_mint_client/
cli.rs

1use std::collections::BTreeMap;
2use std::path::{Path, PathBuf};
3use std::str::FromStr;
4use std::time::Duration;
5use std::{ffi, iter};
6
7use clap::{Parser, Subcommand};
8use fedimint_api_client::api::FederationError;
9use fedimint_core::config::FederationIdPrefix;
10use fedimint_core::encoding::{Decodable, DecodeError, Encodable};
11use fedimint_core::module::registry::ModuleDecoderRegistry;
12use fedimint_core::util::FmtCompact as _;
13use fedimint_core::{Amount, PeerId, TieredMulti};
14use futures::StreamExt;
15use futures::future::join_all;
16use serde::Serialize;
17use serde_json::json;
18use tracing::{info, warn};
19
20use crate::api::MintFederationApi;
21use crate::{
22    BlindNonce, MintClientModule, Nonce, OOBNotes, OOBNotesParseError, ReissueExternalNotesError,
23    ReissueExternalNotesState, SelectNotesWithAtleastAmount, SelectNotesWithExactAmount,
24    SpendOOBError, ValidateNotesError,
25};
26
27#[derive(Parser, Serialize)]
28enum Opts {
29    /// Reissue out of band notes
30    Reissue {
31        notes: Option<OOBNotes>,
32        /// Read serialized notes from a file, or '-' for stdin.
33        #[clap(long)]
34        notes_file: Option<PathBuf>,
35    },
36    /// Prepare notes to send to a third party as a payment
37    Spend {
38        /// The amount of e-cash to spend
39        amount: Amount,
40        /// If the exact amount cannot be represented, return e-cash of a higher
41        /// value instead of failing
42        #[clap(long)]
43        allow_overpay: bool,
44        /// After how many seconds we will try to reclaim the e-cash if it
45        /// hasn't been redeemed by the recipient. Defaults to one week.
46        #[clap(long, default_value_t = 60 * 60 * 24 * 7)]
47        timeout: u64,
48        /// If the necessary information to join the federation the e-cash
49        /// belongs to should be included in the serialized notes
50        #[clap(long)]
51        include_invite: bool,
52    },
53    /// Splits a string containing multiple e-cash notes (e.g. from the `spend`
54    /// command) into ones that contain exactly one.
55    Split {
56        oob_notes: Option<OOBNotes>,
57        /// Read serialized notes from a file, or '-' for stdin.
58        #[clap(long)]
59        notes_file: Option<PathBuf>,
60    },
61    /// Combines two or more serialized e-cash notes strings
62    Combine {
63        oob_notes: Vec<OOBNotes>,
64        /// Read one serialized notes string per file. May be repeated; '-'
65        /// reads stdin once. Cannot be combined with positional notes.
66        #[clap(long)]
67        notes_file: Vec<PathBuf>,
68    },
69    /// Verifies the signatures of e-cash notes, if the online flag is specified
70    /// it also checks with the mint if the notes were already spent
71    Validate {
72        /// Whether to check with the mint if the notes were already spent
73        /// (CAUTION: this hurts privacy)
74        #[clap(long)]
75        online: bool,
76        /// E-Cash note to validate
77        oob_notes: Option<OOBNotes>,
78        /// Read serialized notes from a file, or '-' for stdin.
79        #[clap(long)]
80        notes_file: Option<PathBuf>,
81    },
82    /// Debugging commands querying the federation directly
83    Dev {
84        #[clap(subcommand)]
85        command: DevOpts,
86    },
87}
88
89#[cfg(not(target_family = "wasm"))]
90const MAX_NOTES_BYTES: usize = 16 * 1024 * 1024;
91
92fn read_notes_file(path: &Path) -> Result<OOBNotes, CliCommandError> {
93    #[cfg(not(target_family = "wasm"))]
94    {
95        let encoded = fedimint_core::util::read_secret_file(path, MAX_NOTES_BYTES)?;
96        encoded
97            .parse()
98            .map_err(|_| CliCommandError::InvalidSecretNotes)
99    }
100    #[cfg(target_family = "wasm")]
101    {
102        let _ = path;
103        Err(CliCommandError::UnsupportedSecretInput)
104    }
105}
106
107fn resolve_notes(
108    notes: Option<OOBNotes>,
109    file: Option<PathBuf>,
110) -> Result<OOBNotes, CliCommandError> {
111    match (notes, file) {
112        (Some(notes), None) => Ok(notes),
113        (None, Some(file)) => read_notes_file(&file),
114        (Some(_), Some(_)) => Err(CliCommandError::ConflictingNotes),
115        (None, None) => Err(CliCommandError::MissingNotes),
116    }
117}
118
119fn resolve_notes_list(
120    notes: Vec<OOBNotes>,
121    files: &[PathBuf],
122) -> Result<Vec<OOBNotes>, CliCommandError> {
123    if !notes.is_empty() && !files.is_empty() {
124        return Err(CliCommandError::ConflictingNotes);
125    }
126    if !notes.is_empty() {
127        return Ok(notes);
128    }
129    if files.is_empty() {
130        return Err(CliCommandError::MissingNotes);
131    }
132    #[cfg(not(target_family = "wasm"))]
133    fedimint_core::util::ensure_single_stdin(files.iter().map(PathBuf::as_path))?;
134    files.iter().map(|file| read_notes_file(file)).collect()
135}
136
137#[derive(Subcommand, Serialize)]
138enum DevOpts {
139    /// Ask every guardian if a note's nonce has already been spent
140    ///
141    /// Accepts either a hex-encoded nonce (33 byte compressed secp256k1 public
142    /// key) or an out-of-band e-cash notes string, in which case every nonce it
143    /// contains is checked.
144    CheckNonce {
145        /// Hex-encoded nonce or e-cash notes string
146        nonce: Option<String>,
147        /// Read serialized notes from a file, or '-' for stdin.
148        #[clap(long)]
149        notes_file: Option<PathBuf>,
150    },
151    /// Ask every guardian if e-cash has already been issued for a blind nonce
152    ///
153    /// Accepts a hex-encoded blind nonce (48 byte compressed BLS12-381 G1
154    /// point). Note that the human-readable form logged for a blind nonce is a
155    /// SHA256 digest of it and can not be used here.
156    CheckBlindNonce {
157        /// Hex-encoded blind nonce
158        blind_nonce: String,
159    },
160}
161
162fn resolve_nonce_argument(
163    nonce: Option<String>,
164    file: Option<PathBuf>,
165) -> Result<String, CliCommandError> {
166    match (nonce, file) {
167        (Some(nonce), None) => Ok(nonce),
168        (None, Some(file)) => Ok(read_notes_file(&file)?.to_string()),
169        (Some(_), Some(_)) => Err(CliCommandError::ConflictingNonceArgument),
170        (None, None) => Err(CliCommandError::MissingNonceArgument),
171    }
172}
173
174/// A single guardian's answer to a nonce or blind nonce query
175#[derive(Serialize)]
176#[serde(untagged)]
177enum PeerCheckResult {
178    Answer(bool),
179    Error(String),
180}
181
182/// Asks every guardian if `nonce` was already spent.
183///
184/// Peers that fail to answer are reported as errors instead of failing the
185/// whole query, since seeing the remaining guardians' answers is the point.
186async fn check_nonce_spent(
187    mint: &MintClientModule,
188    nonce: Nonce,
189) -> BTreeMap<PeerId, PeerCheckResult> {
190    let api = mint.client_ctx.module_api();
191
192    join_all(api.all_peers().iter().map(|&peer| {
193        let api = &api;
194        async move {
195            let result = match api.check_note_spent_single_peer(peer, nonce).await {
196                Ok(spent) => PeerCheckResult::Answer(spent),
197                Err(e) => PeerCheckResult::Error(format!("error: {}", e.fmt_compact())),
198            };
199            (peer, result)
200        }
201    }))
202    .await
203    .into_iter()
204    .collect()
205}
206
207/// Asks every guardian if e-cash was already issued for `blind_nonce`.
208async fn check_blind_nonce_used(
209    mint: &MintClientModule,
210    blind_nonce: BlindNonce,
211) -> BTreeMap<PeerId, PeerCheckResult> {
212    let api = mint.client_ctx.module_api();
213
214    join_all(api.all_peers().iter().map(|&peer| {
215        let api = &api;
216        async move {
217            let result = match api
218                .check_blind_nonce_used_single_peer(peer, blind_nonce)
219                .await
220            {
221                Ok(used) => PeerCheckResult::Answer(used),
222                Err(e) => PeerCheckResult::Error(format!("error: {}", e.fmt_compact())),
223            };
224            (peer, result)
225        }
226    }))
227    .await
228    .into_iter()
229    .collect()
230}
231
232async fn check_nonce(
233    mint: &MintClientModule,
234    nonce: &str,
235) -> Result<serde_json::Value, CliCommandError> {
236    if let Ok(nonce) = Nonce::consensus_decode_hex(nonce, &ModuleDecoderRegistry::default()) {
237        return Ok(json!({
238            "nonce": nonce.consensus_encode_to_hex(),
239            "spent": check_nonce_spent(mint, nonce).await,
240        }));
241    }
242
243    let oob_notes = OOBNotes::from_str(nonce).map_err(CliCommandError::InvalidNonceArgument)?;
244
245    let mut nonces = Vec::new();
246    for (amount, note) in oob_notes.notes().iter_items() {
247        let nonce = note.nonce();
248        nonces.push(json!({
249            "nonce": nonce.consensus_encode_to_hex(),
250            "amount_msat": amount.msats,
251            "spent": check_nonce_spent(mint, nonce).await,
252        }));
253    }
254
255    Ok(json!({ "nonces": nonces }))
256}
257
258async fn check_blind_nonce(
259    mint: &MintClientModule,
260    blind_nonce: &str,
261) -> Result<serde_json::Value, CliCommandError> {
262    let blind_nonce =
263        BlindNonce::consensus_decode_hex(blind_nonce, &ModuleDecoderRegistry::default())
264            .map_err(CliCommandError::InvalidBlindNonce)?;
265
266    Ok(json!({
267        "blind_nonce": blind_nonce.consensus_encode_to_hex(),
268        "issued": check_blind_nonce_used(mint, blind_nonce).await,
269    }))
270}
271
272async fn spend(
273    mint: &MintClientModule,
274    amount: Amount,
275    allow_overpay: bool,
276    timeout: u64,
277    include_invite: bool,
278) -> Result<serde_json::Value, CliCommandError> {
279    warn!(
280        "The client will try to double-spend these notes after the timeout to reclaim \
281        any unclaimed e-cash."
282    );
283
284    let timeout = Duration::from_secs(timeout);
285    let (operation, notes) = if allow_overpay {
286        let (operation, notes) = mint
287            .spend_notes_with_selector(
288                &SelectNotesWithAtleastAmount,
289                amount,
290                Some(timeout),
291                include_invite,
292                (),
293            )
294            .await?;
295
296        let overspend_amount = notes.total_amount().saturating_sub(amount);
297        if overspend_amount != Amount::ZERO {
298            warn!("Selected notes {overspend_amount} worth more than requested");
299        }
300
301        (operation, notes)
302    } else {
303        mint.spend_notes_with_selector(
304            &SelectNotesWithExactAmount,
305            amount,
306            Some(timeout),
307            include_invite,
308            (),
309        )
310        .await?
311    };
312    info!("Spend e-cash operation: {}", operation.fmt_short());
313
314    Ok(json!({ "notes": notes }))
315}
316
317fn split(oob_notes: &OOBNotes) -> serde_json::Value {
318    let federation = oob_notes.federation_id_prefix();
319    let notes = oob_notes
320        .notes()
321        .iter()
322        .map(|(amount, notes)| {
323            let notes = notes
324                .iter()
325                .map(|note| {
326                    OOBNotes::new(
327                        federation,
328                        TieredMulti::new(vec![(amount, vec![*note])].into_iter().collect()),
329                    )
330                })
331                .collect::<Vec<_>>();
332            (amount, notes)
333        })
334        .collect::<BTreeMap<_, _>>();
335
336    json!({ "notes": notes })
337}
338
339fn combine(oob_notes: &[OOBNotes]) -> Result<serde_json::Value, CliCommandError> {
340    let federation_id_prefix = {
341        let mut prefixes = oob_notes.iter().map(OOBNotes::federation_id_prefix);
342        let first = prefixes
343            .next()
344            .expect("At least one e-cash notes string expected");
345        for prefix in prefixes {
346            if prefix != first {
347                return Err(CliCommandError::MixedFederations {
348                    first,
349                    other: prefix,
350                });
351            }
352        }
353        first
354    };
355
356    let combined_notes = oob_notes
357        .iter()
358        .flat_map(|notes| notes.notes().iter_items().map(|(amt, note)| (amt, *note)))
359        .collect();
360
361    let combined_oob_notes = OOBNotes::new(federation_id_prefix, combined_notes);
362
363    Ok(json!({ "notes": combined_oob_notes }))
364}
365
366pub(crate) async fn handle_cli_command(
367    mint: &MintClientModule,
368    args: &[ffi::OsString],
369) -> Result<serde_json::Value, CliCommandError> {
370    let opts = Opts::parse_from(iter::once(&ffi::OsString::from("mint")).chain(args.iter()));
371
372    match opts {
373        Opts::Reissue { notes, notes_file } => {
374            let notes = resolve_notes(notes, notes_file)?;
375            let amount = notes.total_amount();
376
377            let operation_id = mint.reissue_external_notes(notes, ()).await?;
378
379            let mut updates = mint
380                .subscribe_reissue_external_notes(operation_id)
381                .await
382                .unwrap()
383                .into_stream();
384
385            while let Some(update) = updates.next().await {
386                if let ReissueExternalNotesState::Failed(e) = update {
387                    return Err(CliCommandError::ReissueFailed(e));
388                }
389            }
390
391            Ok(serde_json::to_value(amount).expect("JSON serialization failed"))
392        }
393        Opts::Spend {
394            amount,
395            allow_overpay,
396            timeout,
397            include_invite,
398        } => spend(mint, amount, allow_overpay, timeout, include_invite).await,
399        Opts::Split {
400            oob_notes,
401            notes_file,
402        } => Ok(split(&resolve_notes(oob_notes, notes_file)?)),
403        Opts::Combine {
404            oob_notes,
405            notes_file,
406        } => combine(&resolve_notes_list(oob_notes, &notes_file)?),
407        Opts::Validate {
408            oob_notes,
409            notes_file,
410            online,
411        } => {
412            let oob_notes = resolve_notes(oob_notes, notes_file)?;
413            let amount = mint.validate_notes(&oob_notes)?;
414
415            if online {
416                let any_spent = mint.check_note_spent(&oob_notes).await?;
417                Ok(json!({
418                    "any_spent": any_spent,
419                    "amount_msat": amount,
420                }))
421            } else {
422                Ok(json!({ "amount_msat": amount }))
423            }
424        }
425        Opts::Dev { command } => match command {
426            DevOpts::CheckNonce { nonce, notes_file } => {
427                check_nonce(mint, &resolve_nonce_argument(nonce, notes_file)?).await
428            }
429            DevOpts::CheckBlindNonce { blind_nonce } => check_blind_nonce(mint, &blind_nonce).await,
430        },
431    }
432}
433
434/// A failure of a `mint` module command.
435#[derive(Debug, thiserror::Error)]
436pub(crate) enum CliCommandError {
437    #[error("Provide either positional nonce/notes or --notes-file, not both")]
438    ConflictingNonceArgument,
439    #[error("Provide positional nonce/notes or --notes-file")]
440    MissingNonceArgument,
441    #[error("Provide either positional notes or --notes-file, not both")]
442    ConflictingNotes,
443    #[error("Provide positional notes or --notes-file")]
444    MissingNotes,
445    #[cfg(not(target_family = "wasm"))]
446    #[error("Invalid e-cash notes in secret input")]
447    InvalidSecretNotes,
448    #[cfg(not(target_family = "wasm"))]
449    #[error(transparent)]
450    SecretInput(#[from] fedimint_core::util::SecretInputError),
451    #[cfg(target_family = "wasm")]
452    #[error("Secret file input is not supported on this platform")]
453    UnsupportedSecretInput,
454    /// The notes could not be reissued.
455    #[error(transparent)]
456    Reissue(#[from] ReissueExternalNotesError),
457
458    /// The reissue transaction failed.
459    #[error("Reissue failed: {0}")]
460    ReissueFailed(String),
461
462    /// The notes to spend could not be selected or prepared.
463    #[error(transparent)]
464    Spend(#[from] SpendOOBError),
465
466    /// Notes of different federations were given to combine.
467    #[error("Trying to combine e-cash from different federations: {first} and {other}")]
468    MixedFederations {
469        first: FederationIdPrefix,
470        other: FederationIdPrefix,
471    },
472
473    /// The notes to validate are invalid.
474    #[error(transparent)]
475    Validate(#[from] ValidateNotesError),
476
477    /// The federation could not say whether the notes are spent.
478    #[error(transparent)]
479    Federation(#[from] FederationError),
480
481    /// The argument of `dev check-nonce` is neither a nonce nor e-cash.
482    #[error("Argument is neither a hex-encoded nonce nor an e-cash notes string")]
483    InvalidNonceArgument(#[source] OOBNotesParseError),
484
485    /// The argument of `dev check-blind-nonce` is not a blind nonce.
486    #[error("Argument is not a hex-encoded blind nonce")]
487    InvalidBlindNonce(#[source] DecodeError),
488}
489
490#[cfg(test)]
491mod tests;