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