Skip to main content

fedimint_server/config/
mod.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::net::SocketAddr;
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use anyhow::{Context, bail, format_err};
7use bitcoin::hashes::sha256;
8pub use fedimint_core::config::{
9    ClientConfig, FederationId, GlobalClientConfig, JsonWithKind, ModuleInitRegistry, P2PMessage,
10    PeerUrl, ServerModuleConfig, ServerModuleConsensusConfig, TypedServerModuleConfig,
11};
12use fedimint_core::core::{ModuleInstanceId, ModuleKind};
13use fedimint_core::envs::{is_env_var_set, is_running_in_test_env};
14use fedimint_core::module::registry::ModuleRegistry;
15use fedimint_core::module::{
16    ApiVersion, CORE_CONSENSUS_VERSION, CoreConsensusVersion, MultiApiVersion,
17    SupportedApiVersionsSummary, SupportedCoreApiVersions, SupportedModuleApiVersions,
18};
19use fedimint_core::net::{DynP2PConnections, Recipient};
20use fedimint_core::setup_code::{PeerEndpoints, PeerSetupCode};
21use fedimint_core::task::sleep;
22use fedimint_core::util::SafeUrl;
23use fedimint_core::{NumPeersExt, PeerId, secp256k1, timing};
24use fedimint_logging::LOG_NET_PEER_DKG;
25use fedimint_server_core::config::PeerHandleOpsExt as _;
26use fedimint_server_core::{
27    ConfigGenModuleArgs, DynServerModule, DynServerModuleInit, ServerModuleInitRegistry,
28};
29use futures::future::select_all;
30use hex::{FromHex, ToHex};
31use peer_handle::PeerHandle;
32use rand::rngs::OsRng;
33use secp256k1::{PublicKey, Secp256k1, SecretKey};
34use serde::{Deserialize, Serialize};
35use tokio::select;
36use tokio_rustls::rustls;
37use tracing::{error, info, warn};
38
39use crate::fedimint_core::encoding::Encodable;
40use crate::net::p2p::P2PStatusReceivers;
41use crate::net::p2p_connector::TlsConfig;
42
43pub mod dkg;
44pub mod dkg_g1;
45pub mod dkg_g2;
46pub mod io;
47pub mod peer_handle;
48pub mod setup;
49
50/// The default maximum open connections the API can handle
51pub const DEFAULT_MAX_CLIENT_CONNECTIONS: u32 = 1000;
52
53/// Consensus broadcast settings that result in 3 minutes session time
54const DEFAULT_BROADCAST_ROUND_DELAY_MS: u16 = 50;
55const DEFAULT_BROADCAST_ROUNDS_PER_SESSION: u16 = 3600;
56
57fn default_broadcast_rounds_per_session() -> u16 {
58    DEFAULT_BROADCAST_ROUNDS_PER_SESSION
59}
60
61/// Consensus broadcast settings that result in 10 seconds session time
62const DEFAULT_TEST_BROADCAST_ROUND_DELAY_MS: u16 = 50;
63const DEFAULT_TEST_BROADCAST_ROUNDS_PER_SESSION: u16 = 200;
64
65#[allow(clippy::unsafe_derive_deserialize)] // clippy fires on `select!` https://github.com/rust-lang/rust-clippy/issues/13062
66#[derive(Debug, Clone, Serialize, Deserialize)]
67/// All the serializable configuration for the fedimint server
68pub struct ServerConfig {
69    /// Contains all configuration that needs to be the same for every server
70    pub consensus: ServerConfigConsensus,
71    /// Contains all configuration that is locally configurable and not secret
72    pub local: ServerConfigLocal,
73    /// Contains all configuration that will be encrypted such as private key
74    /// material
75    pub private: ServerConfigPrivate,
76}
77
78impl ServerConfig {
79    pub fn iter_module_instances(
80        &self,
81    ) -> impl Iterator<Item = (ModuleInstanceId, &ModuleKind)> + '_ {
82        self.consensus.iter_module_instances()
83    }
84
85    pub(crate) fn supported_api_versions_summary(
86        modules: &BTreeMap<ModuleInstanceId, ServerModuleConsensusConfig>,
87        module_registry: &ModuleRegistry<DynServerModule>,
88    ) -> SupportedApiVersionsSummary {
89        SupportedApiVersionsSummary {
90            core: Self::supported_api_versions(),
91            modules: modules
92                .iter()
93                .map(|(&id, config)| {
94                    let module = module_registry.get_expect(id);
95                    (
96                        id,
97                        SupportedModuleApiVersions {
98                            core_consensus: CORE_CONSENSUS_VERSION,
99                            module_consensus: config.version,
100                            api: module.supported_api_versions(),
101                        },
102                    )
103                })
104                .collect(),
105        }
106    }
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct ServerConfigPrivate {
111    /// Optional secret key for our websocket p2p endpoint
112    pub tls_key: Option<String>,
113    /// Optional secret key for our iroh api endpoint
114    #[serde(default)]
115    pub iroh_api_sk: Option<iroh::SecretKey>,
116    /// Optional secret key for our iroh p2p endpoint
117    #[serde(default)]
118    pub iroh_p2p_sk: Option<iroh::SecretKey>,
119    /// Secret key for the atomic broadcast to sign messages
120    pub broadcast_secret_key: SecretKey,
121    /// Secret material from modules
122    pub modules: BTreeMap<ModuleInstanceId, JsonWithKind>,
123}
124
125#[derive(Debug, Clone, Serialize, Deserialize, Encodable)]
126pub struct ServerConfigConsensus {
127    /// The compatibility version used for consensus config checksums
128    ///
129    /// Newly generated configs use `major.minor` plus an exact optional vendor
130    /// suffix; restored legacy configs can contain `major.minor.patch`.
131    ///
132    /// This remains a string because it is persisted in consensus-config JSON
133    /// and its string consensus encoding contributes to the federation ID.
134    /// Changing the field type or encoding would break existing configurations.
135    pub code_version: String,
136    /// Agreed on core consensus version
137    pub version: CoreConsensusVersion,
138    /// Public keys for the atomic broadcast to authenticate messages
139    pub broadcast_public_keys: BTreeMap<PeerId, PublicKey>,
140    /// Number of rounds per session.
141    #[serde(default = "default_broadcast_rounds_per_session")]
142    pub broadcast_rounds_per_session: u16,
143    /// Network addresses and names for all peer APIs
144    pub api_endpoints: BTreeMap<PeerId, PeerUrl>,
145    /// Public keys for all iroh api and p2p endpoints
146    #[serde(default)]
147    pub iroh_endpoints: BTreeMap<PeerId, PeerIrohEndpoints>,
148    /// Certs for TLS communication, required for peer authentication
149    pub tls_certs: BTreeMap<PeerId, String>,
150    /// All configuration that needs to be the same for modules
151    pub modules: BTreeMap<ModuleInstanceId, ServerModuleConsensusConfig>,
152    /// Additional config the federation wants to transmit to the clients
153    pub meta: BTreeMap<String, String>,
154}
155
156#[derive(Debug, Clone, Serialize, Deserialize, Encodable)]
157pub struct PeerIrohEndpoints {
158    /// The peer's name
159    pub name: String,
160    /// Public key for our iroh api endpoint
161    pub api_pk: iroh::PublicKey,
162    /// Public key for our iroh p2p endpoint
163    pub p2p_pk: iroh::PublicKey,
164}
165
166pub fn legacy_consensus_config_hash(cfg: &ServerConfigConsensus) -> sha256::Hash {
167    #[derive(Encodable)]
168    struct LegacyServerConfigConsensusHashMap {
169        code_version: String,
170        version: CoreConsensusVersion,
171        broadcast_public_keys: BTreeMap<PeerId, PublicKey>,
172        broadcast_rounds_per_session: u16,
173        api_endpoints: BTreeMap<PeerId, PeerUrl>,
174        tls_certs: BTreeMap<PeerId, String>,
175        modules: BTreeMap<ModuleInstanceId, ServerModuleConsensusConfig>,
176        meta: BTreeMap<String, String>,
177    }
178
179    LegacyServerConfigConsensusHashMap {
180        code_version: cfg.code_version.clone(),
181        version: cfg.version,
182        broadcast_public_keys: cfg.broadcast_public_keys.clone(),
183        broadcast_rounds_per_session: cfg.broadcast_rounds_per_session,
184        api_endpoints: cfg.api_endpoints.clone(),
185        tls_certs: cfg.tls_certs.clone(),
186        modules: cfg.modules.clone(),
187        meta: cfg.meta.clone(),
188    }
189    .consensus_hash_sha256()
190}
191
192// FIXME: (@leonardo) Should this have another field for the expected transport
193// ? (e.g. clearnet/tor/...)
194#[derive(Debug, Clone, Serialize, Deserialize)]
195pub struct ServerConfigLocal {
196    /// Network addresses and names for all p2p connections
197    pub p2p_endpoints: BTreeMap<PeerId, PeerUrl>,
198    /// Our peer id (generally should not change)
199    pub identity: PeerId,
200    /// How many API connections we will accept
201    pub max_connections: u32,
202    /// Influences the atomic broadcast ordering latency, should be higher than
203    /// the expected latency between peers so everyone can get proposed
204    /// consensus items confirmed. This is only relevant for byzantine
205    /// faults.
206    pub broadcast_round_delay_ms: u16,
207}
208
209/// All the info we configure prior to config gen starting
210#[derive(Debug, Clone)]
211pub struct ConfigGenSettings {
212    /// Bind address for our P2P connection (both iroh and tcp/tls)
213    pub p2p_bind: SocketAddr,
214    /// Bind address for our API
215    pub api_bind: SocketAddr,
216    /// Bind address for our UI connection (always http)
217    pub ui_bind: SocketAddr,
218    /// URL for our P2P connection
219    pub p2p_url: Option<SafeUrl>,
220    /// URL for our API connection
221    pub api_url: Option<SafeUrl>,
222    /// Enable iroh for networking
223    pub enable_iroh: bool,
224    /// Optional URL of the Iroh DNS server
225    pub iroh_dns: Option<SafeUrl>,
226    /// Optional URLs of the Iroh relays to register on
227    pub iroh_relays: Vec<SafeUrl>,
228    /// Bitcoin network for the federation
229    pub network: bitcoin::Network,
230    /// Available modules that can be enabled during setup
231    pub available_modules: BTreeSet<ModuleKind>,
232    /// Modules that should be enabled by default in the setup UI
233    pub default_modules: BTreeSet<ModuleKind>,
234}
235
236#[derive(Debug, Clone)]
237/// All the parameters necessary for generating the `ServerConfig` during setup
238///
239/// * Guardians can create the parameters using a setup UI or CLI tool
240/// * Used for distributed or trusted config generation
241pub struct ConfigGenParams {
242    /// Our own peer id
243    pub identity: PeerId,
244    /// Our TLS certificate private key
245    pub tls_key: Option<Arc<rustls::pki_types::PrivateKeyDer<'static>>>,
246    /// Optional secret key for our iroh api endpoint
247    pub iroh_api_sk: Option<iroh::SecretKey>,
248    /// Optional secret key for our iroh p2p endpoint
249    pub iroh_p2p_sk: Option<iroh::SecretKey>,
250    /// Endpoints of all servers
251    pub peers: BTreeMap<PeerId, PeerSetupCode>,
252    /// (Retired, see <https://github.com/fedimint/fedimint/issues/7889>)
253    /// Guardian-defined key-value pairs that will be passed to the client
254    pub meta: BTreeMap<String, String>,
255    /// Whether to disable base fees for this federation
256    pub disable_base_fees: bool,
257    /// Modules enabled by the leader during setup
258    pub enabled_modules: BTreeSet<ModuleKind>,
259    /// Bitcoin network for this federation
260    pub network: bitcoin::Network,
261}
262
263impl ServerConfigConsensus {
264    pub fn api_endpoints(&self) -> BTreeMap<PeerId, PeerUrl> {
265        if self.iroh_endpoints.is_empty() {
266            self.api_endpoints.clone()
267        } else {
268            self.iroh_endpoints
269                .iter()
270                .map(|(peer, endpoints)| {
271                    let url = PeerUrl {
272                        name: endpoints.name.clone(),
273                        url: SafeUrl::parse(&format!("iroh://{}", endpoints.api_pk))
274                            .expect("Failed to parse iroh url"),
275                    };
276
277                    (*peer, url)
278                })
279                .collect()
280        }
281    }
282
283    pub fn iter_module_instances(
284        &self,
285    ) -> impl Iterator<Item = (ModuleInstanceId, &ModuleKind)> + '_ {
286        self.modules.iter().map(|(k, v)| (*k, &v.kind))
287    }
288
289    pub fn to_client_config(
290        &self,
291        module_config_gens: &ModuleInitRegistry<DynServerModuleInit>,
292    ) -> Result<ClientConfig, anyhow::Error> {
293        let client = ClientConfig {
294            global: GlobalClientConfig {
295                api_endpoints: self.api_endpoints(),
296                broadcast_public_keys: Some(self.broadcast_public_keys.clone()),
297                consensus_version: self.version,
298                meta: self.meta.clone(),
299            },
300            modules: self
301                .modules
302                .iter()
303                .map(|(k, v)| {
304                    let r#gen = module_config_gens
305                        .get(&v.kind)
306                        .ok_or_else(|| format_err!("Module gen kind={} not found", v.kind))?;
307                    Ok((*k, r#gen.get_client_config(*k, v)?))
308                })
309                .collect::<anyhow::Result<BTreeMap<_, _>>>()?,
310        };
311        Ok(client)
312    }
313}
314
315impl ServerConfig {
316    /// Api versions supported by this server
317    pub fn supported_api_versions() -> SupportedCoreApiVersions {
318        SupportedCoreApiVersions {
319            core_consensus: CORE_CONSENSUS_VERSION,
320            api: MultiApiVersion::try_from_iter([ApiVersion {
321                major: 0,
322                minor: 11,
323            }])
324            .expect("not version conflicts"),
325        }
326    }
327    /// Creates a new config from the results of a trusted or distributed key
328    /// setup
329    pub fn from(
330        params: ConfigGenParams,
331        identity: PeerId,
332        broadcast_public_keys: BTreeMap<PeerId, PublicKey>,
333        broadcast_secret_key: SecretKey,
334        modules: BTreeMap<ModuleInstanceId, ServerModuleConfig>,
335        code_version: String,
336    ) -> Self {
337        let consensus = ServerConfigConsensus {
338            // Setup validates untrusted code versions before config generation.
339            // Keep this lower-level API usable by test helpers that use opaque
340            // version strings, as it was before DKG compatibility was added.
341            code_version: fedimint_core::version::DkgVersion::parse(&code_version).map_or_else(
342                |_| fedimint_core::version::release_version(&code_version).to_owned(),
343                |version| version.compatibility_version().to_string(),
344            ),
345            version: CORE_CONSENSUS_VERSION,
346            broadcast_public_keys,
347            broadcast_rounds_per_session: if is_running_in_test_env!() {
348                DEFAULT_TEST_BROADCAST_ROUNDS_PER_SESSION
349            } else {
350                DEFAULT_BROADCAST_ROUNDS_PER_SESSION
351            },
352            api_endpoints: params.api_urls(),
353            iroh_endpoints: params.iroh_endpoints(),
354            tls_certs: params.tls_certs(),
355            modules: modules
356                .iter()
357                .map(|(peer, cfg)| (*peer, cfg.consensus.clone()))
358                .collect(),
359            meta: params.meta.clone(),
360        };
361
362        let local = ServerConfigLocal {
363            p2p_endpoints: params.p2p_urls(),
364            identity,
365            max_connections: DEFAULT_MAX_CLIENT_CONNECTIONS,
366            broadcast_round_delay_ms: if is_running_in_test_env!() {
367                DEFAULT_TEST_BROADCAST_ROUND_DELAY_MS
368            } else {
369                DEFAULT_BROADCAST_ROUND_DELAY_MS
370            },
371        };
372
373        let private = ServerConfigPrivate {
374            tls_key: params
375                .tls_key
376                .map(|key| key.secret_der().to_vec().encode_hex()),
377            iroh_api_sk: params.iroh_api_sk,
378            iroh_p2p_sk: params.iroh_p2p_sk,
379            broadcast_secret_key,
380            modules: modules
381                .iter()
382                .map(|(peer, cfg)| (*peer, cfg.private.clone()))
383                .collect(),
384        };
385
386        Self {
387            consensus,
388            local,
389            private,
390        }
391    }
392
393    pub fn calculate_federation_id(&self) -> FederationId {
394        FederationId(self.consensus.api_endpoints().consensus_hash())
395    }
396
397    /// Constructs a module config by name
398    pub fn get_module_config_typed<T: TypedServerModuleConfig>(
399        &self,
400        id: ModuleInstanceId,
401    ) -> anyhow::Result<T> {
402        let private = Self::get_module_cfg_by_instance_id(&self.private.modules, id)?;
403        let consensus = self
404            .consensus
405            .modules
406            .get(&id)
407            .ok_or_else(|| format_err!("Typed module {id} not found"))?
408            .clone();
409        let module = ServerModuleConfig::from(private, consensus);
410
411        Ok(module.to_typed()?)
412    }
413    pub fn get_module_id_by_kind(
414        &self,
415        kind: impl Into<ModuleKind>,
416    ) -> anyhow::Result<ModuleInstanceId> {
417        let kind = kind.into();
418        Ok(*self
419            .consensus
420            .modules
421            .iter()
422            .find(|(_, v)| v.kind == kind)
423            .ok_or_else(|| format_err!("Module {kind} not found"))?
424            .0)
425    }
426
427    /// Constructs a module config by id
428    pub fn get_module_config(&self, id: ModuleInstanceId) -> anyhow::Result<ServerModuleConfig> {
429        let private = Self::get_module_cfg_by_instance_id(&self.private.modules, id)?;
430        let consensus = self
431            .consensus
432            .modules
433            .get(&id)
434            .ok_or_else(|| format_err!("Module config {id} not found"))?
435            .clone();
436        Ok(ServerModuleConfig::from(private, consensus))
437    }
438
439    fn get_module_cfg_by_instance_id(
440        json: &BTreeMap<ModuleInstanceId, JsonWithKind>,
441        id: ModuleInstanceId,
442    ) -> anyhow::Result<JsonWithKind> {
443        Ok(json
444            .get(&id)
445            .ok_or_else(|| format_err!("Module cfg {id} not found"))
446            .cloned()?
447            .with_fixed_empty_value())
448    }
449
450    pub fn validate_config(
451        &self,
452        identity: &PeerId,
453        module_config_gens: &ServerModuleInitRegistry,
454    ) -> anyhow::Result<()> {
455        let endpoints = self.consensus.api_endpoints().clone();
456        let consensus = self.consensus.clone();
457        let private = self.private.clone();
458
459        let my_public_key = private.broadcast_secret_key.public_key(&Secp256k1::new());
460
461        if Some(&my_public_key) != consensus.broadcast_public_keys.get(identity) {
462            bail!("Broadcast secret key doesn't match corresponding public key");
463        }
464        if endpoints.keys().max().copied().map(PeerId::to_usize) != Some(endpoints.len() - 1) {
465            bail!("Peer ids are not indexed from 0");
466        }
467        if endpoints.keys().min().copied() != Some(PeerId::from(0)) {
468            bail!("Peer ids are not indexed from 0");
469        }
470
471        for (module_id, module_kind) in &self
472            .consensus
473            .modules
474            .iter()
475            .map(|(id, config)| Ok((*id, config.kind.clone())))
476            .collect::<anyhow::Result<BTreeSet<_>>>()?
477        {
478            module_config_gens
479                .get(module_kind)
480                .ok_or_else(|| format_err!("module config gen not found {module_kind}"))?
481                .validate_config(identity, self.get_module_config(*module_id)?)?;
482        }
483
484        Ok(())
485    }
486
487    pub fn trusted_dealer_gen(
488        params: &BTreeMap<PeerId, ConfigGenParams>,
489        registry: &ServerModuleInitRegistry,
490        code_version_str: &str,
491    ) -> BTreeMap<PeerId, Self> {
492        let peer0 = &params[&PeerId::from(0)];
493
494        let mut broadcast_pks = BTreeMap::new();
495        let mut broadcast_sks = BTreeMap::new();
496        for peer_id in peer0.peer_ids() {
497            let (broadcast_sk, broadcast_pk) = secp256k1::generate_keypair(&mut OsRng);
498            broadcast_pks.insert(peer_id, broadcast_pk);
499            broadcast_sks.insert(peer_id, broadcast_sk);
500        }
501
502        let args = ConfigGenModuleArgs {
503            network: peer0.network,
504            disable_base_fees: peer0.disable_base_fees,
505        };
506
507        // Use legacy module ordering for backwards compatibility tests
508        let use_legacy_order = is_env_var_set("FM_BACKWARDS_COMPATIBILITY_TEST");
509        let module_iter: Vec<_> = if use_legacy_order {
510            registry.iter_legacy_order()
511        } else {
512            registry.iter().collect()
513        };
514
515        let module_configs: BTreeMap<_, _> = module_iter
516            .into_iter()
517            .filter(|(kind, _)| peer0.enabled_modules.contains(kind))
518            .enumerate()
519            .map(|(module_id, (_kind, module_init))| {
520                (
521                    module_id as ModuleInstanceId,
522                    module_init.trusted_dealer_gen(&peer0.peer_ids(), &args),
523                )
524            })
525            .collect();
526
527        let server_config: BTreeMap<_, _> = peer0
528            .peer_ids()
529            .iter()
530            .map(|&id| {
531                let config = ServerConfig::from(
532                    params[&id].clone(),
533                    id,
534                    broadcast_pks.clone(),
535                    *broadcast_sks.get(&id).expect("We created this entry"),
536                    module_configs
537                        .iter()
538                        .map(|(module_id, cfgs)| (*module_id, cfgs[&id].clone()))
539                        .collect(),
540                    code_version_str.to_string(),
541                );
542                (id, config)
543            })
544            .collect();
545
546        server_config
547    }
548
549    /// Runs the distributed key gen algorithm
550    pub async fn distributed_gen(
551        params: &ConfigGenParams,
552        registry: ServerModuleInitRegistry,
553        code_version_str: String,
554        connections: DynP2PConnections<P2PMessage>,
555        mut p2p_status_receivers: P2PStatusReceivers,
556    ) -> anyhow::Result<Self> {
557        let _timing /* logs on drop */ = timing::TimeReporter::new("distributed-gen").info();
558
559        // in case we are running by ourselves, avoid DKG
560        if params.peer_ids().len() == 1 {
561            let server = Self::trusted_dealer_gen(
562                &BTreeMap::from([(params.identity, params.clone())]),
563                &registry,
564                &code_version_str,
565            );
566
567            return Ok(server[&params.identity].clone());
568        }
569
570        info!(
571            target: LOG_NET_PEER_DKG,
572            "Waiting for all p2p connections to open..."
573        );
574
575        loop {
576            let mut pending_connection_receivers: Vec<_> = p2p_status_receivers
577                .iter_mut()
578                .filter_map(|(p, r)| {
579                    r.mark_unchanged();
580                    r.borrow().connected.is_none().then_some((*p, r.clone()))
581                })
582                .collect();
583
584            if pending_connection_receivers.is_empty() {
585                break;
586            }
587
588            let disconnected_peers = pending_connection_receivers
589                .iter()
590                .map(|(peer, receiver)| {
591                    let last_error = receiver.borrow().last_error.clone();
592
593                    (*peer, last_error)
594                })
595                .collect::<Vec<_>>();
596
597            info!(
598                target: LOG_NET_PEER_DKG,
599                pending = ?disconnected_peers,
600                "Waiting for all p2p connections to open..."
601            );
602
603            select! {
604                _ = select_all(pending_connection_receivers.iter_mut().map(|r| Box::pin(r.1.changed()))) => {}
605                () = sleep(Duration::from_secs(10)) => {}
606            }
607        }
608
609        let checksum = params.peers.consensus_hash_sha256();
610
611        info!(
612            target: LOG_NET_PEER_DKG,
613            "Comparing connection codes checksum {checksum}..."
614        );
615
616        connections.send(Recipient::Everyone, P2PMessage::Checksum(checksum));
617
618        for peer in params
619            .peer_ids()
620            .into_iter()
621            .filter(|p| *p != params.identity)
622        {
623            let peer_message = receive_from_peer_with_progress(
624                &connections,
625                peer,
626                "connection code checksum message",
627            )
628            .await?;
629
630            if peer_message != P2PMessage::Checksum(checksum) {
631                error!(
632                    target: LOG_NET_PEER_DKG,
633                    expected = ?P2PMessage::Checksum(checksum),
634                    received = ?peer_message,
635                    "Peer {peer} has sent invalid connection code checksum message"
636                );
637
638                bail!("Peer {peer} has sent invalid connection code checksum message");
639            }
640
641            info!(
642                target: LOG_NET_PEER_DKG,
643                "Peer {peer} has sent valid connection code checksum message"
644            );
645        }
646
647        info!(
648            target: LOG_NET_PEER_DKG,
649            "Running config generation..."
650        );
651
652        let handle = PeerHandle::new(
653            params.peer_ids().to_num_peers(),
654            params.identity,
655            &connections,
656        );
657
658        let (broadcast_sk, broadcast_pk) = secp256k1::generate_keypair(&mut OsRng);
659
660        let broadcast_public_keys = handle.exchange_encodable(broadcast_pk).await?;
661
662        let args = ConfigGenModuleArgs {
663            network: params.network,
664            disable_base_fees: params.disable_base_fees,
665        };
666
667        // Use legacy module ordering for backwards compatibility tests
668        let use_legacy_order = is_env_var_set("FM_BACKWARDS_COMPATIBILITY_TEST");
669        let module_iter: Vec<_> = if use_legacy_order {
670            registry.iter_legacy_order()
671        } else {
672            registry.iter().collect()
673        };
674
675        let mut module_cfgs = BTreeMap::new();
676
677        for (module_id, (kind, module_init)) in module_iter
678            .into_iter()
679            .filter(|(kind, _)| params.enabled_modules.contains(kind))
680            .enumerate()
681        {
682            info!(
683                target: LOG_NET_PEER_DKG,
684                "Running config generation for module of kind {kind}..."
685            );
686
687            let cfg = module_init.distributed_gen(&handle, &args).await?;
688
689            module_cfgs.insert(module_id as ModuleInstanceId, cfg);
690        }
691
692        let cfg = ServerConfig::from(
693            params.clone(),
694            params.identity,
695            broadcast_public_keys,
696            broadcast_sk,
697            module_cfgs,
698            code_version_str,
699        );
700
701        let checksum = cfg.consensus.consensus_hash_sha256();
702
703        info!(
704            target: LOG_NET_PEER_DKG,
705            "Comparing consensus config checksum {checksum}..."
706        );
707
708        connections.send(Recipient::Everyone, P2PMessage::Checksum(checksum));
709
710        for peer in params
711            .peer_ids()
712            .into_iter()
713            .filter(|p| *p != params.identity)
714        {
715            let peer_message =
716                receive_from_peer_with_progress(&connections, peer, "consensus config checksum")
717                    .await?;
718
719            if peer_message != P2PMessage::Checksum(checksum) {
720                warn!(
721                    target: LOG_NET_PEER_DKG,
722                    expected = ?P2PMessage::Checksum(checksum),
723                    received = ?peer_message,
724                    config = ?cfg.consensus,
725                    "Peer {peer} has sent invalid consensus config checksum message"
726                );
727
728                bail!("Peer {peer} has sent invalid consensus config checksum message");
729            }
730
731            info!(
732                target: LOG_NET_PEER_DKG,
733                "Peer {peer} has sent valid consensus config checksum message"
734            );
735        }
736
737        info!(
738            target: LOG_NET_PEER_DKG,
739            "Config generation has completed successfully!"
740        );
741
742        Ok(cfg)
743    }
744}
745
746async fn receive_from_peer_with_progress(
747    connections: &DynP2PConnections<P2PMessage>,
748    peer: PeerId,
749    message_description: &'static str,
750) -> anyhow::Result<P2PMessage> {
751    let start = Instant::now();
752
753    loop {
754        select! {
755            // Cancel-safe: `receive_from_peer` is backed by
756            // `async_channel::Receiver::recv`, so dropping this future on the
757            // periodic progress-log tick does not lose messages.
758            peer_message = connections.receive_from_peer(peer) => {
759                return peer_message.context("Unexpected shutdown of p2p connections");
760            }
761            () = sleep(Duration::from_secs(10)) => {
762                info!(
763                    target: LOG_NET_PEER_DKG,
764                    %peer,
765                    message = message_description,
766                    elapsed_secs = start.elapsed().as_secs(),
767                    "Still waiting for peer message"
768                );
769            }
770        }
771    }
772}
773
774impl ServerConfig {
775    pub fn tls_config(&self) -> TlsConfig {
776        TlsConfig {
777            private_key: Arc::new(
778                rustls::pki_types::PrivateKeyDer::try_from(
779                    Vec::from_hex(self.private.tls_key.clone().unwrap()).unwrap(),
780                )
781                .expect("Failed to parse private key"),
782            ),
783            certificates: self
784                .consensus
785                .tls_certs
786                .iter()
787                .map(|(peer, cert)| {
788                    (
789                        *peer,
790                        rustls::pki_types::CertificateDer::from(Vec::from_hex(cert).unwrap()),
791                    )
792                })
793                .collect(),
794            peer_names: self
795                .local
796                .p2p_endpoints
797                .iter()
798                .map(|(id, endpoint)| (*id, endpoint.name.clone()))
799                .collect(),
800        }
801    }
802}
803
804impl ConfigGenParams {
805    pub fn peer_ids(&self) -> Vec<PeerId> {
806        self.peers.keys().copied().collect()
807    }
808
809    pub fn tls_config(&self) -> TlsConfig {
810        TlsConfig {
811            private_key: self.tls_key.clone().unwrap(),
812            certificates: self
813                .tls_certs()
814                .iter()
815                .map(|(peer, cert)| {
816                    (
817                        *peer,
818                        rustls::pki_types::CertificateDer::from(Vec::from_hex(cert).unwrap()),
819                    )
820                })
821                .collect(),
822            peer_names: self
823                .p2p_urls()
824                .into_iter()
825                .map(|(id, peer)| (id, peer.name))
826                .collect(),
827        }
828    }
829
830    pub fn tls_certs(&self) -> BTreeMap<PeerId, String> {
831        self.peers
832            .iter()
833            .filter_map(|(id, peer)| {
834                match peer.endpoints.clone() {
835                    PeerEndpoints::Tcp { cert, .. } => Some(cert.encode_hex()),
836                    PeerEndpoints::Iroh { .. } => None,
837                }
838                .map(|peer| (*id, peer))
839            })
840            .collect()
841    }
842
843    pub fn p2p_urls(&self) -> BTreeMap<PeerId, PeerUrl> {
844        self.peers
845            .iter()
846            .filter_map(|(id, peer)| {
847                match peer.endpoints.clone() {
848                    PeerEndpoints::Tcp { p2p_url, .. } => Some(PeerUrl {
849                        name: peer.name.clone(),
850                        url: p2p_url.clone(),
851                    }),
852                    PeerEndpoints::Iroh { .. } => None,
853                }
854                .map(|peer| (*id, peer))
855            })
856            .collect()
857    }
858
859    pub fn api_urls(&self) -> BTreeMap<PeerId, PeerUrl> {
860        self.peers
861            .iter()
862            .filter_map(|(id, peer)| {
863                match peer.endpoints.clone() {
864                    PeerEndpoints::Tcp { api_url, .. } => Some(PeerUrl {
865                        name: peer.name.clone(),
866                        url: api_url.clone(),
867                    }),
868                    PeerEndpoints::Iroh { .. } => None,
869                }
870                .map(|peer| (*id, peer))
871            })
872            .collect()
873    }
874
875    pub fn iroh_endpoints(&self) -> BTreeMap<PeerId, PeerIrohEndpoints> {
876        self.peers
877            .iter()
878            .filter_map(|(id, peer)| {
879                match peer.endpoints.clone() {
880                    PeerEndpoints::Tcp { .. } => None,
881                    PeerEndpoints::Iroh { api_pk, p2p_pk } => Some(PeerIrohEndpoints {
882                        name: peer.name.clone(),
883                        api_pk,
884                        p2p_pk,
885                    }),
886                }
887                .map(|peer| (*id, peer))
888            })
889            .collect()
890    }
891}
892
893#[cfg(test)]
894mod tests;