Skip to main content

devimint/
cli.rs

1use std::fmt::Write;
2use std::ops::ControlFlow;
3use std::path::{Path, PathBuf};
4use std::time::Duration;
5use std::{env, ffi};
6
7use anyhow::{Context, Result, anyhow, ensure};
8use clap::builder::BoolishValueParser;
9use clap::{Parser, Subcommand};
10use fedimint_core::task::TaskGroup;
11use fedimint_core::util::{FmtCompactAnyhow as _, write_overwrite_async};
12use fedimint_logging::LOG_DEVIMINT;
13use rand::Rng as _;
14use rand::distributions::Alphanumeric;
15use tokio::fs;
16use tokio::time::Instant;
17use tracing::{debug, error, info, trace, warn};
18
19use crate::devfed::DevJitFed;
20use crate::envs::{
21    FM_DEVIMINT_STATIC_DATA_DIR_ENV, FM_FED_SIZE_ENV, FM_FEDERATIONS_BASE_PORT_ENV,
22    FM_GATEWAY_BASE_PORT_ENV, FM_INVITE_CODE_ENV, FM_LINK_TEST_DIR_ENV, FM_NUM_FEDS_ENV,
23    FM_OFFLINE_NODES_ENV, FM_PRE_DKG_ENV, FM_TEST_DIR_ENV,
24};
25use crate::util::{ProcessManager, poll};
26use crate::vars::mkdir;
27use crate::{external_daemons, vars};
28
29fn random_test_dir_suffix() -> String {
30    rand::thread_rng()
31        .sample_iter(&Alphanumeric)
32        .filter(u8::is_ascii_digit)
33        .take(3)
34        .map(char::from)
35        .collect::<String>()
36}
37
38#[derive(Parser, Clone, Default)]
39pub struct CommonArgs {
40    #[clap(short = 'd', long, env = FM_TEST_DIR_ENV)]
41    pub test_dir: Option<PathBuf>,
42
43    /// Don't set up new Federation, start from the state in existing
44    /// devimint data dir
45    #[arg(long, env = "FM_SKIP_SETUP", value_parser = BoolishValueParser::new())]
46    skip_setup: bool,
47
48    /// Do not set up federation and stop at a pre-dkg stage
49    #[arg(long, env = FM_PRE_DKG_ENV, value_parser = BoolishValueParser::new())]
50    pre_dkg: bool,
51
52    /// Number of peers to allocate in every federation
53    #[clap(short = 'n', long, env = FM_FED_SIZE_ENV, default_value = "4")]
54    pub fed_size: usize,
55
56    /// Number of federations to allocate for the test/run
57    #[clap(long, env = FM_NUM_FEDS_ENV, default_value = "1")]
58    pub num_feds: usize,
59
60    #[clap(long, env = FM_LINK_TEST_DIR_ENV)]
61    /// Create a link to the test dir under this path
62    pub link_test_dir: Option<PathBuf>,
63
64    #[clap(long, default_value_t = random_test_dir_suffix())]
65    pub link_test_dir_suffix: String,
66
67    /// Run degraded federation with FM_OFFLINE_NODES shutdown
68    #[clap(long, env = FM_OFFLINE_NODES_ENV, default_value = "0")]
69    pub offline_nodes: usize,
70
71    /// Force a base federations port, e.g. for convenience during dev tasks
72    #[clap(long, env = FM_FEDERATIONS_BASE_PORT_ENV)]
73    pub federations_base_port: Option<u16>,
74
75    /// Force a base gateway port, e.g. for convenience during dev tasks
76    #[clap(long, env = FM_GATEWAY_BASE_PORT_ENV)]
77    pub gateway_base_port: Option<u16>,
78}
79
80impl CommonArgs {
81    pub fn mk_test_dir(&self) -> Result<PathBuf> {
82        if self.skip_setup {
83            ensure!(
84                self.test_dir.is_some(),
85                "When using `--skip-setup`, `--test-dir` must be set"
86            );
87        }
88        let path = self.test_dir();
89
90        std::fs::create_dir_all(&path)
91            .with_context(|| format!("Creating tmp directory {}", path.display()))?;
92
93        Ok(path)
94    }
95
96    pub fn test_dir(&self) -> PathBuf {
97        self.test_dir.clone().unwrap_or_else(|| {
98            std::env::temp_dir().join(format!(
99                "devimint-{}-{}",
100                std::process::id(),
101                self.link_test_dir_suffix
102            ))
103        })
104    }
105}
106
107#[derive(Subcommand)]
108pub enum Cmd {
109    /// Spins up bitcoind and esplora.
110    ExternalDaemons {
111        #[arg(long, trailing_var_arg = true, allow_hyphen_values = true, num_args=1..)]
112        exec: Option<Vec<ffi::OsString>>,
113    },
114    /// Spins up bitcoind, LDK Gateway, lnd w/ gateway, a faucet,
115    /// esplora, and a federation sized from FM_FED_SIZE it opens LN channel
116    /// between the two nodes. it connects the gateways to the federation.
117    /// it finally switches to use the LND gateway for LNv1
118    DevFed {
119        #[arg(long, trailing_var_arg = true, allow_hyphen_values = true, num_args=1..)]
120        exec: Option<Vec<ffi::OsString>>,
121    },
122    /// Spins up a dev federation, backs up fedimint-0, wipes it, and restarts
123    /// it in setup mode for manual guardian restore UI testing.
124    DevFedPreRestore {
125        #[arg(long, trailing_var_arg = true, allow_hyphen_values = true, num_args=1..)]
126        exec: Option<Vec<ffi::OsString>>,
127    },
128    /// Rpc commands to the long running devimint instance. Could be entry point
129    /// for devimint as a cli
130    #[clap(flatten)]
131    Rpc(RpcCmd),
132}
133
134#[derive(Subcommand)]
135pub enum RpcCmd {
136    Wait,
137    Env,
138}
139
140pub async fn setup(arg: CommonArgs) -> Result<(ProcessManager, TaskGroup)> {
141    let test_dir = &arg.mk_test_dir()?;
142    mkdir(test_dir.clone()).await?;
143    let logs_dir: PathBuf = test_dir.join("logs");
144    mkdir(logs_dir.clone()).await?;
145
146    let log_file = fs::OpenOptions::new()
147        .write(true)
148        .create(true)
149        .append(true)
150        .open(logs_dir.join("devimint.log"))
151        .await?
152        .into_std()
153        .await;
154
155    fedimint_logging::TracingSetup::default()
156        .with_file(Some(log_file))
157        // jsonrpsee is expected to fail during startup
158        .with_directive("jsonrpsee-client=off")
159        .init()?;
160
161    let globals = vars::Global::new(
162        test_dir,
163        arg.num_feds,
164        arg.fed_size,
165        arg.offline_nodes,
166        arg.federations_base_port,
167        arg.gateway_base_port,
168    )
169    .await?;
170
171    if let Some(link_test_dir) = arg.link_test_dir.as_ref() {
172        update_test_dir_link(link_test_dir, &arg.test_dir()).await?;
173    }
174    info!(target: LOG_DEVIMINT, path = %globals.FM_DATA_DIR.display(), "Devimint data dir");
175
176    let mut env_string = String::new();
177    for (var, value) in globals.vars() {
178        debug!(var, value, "Env variable set");
179        writeln!(env_string, r#"export {var}="{value}""#)?; // hope that value doesn't contain a "
180        // TODO: Audit that the environment access only happens in single-threaded code.
181        unsafe { std::env::set_var(var, value) };
182    }
183    write_overwrite_async(globals.FM_TEST_DIR.join("env"), env_string).await?;
184    let process_mgr = ProcessManager::new(globals);
185    let task_group = TaskGroup::new();
186    task_group.install_kill_handler();
187    Ok((process_mgr, task_group))
188}
189
190pub async fn update_test_dir_link(
191    link_test_dir: &Path,
192    test_dir: &Path,
193) -> Result<(), anyhow::Error> {
194    let make_link = match fs::read_link(link_test_dir).await {
195        Ok(existing) => {
196            if existing == test_dir {
197                false
198            } else {
199                debug!(
200                    old = %existing.display(),
201                    new = %test_dir.display(),
202                    link = %link_test_dir.display(),
203                    "Updating exinst test dir link"
204                );
205
206                fs::remove_file(link_test_dir).await?;
207                true
208            }
209        }
210        _ => true,
211    };
212    if make_link {
213        debug!(src = %test_dir.display(), dst = %link_test_dir.display(), "Linking test dir");
214        fs::symlink(&test_dir, link_test_dir).await?;
215    }
216    Ok(())
217}
218
219pub async fn cleanup_on_exit<T>(
220    main_process: impl futures::Future<Output = Result<T>>,
221    task_group: TaskGroup,
222) -> Result<Option<T>> {
223    match task_group
224        .make_handle()
225        .cancel_on_shutdown(main_process)
226        .await
227    {
228        Err(_) => {
229            info!("Received shutdown signal before finishing main process, exiting early");
230            Ok(None)
231        }
232        Ok(Ok(v)) => {
233            debug!(target: LOG_DEVIMINT, "Main process finished successfully, shutting down task group");
234            task_group
235                .shutdown_join_all(Duration::from_secs(30))
236                .await?;
237
238            // the caller can drop the v after shutdown
239            Ok(Some(v))
240        }
241        Ok(Err(err)) => {
242            warn!(target: LOG_DEVIMINT, err = %err.fmt_compact_anyhow(), "Main process failed, will shutdown");
243            Err(err)
244        }
245    }
246}
247
248pub async fn write_ready_file<T>(global: &vars::Global, result: Result<T>) -> Result<T> {
249    let ready_file = &global.FM_READY_FILE;
250    match result {
251        Ok(_) => write_overwrite_async(ready_file, "READY").await?,
252        Err(_) => write_overwrite_async(ready_file, "ERROR").await?,
253    }
254    result
255}
256
257pub async fn handle_command(cmd: Cmd, common_args: CommonArgs) -> Result<()> {
258    match cmd {
259        Cmd::ExternalDaemons { exec } => {
260            let (process_mgr, task_group) = setup(common_args).await?;
261            let _daemons =
262                write_ready_file(&process_mgr.globals, external_daemons(&process_mgr).await)
263                    .await?;
264            if let Some(exec) = exec {
265                exec_user_command(exec).await?;
266                task_group.shutdown();
267            }
268            task_group.make_handle().make_shutdown_rx().await;
269        }
270        Cmd::DevFed { exec } => handle_dev_fed_command(common_args, exec, false).await?,
271        Cmd::DevFedPreRestore { exec } => handle_dev_fed_command(common_args, exec, true).await?,
272        Cmd::Rpc(rpc_cmd) => rpc_command(rpc_cmd, common_args).await?,
273    }
274    Ok(())
275}
276
277async fn handle_dev_fed_command(
278    common_args: CommonArgs,
279    exec: Option<Vec<ffi::OsString>>,
280    pre_restore: bool,
281) -> Result<()> {
282    trace!(target: LOG_DEVIMINT, "Starting dev fed");
283    let start_time = Instant::now();
284    let skip_setup = common_args.skip_setup;
285    let pre_dkg = common_args.pre_dkg;
286    ensure!(
287        !pre_restore || (!skip_setup && !pre_dkg),
288        "dev-fed-pre-restore cannot be combined with skip-setup or pre-dkg"
289    );
290    let (process_mgr, task_group) = setup(common_args).await?;
291    let main = {
292        let task_group = task_group.clone();
293        async move {
294            let dev_fed =
295                DevJitFed::new_with_pre_restore(&process_mgr, skip_setup, pre_dkg, pre_restore)?;
296
297            let pegin_start_time = Instant::now();
298            debug!(target: LOG_DEVIMINT, "Peging in client and gateways");
299
300            if !skip_setup && !pre_dkg && !pre_restore {
301                const GW_PEGIN_AMOUNT: u64 = 1_000_000;
302                const CLIENT_PEGIN_AMOUNT: u64 = 1_000_000;
303
304                let (handle, (), ()) = tokio::try_join!(
305                    async {
306                        let (address, handle) =
307                            dev_fed.internal_client().await?.get_deposit_addr().await?;
308                        debug!(
309                            target: LOG_DEVIMINT,
310                            %address,
311                            %handle,
312                            "Sending funds to client deposit addr"
313                        );
314                        dev_fed
315                            .bitcoind()
316                            .await?
317                            .send_to(address, CLIENT_PEGIN_AMOUNT)
318                            .await?;
319                        Ok(handle)
320                    },
321                    async {
322                        let address = dev_fed
323                            .gw_lnd_registered()
324                            .await?
325                            .client()
326                            .get_pegin_addr(&dev_fed.fed().await?.calculate_federation_id())
327                            .await?;
328                        debug!(
329                            target: LOG_DEVIMINT,
330                            %address,
331                            "Sending funds to LND deposit addr"
332                        );
333                        dev_fed
334                            .bitcoind()
335                            .await?
336                            .send_to(address, GW_PEGIN_AMOUNT)
337                            .await
338                            .map(|_| ())
339                    },
340                    async {
341                        if crate::util::supports_lnv2() {
342                            let gw_ldk = dev_fed.gw_ldk_connected().await?;
343                            let address = gw_ldk
344                                .client()
345                                .get_pegin_addr(&dev_fed.fed().await?.calculate_federation_id())
346                                .await?;
347                            debug!(
348                                target: LOG_DEVIMINT,
349                                %address,
350                                "Sending funds to LDK deposit addr"
351                            );
352                            dev_fed
353                                .bitcoind()
354                                .await?
355                                .send_to(address, GW_PEGIN_AMOUNT)
356                                .await
357                                .map(|_| ())
358                        } else {
359                            Ok(())
360                        }
361                    },
362                )?;
363
364                dev_fed.bitcoind().await?.mine_blocks_no_wait(11).await?;
365                if crate::util::supports_wallet_v2() {
366                    if crate::util::FedimintCli::version_or_default().await
367                        >= *crate::version_constants::VERSION_0_12_0_ALPHA
368                    {
369                        // `handle` is the event log position to wait from.
370                        dev_fed
371                            .internal_client()
372                            .await?
373                            .await_receive(&handle)
374                            .await?;
375                    } else {
376                        // Legacy walletv2 (<= 0.11) auto-claims deposits;
377                        // wait for the balance to reflect the pegin.
378                        dev_fed
379                            .internal_client()
380                            .await?
381                            .await_balance(CLIENT_PEGIN_AMOUNT * 1000 * 9 / 10)
382                            .await?;
383                    }
384                } else {
385                    dev_fed
386                        .internal_client()
387                        .await?
388                        .await_deposit(&handle)
389                        .await?;
390                }
391
392                info!(
393                    target: LOG_DEVIMINT,
394                    elapsed_ms = %pegin_start_time.elapsed().as_millis(),
395                    "Pegins completed"
396                );
397            }
398
399            if !pre_dkg && !pre_restore {
400                // TODO: Audit that the environment access only happens in single-threaded
401                // code.
402                unsafe {
403                    std::env::set_var(FM_INVITE_CODE_ENV, dev_fed.fed().await?.invite_code()?);
404                };
405            }
406
407            if pre_restore {
408                let _ = dev_fed.fed().await?;
409            } else {
410                dev_fed.finalize(&process_mgr).await?;
411            }
412
413            let daemons = write_ready_file(&process_mgr.globals, Ok(dev_fed)).await?;
414
415            info!(
416                target: LOG_DEVIMINT,
417                elapsed_ms = %start_time.elapsed().as_millis(),
418                path = %process_mgr.globals.FM_DATA_DIR.display(),
419                "Devfed ready"
420            );
421            if let Some(exec) = exec {
422                debug!(target: LOG_DEVIMINT, "Starting exec command");
423                exec_user_command(exec).await?;
424                task_group.shutdown();
425            }
426
427            debug!(target: LOG_DEVIMINT, "Waiting for group task shutdown");
428            task_group.make_handle().make_shutdown_rx().await;
429
430            Ok::<_, anyhow::Error>(daemons)
431        }
432    };
433    if let Some(fed) = cleanup_on_exit(main, task_group).await? {
434        fed.fast_terminate().await;
435    }
436
437    Ok(())
438}
439
440pub async fn exec_user_command(path: Vec<ffi::OsString>) -> Result<(), anyhow::Error> {
441    let cmd_str = path
442        .join(ffi::OsStr::new(" "))
443        .to_string_lossy()
444        .to_string();
445
446    let path_with_aliases = if let Some(existing_path) = env::var_os("PATH") {
447        let mut path = devimint_static_data_dir();
448        path.push("/aliases:");
449        path.push(existing_path);
450        path
451    } else {
452        let mut path = devimint_static_data_dir();
453        path.push("/aliases");
454        path
455    };
456    debug!(target: LOG_DEVIMINT, cmd = %cmd_str, "Executing user command");
457    if !tokio::process::Command::new(&path[0])
458        .args(&path[1..])
459        .env("PATH", path_with_aliases)
460        .kill_on_drop(true)
461        .status()
462        .await
463        .with_context(|| format!("Executing user command failed: {cmd_str}"))?
464        .success()
465    {
466        error!(cmd = %cmd_str, "User command failed");
467        return Err(anyhow!("User command failed: {cmd_str}"));
468    }
469    Ok(())
470}
471
472fn devimint_static_data_dir() -> ffi::OsString {
473    // If set, use the runtime, otherwise the compile time value
474    env::var_os(FM_DEVIMINT_STATIC_DATA_DIR_ENV).unwrap_or(
475        env!(
476            // Note: constant expression, not allowed, so we can't use the constant :/
477            "FM_DEVIMINT_STATIC_DATA_DIR"
478        )
479        .into(),
480    )
481}
482
483pub async fn rpc_command(rpc: RpcCmd, common: CommonArgs) -> Result<()> {
484    fedimint_logging::TracingSetup::default().init()?;
485    match rpc {
486        RpcCmd::Env => {
487            let env_file = common.test_dir().join("env");
488            poll("env file", || async {
489                if fs::try_exists(&env_file)
490                    .await
491                    .context("env file")
492                    .map_err(ControlFlow::Continue)?
493                {
494                    Ok(())
495                } else {
496                    Err(ControlFlow::Continue(anyhow!("env file not found")))
497                }
498            })
499            .await?;
500            let env = fs::read_to_string(&env_file).await?;
501            print!("{env}");
502            Ok(())
503        }
504        RpcCmd::Wait => {
505            let ready_file = common.test_dir().join("ready");
506            poll("ready file", || async {
507                if fs::try_exists(&ready_file)
508                    .await
509                    .context("ready file")
510                    .map_err(ControlFlow::Continue)?
511                {
512                    Ok(())
513                } else {
514                    Err(ControlFlow::Continue(anyhow!("ready file not found")))
515                }
516            })
517            .await?;
518            let env = fs::read_to_string(&ready_file).await?;
519            print!("{env}");
520
521            // Append invite code to devimint env
522            let test_dir = &common.test_dir();
523            let env_file = test_dir.join("env");
524            let invite_file = test_dir.join("cfg/invite-code");
525            if fs::try_exists(&env_file).await.ok().unwrap_or(false)
526                && fs::try_exists(&invite_file).await.ok().unwrap_or(false)
527            {
528                let invite = fs::read_to_string(&invite_file).await?;
529                let mut env_string = fs::read_to_string(&env_file).await?;
530                writeln!(env_string, r#"export FM_INVITE_CODE="{invite}""#)?;
531                // TODO: Audit that the environment access only happens in single-threaded code.
532                unsafe { std::env::set_var(FM_INVITE_CODE_ENV, invite) };
533                write_overwrite_async(env_file, env_string).await?;
534            }
535
536            Ok(())
537        }
538    }
539}