Skip to main content

fedimintd/
lib.rs

1#![deny(clippy::pedantic)]
2#![allow(clippy::cast_possible_wrap)]
3#![allow(clippy::missing_errors_doc)]
4#![allow(clippy::missing_panics_doc)]
5#![allow(clippy::must_use_candidate)]
6#![allow(clippy::return_self_not_must_use)]
7#![allow(clippy::large_futures)]
8
9mod metrics;
10
11use std::convert::Infallible;
12use std::env;
13use std::fmt::Write as _;
14use std::net::SocketAddr;
15use std::path::PathBuf;
16use std::time::Duration;
17
18use anyhow::Context as _;
19use bitcoin::Network;
20use clap::builder::BoolishValueParser;
21use clap::{ArgGroup, CommandFactory, FromArgMatches, Parser};
22use fedimint_core::db::Database;
23use fedimint_core::envs::{
24    FM_IROH_DNS_ENV, FM_IROH_RELAY_ENV, FM_USE_UNKNOWN_MODULE_ENV, is_env_var_set,
25    is_running_in_test_env,
26};
27use fedimint_core::module::registry::ModuleRegistry;
28use fedimint_core::module::{ApiAuth, CORE_CONSENSUS_VERSION};
29use fedimint_core::rustls::install_crypto_provider;
30use fedimint_core::task::TaskGroup;
31use fedimint_core::timing;
32use fedimint_core::util::{FmtCompact as _, SafeUrl, handle_version_hash_command};
33use fedimint_ln_server::LightningInit;
34use fedimint_logging::{LOG_CORE, LOG_SERVER, TracingSetup};
35use fedimint_meta_server::MetaInit;
36use fedimint_mint_server::MintInit;
37use fedimint_rocksdb::RocksDb;
38use fedimint_server::IrohNextApiSettings;
39use fedimint_server::config::ConfigGenSettings;
40use fedimint_server::config::io::{DB_FILE, PLAINTEXT_PASSWORD};
41use fedimint_server::core::ServerModuleInitRegistry;
42use fedimint_server::net::api::ApiSecrets;
43use fedimint_server_bitcoin_rpc::BitcoindClientWithFallback;
44use fedimint_server_bitcoin_rpc::bitcoind::BitcoindClient;
45use fedimint_server_bitcoin_rpc::esplora::EsploraClient;
46use fedimint_server_bitcoin_rpc::tracked::ServerBitcoinRpcTracked;
47use fedimint_server_core::ServerModuleInitRegistryExt;
48use fedimint_server_core::bitcoin_rpc::IServerBitcoinRpc;
49use fedimint_unknown_server::UnknownInit;
50use fedimint_wallet_server::WalletInit;
51use fedimintd_envs::{
52    FM_API_URL_ENV, FM_BIND_API_ENV, FM_BIND_API_NEXT_ENV, FM_BIND_METRICS_ENV, FM_BIND_P2P_ENV,
53    FM_BIND_TOKIO_CONSOLE_ENV, FM_BIND_UI_ENV, FM_BITCOIN_NETWORK_ENV, FM_BITCOIND_PASSWORD_ENV,
54    FM_BITCOIND_URL_ENV, FM_BITCOIND_URL_PASSWORD_FILE_ENV, FM_BITCOIND_USERNAME_ENV,
55    FM_DATA_DIR_ENV, FM_DB_CHECKPOINT_RETENTION_ENV, FM_DISABLE_META_MODULE_ENV,
56    FM_ENABLE_IROH_ENV, FM_ESPLORA_URL_ENV, FM_FORCE_API_SECRETS_ENV,
57    FM_IROH_API_MAX_CONNECTIONS_ENV, FM_IROH_API_MAX_REQUESTS_PER_CONNECTION_ENV,
58    FM_IROH_NEXT_ENABLE_ENV, FM_IROH_P2P_RELAY_ENV, FM_P2P_MAX_CONNECTION_AGE_SECS_ENV,
59    FM_P2P_URL_ENV, FM_PASSWORD_API_ENV, FM_PASSWORD_UI_ENV, FM_SESSION_TIMEOUT_SECS_ENV,
60};
61use futures::FutureExt as _;
62#[cfg(all(
63    not(feature = "jemalloc"),
64    not(any(target_env = "msvc", target_os = "ios", target_os = "android"))
65))]
66use tracing::warn;
67use tracing::{debug, error, info};
68
69use crate::metrics::APP_START_TS;
70
71/// Time we will wait before forcefully shutting down tasks
72const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10);
73
74#[derive(Parser)]
75#[command(version)]
76#[command(
77    group(
78        ArgGroup::new("bitcoind_password_auth")
79           .args(["bitcoind_password", "bitcoind_url_password_file"])
80           .multiple(false)
81    ),
82    group(
83        ArgGroup::new("bitcoind_auth")
84            .args(["bitcoind_url"])
85            .requires("bitcoind_password_auth")
86            .requires_all(["bitcoind_username", "bitcoind_url"])
87    ),
88    group(
89        ArgGroup::new("bitcoin_rpc")
90            .required(true)
91            .multiple(true)
92            .args(["bitcoind_url", "esplora_url"])
93    )
94)]
95struct ServerOpts {
96    /// Path to folder containing federation config files
97    #[arg(long = "data-dir", env = FM_DATA_DIR_ENV)]
98    data_dir: PathBuf,
99
100    /// Password gating the guardian admin UI on bind-ui. Optional: falls
101    /// back to reading password.private from data-dir, and if neither is
102    /// present the UI is served without a login form. Only safe when
103    /// bind-ui stays on a trusted interface (the default 127.0.0.1).
104    #[arg(long, env = FM_PASSWORD_UI_ENV)]
105    password_ui: Option<String>,
106
107    /// Password gating admin RPCs on the public API (WebSocket on bind-api
108    /// and iroh). Optional and never falls back to disk: when unset, admin
109    /// RPCs return 401 unconditionally, since the public API is always
110    /// network-reachable and must be enabled explicitly.
111    #[arg(long, env = FM_PASSWORD_API_ENV)]
112    password_api: Option<String>,
113
114    /// The bitcoin network of the federation
115    #[arg(long, env = FM_BITCOIN_NETWORK_ENV, default_value = "regtest")]
116    bitcoin_network: Network,
117
118    /// The username to use when connecting to bitcoind
119    #[arg(long, env = FM_BITCOIND_USERNAME_ENV)]
120    bitcoind_username: Option<String>,
121
122    /// The password to use when connecting to bitcoind
123    #[arg(long, env = FM_BITCOIND_PASSWORD_ENV)]
124    bitcoind_password: Option<String>,
125
126    /// Bitcoind RPC URL, e.g. <http://127.0.0.1:8332>
127    /// This should not include authentication parameters, they should be
128    /// included in `FM_BITCOIND_USERNAME` and `FM_BITCOIND_PASSWORD`
129    ///
130    /// With Esplora configured, reads remain bitcoind-first except block count
131    /// uses Esplora while bitcoind reports initial block download. Broadcast
132    /// remains bitcoind-first.
133    #[arg(long, env = FM_BITCOIND_URL_ENV)]
134    bitcoind_url: Option<SafeUrl>,
135
136    /// If set, the password part of `--bitcoind-url` will be set/replaced with
137    /// the content of this file.
138    ///
139    /// This is useful for setups that provide secret material via ramdisk
140    /// e.g. SOPS, age, etc.
141    ///
142    /// Note this is not meant to handle bitcoind's cookie file.
143    #[arg(long, env = FM_BITCOIND_URL_PASSWORD_FILE_ENV)]
144    bitcoind_url_password_file: Option<PathBuf>,
145
146    /// Trusted Esplora HTTP base URL, e.g. <https://mempool.space/api>
147    ///
148    /// With bitcoind configured, retries individual failed reads and supplies
149    /// block count while bitcoind reports initial block download. Hybrid
150    /// construction does not probe either backend or compare their chain
151    /// identities. Esplora can bootstrap while bitcoind is offline and must
152    /// be trusted to serve the intended chain; its chain selection is not
153    /// independently verified.
154    /// Transactions go to Esplora only after a bitcoind broadcast error.
155    /// See SECURITY.md for the trust model.
156    #[arg(long, env = FM_ESPLORA_URL_ENV)]
157    esplora_url: Option<SafeUrl>,
158
159    /// Address we bind to for p2p consensus communication
160    ///
161    /// Should be `0.0.0.0:8173` most of the time, as p2p connectivity is public
162    /// and direct, and the port should be open it in the firewall.
163    #[arg(long, env = FM_BIND_P2P_ENV, default_value = "0.0.0.0:8173")]
164    bind_p2p: SocketAddr,
165
166    /// Address we bind to for the API
167    ///
168    /// Should be `0.0.0.0:8174` most of the time, as api connectivity is public
169    /// and direct, and the port should be open it in the firewall.
170    #[arg(long, env = FM_BIND_API_ENV, default_value = "0.0.0.0:8174")]
171    bind_api: SocketAddr,
172
173    /// Address we bind to for exposing the Web UI
174    ///
175    /// Built-in web UI is exposed as an HTTP port, and typically should
176    /// have TLS terminated by Nginx/Traefik/etc. and forwarded to the locally
177    /// bind port.
178    #[arg(long, env = FM_BIND_UI_ENV, default_value = "127.0.0.1:8175")]
179    bind_ui: SocketAddr,
180
181    /// Our external address for communicating with our peers
182    ///
183    /// `fedimint://<fqdn>:8173` for TCP/TLS p2p connectivity (legacy/standard).
184    ///
185    /// Ignored when Iroh stack is used. (newer/experimental)
186    #[arg(long, env = FM_P2P_URL_ENV)]
187    p2p_url: Option<SafeUrl>,
188
189    /// Our API address for clients to connect to us
190    ///
191    /// Typically `wss://<fqdn>/ws/` for TCP/TLS connectivity (legacy/standard)
192    ///
193    /// Ignored when Iroh stack is used. (newer/experimental)
194    #[arg(long, env = FM_API_URL_ENV)]
195    api_url: Option<SafeUrl>,
196
197    /// Whether to use the Iroh networking stack instead of the legacy
198    /// TCP/TLS/websocket stack. Defaults to Iroh in production and to the
199    /// legacy stack in test environments (`cargo test` / `devimint`). Only
200    /// consulted at DKG / config generation time; existing federations keep the
201    /// stack baked into their config. Pass `--enable-iroh true/false` (or
202    /// `FM_ENABLE_IROH=true/false`) to override.
203    #[arg(long, env = FM_ENABLE_IROH_ENV, value_parser = BoolishValueParser::new())]
204    enable_iroh: Option<bool>,
205
206    /// Optional URL of the Iroh DNS server
207    #[arg(long, env = FM_IROH_DNS_ENV, requires = "enable_iroh")]
208    iroh_dns: Option<SafeUrl>,
209
210    /// Optional URLs of the Iroh relays to use for registering
211    #[arg(long, env = FM_IROH_RELAY_ENV, requires = "enable_iroh", value_delimiter = ',')]
212    iroh_relays: Vec<SafeUrl>,
213
214    /// Optional Iroh 1.0 relay URLs to use for guardian P2P
215    #[arg(long, env = FM_IROH_P2P_RELAY_ENV, value_delimiter = ',')]
216    iroh_p2p_relays: Vec<SafeUrl>,
217
218    /// Number of checkpoints from the current session to retain on disk
219    #[arg(long, env = FM_DB_CHECKPOINT_RETENTION_ENV, default_value = "1")]
220    db_checkpoint_retention: u64,
221
222    /// Exit the process if a consensus session is not completed within this
223    /// many seconds, relying on the process supervisor to restart fedimintd.
224    /// Restarting guardians has been observed to resolve stuck sessions.
225    #[arg(long, env = FM_SESSION_TIMEOUT_SECS_ENV, default_value = "3600")]
226    session_timeout_secs: u64,
227
228    /// Drop a p2p connection to a peer once it exceeds this age in seconds,
229    /// relying on the reconnection logic to re-establish it. Unset by
230    /// default, in which case connections are never dropped due to their age.
231    #[arg(long, env = FM_P2P_MAX_CONNECTION_AGE_SECS_ENV)]
232    p2p_max_connection_age_secs: Option<u64>,
233
234    /// Enable tokio console logging
235    #[arg(long, env = FM_BIND_TOKIO_CONSOLE_ENV)]
236    bind_tokio_console: Option<SocketAddr>,
237
238    /// Enable jaeger for tokio console logging
239    #[arg(long, default_value = "false")]
240    with_jaeger: bool,
241
242    /// Enable prometheus metrics
243    #[arg(long, env = FM_BIND_METRICS_ENV, default_value = "127.0.0.1:8176")]
244    bind_metrics: Option<SocketAddr>,
245
246    /// Comma separated list of API secrets.
247    ///
248    /// Setting it will enforce API authentication and make the Federation
249    /// "private".
250    ///
251    /// The first secret in the list is the "active" one that the peer will use
252    /// itself to connect to other peers. Any further one is accepted by
253    /// this peer, e.g. for the purposes of smooth rotation of secret
254    /// between users.
255    ///
256    /// Note that the value provided here will override any other settings
257    /// that the user might want to set via UI at runtime, etc.
258    /// In the future, managing secrets might be possible via Admin UI
259    /// and defaults will be provided via `FM_DEFAULT_API_SECRETS`.
260    #[arg(long, env = FM_FORCE_API_SECRETS_ENV, default_value = "")]
261    force_api_secrets: ApiSecrets,
262
263    /// Maximum number of concurrent Iroh API connections
264    #[arg(long = "iroh-api-max-connections", env = FM_IROH_API_MAX_CONNECTIONS_ENV, default_value = "1000")]
265    iroh_api_max_connections: usize,
266
267    /// Maximum number of parallel requests per Iroh API connection
268    #[arg(long = "iroh-api-max-requests-per-connection", env = FM_IROH_API_MAX_REQUESTS_PER_CONNECTION_ENV, default_value = "50")]
269    iroh_api_max_requests_per_connection: usize,
270
271    /// Enable the transitional Iroh 1.0 API endpoint alongside Iroh 0.35.
272    ///
273    /// For a federation configured with the legacy Iroh API, this is a runtime
274    /// setting independent of the DKG-only `--enable-iroh` option. It is
275    /// enabled by default. Once the endpoint is advertised, it must remain
276    /// enabled.
277    #[arg(
278        long,
279        env = FM_IROH_NEXT_ENABLE_ENV,
280        default_value_t = true,
281        action = clap::ArgAction::Set,
282        num_args = 0..=1,
283        default_missing_value = "true",
284    )]
285    enable_iroh_next: bool,
286
287    /// Bind address for the transitional Iroh 1.0 API endpoint
288    #[arg(long, env = FM_BIND_API_NEXT_ENV)]
289    bind_api_next: Option<SocketAddr>,
290}
291
292impl ServerOpts {
293    pub async fn get_bitcoind_url_and_password(&self) -> anyhow::Result<(SafeUrl, String)> {
294        let url = self
295            .bitcoind_url
296            .clone()
297            .ok_or_else(|| anyhow::anyhow!("No bitcoind url set"))?;
298        if let Some(password_file) = self.bitcoind_url_password_file.as_ref() {
299            let password = tokio::fs::read_to_string(password_file)
300                .await
301                .context("Failed to read the password")?
302                .trim()
303                .to_owned();
304            Ok((url, password))
305        } else {
306            let password = self
307                .bitcoind_password
308                .clone()
309                .expect("FM_BITCOIND_URL is set but FM_BITCOIND_PASSWORD is not");
310            Ok((url, password))
311        }
312    }
313}
314
315/// Block the thread and run a Fedimintd server
316///
317/// # Arguments
318///
319/// * `module_init_registry` - The registry of available modules.
320///
321/// * `code_version_hash` - The git hash of the code that the `fedimintd` binary
322///   is being built from. This is used mostly for information purposes
323///   (`fedimintd version-hash`). See `fedimint-build` crate for easy way to
324///   obtain it.
325///
326/// * `code_version_vendor_suffix` - An optional vendor string appended to the
327///   internal Fedimint release version, to distinguish binaries built by
328///   different vendors, usually with a different set of modules. It is encoded
329///   as `SemVer` build metadata and therefore must contain dot-separated,
330///   non-empty identifiers with only ASCII alphanumeric characters and hyphens.
331///   Setup/DKG compatibility and consensus config generation require the same
332///   exact optional vendor string as well as the same `major.minor` series.
333#[allow(clippy::too_many_lines)]
334pub async fn run(
335    module_init_registry: ServerModuleInitRegistry,
336    code_version_hash: &str,
337    code_version_vendor_suffix: Option<&str>,
338) -> anyhow::Result<Infallible> {
339    assert_eq!(
340        env!("FEDIMINT_BUILD_CODE_VERSION").len(),
341        code_version_hash.len(),
342        "version_hash must have an expected length"
343    );
344
345    handle_version_hash_command(code_version_hash);
346
347    let fedimint_version = env!("CARGO_PKG_VERSION");
348
349    APP_START_TS
350        .with_label_values(&[fedimint_version, code_version_hash])
351        .set(fedimint_core::time::duration_since_epoch().as_secs() as i64);
352
353    let server_opts = {
354        // Collect env vars from all registered modules and append them to the
355        // long-help text so operators can discover them via `fedimintd --help`.
356        let mut module_env_help = String::from("\nModule environment variables:\n");
357        for (_kind, module_init) in module_init_registry.iter() {
358            for doc in module_init.get_documented_env_vars() {
359                let _ = writeln!(module_env_help, "  {:40}  {}", doc.name, doc.description);
360            }
361        }
362        let matches = ServerOpts::command()
363            .after_long_help(module_env_help)
364            .get_matches();
365        ServerOpts::from_arg_matches(&matches)
366            .expect("clap arg matches must be valid after parsing")
367    };
368
369    let mut tracing_builder = TracingSetup::default();
370
371    tracing_builder
372        .tokio_console_bind(server_opts.bind_tokio_console)
373        .with_jaeger(server_opts.with_jaeger);
374
375    tracing_builder.init().map_err(anyhow::Error::from).unwrap();
376
377    info!("Starting fedimintd (version: {fedimint_version} version_hash: {code_version_hash})");
378
379    #[cfg(all(
380        not(feature = "jemalloc"),
381        not(any(target_env = "msvc", target_os = "ios", target_os = "android"))
382    ))]
383    warn!(
384        target: LOG_SERVER,
385        "fedimintd was built without the `jemalloc` feature. rocksdb is prone to memory \
386         fragmentation with the default allocator; consider rebuilding with `--features jemalloc`."
387    );
388
389    debug!(
390        target: LOG_SERVER,
391        core_consensus = %CORE_CONSENSUS_VERSION,
392        "Supported core consensus version",
393    );
394
395    let code_version_str = code_version_vendor_suffix.map_or_else(
396        || fedimint_version.to_string(),
397        |suffix| format!("{fedimint_version}+{suffix}"),
398    );
399    fedimint_core::version::DkgVersion::parse(&code_version_str)
400        .context("Invalid Fedimint version vendor string")?;
401
402    let timing_total_runtime = timing::TimeReporter::new("total-runtime").info();
403
404    let root_task_group = TaskGroup::new();
405
406    if let Some(bind_metrics) = server_opts.bind_metrics.as_ref() {
407        info!(
408            target: LOG_SERVER,
409            url = %format!("http://{}/metrics", bind_metrics),
410            "Initializing metrics server",
411        );
412        fedimint_metrics::spawn_api_server(*bind_metrics, root_task_group.clone()).await?;
413    }
414
415    let enable_iroh = server_opts.enable_iroh.unwrap_or(!is_running_in_test_env());
416    let iroh_next_api_settings = if server_opts.enable_iroh_next {
417        Some(IrohNextApiSettings::new(server_opts.bind_api_next))
418    } else {
419        None
420    };
421
422    let settings = ConfigGenSettings {
423        p2p_bind: server_opts.bind_p2p,
424        api_bind: server_opts.bind_api,
425        ui_bind: server_opts.bind_ui,
426        p2p_url: server_opts.p2p_url.clone(),
427        api_url: server_opts.api_url.clone(),
428        enable_iroh,
429        iroh_dns: server_opts.iroh_dns.clone(),
430        iroh_relays: server_opts.iroh_relays.clone(),
431        network: server_opts.bitcoin_network,
432        available_modules: module_init_registry.kinds(),
433        default_modules: module_init_registry.default_modules(),
434    };
435
436    let db = Database::new(
437        RocksDb::build(server_opts.data_dir.join(DB_FILE))
438            .open()
439            .await
440            .map_err(anyhow::Error::from)
441            .unwrap(),
442        ModuleRegistry::default(),
443    );
444
445    let dyn_server_bitcoin_rpc = match (
446        server_opts.bitcoind_url.as_ref(),
447        server_opts.esplora_url.as_ref(),
448    ) {
449        (Some(_), None) => {
450            let bitcoind_username = server_opts
451                .bitcoind_username
452                .clone()
453                .expect("FM_BITCOIND_URL is set but FM_BITCOIND_USERNAME is not");
454            let (bitcoind_url, bitcoind_password) = server_opts
455                .get_bitcoind_url_and_password()
456                .await
457                .expect("Failed to get bitcoind url");
458            BitcoindClient::new(bitcoind_username, bitcoind_password, &bitcoind_url)
459                .unwrap()
460                .into_dyn()
461        }
462        (None, Some(url)) => EsploraClient::new(url).unwrap().into_dyn(),
463        (Some(_), Some(esplora_url)) => {
464            let bitcoind_username = server_opts
465                .bitcoind_username
466                .clone()
467                .expect("FM_BITCOIND_URL is set but FM_BITCOIND_USERNAME is not");
468            let (bitcoind_url, bitcoind_password) = server_opts
469                .get_bitcoind_url_and_password()
470                .await
471                .expect("Failed to get bitcoind url");
472            BitcoindClientWithFallback::new(
473                bitcoind_username,
474                bitcoind_password,
475                &bitcoind_url,
476                esplora_url,
477            )
478            .await
479            .unwrap()
480            .into_dyn()
481        }
482        _ => unreachable!("ArgGroup already enforced at least one Bitcoin backend"),
483    };
484    let dyn_server_bitcoin_rpc =
485        ServerBitcoinRpcTracked::new(dyn_server_bitcoin_rpc, "server").into_dyn();
486
487    root_task_group.install_kill_handler();
488
489    install_crypto_provider().await;
490
491    // The UI password falls back to the legacy password.private file on disk
492    // if its env var is not set, since the UI defaults to a loopback bind.
493    // The API password never falls back: the public admin API is always
494    // network-reachable, so it must be enabled explicitly via its env var or
495    // else admin RPCs return 401. Absence of a password for a given plane opts
496    // that plane into passwordless mode (UI) or disabled admin RPCs (API).
497    let password_file = std::fs::read_to_string(server_opts.data_dir.join(PLAINTEXT_PASSWORD))
498        .ok()
499        .map(|s| s.trim().to_owned());
500
501    let auth_ui = server_opts.password_ui.or(password_file).map(ApiAuth::new);
502    let auth_api = server_opts.password_api.map(ApiAuth::new);
503
504    let task_group = root_task_group.clone();
505    let code_version_hash = code_version_hash.to_string();
506    root_task_group.spawn_cancellable("main", async move {
507        fedimint_server::run_with_iroh_p2p_relays_and_next_api(
508            server_opts.data_dir,
509            auth_ui,
510            auth_api,
511            server_opts.force_api_secrets,
512            settings,
513            db,
514            code_version_str,
515            code_version_hash,
516            module_init_registry,
517            task_group,
518            dyn_server_bitcoin_rpc,
519            Box::new(fedimint_server_ui::setup::router),
520            Box::new(fedimint_server_ui::dashboard::router),
521            server_opts.db_checkpoint_retention,
522            Duration::from_secs(server_opts.session_timeout_secs),
523            server_opts
524                .p2p_max_connection_age_secs
525                .map(Duration::from_secs),
526            fedimint_server::ConnectionLimits::new(
527                server_opts.iroh_api_max_connections,
528                server_opts.iroh_api_max_requests_per_connection,
529            ),
530            server_opts.iroh_p2p_relays,
531            iroh_next_api_settings,
532        )
533        .await
534        .unwrap_or_else(|err| panic!("Main task returned error: {}", err.fmt_compact()));
535    });
536
537    let shutdown_future = root_task_group
538        .make_handle()
539        .make_shutdown_rx()
540        .then(|()| async {
541            info!(target: LOG_CORE, "Shutdown called");
542        });
543
544    shutdown_future.await;
545
546    debug!(target: LOG_CORE, "Terminating main task");
547
548    if let Err(err) = root_task_group.join_all(Some(SHUTDOWN_TIMEOUT)).await {
549        error!(target: LOG_CORE, err = %err.fmt_compact(), "Error while shutting down task group");
550    }
551
552    debug!(target: LOG_CORE, "Shutdown complete");
553
554    fedimint_logging::shutdown();
555
556    drop(timing_total_runtime);
557
558    std::process::exit(-1);
559}
560
561pub fn default_modules() -> ServerModuleInitRegistry {
562    let mut server_gens = ServerModuleInitRegistry::new();
563
564    server_gens.attach(MintInit);
565    server_gens.attach(fedimint_mintv2_server::MintInit);
566
567    server_gens.attach(WalletInit);
568    server_gens.attach(fedimint_walletv2_server::WalletInit);
569
570    server_gens.attach(LightningInit);
571    server_gens.attach(fedimint_lnv2_server::LightningInit);
572
573    if !is_env_var_set(FM_DISABLE_META_MODULE_ENV) {
574        server_gens.attach(MetaInit);
575    }
576
577    if is_env_var_set(FM_USE_UNKNOWN_MODULE_ENV) {
578        server_gens.attach(UnknownInit);
579    }
580
581    server_gens
582}
583
584#[cfg(test)]
585mod tests;