Skip to main content

fedimint_testing/
federation.rs

1use std::collections::BTreeMap;
2use std::sync::Arc;
3use std::time::Duration;
4
5use fedimint_api_client::api::{DynGlobalApi, FederationApiExt};
6use fedimint_client::module_init::ClientModuleInitRegistry;
7use fedimint_client::{Client, ClientHandleArc, RootSecret};
8use fedimint_client_module::AdminCreds;
9use fedimint_client_module::secret::{PlainRootSecretStrategy, RootSecretStrategy};
10use fedimint_connectors::ConnectorRegistry;
11use fedimint_core::PeerId;
12use fedimint_core::config::{ClientConfig, FederationId};
13use fedimint_core::core::ModuleKind;
14use fedimint_core::db::Database;
15use fedimint_core::db::mem_impl::MemDatabase;
16use fedimint_core::endpoint_constants::SESSION_COUNT_ENDPOINT;
17use fedimint_core::invite_code::InviteCode;
18use fedimint_core::module::{ApiAuth, ApiRequestErased};
19use fedimint_core::net::peers::IP2PConnections;
20use fedimint_core::rustls::install_crypto_provider;
21use fedimint_core::task::{TaskGroup, block_in_place, sleep_in_test};
22use fedimint_gateway_common::ConnectFedPayload;
23use fedimint_gateway_server::{Gateway, IAdminGateway};
24use fedimint_logging::LOG_TEST;
25use fedimint_rocksdb::RocksDb;
26use fedimint_server::config::ServerConfig;
27use fedimint_server::core::ServerModuleInitRegistry;
28use fedimint_server::net::api::ApiSecrets;
29use fedimint_server::net::p2p::{ReconnectP2PConnections, p2p_status_channels};
30use fedimint_server::net::p2p_connector::{IP2PConnector, TlsTcpConnector};
31use fedimint_server::{ConnectionLimits, consensus};
32use fedimint_server_core::bitcoin_rpc::DynServerBitcoinRpc;
33use fedimint_testing_core::config::local_config_gen_params;
34use tracing::info;
35
36/// Test fixture for a running fedimint federation
37#[derive(Clone)]
38pub struct FederationTest {
39    configs: BTreeMap<PeerId, ServerConfig>,
40    server_init: ServerModuleInitRegistry,
41    client_init: ClientModuleInitRegistry,
42    _task: TaskGroup,
43    num_peers: u16,
44    num_offline: u16,
45    connectors: ConnectorRegistry,
46}
47
48impl FederationTest {
49    /// Create two clients, useful for send/receive tests
50    pub async fn two_clients(&self) -> (ClientHandleArc, ClientHandleArc) {
51        (self.new_client().await, self.new_client().await)
52    }
53
54    /// Create a client connected to this fed
55    pub async fn new_client(&self) -> ClientHandleArc {
56        let client_config = self.configs[&PeerId::from(0)]
57            .consensus
58            .to_client_config(&self.server_init)
59            .unwrap();
60
61        self.new_client_with(client_config, MemDatabase::new().into(), None)
62            .await
63    }
64
65    /// Create a client connected to this fed but using RocksDB instead of MemDB
66    pub async fn new_client_rocksdb(&self) -> ClientHandleArc {
67        let client_config = self.configs[&PeerId::from(0)]
68            .consensus
69            .to_client_config(&self.server_init)
70            .unwrap();
71
72        self.new_client_with(
73            client_config,
74            RocksDb::build(tempfile::tempdir().expect("Couldn't create temp dir"))
75                .open()
76                .await
77                .expect("Couldn't open DB")
78                .into(),
79            None,
80        )
81        .await
82    }
83
84    /// Create a new admin api for the given PeerId
85    pub async fn new_admin_api(&self, peer_id: PeerId) -> anyhow::Result<DynGlobalApi> {
86        let config = self.configs.get(&peer_id).expect("peer to have config");
87
88        DynGlobalApi::new_admin(
89            ConnectorRegistry::build_from_testing_env()?.bind().await?,
90            peer_id,
91            config.consensus.api_endpoints()[&peer_id].url.clone(),
92            None,
93        )
94    }
95
96    /// Create a new admin client connected to this fed
97    pub async fn new_admin_client(&self, peer_id: PeerId, auth: ApiAuth) -> ClientHandleArc {
98        let client_config = self.configs[&PeerId::from(0)]
99            .consensus
100            .to_client_config(&self.server_init)
101            .unwrap();
102
103        let admin_creds = AdminCreds { peer_id, auth };
104
105        self.new_client_with(client_config, MemDatabase::new().into(), Some(admin_creds))
106            .await
107    }
108
109    pub async fn new_client_with(
110        &self,
111        client_config: ClientConfig,
112        db: Database,
113        admin_creds: Option<AdminCreds>,
114    ) -> ClientHandleArc {
115        info!(target: LOG_TEST, "Setting new client with config");
116        let mut client_builder = Client::builder().await.expect("Failed to build client");
117        client_builder.with_module_inits(self.client_init.clone());
118        if let Some(admin_creds) = admin_creds {
119            client_builder.set_admin_creds(admin_creds);
120        }
121        let client_secret = Client::load_or_generate_client_secret(&db).await.unwrap();
122        client_builder
123            .preview_with_existing_config(self.connectors.clone(), client_config, None)
124            .await
125            .expect("Preview failed")
126            .join(
127                db,
128                RootSecret::StandardDoubleDerive(PlainRootSecretStrategy::to_root_secret(
129                    &client_secret,
130                )),
131            )
132            .await
133            .map(Arc::new)
134            .expect("Failed to build client")
135    }
136
137    /// Join a federation with an existing database and root secret
138    pub async fn join_client_with_db(
139        &self,
140        db: Database,
141        root_secret: RootSecret,
142    ) -> ClientHandleArc {
143        let client_config = self.configs[&PeerId::from(0)]
144            .consensus
145            .to_client_config(&self.server_init)
146            .unwrap();
147
148        info!(target: LOG_TEST, "Joining client with existing db");
149        let mut client_builder = Client::builder().await.expect("Failed to build client");
150        client_builder.with_module_inits(self.client_init.clone());
151        client_builder
152            .preview_with_existing_config(self.connectors.clone(), client_config, None)
153            .await
154            .expect("Preview failed")
155            .join(db, root_secret)
156            .await
157            .map(Arc::new)
158            .expect("Failed to join client")
159    }
160
161    /// Create a recovering client with an existing database and root secret.
162    /// Returns both the client and the database so a new client can be created
163    /// with the same DB after recovery completes.
164    pub async fn recover_client_with_db(
165        &self,
166        db: Database,
167        root_secret: RootSecret,
168    ) -> ClientHandleArc {
169        let client_config = self.configs[&PeerId::from(0)]
170            .consensus
171            .to_client_config(&self.server_init)
172            .unwrap();
173
174        info!(target: LOG_TEST, "Recovering client with existing db");
175        let mut client_builder = Client::builder().await.expect("Failed to build client");
176        client_builder.with_module_inits(self.client_init.clone());
177        client_builder
178            .preview_with_existing_config(self.connectors.clone(), client_config, None)
179            .await
180            .expect("Preview failed")
181            .recover(db, root_secret, None)
182            .await
183            .map(Arc::new)
184            .expect("Failed to recover client")
185    }
186
187    /// Open an existing client database (e.g., after recovery)
188    pub async fn open_client_with_db(
189        &self,
190        db: Database,
191        root_secret: RootSecret,
192    ) -> ClientHandleArc {
193        info!(target: LOG_TEST, "Opening client with existing db");
194        let mut client_builder = Client::builder().await.expect("Failed to build client");
195        client_builder.with_module_inits(self.client_init.clone());
196        client_builder
197            .open(self.connectors.clone(), db, root_secret)
198            .await
199            .map(Arc::new)
200            .expect("Failed to open client")
201    }
202
203    /// Return first invite code for gateways
204    pub fn invite_code(&self) -> InviteCode {
205        self.configs[&PeerId::from(0)].get_invite_code(None)
206    }
207
208    ///  Return the federation id
209    pub fn id(&self) -> FederationId {
210        self.configs[&PeerId::from(0)]
211            .consensus
212            .to_client_config(&self.server_init)
213            .unwrap()
214            .global
215            .calculate_federation_id()
216    }
217
218    /// Connects a gateway to this `FederationTest`
219    pub async fn connect_gateway(&self, gw: &Gateway) {
220        gw.handle_connect_federation(ConnectFedPayload {
221            invite_code: self.invite_code().to_string(),
222            use_tor: Some(false),
223            recover: Some(false),
224        })
225        .await
226        .expect("Failed to connect federation");
227    }
228
229    /// Return all online PeerIds
230    pub fn online_peer_ids(&self) -> impl Iterator<Item = PeerId> + use<> {
231        // we can assume this ordering since peers are started in ascending order
232        (0..(self.num_peers - self.num_offline)).map(PeerId::from)
233    }
234
235    /// Returns true if the federation is running in a degraded state
236    pub fn is_degraded(&self) -> bool {
237        self.num_offline > 0
238    }
239}
240
241/// Builder struct for creating a `FederationTest`.
242#[derive(Clone, Debug)]
243pub struct FederationTestBuilder {
244    num_peers: u16,
245    num_offline: u16,
246    base_port: u16,
247    primary_module_kind: ModuleKind,
248    version_hash: String,
249    server_init: ServerModuleInitRegistry,
250    client_init: ClientModuleInitRegistry,
251    bitcoin_rpc_connection: DynServerBitcoinRpc,
252    enable_mint_fees: bool,
253}
254
255impl FederationTestBuilder {
256    pub fn new(
257        server_init: ServerModuleInitRegistry,
258        client_init: ClientModuleInitRegistry,
259        primary_module_kind: ModuleKind,
260        num_offline: u16,
261        bitcoin_rpc_connection: DynServerBitcoinRpc,
262    ) -> FederationTestBuilder {
263        let num_peers = 4;
264        Self {
265            num_peers,
266            num_offline,
267            base_port: block_in_place(|| fedimint_portalloc::port_alloc(num_peers * 3))
268                .expect("Failed to allocate a port range"),
269            primary_module_kind,
270            version_hash: "fedimint-testing-dummy-version-hash".to_owned(),
271            server_init,
272            client_init,
273            bitcoin_rpc_connection,
274            enable_mint_fees: true,
275        }
276    }
277
278    pub fn num_peers(mut self, num_peers: u16) -> FederationTestBuilder {
279        self.num_peers = num_peers;
280        self
281    }
282
283    pub fn num_offline(mut self, num_offline: u16) -> FederationTestBuilder {
284        self.num_offline = num_offline;
285        self
286    }
287
288    pub fn base_port(mut self, base_port: u16) -> FederationTestBuilder {
289        self.base_port = base_port;
290        self
291    }
292
293    pub fn primary_module_kind(mut self, primary_module_kind: ModuleKind) -> FederationTestBuilder {
294        self.primary_module_kind = primary_module_kind;
295        self
296    }
297
298    pub fn version_hash(mut self, version_hash: String) -> FederationTestBuilder {
299        self.version_hash = version_hash;
300        self
301    }
302
303    pub fn disable_mint_fees(mut self) -> FederationTestBuilder {
304        self.enable_mint_fees = false;
305        self
306    }
307
308    #[allow(clippy::too_many_lines)]
309    pub async fn build(self) -> FederationTest {
310        install_crypto_provider().await;
311        let num_offline = self.num_offline;
312        assert!(
313            self.num_peers > 3 * self.num_offline,
314            "too many peers offline ({num_offline}) to reach consensus"
315        );
316        let peers = (0..self.num_peers).map(PeerId::from).collect::<Vec<_>>();
317        let params = local_config_gen_params(
318            &peers,
319            self.base_port,
320            self.enable_mint_fees,
321            &self.server_init,
322        )
323        .expect("Generates local config");
324
325        let configs =
326            ServerConfig::trusted_dealer_gen(&params, &self.server_init, &self.version_hash);
327
328        let task_group = TaskGroup::new();
329        for (peer_id, cfg) in configs.clone() {
330            let peer_port = self.base_port + u16::from(peer_id) * 3;
331
332            let p2p_bind = format!("127.0.0.1:{peer_port}").parse().unwrap();
333            let api_bind = format!("127.0.0.1:{}", peer_port + 1).parse().unwrap();
334            let ui_bind = format!("127.0.0.1:{}", peer_port + 2).parse().unwrap();
335
336            if u16::from(peer_id) >= self.num_peers - self.num_offline {
337                continue;
338            }
339
340            let instances = cfg.consensus.iter_module_instances();
341            let decoders = self.server_init.available_decoders(instances).unwrap();
342            let db = Database::new(MemDatabase::new(), decoders);
343            let module_init_registry = self.server_init.clone();
344            let subgroup = task_group.make_subgroup();
345            let checkpoint_dir = tempfile::Builder::new().tempdir().unwrap().keep();
346            let code_version_str = env!("CARGO_PKG_VERSION");
347
348            let connector = TlsTcpConnector::new(
349                cfg.tls_config(),
350                p2p_bind,
351                cfg.local.p2p_endpoints.clone(),
352                cfg.local.identity,
353            )
354            .await
355            .into_dyn();
356
357            let (p2p_status_senders, p2p_status_receivers) = p2p_status_channels(connector.peers());
358
359            let connections = ReconnectP2PConnections::new(
360                cfg.local.identity,
361                connector,
362                &task_group,
363                p2p_status_senders,
364            )
365            .into_dyn();
366
367            let bitcoin_rpc_connection = self.bitcoin_rpc_connection.clone();
368
369            task_group.spawn("fedimintd", move |_| async move {
370                Box::pin(consensus::run(
371                    ConnectorRegistry::build_from_testing_env()
372                        .unwrap()
373                        .bind()
374                        .await
375                        .unwrap(),
376                    connections,
377                    p2p_status_receivers,
378                    api_bind,
379                    None,
380                    vec![],
381                    cfg.clone(),
382                    db.clone(),
383                    module_init_registry,
384                    &subgroup,
385                    ApiSecrets::default(),
386                    checkpoint_dir,
387                    code_version_str.to_string(),
388                    bitcoin_rpc_connection,
389                    ui_bind,
390                    Box::new(|_| axum::Router::new()),
391                    1,
392                    ConnectionLimits {
393                        max_connections: 1000,
394                        max_requests_per_connection: 100,
395                    },
396                ))
397                .await
398                .expect("Could not initialise consensus");
399            });
400        }
401
402        for (peer_id, config) in configs.clone() {
403            if u16::from(peer_id) >= self.num_peers - self.num_offline {
404                continue;
405            }
406
407            let connectors = ConnectorRegistry::build_from_testing_env()
408                .unwrap()
409                .bind()
410                .await
411                .unwrap();
412            let api = DynGlobalApi::new_admin(
413                connectors,
414                peer_id,
415                config.consensus.api_endpoints()[&peer_id].url.clone(),
416                None,
417            )
418            .unwrap();
419
420            while let Err(e) = api
421                .request_admin_no_auth::<u64>(SESSION_COUNT_ENDPOINT, ApiRequestErased::default())
422                .await
423            {
424                sleep_in_test(
425                    format!("Waiting for api of peer {peer_id} to come online: {e}"),
426                    Duration::from_millis(500),
427                )
428                .await;
429            }
430        }
431
432        FederationTest {
433            configs,
434            server_init: self.server_init,
435            client_init: self.client_init,
436            _task: task_group,
437            num_peers: self.num_peers,
438            num_offline: self.num_offline,
439            connectors: ConnectorRegistry::build_from_testing_env()
440                .expect("Failed to initialize endpoints for testing (env)")
441                .bind()
442                .await
443                .expect("Failed to initialize endpoints for testing"),
444        }
445    }
446}