fedimint_server/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#![deny(clippy::pedantic)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_possible_wrap)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::doc_markdown)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::missing_panics_doc)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::must_use_candidate)]
#![allow(clippy::return_self_not_must_use)]
#![allow(clippy::similar_names)]
#![allow(clippy::too_many_lines)]

extern crate fedimint_core;

use std::fs;
use std::path::{Path, PathBuf};

use config::io::{read_server_config, PLAINTEXT_PASSWORD};
use config::ServerConfig;
use fedimint_aead::random_salt;
use fedimint_core::config::ServerModuleInitRegistry;
use fedimint_core::db::Database;
use fedimint_core::epoch::ConsensusItem;
use fedimint_core::task::TaskGroup;
use fedimint_core::util::write_new;
use fedimint_logging::{LOG_CONSENSUS, LOG_CORE};
use net::api::ApiSecrets;
use tracing::{info, warn};

use crate::config::api::{ConfigGenApi, ConfigGenSettings};
use crate::config::io::{write_server_config, SALT_FILE};
use crate::metrics::initialize_gauge_metrics;
use crate::net::api::announcement::start_api_announcement_service;
use crate::net::api::RpcHandlerCtx;
use crate::net::connect::TlsTcpConnector;

pub mod envs;
pub mod metrics;

/// The actual implementation of consensus
pub mod consensus;

/// Networking for mint-to-mint and client-to-mint communiccation
pub mod net;

/// Fedimint toplevel config
pub mod config;

/// Implementation of multiplexed peer connections
pub mod multiplexed;

pub async fn run(
    data_dir: PathBuf,
    force_api_secrets: ApiSecrets,
    settings: ConfigGenSettings,
    db: Database,
    code_version_str: String,
    module_init_registry: &ServerModuleInitRegistry,
    task_group: TaskGroup,
) -> anyhow::Result<()> {
    let cfg = match get_config(&data_dir)? {
        Some(cfg) => cfg,
        None => {
            run_config_gen(
                data_dir.clone(),
                settings.clone(),
                db.clone(),
                code_version_str.clone(),
                task_group.make_subgroup(),
                force_api_secrets.clone(),
            )
            .await?
        }
    };

    let decoders = module_init_registry.decoders_strict(
        cfg.consensus
            .modules
            .iter()
            .map(|(id, config)| (*id, &config.kind)),
    )?;

    let db = db.with_decoders(decoders);

    initialize_gauge_metrics(&db).await;

    start_api_announcement_service(&db, &task_group, &cfg, force_api_secrets.get_active()).await;

    consensus::run(
        settings.p2p_bind,
        settings.api_bind,
        cfg,
        db,
        module_init_registry.clone(),
        &task_group,
        force_api_secrets,
        data_dir,
        code_version_str,
    )
    .await?;

    info!(target: LOG_CONSENSUS, "Shutting down tasks");

    task_group.shutdown();

    Ok(())
}

pub fn get_config(data_dir: &Path) -> anyhow::Result<Option<ServerConfig>> {
    // Attempt get the config with local password, otherwise start config gen
    let path = data_dir.join(PLAINTEXT_PASSWORD);
    if let Ok(password_untrimmed) = fs::read_to_string(&path) {
        // We definitely don't want leading/trailing newlines, and user
        // editing the file manually will probably get a free newline added
        // by the text editor.
        let password = password_untrimmed.trim_matches('\n');
        // In the future we also don't want to support any leading/trailing newlines
        let password_fully_trimmed = password.trim();
        if password_fully_trimmed != password {
            warn!(
                target: LOG_CORE,
                path = %path.display(),
                "Password in the password file contains leading/trailing whitespaces. This will an error in the future."
            );
        }
        return Ok(Some(read_server_config(password, data_dir)?));
    }

    Ok(None)
}

pub async fn run_config_gen(
    data_dir: PathBuf,
    settings: ConfigGenSettings,
    db: Database,
    code_version_str: String,
    task_group: TaskGroup,
    force_api_secrets: ApiSecrets,
) -> anyhow::Result<ServerConfig> {
    info!(target: LOG_CONSENSUS, "Starting config gen");

    initialize_gauge_metrics(&db).await;

    let (cfg_sender, mut cfg_receiver) = tokio::sync::mpsc::channel(1);

    let config_gen = ConfigGenApi::new(
        settings.p2p_bind,
        settings.clone(),
        db.clone(),
        cfg_sender,
        &task_group,
        code_version_str.clone(),
        force_api_secrets.get_active(),
    );

    let mut rpc_module = RpcHandlerCtx::new_module(config_gen);

    net::api::attach_endpoints(&mut rpc_module, config::api::server_endpoints(), None);

    let api_handler = net::api::spawn(
        "config-gen",
        settings.api_bind,
        rpc_module,
        10,
        force_api_secrets.clone(),
    )
    .await;

    let cfg = cfg_receiver.recv().await.expect("should not close");

    api_handler
        .stop()
        .expect("Config api should still be running");

    api_handler.stopped().await;

    // TODO: Make writing password optional
    write_new(data_dir.join(PLAINTEXT_PASSWORD), &cfg.private.api_auth.0)?;
    write_new(data_dir.join(SALT_FILE), random_salt())?;
    write_server_config(
        &cfg,
        &data_dir,
        &cfg.private.api_auth.0,
        &settings.registry,
        force_api_secrets.get_active(),
    )?;

    Ok(cfg)
}