fedimint_server/
lib.rs

1#![deny(clippy::pedantic)]
2#![allow(clippy::cast_possible_truncation)]
3#![allow(clippy::cast_possible_wrap)]
4#![allow(clippy::cast_precision_loss)]
5#![allow(clippy::cast_sign_loss)]
6#![allow(clippy::doc_markdown)]
7#![allow(clippy::missing_errors_doc)]
8#![allow(clippy::missing_panics_doc)]
9#![allow(clippy::module_name_repetitions)]
10#![allow(clippy::must_use_candidate)]
11#![allow(clippy::needless_lifetimes)]
12#![allow(clippy::ref_option)]
13#![allow(clippy::return_self_not_must_use)]
14#![allow(clippy::similar_names)]
15#![allow(clippy::too_many_lines)]
16#![allow(clippy::needless_pass_by_value)]
17#![allow(clippy::manual_let_else)]
18#![allow(clippy::match_wildcard_for_single_variants)]
19#![allow(clippy::trivially_copy_pass_by_ref)]
20
21//! Server side fedimint module traits
22
23extern crate fedimint_core;
24pub mod connection_limits;
25pub mod db;
26
27use std::fs;
28use std::path::{Path, PathBuf};
29use std::time::Duration;
30
31use anyhow::Context;
32use config::ServerConfig;
33use config::io::{PLAINTEXT_PASSWORD, read_server_config};
34pub use connection_limits::ConnectionLimits;
35use fedimint_aead::random_salt;
36use fedimint_connectors::ConnectorRegistry;
37use fedimint_core::config::P2PMessage;
38use fedimint_core::db::{Database, DatabaseTransaction, IDatabaseTransactionOpsCoreTyped as _};
39use fedimint_core::epoch::ConsensusItem;
40use fedimint_core::net::peers::DynP2PConnections;
41use fedimint_core::task::{TaskGroup, sleep};
42use fedimint_core::util::write_new;
43use fedimint_logging::LOG_CONSENSUS;
44pub use fedimint_server_core as core;
45use fedimint_server_core::ServerModuleInitRegistry;
46use fedimint_server_core::bitcoin_rpc::DynServerBitcoinRpc;
47use fedimint_server_core::dashboard_ui::DynDashboardApi;
48use fedimint_server_core::setup_ui::{DynSetupApi, ISetupApi};
49use jsonrpsee::RpcModule;
50use net::api::ApiSecrets;
51use net::p2p::P2PStatusReceivers;
52use net::p2p_connector::IrohConnector;
53use tokio::net::TcpListener;
54use tracing::info;
55
56use crate::config::ConfigGenSettings;
57use crate::config::io::{
58    SALT_FILE, finalize_password_change, recover_interrupted_password_change, trim_password,
59    write_server_config,
60};
61use crate::config::setup::SetupApi;
62use crate::db::{ServerInfo, ServerInfoKey};
63use crate::fedimint_core::net::peers::IP2PConnections;
64use crate::metrics::initialize_gauge_metrics;
65use crate::net::api::announcement::start_api_announcement_service;
66use crate::net::api::guardian_metadata::start_guardian_metadata_service;
67use crate::net::p2p::{ReconnectP2PConnections, p2p_status_channels};
68use crate::net::p2p_connector::{IP2PConnector, TlsTcpConnector};
69
70pub mod metrics;
71
72/// The actual implementation of consensus
73pub mod consensus;
74
75/// Networking for mint-to-mint and client-to-mint communiccation
76pub mod net;
77
78/// Fedimint toplevel config
79pub mod config;
80
81/// A function/closure type for handling dashboard UI
82pub type DashboardUiRouter = Box<dyn Fn(DynDashboardApi) -> axum::Router + Send>;
83
84/// A function/closure type for handling setup UI
85pub type SetupUiRouter = Box<dyn Fn(DynSetupApi) -> axum::Router + Send>;
86
87#[allow(clippy::too_many_arguments)]
88pub async fn run(
89    data_dir: PathBuf,
90    force_api_secrets: ApiSecrets,
91    settings: ConfigGenSettings,
92    db: Database,
93    code_version_str: String,
94    module_init_registry: ServerModuleInitRegistry,
95    task_group: TaskGroup,
96    bitcoin_rpc: DynServerBitcoinRpc,
97    setup_ui_router: SetupUiRouter,
98    dashboard_ui_router: DashboardUiRouter,
99    db_checkpoint_retention: u64,
100    iroh_api_limits: ConnectionLimits,
101) -> anyhow::Result<()> {
102    let (cfg, connections, p2p_status_receivers) = match get_config(&data_dir)? {
103        Some(cfg) => {
104            let connector = if cfg.consensus.iroh_endpoints.is_empty() {
105                TlsTcpConnector::new(
106                    cfg.tls_config(),
107                    settings.p2p_bind,
108                    cfg.local.p2p_endpoints.clone(),
109                    cfg.local.identity,
110                )
111                .await
112                .into_dyn()
113            } else {
114                IrohConnector::new(
115                    cfg.private.iroh_p2p_sk.clone().unwrap(),
116                    settings.p2p_bind,
117                    settings.iroh_dns.clone(),
118                    settings.iroh_relays.clone(),
119                    cfg.consensus
120                        .iroh_endpoints
121                        .iter()
122                        .map(|(peer, endpoints)| (*peer, endpoints.p2p_pk))
123                        .collect(),
124                )
125                .await?
126                .into_dyn()
127            };
128
129            let (p2p_status_senders, p2p_status_receivers) = p2p_status_channels(connector.peers());
130
131            let connections = ReconnectP2PConnections::new(
132                cfg.local.identity,
133                connector,
134                &task_group,
135                p2p_status_senders,
136            )
137            .into_dyn();
138
139            (cfg, connections, p2p_status_receivers)
140        }
141        None => {
142            Box::pin(run_config_gen(
143                data_dir.clone(),
144                settings.clone(),
145                db.clone(),
146                &task_group,
147                code_version_str.clone(),
148                force_api_secrets.clone(),
149                setup_ui_router,
150                module_init_registry.clone(),
151            ))
152            .await?
153        }
154    };
155
156    let decoders = module_init_registry.decoders_strict(
157        cfg.consensus
158            .modules
159            .iter()
160            .map(|(id, config)| (*id, &config.kind)),
161    )?;
162
163    let db = db.with_decoders(decoders);
164
165    initialize_gauge_metrics(&task_group, &db).await;
166
167    start_api_announcement_service(&db, &task_group, &cfg, force_api_secrets.get_active()).await?;
168    start_guardian_metadata_service(&db, &task_group, &cfg, force_api_secrets.get_active()).await?;
169
170    info!(target: LOG_CONSENSUS, "Starting consensus...");
171
172    let connectors = ConnectorRegistry::build_from_server_defaults()
173        .bind()
174        .await?;
175
176    Box::pin(consensus::run(
177        connectors,
178        connections,
179        p2p_status_receivers,
180        settings.api_bind,
181        settings.iroh_dns,
182        settings.iroh_relays,
183        cfg,
184        db,
185        module_init_registry.clone(),
186        &task_group,
187        force_api_secrets,
188        data_dir,
189        code_version_str,
190        bitcoin_rpc,
191        settings.ui_bind,
192        dashboard_ui_router,
193        db_checkpoint_retention,
194        iroh_api_limits,
195    ))
196    .await?;
197
198    info!(target: LOG_CONSENSUS, "Shutting down tasks...");
199
200    task_group.shutdown();
201
202    Ok(())
203}
204
205async fn update_server_info_version_dbtx(
206    dbtx: &mut DatabaseTransaction<'_>,
207    code_version_str: &str,
208) {
209    let mut server_info = dbtx.get_value(&ServerInfoKey).await.unwrap_or(ServerInfo {
210        init_version: code_version_str.to_string(),
211        last_version: code_version_str.to_string(),
212    });
213    server_info.last_version = code_version_str.to_string();
214    dbtx.insert_entry(&ServerInfoKey, &server_info).await;
215}
216
217pub fn get_config(data_dir: &Path) -> anyhow::Result<Option<ServerConfig>> {
218    recover_interrupted_password_change(data_dir)?;
219
220    // Attempt get the config with local password, otherwise start config gen
221    let path = data_dir.join(PLAINTEXT_PASSWORD);
222    if let Ok(password_untrimmed) = fs::read_to_string(&path) {
223        let password = trim_password(&password_untrimmed);
224        let cfg = read_server_config(password, data_dir)?;
225        finalize_password_change(data_dir)?;
226        return Ok(Some(cfg));
227    }
228
229    Ok(None)
230}
231
232#[allow(clippy::too_many_arguments)]
233pub async fn run_config_gen(
234    data_dir: PathBuf,
235    settings: ConfigGenSettings,
236    db: Database,
237    task_group: &TaskGroup,
238    code_version_str: String,
239    api_secrets: ApiSecrets,
240    setup_ui_handler: SetupUiRouter,
241    module_init_registry: ServerModuleInitRegistry,
242) -> anyhow::Result<(
243    ServerConfig,
244    DynP2PConnections<P2PMessage>,
245    P2PStatusReceivers,
246)> {
247    info!(target: LOG_CONSENSUS, "Starting config gen");
248
249    initialize_gauge_metrics(task_group, &db).await;
250
251    let (cgp_sender, mut cgp_receiver) = tokio::sync::mpsc::channel(1);
252
253    let setup_api = SetupApi::new(settings.clone(), db.clone(), cgp_sender);
254
255    let mut rpc_module = RpcModule::new(setup_api.clone());
256
257    net::api::attach_endpoints(&mut rpc_module, config::setup::server_endpoints(), None);
258
259    let api_handler = net::api::spawn(
260        "setup",
261        // config gen always uses ws api
262        settings.api_bind,
263        rpc_module,
264        10,
265        api_secrets.clone(),
266    )
267    .await;
268
269    let ui_task_group = TaskGroup::new();
270
271    let ui_service = setup_ui_handler(setup_api.clone().into_dyn()).into_make_service();
272
273    let ui_listener = TcpListener::bind(settings.ui_bind)
274        .await
275        .expect("Failed to bind setup UI");
276
277    ui_task_group.spawn("setup-ui", move |handle| async move {
278        axum::serve(ui_listener, ui_service)
279            .with_graceful_shutdown(handle.make_shutdown_rx())
280            .await
281            .expect("Failed to serve setup UI");
282    });
283
284    info!(target: LOG_CONSENSUS, "Setup UI running at http://{} 🚀", settings.ui_bind);
285
286    let cg_params = cgp_receiver
287        .recv()
288        .await
289        .expect("Config gen params receiver closed unexpectedly");
290
291    // HACK: The `start-dkg` API call needs to have some time to finish
292    // before we shut down api handling. There's no easy and good way to do
293    // that other than just giving it some grace period.
294    sleep(Duration::from_millis(100)).await;
295
296    api_handler
297        .stop()
298        .expect("Config api should still be running");
299
300    api_handler.stopped().await;
301
302    ui_task_group
303        .shutdown_join_all(None)
304        .await
305        .context("Failed to shutdown UI server after config gen")?;
306
307    let connector = if cg_params.iroh_endpoints().is_empty() {
308        TlsTcpConnector::new(
309            cg_params.tls_config(),
310            settings.p2p_bind,
311            cg_params.p2p_urls(),
312            cg_params.identity,
313        )
314        .await
315        .into_dyn()
316    } else {
317        IrohConnector::new(
318            cg_params.iroh_p2p_sk.clone().unwrap(),
319            settings.p2p_bind,
320            settings.iroh_dns,
321            settings.iroh_relays,
322            cg_params
323                .iroh_endpoints()
324                .iter()
325                .map(|(peer, endpoints)| (*peer, endpoints.p2p_pk))
326                .collect(),
327        )
328        .await?
329        .into_dyn()
330    };
331
332    let (p2p_status_senders, p2p_status_receivers) = p2p_status_channels(connector.peers());
333
334    let connections = ReconnectP2PConnections::new(
335        cg_params.identity,
336        connector,
337        task_group,
338        p2p_status_senders,
339    )
340    .into_dyn();
341
342    let cfg = ServerConfig::distributed_gen(
343        &cg_params,
344        module_init_registry.clone(),
345        code_version_str.clone(),
346        connections.clone(),
347        p2p_status_receivers.clone(),
348    )
349    .await?;
350
351    assert_ne!(
352        cfg.consensus.iroh_endpoints.is_empty(),
353        cfg.consensus.api_endpoints.is_empty(),
354    );
355
356    // TODO: Make writing password optional
357    write_new(data_dir.join(PLAINTEXT_PASSWORD), &cfg.private.api_auth.0)?;
358    write_new(data_dir.join(SALT_FILE), random_salt())?;
359    write_server_config(
360        &cfg,
361        &data_dir,
362        &cfg.private.api_auth.0,
363        &module_init_registry,
364        api_secrets.get_active(),
365    )?;
366
367    Ok((cfg, connections, p2p_status_receivers))
368}