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