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::{ArgGroup, CommandFactory, FromArgMatches, Parser};
21use fedimint_core::db::Database;
22use fedimint_core::envs::{
23    FM_IROH_DNS_ENV, FM_IROH_RELAY_ENV, FM_USE_UNKNOWN_MODULE_ENV, is_env_var_set,
24};
25use fedimint_core::module::CORE_CONSENSUS_VERSION;
26use fedimint_core::module::registry::ModuleRegistry;
27use fedimint_core::rustls::install_crypto_provider;
28use fedimint_core::task::TaskGroup;
29use fedimint_core::timing;
30use fedimint_core::util::{FmtCompactAnyhow as _, SafeUrl, handle_version_hash_command};
31use fedimint_ln_server::LightningInit;
32use fedimint_logging::{LOG_CORE, LOG_SERVER, TracingSetup};
33use fedimint_meta_server::MetaInit;
34use fedimint_mint_server::MintInit;
35use fedimint_rocksdb::RocksDb;
36use fedimint_server::config::ConfigGenSettings;
37use fedimint_server::config::io::DB_FILE;
38use fedimint_server::core::ServerModuleInitRegistry;
39use fedimint_server::net::api::ApiSecrets;
40use fedimint_server_bitcoin_rpc::BitcoindClientWithFallback;
41use fedimint_server_bitcoin_rpc::bitcoind::BitcoindClient;
42use fedimint_server_bitcoin_rpc::esplora::EsploraClient;
43use fedimint_server_bitcoin_rpc::tracked::ServerBitcoinRpcTracked;
44use fedimint_server_core::ServerModuleInitRegistryExt;
45use fedimint_server_core::bitcoin_rpc::IServerBitcoinRpc;
46use fedimint_unknown_server::UnknownInit;
47use fedimint_wallet_server::WalletInit;
48use fedimintd_envs::{
49    FM_API_URL_ENV, FM_BIND_API_ENV, FM_BIND_METRICS_ENV, FM_BIND_P2P_ENV,
50    FM_BIND_TOKIO_CONSOLE_ENV, FM_BIND_UI_ENV, FM_BITCOIN_NETWORK_ENV, FM_BITCOIND_PASSWORD_ENV,
51    FM_BITCOIND_URL_ENV, FM_BITCOIND_URL_PASSWORD_FILE_ENV, FM_BITCOIND_USERNAME_ENV,
52    FM_DATA_DIR_ENV, FM_DB_CHECKPOINT_RETENTION_ENV, FM_DISABLE_META_MODULE_ENV,
53    FM_ENABLE_IROH_ENV, FM_ESPLORA_URL_ENV, FM_FORCE_API_SECRETS_ENV,
54    FM_IROH_API_MAX_CONNECTIONS_ENV, FM_IROH_API_MAX_REQUESTS_PER_CONNECTION_ENV, FM_P2P_URL_ENV,
55};
56use futures::FutureExt as _;
57#[cfg(all(
58    not(feature = "jemalloc"),
59    not(any(target_env = "msvc", target_os = "ios", target_os = "android"))
60))]
61use tracing::warn;
62use tracing::{debug, error, info};
63
64use crate::metrics::APP_START_TS;
65
66/// Time we will wait before forcefully shutting down tasks
67const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10);
68
69#[derive(Parser)]
70#[command(version)]
71#[command(
72    group(
73        ArgGroup::new("bitcoind_password_auth")
74           .args(["bitcoind_password", "bitcoind_url_password_file"])
75           .multiple(false)
76    ),
77    group(
78        ArgGroup::new("bitcoind_auth")
79            .args(["bitcoind_url"])
80            .requires("bitcoind_password_auth")
81            .requires_all(["bitcoind_username", "bitcoind_url"])
82    ),
83    group(
84        ArgGroup::new("bitcoin_rpc")
85            .required(true)
86            .multiple(true)
87            .args(["bitcoind_url", "esplora_url"])
88    )
89)]
90struct ServerOpts {
91    /// Path to folder containing federation config files
92    #[arg(long = "data-dir", env = FM_DATA_DIR_ENV)]
93    data_dir: PathBuf,
94
95    /// The bitcoin network of the federation
96    #[arg(long, env = FM_BITCOIN_NETWORK_ENV, default_value = "regtest")]
97    bitcoin_network: Network,
98
99    /// The username to use when connecting to bitcoind
100    #[arg(long, env = FM_BITCOIND_USERNAME_ENV)]
101    bitcoind_username: Option<String>,
102
103    /// The password to use when connecting to bitcoind
104    #[arg(long, env = FM_BITCOIND_PASSWORD_ENV)]
105    bitcoind_password: Option<String>,
106
107    /// Bitcoind RPC URL, e.g. <http://127.0.0.1:8332>
108    /// This should not include authentication parameters, they should be
109    /// included in `FM_BITCOIND_USERNAME` and `FM_BITCOIND_PASSWORD`
110    #[arg(long, env = FM_BITCOIND_URL_ENV)]
111    bitcoind_url: Option<SafeUrl>,
112
113    /// If set, the password part of `--bitcoind-url` will be set/replaced with
114    /// the content of this file.
115    ///
116    /// This is useful for setups that provide secret material via ramdisk
117    /// e.g. SOPS, age, etc.
118    ///
119    /// Note this is not meant to handle bitcoind's cookie file.
120    #[arg(long, env = FM_BITCOIND_URL_PASSWORD_FILE_ENV)]
121    bitcoind_url_password_file: Option<PathBuf>,
122
123    /// Esplora HTTP base URL, e.g. <https://mempool.space/api>
124    #[arg(long, env = FM_ESPLORA_URL_ENV)]
125    esplora_url: Option<SafeUrl>,
126
127    /// Address we bind to for p2p consensus communication
128    ///
129    /// Should be `0.0.0.0:8173` most of the time, as p2p connectivity is public
130    /// and direct, and the port should be open it in the firewall.
131    #[arg(long, env = FM_BIND_P2P_ENV, default_value = "0.0.0.0:8173")]
132    bind_p2p: SocketAddr,
133
134    /// Address we bind to for the API
135    ///
136    /// Should be `0.0.0.0:8174` most of the time, as api connectivity is public
137    /// and direct, and the port should be open it in the firewall.
138    #[arg(long, env = FM_BIND_API_ENV, default_value = "0.0.0.0:8174")]
139    bind_api: SocketAddr,
140
141    /// Address we bind to for exposing the Web UI
142    ///
143    /// Built-in web UI is exposed as an HTTP port, and typically should
144    /// have TLS terminated by Nginx/Traefik/etc. and forwarded to the locally
145    /// bind port.
146    #[arg(long, env = FM_BIND_UI_ENV, default_value = "127.0.0.1:8175")]
147    bind_ui: SocketAddr,
148
149    /// Our external address for communicating with our peers
150    ///
151    /// `fedimint://<fqdn>:8173` for TCP/TLS p2p connectivity (legacy/standard).
152    ///
153    /// Ignored when Iroh stack is used. (newer/experimental)
154    #[arg(long, env = FM_P2P_URL_ENV)]
155    p2p_url: Option<SafeUrl>,
156
157    /// Our API address for clients to connect to us
158    ///
159    /// Typically `wss://<fqdn>/ws/` for TCP/TLS connectivity (legacy/standard)
160    ///
161    /// Ignored when Iroh stack is used. (newer/experimental)
162    #[arg(long, env = FM_API_URL_ENV)]
163    api_url: Option<SafeUrl>,
164
165    #[arg(long, env = FM_ENABLE_IROH_ENV)]
166    enable_iroh: bool,
167
168    /// Optional URL of the Iroh DNS server
169    #[arg(long, env = FM_IROH_DNS_ENV, requires = "enable_iroh")]
170    iroh_dns: Option<SafeUrl>,
171
172    /// Optional URLs of the Iroh relays to use for registering
173    #[arg(long, env = FM_IROH_RELAY_ENV, requires = "enable_iroh", value_delimiter = ',')]
174    iroh_relays: Vec<SafeUrl>,
175
176    /// Number of checkpoints from the current session to retain on disk
177    #[arg(long, env = FM_DB_CHECKPOINT_RETENTION_ENV, default_value = "1")]
178    db_checkpoint_retention: u64,
179
180    /// Enable tokio console logging
181    #[arg(long, env = FM_BIND_TOKIO_CONSOLE_ENV)]
182    bind_tokio_console: Option<SocketAddr>,
183
184    /// Enable jaeger for tokio console logging
185    #[arg(long, default_value = "false")]
186    with_jaeger: bool,
187
188    /// Enable prometheus metrics
189    #[arg(long, env = FM_BIND_METRICS_ENV, default_value = "127.0.0.1:8176")]
190    bind_metrics: Option<SocketAddr>,
191
192    /// Comma separated list of API secrets.
193    ///
194    /// Setting it will enforce API authentication and make the Federation
195    /// "private".
196    ///
197    /// The first secret in the list is the "active" one that the peer will use
198    /// itself to connect to other peers. Any further one is accepted by
199    /// this peer, e.g. for the purposes of smooth rotation of secret
200    /// between users.
201    ///
202    /// Note that the value provided here will override any other settings
203    /// that the user might want to set via UI at runtime, etc.
204    /// In the future, managing secrets might be possible via Admin UI
205    /// and defaults will be provided via `FM_DEFAULT_API_SECRETS`.
206    #[arg(long, env = FM_FORCE_API_SECRETS_ENV, default_value = "")]
207    force_api_secrets: ApiSecrets,
208
209    /// Maximum number of concurrent Iroh API connections
210    #[arg(long = "iroh-api-max-connections", env = FM_IROH_API_MAX_CONNECTIONS_ENV, default_value = "1000")]
211    iroh_api_max_connections: usize,
212
213    /// Maximum number of parallel requests per Iroh API connection
214    #[arg(long = "iroh-api-max-requests-per-connection", env = FM_IROH_API_MAX_REQUESTS_PER_CONNECTION_ENV, default_value = "50")]
215    iroh_api_max_requests_per_connection: usize,
216}
217
218impl ServerOpts {
219    pub async fn get_bitcoind_url_and_password(&self) -> anyhow::Result<(SafeUrl, String)> {
220        let url = self
221            .bitcoind_url
222            .clone()
223            .ok_or_else(|| anyhow::anyhow!("No bitcoind url set"))?;
224        if let Some(password_file) = self.bitcoind_url_password_file.as_ref() {
225            let password = tokio::fs::read_to_string(password_file)
226                .await
227                .context("Failed to read the password")?
228                .trim()
229                .to_owned();
230            Ok((url, password))
231        } else {
232            let password = self
233                .bitcoind_password
234                .clone()
235                .expect("FM_BITCOIND_URL is set but FM_BITCOIND_PASSWORD is not");
236            Ok((url, password))
237        }
238    }
239}
240
241/// Block the thread and run a Fedimintd server
242///
243/// # Arguments
244///
245/// * `module_init_registry` - The registry of available modules.
246///
247/// * `code_version_hash` - The git hash of the code that the `fedimintd` binary
248///   is being built from. This is used mostly for information purposes
249///   (`fedimintd version-hash`). See `fedimint-build` crate for easy way to
250///   obtain it.
251///
252/// * `code_version_vendor_suffix` - An optional suffix that will be appended to
253///   the internal fedimint release version, to distinguish binaries built by
254///   different vendors, usually with a different set of modules. Currently DKG
255///   will enforce that the combined `code_version` is the same between all
256///   peers.
257#[allow(clippy::too_many_lines)]
258pub async fn run(
259    module_init_registry: ServerModuleInitRegistry,
260    code_version_hash: &str,
261    code_version_vendor_suffix: Option<&str>,
262) -> anyhow::Result<Infallible> {
263    assert_eq!(
264        env!("FEDIMINT_BUILD_CODE_VERSION").len(),
265        code_version_hash.len(),
266        "version_hash must have an expected length"
267    );
268
269    handle_version_hash_command(code_version_hash);
270
271    let fedimint_version = env!("CARGO_PKG_VERSION");
272
273    APP_START_TS
274        .with_label_values(&[fedimint_version, code_version_hash])
275        .set(fedimint_core::time::duration_since_epoch().as_secs() as i64);
276
277    let server_opts = {
278        // Collect env vars from all registered modules and append them to the
279        // long-help text so operators can discover them via `fedimintd --help`.
280        let mut module_env_help = String::from("\nModule environment variables:\n");
281        for (_kind, module_init) in module_init_registry.iter() {
282            for doc in module_init.get_documented_env_vars() {
283                let _ = writeln!(module_env_help, "  {:40}  {}", doc.name, doc.description);
284            }
285        }
286        let matches = ServerOpts::command()
287            .after_long_help(module_env_help)
288            .get_matches();
289        ServerOpts::from_arg_matches(&matches)
290            .expect("clap arg matches must be valid after parsing")
291    };
292
293    let mut tracing_builder = TracingSetup::default();
294
295    tracing_builder
296        .tokio_console_bind(server_opts.bind_tokio_console)
297        .with_jaeger(server_opts.with_jaeger);
298
299    tracing_builder.init().unwrap();
300
301    info!("Starting fedimintd (version: {fedimint_version} version_hash: {code_version_hash})");
302
303    #[cfg(all(
304        not(feature = "jemalloc"),
305        not(any(target_env = "msvc", target_os = "ios", target_os = "android"))
306    ))]
307    warn!(
308        target: LOG_SERVER,
309        "fedimintd was built without the `jemalloc` feature. rocksdb is prone to memory \
310         fragmentation with the default allocator; consider rebuilding with `--features jemalloc`."
311    );
312
313    debug!(
314        target: LOG_SERVER,
315        core_consensus = %CORE_CONSENSUS_VERSION,
316        "Supported core consensus version",
317    );
318    for (kind, module) in module_init_registry.iter() {
319        let supported = module.supported_api_versions();
320        debug!(
321            target: LOG_SERVER,
322            module = %kind,
323            supported = %supported,
324            "Supported module versions",
325        );
326    }
327    let code_version_str = code_version_vendor_suffix.map_or_else(
328        || fedimint_version.to_string(),
329        |suffix| format!("{fedimint_version}+{suffix}"),
330    );
331
332    let timing_total_runtime = timing::TimeReporter::new("total-runtime").info();
333
334    let root_task_group = TaskGroup::new();
335
336    if let Some(bind_metrics) = server_opts.bind_metrics.as_ref() {
337        info!(
338            target: LOG_SERVER,
339            url = %format!("http://{}/metrics", bind_metrics),
340            "Initializing metrics server",
341        );
342        fedimint_metrics::spawn_api_server(*bind_metrics, root_task_group.clone()).await?;
343    }
344
345    let settings = ConfigGenSettings {
346        p2p_bind: server_opts.bind_p2p,
347        api_bind: server_opts.bind_api,
348        ui_bind: server_opts.bind_ui,
349        p2p_url: server_opts.p2p_url.clone(),
350        api_url: server_opts.api_url.clone(),
351        enable_iroh: server_opts.enable_iroh,
352        iroh_dns: server_opts.iroh_dns.clone(),
353        iroh_relays: server_opts.iroh_relays.clone(),
354        network: server_opts.bitcoin_network,
355        available_modules: module_init_registry.kinds(),
356        default_modules: module_init_registry.default_modules(),
357    };
358
359    let db = Database::new(
360        RocksDb::build(server_opts.data_dir.join(DB_FILE))
361            .open()
362            .await
363            .unwrap(),
364        ModuleRegistry::default(),
365    );
366
367    let dyn_server_bitcoin_rpc = match (
368        server_opts.bitcoind_url.as_ref(),
369        server_opts.esplora_url.as_ref(),
370    ) {
371        (Some(_), None) => {
372            let bitcoind_username = server_opts
373                .bitcoind_username
374                .clone()
375                .expect("FM_BITCOIND_URL is set but FM_BITCOIND_USERNAME is not");
376            let (bitcoind_url, bitcoind_password) = server_opts
377                .get_bitcoind_url_and_password()
378                .await
379                .expect("Failed to get bitcoind url");
380            BitcoindClient::new(bitcoind_username, bitcoind_password, &bitcoind_url)
381                .unwrap()
382                .into_dyn()
383        }
384        (None, Some(url)) => EsploraClient::new(url).unwrap().into_dyn(),
385        (Some(_), Some(esplora_url)) => {
386            let bitcoind_username = server_opts
387                .bitcoind_username
388                .clone()
389                .expect("FM_BITCOIND_URL is set but FM_BITCOIND_USERNAME is not");
390            let (bitcoind_url, bitcoind_password) = server_opts
391                .get_bitcoind_url_and_password()
392                .await
393                .expect("Failed to get bitcoind url");
394            BitcoindClientWithFallback::new(
395                bitcoind_username,
396                bitcoind_password,
397                &bitcoind_url,
398                esplora_url,
399            )
400            .unwrap()
401            .into_dyn()
402        }
403        _ => unreachable!("ArgGroup already enforced XOR relation"),
404    };
405    let dyn_server_bitcoin_rpc =
406        ServerBitcoinRpcTracked::new(dyn_server_bitcoin_rpc, "server").into_dyn();
407
408    root_task_group.install_kill_handler();
409
410    install_crypto_provider().await;
411
412    let task_group = root_task_group.clone();
413    root_task_group.spawn_cancellable("main", async move {
414        fedimint_server::run(
415            server_opts.data_dir,
416            server_opts.force_api_secrets,
417            settings,
418            db,
419            code_version_str,
420            module_init_registry,
421            task_group,
422            dyn_server_bitcoin_rpc,
423            Box::new(fedimint_server_ui::setup::router),
424            Box::new(fedimint_server_ui::dashboard::router),
425            server_opts.db_checkpoint_retention,
426            fedimint_server::ConnectionLimits::new(
427                server_opts.iroh_api_max_connections,
428                server_opts.iroh_api_max_requests_per_connection,
429            ),
430        )
431        .await
432        .unwrap_or_else(|err| panic!("Main task returned error: {}", err.fmt_compact_anyhow()));
433    });
434
435    let shutdown_future = root_task_group
436        .make_handle()
437        .make_shutdown_rx()
438        .then(|()| async {
439            info!(target: LOG_CORE, "Shutdown called");
440        });
441
442    shutdown_future.await;
443
444    debug!(target: LOG_CORE, "Terminating main task");
445
446    if let Err(err) = root_task_group.join_all(Some(SHUTDOWN_TIMEOUT)).await {
447        error!(target: LOG_CORE, err = %err.fmt_compact_anyhow(), "Error while shutting down task group");
448    }
449
450    debug!(target: LOG_CORE, "Shutdown complete");
451
452    fedimint_logging::shutdown();
453
454    drop(timing_total_runtime);
455
456    std::process::exit(-1);
457}
458
459pub fn default_modules() -> ServerModuleInitRegistry {
460    let mut server_gens = ServerModuleInitRegistry::new();
461
462    server_gens.attach(MintInit);
463    server_gens.attach(fedimint_mintv2_server::MintInit);
464
465    server_gens.attach(WalletInit);
466    server_gens.attach(fedimint_walletv2_server::WalletInit);
467
468    server_gens.attach(LightningInit);
469    server_gens.attach(fedimint_lnv2_server::LightningInit);
470
471    if !is_env_var_set(FM_DISABLE_META_MODULE_ENV) {
472        server_gens.attach(MetaInit);
473    }
474
475    if is_env_var_set(FM_USE_UNKNOWN_MODULE_ENV) {
476        server_gens.attach(UnknownInit);
477    }
478
479    server_gens
480}