Skip to main content

fedimint_cli/
cli.rs

1use std::path::PathBuf;
2use std::time::Duration;
3
4use clap::builder::BoolishValueParser;
5use clap::{Args, Parser, Subcommand};
6use fedimint_core::config::FederationId;
7use fedimint_core::core::OperationId;
8use fedimint_core::util::SafeUrl;
9use fedimint_core::{Amount, PeerId, TieredMulti};
10use fedimint_eventlog::EventLogId;
11use fedimint_mint_client::SpendableNote;
12use serde::{Deserialize, Serialize};
13
14use crate::client::{ClientCmd, ModuleSelector};
15#[cfg(feature = "tor")]
16use crate::envs::FM_USE_TOR_ENV;
17use crate::envs::{
18    FM_API_SECRET_ENV, FM_CLIENT_DIR_ENV, FM_DB_BACKEND_ENV, FM_FEDERATION_SECRET_HEX_ENV,
19    FM_IROH_ENABLE_DHT_ENV, FM_OUR_ID_ENV, FM_PASSWORD_API_ENV,
20};
21use crate::utils::parse_peer_id;
22
23fn parse_wait_duration(seconds: &str) -> anyhow::Result<Duration> {
24    Ok(Duration::try_from_secs_f32(seconds.parse()?)?)
25}
26
27#[cfg(test)]
28mod tests;
29
30#[derive(Debug, Clone, Copy, clap::ValueEnum)]
31pub(crate) enum DatabaseBackend {
32    /// Use RocksDB database backend
33    #[value(name = "rocksdb")]
34    RocksDb,
35    /// Use CursedRedb database backend (hybrid memory/redb)
36    #[value(name = "cursed-redb")]
37    CursedRedb,
38}
39
40#[derive(Parser, Clone)]
41#[command(version)]
42pub(crate) struct Opts {
43    /// The working directory of the client containing the config and db
44    #[arg(long = "data-dir", env = FM_CLIENT_DIR_ENV)]
45    pub data_dir: Option<PathBuf>,
46
47    /// Peer id of the guardian
48    #[arg(env = FM_OUR_ID_ENV, long, value_parser = parse_peer_id)]
49    pub our_id: Option<PeerId>,
50
51    /// Guardian password for authentication
52    #[arg(long, env = FM_PASSWORD_API_ENV, hide_env_values = true)]
53    pub password: Option<String>,
54    /// Read the guardian password from a protected UTF-8 file (`-` for stdin).
55    #[arg(long)]
56    pub password_file: Option<PathBuf>,
57
58    /// Federation secret as consensus-encoded hex.
59    #[arg(long, env = FM_FEDERATION_SECRET_HEX_ENV, hide_env_values = true)]
60    pub federation_secret_hex: Option<String>,
61    /// Read the federation secret from a protected UTF-8 file (`-` for stdin).
62    #[arg(long)]
63    pub federation_secret_hex_file: Option<PathBuf>,
64
65    #[cfg(feature = "tor")]
66    /// Activate usage of Tor as the Connector when building the Client
67    #[arg(long, env = FM_USE_TOR_ENV, value_parser = BoolishValueParser::new())]
68    pub use_tor: bool,
69
70    // Enable using DHT name resolution in Iroh
71    #[arg(long, env = FM_IROH_ENABLE_DHT_ENV, value_parser = BoolishValueParser::new())]
72    pub iroh_enable_dht: Option<bool>,
73
74    /// Database backend to use.
75    #[arg(long, env = FM_DB_BACKEND_ENV, value_enum, default_value = "rocksdb")]
76    pub db_backend: DatabaseBackend,
77
78    /// Activate more verbose logging, for full control use the RUST_LOG env
79    /// variable
80    #[arg(short = 'v', long)]
81    pub verbose: bool,
82
83    #[clap(subcommand)]
84    pub command: Command,
85}
86
87#[derive(Subcommand, Clone)]
88pub(crate) enum Command {
89    /// Print the latest Git commit hash this bin. was built with.
90    VersionHash,
91
92    #[clap(flatten)]
93    Client(ClientCmd),
94
95    #[clap(subcommand)]
96    Admin(AdminCmd),
97
98    #[clap(subcommand)]
99    Dev(DevCmd),
100
101    /// Config enabling client to establish websocket connection to federation
102    InviteCode {
103        peer: PeerId,
104    },
105
106    /// Join a federation using its InviteCode
107    #[clap(alias = "join-federation")]
108    Join {
109        invite_code: Option<String>,
110        /// Read an invite code from a file (`-` for stdin).
111        #[arg(long)]
112        invite_code_file: Option<PathBuf>,
113    },
114
115    Completion {
116        shell: clap_complete::Shell,
117    },
118}
119
120#[allow(clippy::large_enum_variant)]
121#[derive(Debug, Clone, Subcommand)]
122pub(crate) enum AdminCmd {
123    /// Store admin credentials (peer_id and password) in the client database.
124    ///
125    /// This allows subsequent admin commands to be run without specifying
126    /// `--our-id` and `--password` each time.
127    ///
128    /// The command will verify the credentials by making an authenticated
129    /// API call before storing them.
130    Auth {
131        /// Guardian's peer ID
132        #[arg(long, env = FM_OUR_ID_ENV)]
133        peer_id: u16,
134        /// Guardian password for authentication
135        #[arg(long, env = FM_PASSWORD_API_ENV, hide_env_values = true)]
136        password: Option<String>,
137        /// Read the guardian password from a protected file (`-` for stdin).
138        #[arg(long)]
139        password_file: Option<PathBuf>,
140        /// Skip interactive endpoint verification
141        #[arg(long)]
142        no_verify: bool,
143        /// Force overwrite existing stored credentials
144        #[arg(long)]
145        force: bool,
146    },
147
148    /// Show the status according to the `status` endpoint
149    Status,
150
151    /// Start fresh availability observations for a peer on this guardian
152    ResetPeerAvailability {
153        peer_id: PeerId,
154    },
155
156    /// Show an audit across all modules
157    Audit,
158
159    /// Download guardian config to back it up
160    GuardianConfigBackup,
161
162    Setup(SetupAdminArgs),
163    /// Sign and announce a new API endpoint. The previous one will be
164    /// invalidated
165    SignApiAnnouncement {
166        /// New API URL to announce
167        api_url: SafeUrl,
168        /// Provide the API url for the guardian directly in case the old one
169        /// isn't reachable anymore
170        #[clap(long)]
171        override_url: Option<SafeUrl>,
172    },
173    /// Sign guardian metadata
174    SignGuardianMetadata {
175        /// API URLs (can be specified multiple times or comma-separated)
176        #[clap(long, value_delimiter = ',')]
177        api_urls: Vec<SafeUrl>,
178        /// Pkarr ID (z32 format)
179        #[clap(long)]
180        pkarr_id: String,
181    },
182    /// Stop fedimintd after the specified session to do a coordinated upgrade
183    Shutdown {
184        /// Session index to stop after
185        session_idx: u64,
186    },
187    /// Show statistics about client backups stored by the federation
188    BackupStatistics,
189}
190
191#[derive(Debug, Clone, Args)]
192pub(crate) struct SetupAdminArgs {
193    pub endpoint: SafeUrl,
194
195    #[clap(subcommand)]
196    pub subcommand: SetupAdminCmd,
197}
198
199#[derive(Debug, Clone, Subcommand)]
200pub(crate) enum SetupAdminCmd {
201    Status,
202    SetLocalParams {
203        name: String,
204        /// Deprecated and ignored by new guardians. After setup, set
205        /// federation_name in the guardian dashboard's Meta module; a guardian
206        /// consensus threshold must submit the same metadata.
207        #[clap(long)]
208        federation_name: Option<String>,
209        #[clap(long)]
210        federation_size: Option<u32>,
211    },
212    AddPeer {
213        info: String,
214    },
215    StartDkg,
216}
217
218#[derive(Debug, Clone, Subcommand)]
219pub(crate) enum DecodeType {
220    /// Decode an invite code string into a JSON representation
221    InviteCode {
222        invite_code: Option<String>,
223        /// Read an invite code from a file (`-` for stdin).
224        #[arg(long)]
225        invite_code_file: Option<PathBuf>,
226    },
227    /// Decode a string of ecash notes into a JSON representation
228    Notes {
229        /// Base64 e-cash notes to be decoded
230        notes: Option<String>,
231        /// File containing base64 e-cash notes to be decoded
232        #[arg(long)]
233        file: Option<PathBuf>,
234    },
235    /// Decode a transaction hex string and print it to stdout
236    Transaction { hex_string: String },
237    /// Decode a setup code (as shared during a federation setup ceremony)
238    /// string into a JSON representation
239    SetupCode { setup_code: String },
240}
241
242#[derive(Debug, Clone, Deserialize, Serialize)]
243pub(crate) struct OOBNotesJson {
244    pub federation_id_prefix: String,
245    pub notes: TieredMulti<SpendableNote>,
246}
247
248#[derive(Debug, Clone, Subcommand)]
249pub(crate) enum EncodeType {
250    /// Encode connection info from its constituent parts
251    InviteCode {
252        #[clap(long)]
253        url: SafeUrl,
254        #[clap(long = "federation_id")]
255        federation_id: FederationId,
256        #[clap(long = "peer")]
257        peer: PeerId,
258        #[arg(env = FM_API_SECRET_ENV, hide_env_values = true)]
259        api_secret: Option<String>,
260        /// Read the API secret from a protected file (`-` for stdin).
261        #[arg(long)]
262        api_secret_file: Option<PathBuf>,
263    },
264
265    /// Encode a JSON string of notes to an ecash string
266    Notes {
267        notes_json: Option<String>,
268        /// Read note JSON from a protected file (`-` for stdin).
269        #[arg(long)]
270        notes_json_file: Option<PathBuf>,
271    },
272}
273
274#[derive(Debug, Clone, Subcommand)]
275pub(crate) enum DevCmd {
276    /// Send direct method call to the API. If you specify --peer-id, it will
277    /// just ask one server, otherwise it will try to get consensus from all
278    /// servers.
279    #[command(after_long_help = r#"
280Examples:
281
282  fedimint-cli dev api --peer-id 0 config '"fed114znk7uk7ppugdjuytr8venqf2tkywd65cqvg3u93um64tu5cw4yr0n3fvn7qmwvm4g48cpndgnm4gqq4waen5te0xyerwt3s9cczuvf6xyurzde597s7crdvsk2vmyarjw9gwyqjdzj"'
283    "#)]
284    Api {
285        /// JSON-RPC method to call
286        method: String,
287        /// JSON-RPC parameters for the request
288        ///
289        /// Note: single jsonrpc argument params string, which might require
290        /// double-quotes (see example above).
291        params: Option<String>,
292        /// Read JSON parameters from a file (`-` for stdin).
293        #[arg(long)]
294        params_file: Option<PathBuf>,
295        /// Which server to send request to
296        #[clap(long = "peer-id")]
297        peer_id: Option<u16>,
298
299        /// Module selector (either module id or module kind)
300        #[clap(long = "module")]
301        module: Option<ModuleSelector>,
302
303        /// Guardian password in case authenticated API endpoints are being
304        /// called. Only use together with --peer-id.
305        #[clap(long, requires = "peer_id")]
306        password: Option<String>,
307        /// Read the guardian password from a protected file (`-` for stdin).
308        #[arg(long, requires = "peer_id")]
309        password_file: Option<PathBuf>,
310    },
311
312    ApiAnnouncements,
313
314    GuardianMetadata,
315
316    /// Advance the note_idx
317    AdvanceNoteIdx {
318        #[clap(long, default_value = "1")]
319        count: usize,
320
321        #[clap(long)]
322        amount: Amount,
323    },
324
325    /// Wait for the fed to reach a consensus block count
326    WaitBlockCount {
327        count: u64,
328    },
329
330    /// Just start the `Client` and wait
331    Wait {
332        /// Limit the wait time in seconds
333        #[arg(value_parser = parse_wait_duration)]
334        seconds: Option<Duration>,
335    },
336
337    /// Wait for all state machines to complete
338    WaitComplete,
339
340    /// Decode invite code or ecash notes string into a JSON representation
341    Decode {
342        #[clap(subcommand)]
343        decode_type: DecodeType,
344    },
345
346    /// Encode an invite code or ecash notes into binary
347    Encode {
348        #[clap(subcommand)]
349        encode_type: EncodeType,
350    },
351
352    /// Gets the current fedimint AlephBFT block count
353    SessionCount,
354
355    /// Show public guardian IPs and iroh connection paths from an invite code
356    #[command(
357        name = "query-federation-ips",
358        visible_aliases = ["federation-ip-query", "iroh-ip-query"]
359    )]
360    QueryFederationIps {
361        invite_code: Option<String>,
362        /// Read an invite code from a file (`-` for stdin).
363        #[arg(long)]
364        invite_code_file: Option<PathBuf>,
365        /// Time to wait for iroh to discover a direct path to each guardian
366        #[arg(long, default_value = "5")]
367        path_timeout_seconds: u64,
368        /// Fail unless every iroh guardian reaches a direct or mixed path
369        /// before timeout
370        #[arg(long)]
371        require_direct: bool,
372    },
373
374    /// Returns the client config
375    Config,
376
377    ConfigDecrypt {
378        /// Encrypted config file
379        #[arg(long = "in-file")]
380        in_file: PathBuf,
381        /// Plaintext config file output
382        #[arg(long = "out-file")]
383        out_file: PathBuf,
384        /// Encryption salt file, otherwise defaults to the salt file from the
385        /// `in_file` directory
386        #[arg(long = "salt-file")]
387        salt_file: Option<PathBuf>,
388        /// The password that encrypts the configs
389        #[arg(env = FM_PASSWORD_API_ENV, hide_env_values = true)]
390        password: Option<String>,
391        /// Read the encryption password from a protected file (`-` for stdin).
392        #[arg(long)]
393        password_file: Option<PathBuf>,
394    },
395
396    ConfigEncrypt {
397        /// Plaintext config file
398        #[arg(long = "in-file")]
399        in_file: PathBuf,
400        /// Encrypted config file output
401        #[arg(long = "out-file")]
402        out_file: PathBuf,
403        /// Encryption salt file, otherwise defaults to the salt file from the
404        /// `out_file` directory
405        #[arg(long = "salt-file")]
406        salt_file: Option<PathBuf>,
407        /// The password that encrypts the configs
408        #[arg(env = FM_PASSWORD_API_ENV, hide_env_values = true)]
409        password: Option<String>,
410        /// Read the encryption password from a protected file (`-` for stdin).
411        #[arg(long)]
412        password_file: Option<PathBuf>,
413    },
414
415    /// Lists active and inactive state machine states of the operation
416    /// chronologically
417    ListOperationStates {
418        operation_id: OperationId,
419    },
420    /// Returns the federation's meta fields. If they are set correctly via the
421    /// meta module these are returned, otherwise the legacy mechanism
422    /// (config+override file) is used.
423    MetaFields,
424    /// Gets the tagged fedimintd version for a peer
425    PeerVersion {
426        #[clap(long)]
427        peer_id: u16,
428    },
429    /// Dump Client's Event Log
430    ShowEventLog {
431        #[arg(long)]
432        pos: Option<EventLogId>,
433        #[arg(long, default_value = "10")]
434        limit: u64,
435    },
436    /// Dump Client's Trimable Event Log
437    ShowEventLogTrimable {
438        #[arg(long)]
439        pos: Option<EventLogId>,
440        #[arg(long, default_value = "10")]
441        limit: u64,
442    },
443    /// Print the id the next entry appended to the client's event log will be
444    /// assigned (the position just past the current end of the log).
445    NextEventLogId,
446    /// Test the built-in event handling and tracking by printing events to
447    /// console
448    TestEventLogHandling,
449    /// Manually submit a fedimint transaction to guardians
450    ///
451    /// This can be useful to check why a transaction may have been rejected
452    /// when debugging client issues.
453    SubmitTransaction {
454        /// Hex-encoded fedimint transaction
455        transaction: String,
456    },
457    /// Show the chain ID (bitcoin block hash at height 1) cached in the client
458    /// database
459    ChainId,
460    /// Force refresh API versions from the federation, bypassing cached values.
461    /// Queries all peers for their supported API versions and updates the
462    /// cache.
463    RefreshApiVersions,
464    /// Trigger a panic to verify backtrace handling
465    Panic,
466    /// Visualize client internals for debugging
467    Visualize {
468        #[clap(subcommand)]
469        visualize_type: VisualizeCmd,
470    },
471}
472
473#[derive(Debug, Clone, Subcommand)]
474pub(crate) enum VisualizeCmd {
475    /// Show every e-cash note with creation/spending provenance
476    Notes {
477        #[arg(long)]
478        limit: Option<usize>,
479    },
480    /// Show transactions with inputs and outputs
481    Transactions {
482        /// Show a specific operation (by full ID)
483        operation_id: Option<OperationId>,
484        /// How many most-recent operations to show (ignored if operation_id is
485        /// given)
486        #[arg(long)]
487        limit: Option<usize>,
488    },
489    /// Show operations with their state machines
490    Operations {
491        /// Show a specific operation (by full ID)
492        operation_id: Option<OperationId>,
493        /// How many most-recent operations to show (ignored if operation_id is
494        /// given)
495        #[arg(long)]
496        limit: Option<usize>,
497    },
498}