devimint/
federation.rs

1mod config;
2
3use std::collections::{BTreeMap, HashMap, HashSet};
4use std::ops::ControlFlow;
5use std::path::PathBuf;
6use std::str::FromStr;
7use std::time::Duration;
8use std::{env, fs, iter};
9
10use anyhow::{Context, Result, anyhow, bail};
11use bitcoincore_rpc::bitcoin::Network;
12use fedimint_api_client::api::DynGlobalApi;
13use fedimint_api_client::api::net::Connector;
14use fedimint_client_module::module::ClientModule;
15use fedimint_core::admin_client::{ServerStatusLegacy, SetupStatus};
16use fedimint_core::config::{ClientConfig, ServerModuleConfigGenParamsRegistry, load_from_file};
17use fedimint_core::core::LEGACY_HARDCODED_INSTANCE_ID_WALLET;
18use fedimint_core::envs::BitcoinRpcConfig;
19use fedimint_core::invite_code::InviteCode;
20use fedimint_core::module::registry::ModuleDecoderRegistry;
21use fedimint_core::module::{ApiAuth, ModuleCommon};
22use fedimint_core::runtime::block_in_place;
23use fedimint_core::task::block_on;
24use fedimint_core::task::jit::JitTryAnyhow;
25use fedimint_core::util::SafeUrl;
26use fedimint_core::{Amount, NumPeers, PeerId};
27use fedimint_gateway_common::WithdrawResponse;
28use fedimint_logging::LOG_DEVIMINT;
29use fedimint_server::config::ConfigGenParams;
30use fedimint_testing_core::config::local_config_gen_params;
31use fedimint_testing_core::node_type::LightningNodeType;
32use fedimint_wallet_client::WalletClientModule;
33use fedimint_wallet_client::config::WalletClientConfig;
34use fs_lock::FileLock;
35use futures::future::{join_all, try_join_all};
36use rand::Rng;
37use tokio::task::{JoinSet, spawn_blocking};
38use tokio::time::Instant;
39use tracing::{debug, info};
40
41use super::external::Bitcoind;
42use super::util::{Command, ProcessHandle, ProcessManager, cmd};
43use super::vars::utf8;
44use crate::envs::{FM_CLIENT_DIR_ENV, FM_DATA_DIR_ENV};
45use crate::util::{FedimintdCmd, poll, poll_simple, poll_with_timeout};
46use crate::version_constants::{VERSION_0_6_0_ALPHA, VERSION_0_7_0_ALPHA};
47use crate::{poll_eq, vars};
48
49// TODO: Are we still using the 3rd port for anything?
50/// Number of ports we allocate for every `fedimintd` instance
51pub const PORTS_PER_FEDIMINTD: u16 = 4;
52/// Which port is for p2p inside the range from [`PORTS_PER_FEDIMINTD`]
53pub const FEDIMINTD_P2P_PORT_OFFSET: u16 = 0;
54/// Which port is for api inside the range from [`PORTS_PER_FEDIMINTD`]
55pub const FEDIMINTD_API_PORT_OFFSET: u16 = 1;
56/// Which port is for the web ui inside the range from [`PORTS_PER_FEDIMINTD`]
57pub const FEDIMINTD_UI_PORT_OFFSET: u16 = 2;
58/// Which port is for prometheus inside the range from [`PORTS_PER_FEDIMINTD`]
59pub const FEDIMINTD_METRICS_PORT_OFFSET: u16 = 3;
60
61#[derive(Clone)]
62pub struct Federation {
63    // client is only for internal use, use cli commands instead
64    pub members: BTreeMap<usize, Fedimintd>,
65    pub vars: BTreeMap<usize, vars::Fedimintd>,
66    pub bitcoind: Bitcoind,
67
68    /// Built in [`Client`], already joined
69    client: JitTryAnyhow<Client>,
70}
71
72impl Drop for Federation {
73    fn drop(&mut self) {
74        block_in_place(|| {
75            block_on(async {
76                let mut set = JoinSet::new();
77
78                while let Some((_id, fedimintd)) = self.members.pop_first() {
79                    set.spawn(async { drop(fedimintd) });
80                }
81                while (set.join_next().await).is_some() {}
82            });
83        });
84    }
85}
86/// `fedimint-cli` instance (basically path with client state: config + db)
87#[derive(Clone)]
88pub struct Client {
89    name: String,
90}
91
92impl Client {
93    fn clients_dir() -> PathBuf {
94        let data_dir: PathBuf = env::var(FM_DATA_DIR_ENV)
95            .expect("FM_DATA_DIR_ENV not set")
96            .parse()
97            .expect("FM_DATA_DIR_ENV invalid");
98        data_dir.join("clients")
99    }
100
101    fn client_dir(&self) -> PathBuf {
102        Self::clients_dir().join(&self.name)
103    }
104
105    pub fn client_name_lock(name: &str) -> Result<FileLock> {
106        let lock_path = Self::clients_dir().join(format!(".{name}.lock"));
107        let file_lock = std::fs::OpenOptions::new()
108            .write(true)
109            .create(true)
110            .truncate(true)
111            .open(&lock_path)
112            .with_context(|| format!("Failed to open {}", lock_path.display()))?;
113
114        fs_lock::FileLock::new_exclusive(file_lock)
115            .with_context(|| format!("Failed to lock {}", lock_path.display()))
116    }
117
118    /// Create a [`Client`] that starts with a fresh state.
119    pub async fn create(name: impl ToString) -> Result<Client> {
120        let name = name.to_string();
121        spawn_blocking(move || {
122            let _lock = Self::client_name_lock(&name);
123            for i in 0u64.. {
124                let client = Self {
125                    name: format!("{name}-{i}"),
126                };
127
128                if !client.client_dir().exists() {
129                    std::fs::create_dir_all(client.client_dir())?;
130                    return Ok(client);
131                }
132            }
133            unreachable!()
134        })
135        .await?
136    }
137
138    /// Open or create a [`Client`] that starts with a fresh state.
139    pub fn open_or_create(name: &str) -> Result<Client> {
140        block_in_place(|| {
141            let _lock = Self::client_name_lock(name);
142            let client = Self {
143                name: format!("{name}-0"),
144            };
145            if !client.client_dir().exists() {
146                std::fs::create_dir_all(client.client_dir())?;
147            }
148            Ok(client)
149        })
150    }
151
152    /// Client to join a federation
153    pub async fn join_federation(&self, invite_code: String) -> Result<()> {
154        debug!(target: LOG_DEVIMINT, "Joining federation with the main client");
155        cmd!(self, "join-federation", invite_code).run().await?;
156
157        Ok(())
158    }
159
160    /// Client to join a federation with a restore procedure
161    pub async fn restore_federation(&self, invite_code: String, mnemonic: String) -> Result<()> {
162        debug!(target: LOG_DEVIMINT, "Joining federation with restore procedure");
163        cmd!(
164            self,
165            "restore",
166            "--invite-code",
167            invite_code,
168            "--mnemonic",
169            mnemonic
170        )
171        .run()
172        .await?;
173
174        Ok(())
175    }
176
177    /// Client to join a federation
178    pub async fn new_restored(&self, name: &str, invite_code: String) -> Result<Self> {
179        let restored = Self::open_or_create(name)?;
180
181        let mnemonic = cmd!(self, "print-secret").out_json().await?["secret"]
182            .as_str()
183            .unwrap()
184            .to_owned();
185
186        debug!(target: LOG_DEVIMINT, name, "Restoring from mnemonic");
187        cmd!(
188            restored,
189            "restore",
190            "--invite-code",
191            invite_code,
192            "--mnemonic",
193            mnemonic
194        )
195        .run()
196        .await?;
197
198        Ok(restored)
199    }
200
201    /// Create a [`Client`] that starts with a state that is a copy of
202    /// of another one.
203    pub async fn new_forked(&self, name: impl ToString) -> Result<Client> {
204        let new = Client::create(name).await?;
205
206        cmd!(
207            "cp",
208            "-R",
209            self.client_dir().join("client.db").display(),
210            new.client_dir().display()
211        )
212        .run()
213        .await?;
214
215        Ok(new)
216    }
217
218    pub async fn balance(&self) -> Result<u64> {
219        Ok(cmd!(self, "info").out_json().await?["total_amount_msat"]
220            .as_u64()
221            .unwrap())
222    }
223
224    pub async fn get_deposit_addr(&self) -> Result<(String, String)> {
225        let deposit = cmd!(self, "deposit-address").out_json().await?;
226        Ok((
227            deposit["address"].as_str().unwrap().to_string(),
228            deposit["operation_id"].as_str().unwrap().to_string(),
229        ))
230    }
231
232    pub async fn await_deposit(&self, operation_id: &str) -> Result<()> {
233        cmd!(self, "await-deposit", operation_id).run().await
234    }
235
236    pub fn cmd(&self) -> Command {
237        cmd!(
238            crate::util::get_fedimint_cli_path(),
239            format!("--data-dir={}", self.client_dir().display())
240        )
241    }
242
243    pub fn get_name(&self) -> &str {
244        &self.name
245    }
246
247    /// Returns the current consensus session count
248    pub async fn get_session_count(&self) -> Result<u64> {
249        cmd!(self, "dev", "session-count").out_json().await?["count"]
250            .as_u64()
251            .context("count field wasn't a number")
252    }
253
254    /// Returns once all active state machines complete
255    pub async fn wait_complete(&self) -> Result<()> {
256        cmd!(self, "dev", "wait-complete").run().await
257    }
258
259    /// Returns once the current session completes
260    pub async fn wait_session(&self) -> anyhow::Result<()> {
261        info!("Waiting for a new session");
262        let session_count = self.get_session_count().await?;
263        self.wait_session_outcome(session_count).await?;
264        Ok(())
265    }
266
267    /// Returns once the provided session count completes
268    pub async fn wait_session_outcome(&self, session_count: u64) -> anyhow::Result<()> {
269        let timeout = {
270            let current_session_count = self.get_session_count().await?;
271            let sessions_to_wait = session_count.saturating_sub(current_session_count) + 1;
272            let session_duration_seconds = 180;
273            Duration::from_secs(sessions_to_wait * session_duration_seconds)
274        };
275
276        let start = Instant::now();
277        poll_with_timeout("Waiting for a new session", timeout, || async {
278            info!("Awaiting session outcome {session_count}");
279            match cmd!(self, "dev", "api", "await_session_outcome", session_count)
280                .run()
281                .await
282            {
283                Err(e) => Err(ControlFlow::Continue(e)),
284                Ok(()) => Ok(()),
285            }
286        })
287        .await?;
288
289        let session_found_in = start.elapsed();
290        info!("session found in {session_found_in:?}");
291        Ok(())
292    }
293}
294
295impl Federation {
296    pub async fn new(
297        process_mgr: &ProcessManager,
298        bitcoind: Bitcoind,
299        skip_setup: bool,
300        pre_dkg: bool,
301        // Which of the pre-allocated federations to use (most tests just use single `0` one)
302        fed_index: usize,
303        federation_name: String,
304    ) -> Result<Self> {
305        let num_peers = NumPeers::from(process_mgr.globals.FM_FED_SIZE);
306        let mut members = BTreeMap::new();
307        let mut peer_to_env_vars_map = BTreeMap::new();
308
309        let peers: Vec<_> = num_peers.peer_ids().collect();
310        let params: HashMap<PeerId, ConfigGenParams> =
311            local_config_gen_params(&peers, process_mgr.globals.FM_FEDERATION_BASE_PORT)?;
312
313        let mut admin_clients: BTreeMap<PeerId, DynGlobalApi> = BTreeMap::new();
314        let mut endpoints: BTreeMap<PeerId, _> = BTreeMap::new();
315        for peer_id in num_peers.peer_ids() {
316            let peer_env_vars = vars::Fedimintd::init(
317                &process_mgr.globals,
318                federation_name.clone(),
319                peer_id,
320                process_mgr
321                    .globals
322                    .fedimintd_overrides
323                    .peer_expect(fed_index, peer_id),
324            )
325            .await?;
326            members.insert(
327                peer_id.to_usize(),
328                Fedimintd::new(
329                    process_mgr,
330                    bitcoind.clone(),
331                    peer_id.to_usize(),
332                    &peer_env_vars,
333                    federation_name.clone(),
334                )
335                .await?,
336            );
337            let admin_client = DynGlobalApi::from_setup_endpoint(
338                SafeUrl::parse(&peer_env_vars.FM_API_URL)?,
339                &process_mgr.globals.FM_FORCE_API_SECRETS.get_active(),
340            )
341            .await?;
342            endpoints.insert(peer_id, peer_env_vars.FM_API_URL.clone());
343            admin_clients.insert(peer_id, admin_client);
344            peer_to_env_vars_map.insert(peer_id.to_usize(), peer_env_vars);
345        }
346
347        if !skip_setup && !pre_dkg {
348            // we don't guarantee backwards-compatibility for dkg, so we use the
349            // fedimint-cli version that matches fedimintd
350            let (original_fedimint_cli_path, original_fm_mint_client) =
351                crate::util::use_matching_fedimint_cli_for_dkg().await?;
352
353            let fedimint_cli_version = crate::util::FedimintCli::version_or_default().await;
354
355            if fedimint_cli_version >= *VERSION_0_7_0_ALPHA {
356                run_cli_dkg_v2(params, endpoints).await?;
357            } else {
358                run_cli_dkg(params, endpoints).await?;
359            }
360
361            // we're done with dkg, so we can reset the fedimint-cli version
362            crate::util::use_fedimint_cli(original_fedimint_cli_path, original_fm_mint_client);
363
364            // move configs to config directory
365            let client_dir = utf8(&process_mgr.globals.FM_CLIENT_DIR);
366            let invite_code_filename_original = "invite-code";
367
368            for peer_env_vars in peer_to_env_vars_map.values() {
369                let peer_data_dir = utf8(&peer_env_vars.FM_DATA_DIR);
370
371                let invite_code = poll_simple("awaiting-invite-code", || async {
372                    tokio::fs::read_to_string(format!(
373                        "{peer_data_dir}/{invite_code_filename_original}"
374                    ))
375                    .await
376                    .map_err(Into::into)
377                })
378                .await
379                .context("Awaiting invite code file")?;
380
381                Connector::default()
382                    .download_from_invite_code(&InviteCode::from_str(&invite_code)?)
383                    .await?;
384            }
385
386            // copy over invite-code file to client directory
387            let peer_data_dir = utf8(&peer_to_env_vars_map[&0].FM_DATA_DIR);
388
389            tokio::fs::copy(
390                format!("{peer_data_dir}/{invite_code_filename_original}"),
391                format!("{client_dir}/{invite_code_filename_original}"),
392            )
393            .await
394            .context("copying invite-code file")?;
395
396            // move each guardian's invite-code file to the client's directory
397            // appending the peer id to the end
398            for (index, peer_env_vars) in &peer_to_env_vars_map {
399                let peer_data_dir = utf8(&peer_env_vars.FM_DATA_DIR);
400
401                let invite_code_filename_indexed =
402                    format!("{invite_code_filename_original}-{index}");
403                tokio::fs::rename(
404                    format!("{peer_data_dir}/{invite_code_filename_original}"),
405                    format!("{client_dir}/{invite_code_filename_indexed}"),
406                )
407                .await
408                .context("moving invite-code file")?;
409            }
410
411            debug!("Moved invite-code files to client data directory");
412        }
413
414        let client = JitTryAnyhow::new_try({
415            move || async move {
416                let client = Client::open_or_create(federation_name.as_str())?;
417                let invite_code = Self::invite_code_static()?;
418                if !skip_setup && !pre_dkg {
419                    cmd!(client, "join-federation", invite_code).run().await?;
420                }
421                Ok(client)
422            }
423        });
424
425        Ok(Self {
426            members,
427            vars: peer_to_env_vars_map,
428            bitcoind,
429            client,
430        })
431    }
432
433    pub fn client_config(&self) -> Result<ClientConfig> {
434        let cfg_path = self.vars[&0].FM_DATA_DIR.join("client.json");
435        load_from_file(&cfg_path)
436    }
437
438    pub fn module_client_config<M: ClientModule>(
439        &self,
440    ) -> Result<Option<<M::Common as ModuleCommon>::ClientConfig>> {
441        self.client_config()?
442            .modules
443            .iter()
444            .find_map(|(module_instance_id, module_cfg)| {
445                if module_cfg.kind == M::kind() {
446                    let decoders = ModuleDecoderRegistry::new(vec![(
447                        *module_instance_id,
448                        M::kind(),
449                        M::decoder(),
450                    )]);
451                    Some(
452                        module_cfg
453                            .config
454                            .clone()
455                            .redecode_raw(&decoders)
456                            .expect("Decoding client cfg failed")
457                            .expect_decoded_ref()
458                            .as_any()
459                            .downcast_ref::<<M::Common as ModuleCommon>::ClientConfig>()
460                            .cloned()
461                            .context("Cast to module config failed"),
462                    )
463                } else {
464                    None
465                }
466            })
467            .transpose()
468    }
469
470    pub fn deposit_fees(&self) -> Result<Amount> {
471        Ok(self
472            .module_client_config::<WalletClientModule>()?
473            .context("No wallet module found")?
474            .fee_consensus
475            .peg_in_abs)
476    }
477
478    /// Read the invite code from the client data dir
479    pub fn invite_code(&self) -> Result<String> {
480        let data_dir: PathBuf = env::var(FM_CLIENT_DIR_ENV)?.parse()?;
481        let invite_code = fs::read_to_string(data_dir.join("invite-code"))?;
482        Ok(invite_code)
483    }
484
485    pub fn invite_code_static() -> Result<String> {
486        let data_dir: PathBuf = env::var(FM_CLIENT_DIR_ENV)?.parse()?;
487        let invite_code = fs::read_to_string(data_dir.join("invite-code"))?;
488        Ok(invite_code)
489    }
490    pub fn invite_code_for(peer_id: PeerId) -> Result<String> {
491        let data_dir: PathBuf = env::var(FM_CLIENT_DIR_ENV)?.parse()?;
492        let name = format!("invite-code-{peer_id}");
493        let invite_code = fs::read_to_string(data_dir.join(name))?;
494        Ok(invite_code)
495    }
496
497    /// Built-in, default, internal [`Client`]
498    ///
499    /// We should be moving away from using it for anything.
500    pub async fn internal_client(&self) -> Result<&Client> {
501        self.client
502            .get_try()
503            .await
504            .context("Internal client joining Federation")
505    }
506
507    /// New [`Client`] that already joined `self`
508    pub async fn new_joined_client(&self, name: impl ToString) -> Result<Client> {
509        let client = Client::create(name).await?;
510        client.join_federation(self.invite_code()?).await?;
511        Ok(client)
512    }
513
514    pub async fn start_server(&mut self, process_mgr: &ProcessManager, peer: usize) -> Result<()> {
515        if self.members.contains_key(&peer) {
516            bail!("fedimintd-{peer} already running");
517        }
518        self.members.insert(
519            peer,
520            Fedimintd::new(
521                process_mgr,
522                self.bitcoind.clone(),
523                peer,
524                &self.vars[&peer],
525                "default".to_string(),
526            )
527            .await?,
528        );
529        Ok(())
530    }
531
532    pub async fn terminate_server(&mut self, peer_id: usize) -> Result<()> {
533        let Some((_, fedimintd)) = self.members.remove_entry(&peer_id) else {
534            bail!("fedimintd-{peer_id} does not exist");
535        };
536        fedimintd.terminate().await?;
537        Ok(())
538    }
539
540    /// Starts all peers not currently running.
541    pub async fn start_all_servers(&mut self, process_mgr: &ProcessManager) -> Result<()> {
542        info!("starting all servers");
543        let fed_size = process_mgr.globals.FM_FED_SIZE;
544        for peer_id in 0..fed_size {
545            if self.members.contains_key(&peer_id) {
546                continue;
547            }
548            self.start_server(process_mgr, peer_id).await?;
549        }
550        self.await_all_peers().await?;
551        Ok(())
552    }
553
554    /// Terminates all running peers.
555    pub async fn terminate_all_servers(&mut self) -> Result<()> {
556        info!("terminating all servers");
557        let running_peer_ids: Vec<_> = self.members.keys().copied().collect();
558        for peer_id in running_peer_ids {
559            self.terminate_server(peer_id).await?;
560        }
561        Ok(())
562    }
563
564    /// Coordinated shutdown of all peers that restart using the provided
565    /// `bin_path`. Returns `Ok()` once all peers are online.
566    ///
567    /// Staggering the restart more closely simulates upgrades in the wild.
568    pub async fn restart_all_staggered_with_bin(
569        &mut self,
570        process_mgr: &ProcessManager,
571        bin_path: &PathBuf,
572    ) -> Result<()> {
573        let fed_size = process_mgr.globals.FM_FED_SIZE;
574
575        // ensure all peers are online
576        self.start_all_servers(process_mgr).await?;
577
578        // staggered shutdown of peers
579        while self.num_members() > 0 {
580            self.terminate_server(self.num_members() - 1).await?;
581            if self.num_members() > 0 {
582                fedimint_core::task::sleep_in_test(
583                    "waiting to shutdown remaining peers",
584                    Duration::from_secs(10),
585                )
586                .await;
587            }
588        }
589
590        // TODO: Audit that the environment access only happens in single-threaded code.
591        unsafe { std::env::set_var("FM_FEDIMINTD_BASE_EXECUTABLE", bin_path) };
592
593        // staggered restart
594        for peer_id in 0..fed_size {
595            self.start_server(process_mgr, peer_id).await?;
596            if peer_id < fed_size - 1 {
597                fedimint_core::task::sleep_in_test(
598                    "waiting to restart remaining peers",
599                    Duration::from_secs(10),
600                )
601                .await;
602            }
603        }
604
605        self.await_all_peers().await?;
606
607        let fedimintd_version = crate::util::FedimintdCmd::version_or_default().await;
608        info!("upgraded fedimintd to version: {}", fedimintd_version);
609        Ok(())
610    }
611
612    pub async fn restart_all_with_bin(
613        &mut self,
614        process_mgr: &ProcessManager,
615        bin_path: &PathBuf,
616    ) -> Result<()> {
617        // get the version we're upgrading to, temporarily updating the fedimintd path
618        let current_fedimintd_path = std::env::var("FM_FEDIMINTD_BASE_EXECUTABLE")?;
619        // TODO: Audit that the environment access only happens in single-threaded code.
620        unsafe { std::env::set_var("FM_FEDIMINTD_BASE_EXECUTABLE", bin_path) };
621        // TODO: Audit that the environment access only happens in single-threaded code.
622        unsafe { std::env::set_var("FM_FEDIMINTD_BASE_EXECUTABLE", current_fedimintd_path) };
623
624        self.restart_all_staggered_with_bin(process_mgr, bin_path)
625            .await
626    }
627
628    pub async fn degrade_federation(&mut self, process_mgr: &ProcessManager) -> Result<()> {
629        let fed_size = process_mgr.globals.FM_FED_SIZE;
630        let offline_nodes = process_mgr.globals.FM_OFFLINE_NODES;
631        anyhow::ensure!(
632            fed_size > 3 * offline_nodes,
633            "too many offline nodes ({offline_nodes}) to reach consensus"
634        );
635
636        while self.num_members() > fed_size - offline_nodes {
637            self.terminate_server(self.num_members() - 1).await?;
638        }
639
640        if offline_nodes > 0 {
641            info!(fed_size, offline_nodes, "federation is degraded");
642        }
643        Ok(())
644    }
645
646    pub async fn pegin_client_no_wait(&self, amount: u64, client: &Client) -> Result<String> {
647        let deposit_fees_msat = self.deposit_fees()?.msats;
648        assert_eq!(
649            deposit_fees_msat % 1000,
650            0,
651            "Deposit fees expected to be whole sats in test suite"
652        );
653        let deposit_fees = deposit_fees_msat / 1000;
654        info!(amount, deposit_fees, "Pegging-in client funds");
655
656        let (address, operation_id) = client.get_deposit_addr().await?;
657
658        self.bitcoind
659            .send_to(address, amount + deposit_fees)
660            .await?;
661        self.bitcoind.mine_blocks(21).await?;
662
663        Ok(operation_id)
664    }
665
666    pub async fn pegin_client(&self, amount: u64, client: &Client) -> Result<()> {
667        let operation_id = self.pegin_client_no_wait(amount, client).await?;
668
669        client.await_deposit(&operation_id).await?;
670        Ok(())
671    }
672
673    /// Inititates multiple peg-ins to the same federation for the set of
674    /// gateways to save on mining blocks in parallel.
675    pub async fn pegin_gateways(
676        &self,
677        amount: u64,
678        gateways: Vec<&super::gatewayd::Gatewayd>,
679    ) -> Result<()> {
680        let deposit_fees_msat = self.deposit_fees()?.msats;
681        assert_eq!(
682            deposit_fees_msat % 1000,
683            0,
684            "Deposit fees expected to be whole sats in test suite"
685        );
686        let deposit_fees = deposit_fees_msat / 1000;
687        info!(amount, deposit_fees, "Pegging-in gateway funds");
688        let fed_id = self.calculate_federation_id();
689        for gw in gateways.clone() {
690            let pegin_addr = gw.get_pegin_addr(&fed_id).await?;
691            self.bitcoind
692                .send_to(pegin_addr, amount + deposit_fees)
693                .await?;
694        }
695
696        self.bitcoind.mine_blocks(21).await?;
697        let bitcoind_block_height: u64 = self.bitcoind.get_block_count().await? - 1;
698        try_join_all(gateways.into_iter().map(|gw| {
699            poll("gateway pegin", || async {
700                let gw_info = gw.get_info().await.map_err(ControlFlow::Continue)?;
701                let block_height: u64 = gw_info["block_height"]
702                    .as_u64()
703                    .expect("Could not parse block height");
704                if bitcoind_block_height != block_height {
705                    return Err(std::ops::ControlFlow::Continue(anyhow::anyhow!(
706                        "gateway block height is not synced"
707                    )));
708                }
709
710                let gateway_balance = gw
711                    .ecash_balance(fed_id.clone())
712                    .await
713                    .map_err(ControlFlow::Continue)?;
714                poll_eq!(gateway_balance, amount * 1000)
715            })
716        }))
717        .await?;
718
719        Ok(())
720    }
721
722    /// Initiates multiple peg-outs from the same federation for the set of
723    /// gateways to save on mining blocks in parallel.
724    pub async fn pegout_gateways(
725        &self,
726        amount: u64,
727        gateways: Vec<&super::gatewayd::Gatewayd>,
728    ) -> Result<()> {
729        info!(amount, "Pegging-out gateway funds");
730        let fed_id = self.calculate_federation_id();
731        let mut peg_outs: BTreeMap<LightningNodeType, (Amount, WithdrawResponse)> = BTreeMap::new();
732        for gw in gateways.clone() {
733            let prev_fed_ecash_balance = gw
734                .get_balances()
735                .await?
736                .ecash_balances
737                .into_iter()
738                .find(|fed| fed.federation_id.to_string() == fed_id)
739                .expect("Gateway has not joined federation")
740                .ecash_balance_msats;
741
742            let pegout_address = self.bitcoind.get_new_address().await?;
743            let value = cmd!(
744                gw,
745                "ecash",
746                "pegout",
747                "--federation-id",
748                fed_id,
749                "--amount",
750                amount,
751                "--address",
752                pegout_address
753            )
754            .out_json()
755            .await?;
756            let response: WithdrawResponse = serde_json::from_value(value)?;
757            peg_outs.insert(gw.ln.ln_type(), (prev_fed_ecash_balance, response));
758        }
759        self.bitcoind.mine_blocks(21).await?;
760
761        try_join_all(
762            peg_outs
763                .values()
764                .map(|(_, pegout)| self.bitcoind.poll_get_transaction(pegout.txid)),
765        )
766        .await?;
767
768        for gw in gateways.clone() {
769            let after_fed_ecash_balance = gw
770                .get_balances()
771                .await?
772                .ecash_balances
773                .into_iter()
774                .find(|fed| fed.federation_id.to_string() == fed_id)
775                .expect("Gateway has not joined federation")
776                .ecash_balance_msats;
777
778            let ln_type = gw.ln.ln_type();
779            let prev_balance = peg_outs
780                .get(&ln_type)
781                .expect("peg out does not exist")
782                .0
783                .msats;
784            let fees = peg_outs
785                .get(&ln_type)
786                .expect("peg out does not exist")
787                .1
788                .fees;
789            let total_fee = fees.amount().to_sat() * 1000;
790            assert_eq!(
791                prev_balance - amount - total_fee,
792                after_fed_ecash_balance.msats,
793                "new balance did not equal prev balance minus withdraw_amount minus fees"
794            );
795        }
796
797        Ok(())
798    }
799
800    pub fn calculate_federation_id(&self) -> String {
801        self.client_config()
802            .unwrap()
803            .global
804            .calculate_federation_id()
805            .to_string()
806    }
807
808    pub async fn await_block_sync(&self) -> Result<u64> {
809        let finality_delay = self.get_finality_delay()?;
810        let block_count = self.bitcoind.get_block_count().await?;
811        let expected = block_count.saturating_sub(finality_delay.into());
812        cmd!(
813            self.internal_client().await?,
814            "dev",
815            "wait-block-count",
816            expected
817        )
818        .run()
819        .await?;
820        Ok(expected)
821    }
822
823    fn get_finality_delay(&self) -> Result<u32, anyhow::Error> {
824        let client_config = &self.client_config()?;
825        let wallet_cfg = client_config
826            .modules
827            .get(&LEGACY_HARDCODED_INSTANCE_ID_WALLET)
828            .context("wallet module not found")?
829            .clone()
830            .redecode_raw(&ModuleDecoderRegistry::new([(
831                LEGACY_HARDCODED_INSTANCE_ID_WALLET,
832                fedimint_wallet_client::KIND,
833                fedimint_wallet_client::WalletModuleTypes::decoder(),
834            )]))?;
835        let wallet_cfg: &WalletClientConfig = wallet_cfg.cast()?;
836
837        let finality_delay = wallet_cfg.finality_delay;
838        Ok(finality_delay)
839    }
840
841    pub async fn await_gateways_registered(&self) -> Result<()> {
842        let start_time = Instant::now();
843        debug!(target: LOG_DEVIMINT, "Awaiting LN gateways registration");
844
845        poll("gateways registered", || async {
846            let num_gateways = cmd!(
847                self.internal_client()
848                    .await
849                    .map_err(ControlFlow::Continue)?,
850                "list-gateways"
851            )
852            .out_json()
853            .await
854            .map_err(ControlFlow::Continue)?
855            .as_array()
856            .context("invalid output")
857            .map_err(ControlFlow::Break)?
858            .len();
859            poll_eq!(num_gateways, 1)
860        })
861        .await?;
862        debug!(target: LOG_DEVIMINT,
863            elapsed_ms = %start_time.elapsed().as_millis(),
864            "Gateways registered");
865        Ok(())
866    }
867
868    pub async fn await_all_peers(&self) -> Result<()> {
869        let fedimin_cli_version = crate::util::FedimintCli::version_or_default().await;
870        poll("Waiting for all peers to be online", || async {
871            if fedimin_cli_version < *VERSION_0_6_0_ALPHA {
872                cmd!(
873                    self.internal_client()
874                        .await
875                        .map_err(ControlFlow::Continue)?,
876                    "dev",
877                    "api",
878                    "module_{LEGACY_HARDCODED_INSTANCE_ID_WALLET}_block_count"
879                )
880            } else {
881                cmd!(
882                    self.internal_client()
883                        .await
884                        .map_err(ControlFlow::Continue)?,
885                    "dev",
886                    "api",
887                    "--module",
888                    LEGACY_HARDCODED_INSTANCE_ID_WALLET,
889                    "block_count"
890                )
891            }
892            .run()
893            .await
894            .map_err(ControlFlow::Continue)?;
895            Ok(())
896        })
897        .await
898    }
899
900    /// Mines enough blocks to finalize mempool transactions, then waits for
901    /// federation to process finalized blocks.
902    ///
903    /// ex:
904    ///   tx submitted to mempool at height 100
905    ///   finality delay = 10
906    ///   mine finality delay blocks + 1 => new height 111
907    ///   tx included in block 101
908    ///   highest finalized height = 111 - 10 = 101
909    pub async fn finalize_mempool_tx(&self) -> Result<()> {
910        let finality_delay = self.get_finality_delay()?;
911        let blocks_to_mine = finality_delay + 1;
912        self.bitcoind.mine_blocks(blocks_to_mine.into()).await?;
913        self.await_block_sync().await?;
914        Ok(())
915    }
916
917    pub async fn mine_then_wait_blocks_sync(&self, blocks: u64) -> Result<()> {
918        self.bitcoind.mine_blocks(blocks).await?;
919        self.await_block_sync().await?;
920        Ok(())
921    }
922
923    pub fn num_members(&self) -> usize {
924        self.members.len()
925    }
926
927    pub fn member_ids(&self) -> impl Iterator<Item = PeerId> + '_ {
928        self.members
929            .keys()
930            .map(|&peer_id| PeerId::from(peer_id as u16))
931    }
932}
933
934#[derive(Clone)]
935pub struct Fedimintd {
936    _bitcoind: Bitcoind,
937    process: ProcessHandle,
938}
939
940impl Fedimintd {
941    pub async fn new(
942        process_mgr: &ProcessManager,
943        bitcoind: Bitcoind,
944        peer_id: usize,
945        env: &vars::Fedimintd,
946        fed_name: String,
947    ) -> Result<Self> {
948        debug!(target: LOG_DEVIMINT, "Starting fedimintd-{fed_name}-{peer_id}");
949        let process = process_mgr
950            .spawn_daemon(
951                &format!("fedimintd-{fed_name}-{peer_id}"),
952                cmd!(FedimintdCmd).envs(env.vars()),
953            )
954            .await?;
955
956        Ok(Self {
957            _bitcoind: bitcoind,
958            process,
959        })
960    }
961
962    pub async fn terminate(self) -> Result<()> {
963        self.process.terminate().await
964    }
965}
966
967pub async fn run_cli_dkg(
968    params: HashMap<PeerId, ConfigGenParams>,
969    endpoints: BTreeMap<PeerId, String>,
970) -> Result<()> {
971    let auth_for = |peer: &PeerId| -> &ApiAuth { &params[peer].api_auth };
972
973    debug!(target: LOG_DEVIMINT, "Running DKG");
974    for endpoint in endpoints.values() {
975        poll("trying-to-connect-to-peers", || async {
976            crate::util::FedimintCli
977                .ws_status(endpoint)
978                .await
979                .context("dkg status")
980                .map_err(ControlFlow::Continue)
981        })
982        .await?;
983    }
984
985    debug!(target: LOG_DEVIMINT, "Connected to all peers");
986
987    for (peer_id, endpoint) in &endpoints {
988        let status = crate::util::FedimintCli.ws_status(endpoint).await?;
989        assert_eq!(
990            status.server,
991            ServerStatusLegacy::AwaitingPassword,
992            "peer_id isn't waiting for password: {peer_id}"
993        );
994    }
995
996    debug!(target: LOG_DEVIMINT, "Setting passwords");
997    for (peer_id, endpoint) in &endpoints {
998        crate::util::FedimintCli
999            .set_password(auth_for(peer_id), endpoint)
1000            .await?;
1001    }
1002    let (leader_id, leader_endpoint) = endpoints.first_key_value().context("missing peer")?;
1003    let followers = endpoints
1004        .iter()
1005        .filter(|(id, _)| *id != leader_id)
1006        .collect::<BTreeMap<_, _>>();
1007
1008    debug!(target: LOG_DEVIMINT, "calling set_config_gen_connections for leader");
1009    let leader_name = "leader".to_string();
1010    crate::util::FedimintCli
1011        .set_config_gen_connections(auth_for(leader_id), leader_endpoint, &leader_name, None)
1012        .await?;
1013
1014    let server_gen_params = ServerModuleConfigGenParamsRegistry::default();
1015
1016    debug!(target: LOG_DEVIMINT, "calling set_config_gen_params for leader");
1017    cli_set_config_gen_params(
1018        leader_endpoint,
1019        auth_for(leader_id),
1020        server_gen_params.clone(),
1021    )
1022    .await?;
1023
1024    let followers_names = followers
1025        .keys()
1026        .map(|peer_id| {
1027            (*peer_id, {
1028                // This is to be clear that the name will be unrelated to peer id
1029                let random_string = rand::thread_rng()
1030                    .sample_iter(&rand::distributions::Alphanumeric)
1031                    .take(5)
1032                    .map(char::from)
1033                    .collect::<String>();
1034                format!("random-{random_string}{peer_id}")
1035            })
1036        })
1037        .collect::<BTreeMap<_, _>>();
1038    for (peer_id, endpoint) in &followers {
1039        let name = followers_names
1040            .get(peer_id)
1041            .context("missing follower name")?;
1042        debug!(target: LOG_DEVIMINT, "calling set_config_gen_connections for {peer_id} {name}");
1043
1044        crate::util::FedimintCli
1045            .set_config_gen_connections(auth_for(peer_id), endpoint, name, Some(leader_endpoint))
1046            .await?;
1047
1048        cli_set_config_gen_params(endpoint, auth_for(peer_id), server_gen_params.clone()).await?;
1049    }
1050
1051    debug!(target: LOG_DEVIMINT, "calling get_config_gen_peers for leader");
1052    let peers = crate::util::FedimintCli
1053        .get_config_gen_peers(leader_endpoint)
1054        .await?;
1055
1056    let found_names = peers
1057        .into_iter()
1058        .map(|peer| peer.name)
1059        .collect::<HashSet<_>>();
1060    let all_names = followers_names
1061        .values()
1062        .cloned()
1063        .chain(iter::once(leader_name))
1064        .collect::<HashSet<_>>();
1065    assert_eq!(found_names, all_names);
1066
1067    debug!(target: LOG_DEVIMINT, "Waiting for SharingConfigGenParams");
1068    cli_wait_server_status(leader_endpoint, ServerStatusLegacy::SharingConfigGenParams).await?;
1069
1070    debug!(target: LOG_DEVIMINT, "Getting consensus configs");
1071    let mut configs = vec![];
1072    for endpoint in endpoints.values() {
1073        let config = crate::util::FedimintCli
1074            .consensus_config_gen_params_legacy(endpoint)
1075            .await?;
1076        configs.push(config);
1077    }
1078    // Confirm all consensus configs are the same
1079    let mut consensus: Vec<_> = configs.iter().map(|p| p.consensus.clone()).collect();
1080    consensus.dedup();
1081    assert_eq!(consensus.len(), 1);
1082    // Confirm all peer ids are unique
1083    let ids = configs
1084        .iter()
1085        .map(|p| p.our_current_id)
1086        .collect::<HashSet<_>>();
1087    assert_eq!(ids.len(), endpoints.len());
1088    let dkg_results = endpoints
1089        .iter()
1090        .map(|(peer_id, endpoint)| crate::util::FedimintCli.run_dkg(auth_for(peer_id), endpoint));
1091    debug!(target: LOG_DEVIMINT, "Running DKG");
1092    let (dkg_results, leader_wait_result) = tokio::join!(
1093        join_all(dkg_results),
1094        cli_wait_server_status(leader_endpoint, ServerStatusLegacy::VerifyingConfigs)
1095    );
1096    for result in dkg_results {
1097        result?;
1098    }
1099    leader_wait_result?;
1100
1101    // verify config hashes equal for all peers
1102    debug!(target: LOG_DEVIMINT, "Verifying config hashes");
1103    let mut hashes = HashSet::new();
1104    for (peer_id, endpoint) in &endpoints {
1105        cli_wait_server_status(endpoint, ServerStatusLegacy::VerifyingConfigs).await?;
1106        let hash = crate::util::FedimintCli
1107            .get_verify_config_hash(auth_for(peer_id), endpoint)
1108            .await?;
1109        hashes.insert(hash);
1110    }
1111    assert_eq!(hashes.len(), 1);
1112    for (peer_id, endpoint) in &endpoints {
1113        let result = crate::util::FedimintCli
1114            .start_consensus(auth_for(peer_id), endpoint)
1115            .await;
1116        if let Err(e) = result {
1117            tracing::debug!(target: LOG_DEVIMINT, "Error calling start_consensus: {e:?}, trying to continue...");
1118        }
1119        cli_wait_server_status(endpoint, ServerStatusLegacy::ConsensusRunning).await?;
1120    }
1121    Ok(())
1122}
1123
1124pub async fn run_cli_dkg_v2(
1125    params: HashMap<PeerId, ConfigGenParams>,
1126    endpoints: BTreeMap<PeerId, String>,
1127) -> Result<()> {
1128    let auth_for = |peer: &PeerId| -> &ApiAuth { &params[peer].api_auth };
1129
1130    for (peer, endpoint) in &endpoints {
1131        let status = poll("awaiting-setup-status-awaiting-local-params", || async {
1132            crate::util::FedimintCli
1133                .setup_status(auth_for(peer), endpoint)
1134                .await
1135                .map_err(ControlFlow::Continue)
1136        })
1137        .await
1138        .unwrap();
1139
1140        assert_eq!(status, SetupStatus::AwaitingLocalParams);
1141    }
1142
1143    debug!(target: LOG_DEVIMINT, "Setting local parameters...");
1144
1145    let mut connection_info = BTreeMap::new();
1146
1147    for (peer, endpoint) in &endpoints {
1148        let info = if peer.to_usize() == 0 {
1149            crate::util::FedimintCli
1150                .set_local_params_leader(peer, auth_for(peer), endpoint)
1151                .await?
1152        } else {
1153            crate::util::FedimintCli
1154                .set_local_params_follower(peer, auth_for(peer), endpoint)
1155                .await?
1156        };
1157
1158        connection_info.insert(peer, info);
1159    }
1160
1161    debug!(target: LOG_DEVIMINT, "Exchanging peer connection info...");
1162
1163    for (peer, info) in connection_info {
1164        for (p, endpoint) in &endpoints {
1165            if p != peer {
1166                crate::util::FedimintCli
1167                    .add_peer(&info, auth_for(p), endpoint)
1168                    .await?;
1169            }
1170        }
1171    }
1172
1173    debug!(target: LOG_DEVIMINT, "Starting DKG...");
1174
1175    for (peer, endpoint) in &endpoints {
1176        crate::util::FedimintCli
1177            .start_dkg(auth_for(peer), endpoint)
1178            .await?;
1179    }
1180
1181    Ok(())
1182}
1183
1184async fn cli_set_config_gen_params(
1185    endpoint: &str,
1186    auth: &ApiAuth,
1187    mut server_gen_params: ServerModuleConfigGenParamsRegistry,
1188) -> Result<()> {
1189    self::config::attach_default_module_init_params(
1190        &BitcoinRpcConfig::get_defaults_from_env_vars()?,
1191        &mut server_gen_params,
1192        Network::Regtest,
1193        10,
1194    );
1195
1196    let meta = iter::once(("federation_name".to_string(), "testfed".to_string())).collect();
1197
1198    crate::util::FedimintCli
1199        .set_config_gen_params(auth, endpoint, meta, server_gen_params)
1200        .await?;
1201
1202    Ok(())
1203}
1204
1205async fn cli_wait_server_status(endpoint: &str, expected_status: ServerStatusLegacy) -> Result<()> {
1206    poll(
1207        &format!("waiting-server-status: {expected_status:?}"),
1208        || async {
1209            let server_status = crate::util::FedimintCli
1210                .ws_status(endpoint)
1211                .await
1212                .context("server status")
1213                .map_err(ControlFlow::Continue)?
1214                .server;
1215            if server_status == expected_status {
1216                Ok(())
1217            } else {
1218                Err(ControlFlow::Continue(anyhow!(
1219                    "expected status: {expected_status:?} current status: {server_status:?}"
1220                )))
1221            }
1222        },
1223    )
1224    .await?;
1225    Ok(())
1226}