Skip to main content

devimint/
federation.rs

1use std::collections::BTreeMap;
2use std::future::Future;
3use std::ops::ControlFlow;
4use std::path::{Path, PathBuf};
5use std::str::FromStr;
6use std::time::Duration;
7use std::{env, fs};
8
9use anyhow::{Context, Result, bail};
10use fedimint_api_client::api::{ClientConfigDownloadError, DynGlobalApi};
11use fedimint_api_client::try_download_client_config;
12use fedimint_client_module::module::ClientModule;
13use fedimint_connectors::ConnectorRegistry;
14use fedimint_core::admin_client::SetupStatus;
15use fedimint_core::config::{ClientConfig, load_from_file};
16use fedimint_core::core::{Account, ModuleInstanceId, ModuleKind};
17use fedimint_core::invite_code::InviteCode;
18use fedimint_core::module::ModuleCommon;
19use fedimint_core::module::registry::ModuleDecoderRegistry;
20use fedimint_core::runtime::block_in_place;
21use fedimint_core::task::block_on;
22use fedimint_core::task::jit::JitTry;
23use fedimint_core::util::SafeUrl;
24use fedimint_core::{Amount, NumPeers, PeerId};
25use fedimint_gateway_common::WithdrawResponse;
26use fedimint_logging::LOG_DEVIMINT;
27use fedimint_server::config::io::{CONSENSUS_CONFIG, JSON_EXT, LOCAL_CONFIG, PRIVATE_CONFIG};
28use fedimint_testing_core::config::API_AUTH;
29use fedimint_testing_core::node_type::LightningNodeType;
30use fedimint_wallet_client::WalletClientModule;
31use fedimint_wallet_client::config::WalletClientConfig;
32use fs_lock::FileLock;
33use futures::future::{join_all, try_join_all};
34use tokio::task::{JoinSet, spawn_blocking};
35use tokio::time::Instant;
36use tracing::{debug, info};
37
38use super::external::Bitcoind;
39use super::util::{Command, ProcessHandle, ProcessManager, cmd};
40use super::vars::utf8;
41use crate::envs::{FM_CLIENT_DIR_ENV, FM_DATA_DIR_ENV};
42use crate::util::{FedimintdCmd, poll, poll_simple, poll_with_timeout};
43use crate::version_constants::{VERSION_0_10_0_ALPHA, VERSION_0_11_0_ALPHA, VERSION_0_12_0_ALPHA};
44use crate::{poll_almost_equal, poll_eq, vars};
45
46// TODO: Are we still using the 3rd port for anything?
47/// Number of ports we allocate for every `fedimintd` instance
48pub const PORTS_PER_FEDIMINTD: u16 = 4;
49/// Which port is for p2p inside the range from [`PORTS_PER_FEDIMINTD`]
50pub const FEDIMINTD_P2P_PORT_OFFSET: u16 = 0;
51/// Which port is for api inside the range from [`PORTS_PER_FEDIMINTD`]
52pub const FEDIMINTD_API_PORT_OFFSET: u16 = 1;
53/// Which port is for the web ui inside the range from [`PORTS_PER_FEDIMINTD`]
54pub const FEDIMINTD_UI_PORT_OFFSET: u16 = 2;
55/// Which port is for prometheus inside the range from [`PORTS_PER_FEDIMINTD`]
56pub const FEDIMINTD_METRICS_PORT_OFFSET: u16 = 3;
57
58/// Runs one readiness query for every peer expected to be running.
59async fn query_running_peers<T, Q, F>(members: &BTreeMap<usize, T>, mut query: Q) -> Result<()>
60where
61    Q: FnMut(usize) -> F,
62    F: Future<Output = Result<()>>,
63{
64    for peer_id in members.keys().copied() {
65        query(peer_id)
66            .await
67            .with_context(|| format!("peer {peer_id} is not online"))?;
68    }
69    Ok(())
70}
71
72async fn await_client_config(connectors: &ConnectorRegistry, invite: &InviteCode) -> Result<()> {
73    let api = DynGlobalApi::new(
74        connectors.clone(),
75        invite.peers(),
76        invite.api_secret().as_deref(),
77    );
78    // The invite file is written before module initialization and the consensus
79    // API starts. Fixture readiness must not depend on the short, finite retry
80    // policy used by client-config downloads in tests.
81    poll("awaiting client config API", || async {
82        match try_download_client_config(
83            connectors,
84            &api,
85            invite.federation_id(),
86            invite.api_secret(),
87        )
88        .await
89        {
90            Ok(_) => Ok(()),
91            Err(err @ ClientConfigDownloadError::Federation(_)) => {
92                Err(ControlFlow::Continue(err.into()))
93            }
94            Err(err) => Err(ControlFlow::Break(err.into())),
95        }
96    })
97    .await
98}
99
100#[derive(Clone)]
101pub struct Federation {
102    // client is only for internal use, use cli commands instead
103    pub members: BTreeMap<usize, Fedimintd>,
104    pub vars: BTreeMap<usize, vars::Fedimintd>,
105    pub bitcoind: Bitcoind,
106
107    /// Built in [`Client`], already joined
108    client: JitTry<Client, anyhow::Error>,
109    #[allow(dead_code)] // Will need it later, maybe
110    connectors: ConnectorRegistry,
111}
112
113impl Drop for Federation {
114    fn drop(&mut self) {
115        block_in_place(|| {
116            block_on(async {
117                let mut set = JoinSet::new();
118
119                while let Some((_id, fedimintd)) = self.members.pop_first() {
120                    set.spawn(async { drop(fedimintd) });
121                }
122                while (set.join_next().await).is_some() {}
123            });
124        });
125    }
126}
127/// `fedimint-cli` instance (basically path with client state: config + db)
128#[derive(Clone)]
129pub struct Client {
130    name: String,
131}
132
133impl Client {
134    fn clients_dir() -> PathBuf {
135        let data_dir: PathBuf = env::var(FM_DATA_DIR_ENV)
136            .expect("FM_DATA_DIR_ENV not set")
137            .parse()
138            .expect("FM_DATA_DIR_ENV invalid");
139        data_dir.join("clients")
140    }
141
142    fn client_dir(&self) -> PathBuf {
143        Self::clients_dir().join(&self.name)
144    }
145
146    pub fn client_name_lock(name: &str) -> Result<FileLock> {
147        let lock_path = Self::clients_dir().join(format!(".{name}.lock"));
148        let file_lock = std::fs::OpenOptions::new()
149            .write(true)
150            .create(true)
151            .truncate(true)
152            .open(&lock_path)
153            .with_context(|| format!("Failed to open {}", lock_path.display()))?;
154
155        fs_lock::FileLock::new_exclusive(file_lock)
156            .with_context(|| format!("Failed to lock {}", lock_path.display()))
157    }
158
159    /// Create a [`Client`] that starts with a fresh state.
160    pub async fn create(name: impl ToString) -> Result<Client> {
161        let name = name.to_string();
162        spawn_blocking(move || {
163            let _lock = Self::client_name_lock(&name);
164            for i in 0u64.. {
165                let client = Self {
166                    name: format!("{name}-{i}"),
167                };
168
169                if !client.client_dir().exists() {
170                    std::fs::create_dir_all(client.client_dir())?;
171                    return Ok(client);
172                }
173            }
174            unreachable!()
175        })
176        .await?
177    }
178
179    /// Open or create a [`Client`] that starts with a fresh state.
180    pub fn open_or_create(name: &str) -> Result<Client> {
181        block_in_place(|| {
182            let _lock = Self::client_name_lock(name);
183            let client = Self {
184                name: format!("{name}-0"),
185            };
186            if !client.client_dir().exists() {
187                std::fs::create_dir_all(client.client_dir())?;
188            }
189            Ok(client)
190        })
191    }
192
193    /// Client to join a federation
194    pub async fn join_federation(&self, invite_code: String) -> Result<()> {
195        debug!(target: LOG_DEVIMINT, "Joining federation with the main client");
196        cmd!(self, "join-federation", invite_code).run().await?;
197
198        Ok(())
199    }
200
201    /// Client to join a federation with a restore procedure
202    pub async fn restore_federation(&self, invite_code: String, mnemonic: String) -> Result<()> {
203        debug!(target: LOG_DEVIMINT, "Joining federation with restore procedure");
204        cmd!(
205            self,
206            "restore",
207            "--invite-code",
208            invite_code,
209            "--mnemonic",
210            mnemonic
211        )
212        .run()
213        .await?;
214
215        Ok(())
216    }
217
218    /// Client to join a federation
219    pub async fn new_restored(&self, name: &str, invite_code: String) -> Result<Self> {
220        let restored = Self::open_or_create(name)?;
221
222        let mnemonic = cmd!(self, "print-secret").out_json().await?["secret"]
223            .as_str()
224            .unwrap()
225            .to_owned();
226
227        debug!(target: LOG_DEVIMINT, name, "Restoring from mnemonic");
228        cmd!(
229            restored,
230            "restore",
231            "--invite-code",
232            invite_code,
233            "--mnemonic",
234            mnemonic
235        )
236        .run()
237        .await?;
238
239        Ok(restored)
240    }
241
242    /// Create a [`Client`] that starts with a state that is a copy of
243    /// of another one.
244    pub async fn new_forked(&self, name: impl ToString) -> Result<Client> {
245        let new = Client::create(name).await?;
246
247        cmd!(
248            "cp",
249            "-R",
250            self.client_dir().join("client.db").display(),
251            new.client_dir().display()
252        )
253        .run()
254        .await?;
255
256        Ok(new)
257    }
258
259    pub async fn balance(&self) -> Result<u64> {
260        Ok(cmd!(self, "info").out_json().await?["total_amount_msat"]
261            .as_u64()
262            .unwrap())
263    }
264
265    /// The balance of one of the client's accounts in msats. Requires a
266    /// `fedimint-cli` of 0.14.0-alpha or later, which added accounts.
267    pub async fn balance_for(&self, account: Account) -> Result<u64> {
268        cmd!(self, "info", "--account", account.to_string())
269            .out_json()
270            .await?["total_amount_msat"]
271            .as_u64()
272            .with_context(|| format!("info --account {account} has no total_amount_msat"))
273    }
274
275    /// Waits for the client balance to reach at least `min_balance_msat`.
276    pub async fn await_balance(&self, min_balance_msat: u64) -> Result<()> {
277        loop {
278            cmd!(self, "dev", "wait", "3").out_json().await?;
279
280            let balance = self.balance().await?;
281            if min_balance_msat <= balance {
282                return Ok(());
283            }
284
285            info!(
286                target: LOG_DEVIMINT,
287                balance,
288                min_balance_msat,
289                "Waiting for client balance to reach minimum"
290            );
291        }
292    }
293
294    /// Waits for the next walletv2 receive recorded at or after `position` (as
295    /// returned by [`Self::get_deposit_addr`] or a prior `await_receive`) to be
296    /// claimed, and returns the event log position to use for the following
297    /// wait.
298    pub async fn await_receive(&self, position: &str) -> Result<String> {
299        let output = cmd!(self, "module", "walletv2", "await-receive", position)
300            .out_json()
301            .await?;
302
303        // Walletv2 `await-receive` returns `[final_state, next_position]`.
304        Ok(output[1].to_string())
305    }
306
307    pub async fn get_deposit_addr(&self) -> Result<(String, String)> {
308        if crate::util::supports_wallet_v2() {
309            if crate::util::FedimintCli::version_or_default().await >= *VERSION_0_12_0_ALPHA {
310                // Capture the event log position *before* deriving the address so
311                // `await_receive` can wait from it; there is no operation id as
312                // deposits are auto-claimed.
313                let position = cmd!(self, "dev", "next-event-log-id").out_json().await?;
314
315                let address = cmd!(self, "module", "walletv2", "receive")
316                    .out_json()
317                    .await?;
318
319                Ok((address.as_str().unwrap().to_string(), position.to_string()))
320            } else {
321                // Legacy walletv2 (<= 0.11): `receive` returns the bare address
322                // and deposits are auto-claimed, so there is no position or
323                // operation id to wait on.
324                let address = cmd!(self, "module", "walletv2", "receive")
325                    .out_json()
326                    .await?;
327
328                Ok((address.as_str().unwrap().to_string(), String::new()))
329            }
330        } else {
331            let deposit = cmd!(self, "module", "wallet", "new-deposit-address")
332                .out_json()
333                .await?;
334            Ok((
335                deposit["address"].as_str().unwrap().to_string(),
336                deposit["operation_id"].as_str().unwrap().to_string(),
337            ))
338        }
339    }
340
341    pub async fn await_deposit(&self, operation_id: &str) -> Result<()> {
342        cmd!(
343            self,
344            "module",
345            "wallet",
346            "await-deposit",
347            "--operation-id",
348            operation_id
349        )
350        .run()
351        .await
352    }
353
354    pub fn cmd(&self) -> Command {
355        cmd!(
356            crate::util::get_fedimint_cli_path(),
357            format!("--data-dir={}", self.client_dir().display())
358        )
359    }
360
361    pub fn get_name(&self) -> &str {
362        &self.name
363    }
364
365    /// Returns the current consensus session count
366    pub async fn get_session_count(&self) -> Result<u64> {
367        cmd!(self, "dev", "session-count").out_json().await?["count"]
368            .as_u64()
369            .context("count field wasn't a number")
370    }
371
372    /// Returns once all active state machines complete
373    pub async fn wait_complete(&self) -> Result<()> {
374        cmd!(self, "dev", "wait-complete").run().await
375    }
376
377    /// Returns once the current session completes
378    pub async fn wait_session(&self) -> anyhow::Result<()> {
379        info!("Waiting for a new session");
380        let session_count = self.get_session_count().await?;
381        self.wait_session_outcome(session_count).await?;
382        Ok(())
383    }
384
385    /// Returns once the provided session count completes
386    pub async fn wait_session_outcome(&self, session_count: u64) -> anyhow::Result<()> {
387        let timeout = {
388            let current_session_count = self.get_session_count().await?;
389            let sessions_to_wait = session_count.saturating_sub(current_session_count) + 1;
390            let session_duration_seconds = 180;
391            Duration::from_secs(sessions_to_wait * session_duration_seconds)
392        };
393
394        let start = Instant::now();
395        poll_with_timeout("Waiting for a new session", timeout, || async {
396            info!("Awaiting session outcome {session_count}");
397            match cmd!(self, "dev", "api", "await_session_outcome", session_count)
398                .run()
399                .await
400            {
401                Err(e) => Err(ControlFlow::Continue(e)),
402                Ok(()) => Ok(()),
403            }
404        })
405        .await?;
406
407        let session_found_in = start.elapsed();
408        info!("session found in {session_found_in:?}");
409        Ok(())
410    }
411}
412
413impl Federation {
414    pub async fn new(
415        process_mgr: &ProcessManager,
416        bitcoind: Bitcoind,
417        skip_setup: bool,
418        pre_dkg: bool,
419        pre_restore: bool,
420        // Which of the pre-allocated federations to use (most tests just use single `0` one)
421        fed_index: usize,
422        federation_name: String,
423    ) -> Result<Self> {
424        let num_peers = NumPeers::new(process_mgr.globals.FM_FED_SIZE)
425            .ok_or_else(|| anyhow::anyhow!("a federation must have at least one guardian"))?;
426        let mut members = BTreeMap::new();
427        let mut peer_to_env_vars_map = BTreeMap::new();
428
429        let mut admin_clients: BTreeMap<PeerId, DynGlobalApi> = BTreeMap::new();
430        let mut api_endpoints: BTreeMap<PeerId, _> = BTreeMap::new();
431
432        let connectors = ConnectorRegistry::build_from_testing_env().bind().await;
433        for peer_id in num_peers.peer_ids() {
434            let peer_env_vars = vars::Fedimintd::init(
435                &process_mgr.globals,
436                federation_name.clone(),
437                peer_id,
438                process_mgr
439                    .globals
440                    .fedimintd_overrides
441                    .peer_expect(fed_index, peer_id),
442            )
443            .await?;
444            members.insert(
445                peer_id.to_usize(),
446                Fedimintd::new(
447                    process_mgr,
448                    bitcoind.clone(),
449                    peer_id.to_usize(),
450                    &peer_env_vars,
451                    federation_name.clone(),
452                )
453                .await?,
454            );
455            let admin_client = DynGlobalApi::new_admin_setup(
456                connectors.clone(),
457                SafeUrl::parse(&peer_env_vars.FM_API_URL)?,
458                // TODO: will need it somewhere
459                // &process_mgr.globals.FM_FORCE_API_SECRETS.get_active(),
460            );
461            api_endpoints.insert(peer_id, peer_env_vars.FM_API_URL.clone());
462            admin_clients.insert(peer_id, admin_client);
463            peer_to_env_vars_map.insert(peer_id.to_usize(), peer_env_vars);
464        }
465
466        if !skip_setup && !pre_dkg {
467            // we don't guarantee backwards-compatibility for dkg, so we use the
468            // fedimint-cli version that matches fedimintd
469            let (original_fedimint_cli_path, original_fm_mint_client) =
470                crate::util::use_matching_fedimint_cli_for_dkg().await?;
471
472            run_cli_dkg_v2(api_endpoints).await?;
473
474            // we're done with dkg, so we can reset the fedimint-cli version
475            crate::util::use_fedimint_cli(original_fedimint_cli_path, original_fm_mint_client);
476
477            // move configs to config directory
478            let client_dir = utf8(&process_mgr.globals.FM_CLIENT_DIR);
479            let invite_code_filename_original = "invite-code";
480
481            for peer_env_vars in peer_to_env_vars_map.values() {
482                let peer_data_dir = utf8(&peer_env_vars.FM_DATA_DIR);
483
484                let invite_code = poll_simple("awaiting-invite-code", || async {
485                    let path = format!("{peer_data_dir}/{invite_code_filename_original}");
486                    tokio::fs::read_to_string(&path)
487                        .await
488                        .with_context(|| format!("Awaiting invite code file: {path}"))
489                })
490                .await
491                .context("Awaiting invite code file")?;
492
493                await_client_config(&connectors, &InviteCode::from_str(&invite_code)?).await?;
494            }
495
496            // copy over invite-code file to client directory
497            let peer_data_dir = utf8(&peer_to_env_vars_map[&0].FM_DATA_DIR);
498
499            tokio::fs::copy(
500                format!("{peer_data_dir}/{invite_code_filename_original}"),
501                format!("{client_dir}/{invite_code_filename_original}"),
502            )
503            .await
504            .context("copying invite-code file")?;
505
506            // move each guardian's invite-code file to the client's directory
507            // appending the peer id to the end
508            for (index, peer_env_vars) in &peer_to_env_vars_map {
509                let peer_data_dir = utf8(&peer_env_vars.FM_DATA_DIR);
510
511                let invite_code_filename_indexed =
512                    format!("{invite_code_filename_original}-{index}");
513                tokio::fs::rename(
514                    format!("{peer_data_dir}/{invite_code_filename_original}"),
515                    format!("{client_dir}/{invite_code_filename_indexed}"),
516                )
517                .await
518                .context("moving invite-code file")?;
519            }
520
521            debug!("Moved invite-code files to client data directory");
522
523            if pre_restore {
524                Self::restart_guardian_for_manual_restore(
525                    process_mgr,
526                    &mut members,
527                    &peer_to_env_vars_map,
528                    &bitcoind,
529                )
530                .await?;
531            }
532        }
533
534        let client = JitTry::<_, anyhow::Error>::new_try({
535            move || async move {
536                let client = Client::open_or_create(federation_name.as_str())?;
537                let invite_code = Self::invite_code_static()?;
538                if !skip_setup && !pre_dkg {
539                    cmd!(client, "join-federation", invite_code).run().await?;
540                }
541                Ok(client)
542            }
543        });
544
545        Ok(Self {
546            members,
547            vars: peer_to_env_vars_map,
548            bitcoind,
549            client,
550            connectors,
551        })
552    }
553
554    async fn restart_guardian_for_manual_restore(
555        process_mgr: &ProcessManager,
556        members: &mut BTreeMap<usize, Fedimintd>,
557        peer_to_env_vars_map: &BTreeMap<usize, vars::Fedimintd>,
558        bitcoind: &Bitcoind,
559    ) -> Result<()> {
560        const RESTORE_PEER: usize = 0;
561
562        let peer_env_vars = &peer_to_env_vars_map[&RESTORE_PEER];
563        let backup_dir = process_mgr.globals.FM_TEST_DIR.join("fedimintd-backups");
564        tokio::fs::create_dir_all(&backup_dir)
565            .await
566            .context("Creating fedimintd backup directory")?;
567        let backup_path = backup_dir.join("fedimint-0-guardian-backup.tar");
568
569        Self::write_guardian_backup_tar(&peer_env_vars.FM_DATA_DIR, &backup_path).await?;
570        info!(
571            target: LOG_DEVIMINT,
572            path = %backup_path.display(),
573            "Wrote guardian backup for manual restore"
574        );
575
576        let fedimintd = members
577            .remove(&RESTORE_PEER)
578            .context("Missing fedimint-0 process")?;
579        fedimintd.terminate().await?;
580        tokio::fs::remove_dir_all(&peer_env_vars.FM_DATA_DIR)
581            .await
582            .with_context(|| format!("Removing {}", peer_env_vars.FM_DATA_DIR.display()))?;
583        tokio::fs::create_dir_all(&peer_env_vars.FM_DATA_DIR)
584            .await
585            .with_context(|| format!("Creating {}", peer_env_vars.FM_DATA_DIR.display()))?;
586
587        let fedimintd = Fedimintd::new(
588            process_mgr,
589            bitcoind.clone(),
590            RESTORE_PEER,
591            peer_env_vars,
592            "default".to_string(),
593        )
594        .await?;
595        members.insert(RESTORE_PEER, fedimintd);
596
597        info!(
598            target: LOG_DEVIMINT,
599            ui = %peer_env_vars.FM_BIND_UI,
600            backup = %backup_path.display(),
601            "fedimint-0 restarted in setup mode for manual restore"
602        );
603
604        Ok(())
605    }
606
607    async fn write_guardian_backup_tar(data_dir: &Path, backup_path: &Path) -> Result<()> {
608        let data_dir = data_dir.to_path_buf();
609        let backup_path = backup_path.to_path_buf();
610        spawn_blocking(move || {
611            let file = fs::File::options()
612                .write(true)
613                .create_new(true)
614                .open(&backup_path)
615                .with_context(|| format!("Creating {}", backup_path.display()))?;
616            let mut archive = tar::Builder::new(file);
617            for path in [
618                PathBuf::from(LOCAL_CONFIG).with_extension(JSON_EXT),
619                PathBuf::from(CONSENSUS_CONFIG).with_extension(JSON_EXT),
620                PathBuf::from(PRIVATE_CONFIG).with_extension(JSON_EXT),
621            ] {
622                archive
623                    .append_path_with_name(data_dir.join(&path), &path)
624                    .with_context(|| format!("Adding {} to backup", path.display()))?;
625            }
626            archive.finish().context("Finishing guardian backup tar")?;
627            Ok::<_, anyhow::Error>(())
628        })
629        .await?
630    }
631
632    pub fn client_config(&self) -> Result<ClientConfig> {
633        let cfg_path = self.vars[&0].FM_DATA_DIR.join("client.json");
634        Ok(load_from_file(&cfg_path)?)
635    }
636
637    /// Get the module instance ID for a given module kind
638    pub fn module_instance_id_by_kind(&self, kind: &ModuleKind) -> Result<ModuleInstanceId> {
639        self.client_config()?
640            .modules
641            .iter()
642            .find_map(|(id, cfg)| if &cfg.kind == kind { Some(*id) } else { None })
643            .with_context(|| format!("Module kind {kind} not found"))
644    }
645
646    pub fn module_client_config<M: ClientModule>(
647        &self,
648    ) -> Result<Option<<M::Common as ModuleCommon>::ClientConfig>> {
649        self.client_config()?
650            .modules
651            .iter()
652            .find_map(|(module_instance_id, module_cfg)| {
653                if module_cfg.kind == M::kind() {
654                    let decoders = ModuleDecoderRegistry::new(vec![(
655                        *module_instance_id,
656                        M::kind(),
657                        M::decoder(),
658                    )]);
659                    Some(
660                        module_cfg
661                            .config
662                            .clone()
663                            .redecode_raw(&decoders)
664                            .expect("Decoding client cfg failed")
665                            .expect_decoded_ref()
666                            .as_any()
667                            .downcast_ref::<<M::Common as ModuleCommon>::ClientConfig>()
668                            .cloned()
669                            .context("Cast to module config failed"),
670                    )
671                } else {
672                    None
673                }
674            })
675            .transpose()
676    }
677
678    pub fn deposit_fees(&self) -> Result<Amount> {
679        if crate::util::supports_wallet_v2() {
680            Ok(self
681                .module_client_config::<fedimint_walletv2_client::WalletClientModule>()?
682                .context("No walletv2 module found")?
683                .fee_consensus
684                .base)
685        } else {
686            Ok(self
687                .module_client_config::<WalletClientModule>()?
688                .context("No wallet module found")?
689                .fee_consensus
690                .peg_in_abs)
691        }
692    }
693
694    /// Read the invite code from the client data dir
695    pub fn invite_code(&self) -> Result<String> {
696        let data_dir: PathBuf = env::var(FM_CLIENT_DIR_ENV)?.parse()?;
697        let invite_code = fs::read_to_string(data_dir.join("invite-code"))?;
698        Ok(invite_code)
699    }
700
701    pub fn invite_code_static() -> Result<String> {
702        let data_dir: PathBuf = env::var(FM_CLIENT_DIR_ENV)?.parse()?;
703        let invite_code = fs::read_to_string(data_dir.join("invite-code"))?;
704        Ok(invite_code)
705    }
706    pub fn invite_code_for(peer_id: PeerId) -> Result<String> {
707        let data_dir: PathBuf = env::var(FM_CLIENT_DIR_ENV)?.parse()?;
708        let name = format!("invite-code-{peer_id}");
709        let invite_code = fs::read_to_string(data_dir.join(name))?;
710        Ok(invite_code)
711    }
712
713    /// Built-in, default, internal [`Client`]
714    ///
715    /// We should be moving away from using it for anything.
716    pub async fn internal_client(&self) -> Result<&Client> {
717        self.client
718            .get_try()
719            .await
720            .context("Internal client joining Federation")
721    }
722
723    /// New [`Client`] that already joined `self`
724    pub async fn new_joined_client(&self, name: impl ToString) -> Result<Client> {
725        let client = Client::create(name).await?;
726        client.join_federation(self.invite_code()?).await?;
727        Ok(client)
728    }
729
730    /// Add a gateway to every guardian's list of lnv2 gateways.
731    ///
732    /// Clients only see lnv2 gateways that guardians have added via the
733    /// authenticated lnv2 admin endpoint. Devimint has no human
734    /// guardians, so this calls that endpoint with the well-known test
735    /// credentials for each running guardian.
736    pub async fn add_lnv2_gateway(&self, gateway: &str) -> Result<()> {
737        let client = self.internal_client().await?;
738        for peer_id in self.members.keys() {
739            // The add runs concurrently with the rest of the dev-fed setup,
740            // so a single attempt can fail transiently, e.g. on an iroh
741            // connection under CI load.
742            poll("adding lnv2 gateway", || async {
743                cmd!(
744                    client,
745                    "--our-id",
746                    peer_id.to_string(),
747                    "--password",
748                    API_AUTH.as_str(),
749                    "module",
750                    "lnv2",
751                    "gateways",
752                    "add",
753                    gateway
754                )
755                .run()
756                .await
757                .map_err(ControlFlow::Continue)
758            })
759            .await?;
760        }
761        Ok(())
762    }
763
764    pub async fn start_server(&mut self, process_mgr: &ProcessManager, peer: usize) -> Result<()> {
765        if self.members.contains_key(&peer) {
766            bail!("fedimintd-{peer} already running");
767        }
768        self.members.insert(
769            peer,
770            Fedimintd::new(
771                process_mgr,
772                self.bitcoind.clone(),
773                peer,
774                &self.vars[&peer],
775                "default".to_string(),
776            )
777            .await?,
778        );
779        Ok(())
780    }
781
782    pub async fn terminate_server(&mut self, peer_id: usize) -> Result<()> {
783        let Some((_, fedimintd)) = self.members.remove_entry(&peer_id) else {
784            bail!("fedimintd-{peer_id} does not exist");
785        };
786        fedimintd.terminate().await?;
787        Ok(())
788    }
789
790    pub async fn await_server_terminated(&mut self, peer_id: usize) -> Result<()> {
791        let Some(fedimintd) = self.members.get_mut(&peer_id) else {
792            bail!("fedimintd-{peer_id} does not exist");
793        };
794        fedimintd.await_terminated().await?;
795        self.members.remove(&peer_id);
796        Ok(())
797    }
798
799    /// Starts all peers not currently running.
800    pub async fn start_all_servers(&mut self, process_mgr: &ProcessManager) -> Result<()> {
801        info!("starting all servers");
802        let fed_size = process_mgr.globals.FM_FED_SIZE;
803        for peer_id in 0..fed_size {
804            if self.members.contains_key(&peer_id) {
805                continue;
806            }
807            self.start_server(process_mgr, peer_id).await?;
808        }
809        self.await_all_peers().await?;
810        Ok(())
811    }
812
813    /// Terminates all running peers.
814    pub async fn terminate_all_servers(&mut self) -> Result<()> {
815        info!("terminating all servers");
816        let running_peer_ids: Vec<_> = self.members.keys().copied().collect();
817        for peer_id in running_peer_ids {
818            self.terminate_server(peer_id).await?;
819        }
820        Ok(())
821    }
822
823    /// Coordinated shutdown of all peers that restart using the provided
824    /// `bin_path`. Returns `Ok()` once all peers are online.
825    ///
826    /// Staggering the restart more closely simulates upgrades in the wild.
827    pub async fn restart_all_staggered_with_bin(
828        &mut self,
829        process_mgr: &ProcessManager,
830        bin_path: &PathBuf,
831    ) -> Result<()> {
832        let fed_size = process_mgr.globals.FM_FED_SIZE;
833
834        // ensure all peers are online
835        self.start_all_servers(process_mgr).await?;
836
837        // staggered shutdown of peers
838        while self.num_members() > 0 {
839            self.terminate_server(self.num_members() - 1).await?;
840            if self.num_members() > 0 {
841                fedimint_core::task::sleep_in_test(
842                    "waiting to shutdown remaining peers",
843                    Duration::from_secs(10),
844                )
845                .await;
846            }
847        }
848
849        // TODO: Audit that the environment access only happens in single-threaded code.
850        unsafe { std::env::set_var("FM_FEDIMINTD_BASE_EXECUTABLE", bin_path) };
851
852        // staggered restart
853        for peer_id in 0..fed_size {
854            self.start_server(process_mgr, peer_id).await?;
855            if peer_id < fed_size - 1 {
856                fedimint_core::task::sleep_in_test(
857                    "waiting to restart remaining peers",
858                    Duration::from_secs(10),
859                )
860                .await;
861            }
862        }
863
864        self.await_all_peers().await?;
865
866        let fedimintd_version = crate::util::FedimintdCmd::version_or_default().await;
867        info!("upgraded fedimintd to version: {}", fedimintd_version);
868        Ok(())
869    }
870
871    pub async fn restart_all_with_bin(
872        &mut self,
873        process_mgr: &ProcessManager,
874        bin_path: &PathBuf,
875    ) -> Result<()> {
876        // get the version we're upgrading to, temporarily updating the fedimintd path
877        let current_fedimintd_path = std::env::var("FM_FEDIMINTD_BASE_EXECUTABLE")?;
878        // TODO: Audit that the environment access only happens in single-threaded code.
879        unsafe { std::env::set_var("FM_FEDIMINTD_BASE_EXECUTABLE", bin_path) };
880        // TODO: Audit that the environment access only happens in single-threaded code.
881        unsafe { std::env::set_var("FM_FEDIMINTD_BASE_EXECUTABLE", current_fedimintd_path) };
882
883        self.restart_all_staggered_with_bin(process_mgr, bin_path)
884            .await
885    }
886
887    pub async fn degrade_federation(&mut self, process_mgr: &ProcessManager) -> Result<()> {
888        let fed_size = process_mgr.globals.FM_FED_SIZE;
889        let offline_nodes = process_mgr.globals.FM_OFFLINE_NODES;
890        anyhow::ensure!(
891            fed_size > 3 * offline_nodes,
892            "too many offline nodes ({offline_nodes}) to reach consensus"
893        );
894
895        while self.num_members() > fed_size - offline_nodes {
896            self.terminate_server(self.num_members() - 1).await?;
897        }
898
899        if 0 < offline_nodes {
900            info!(fed_size, offline_nodes, "federation is degraded");
901        }
902        Ok(())
903    }
904
905    pub async fn send_to_address(&self, address: String, amount: u64) -> Result<()> {
906        self.bitcoind.send_to(address, amount).await?;
907
908        self.bitcoind.mine_blocks(21).await?;
909
910        Ok(())
911    }
912
913    pub async fn pegin_client_no_wait(&self, amount: u64, client: &Client) -> Result<String> {
914        let deposit_fees_msat = self.deposit_fees()?.msats;
915        assert_eq!(
916            deposit_fees_msat % 1000,
917            0,
918            "Deposit fees expected to be whole sats in test suite"
919        );
920        let deposit_fees = deposit_fees_msat / 1000;
921        info!(amount, deposit_fees, "Pegging-in client funds");
922
923        // For walletv1 this is the deposit operation id; for walletv2 it is the
924        // event log position to wait for the receive from.
925        let (address, handle) = client.get_deposit_addr().await?;
926
927        self.bitcoind
928            .send_to(address, amount + deposit_fees)
929            .await?;
930        self.bitcoind.mine_blocks(21).await?;
931
932        Ok(handle)
933    }
934
935    pub async fn pegin_client(&self, amount: u64, client: &Client) -> Result<()> {
936        let walletv2_await_receive = crate::util::supports_wallet_v2()
937            && crate::util::FedimintCli::version_or_default().await >= *VERSION_0_12_0_ALPHA;
938
939        // Legacy walletv2 (<= 0.11) auto-claims deposits with no way to wait on
940        // them directly, so capture the balance before the deposit to wait for
941        // it to increase.
942        let initial_balance = if crate::util::supports_wallet_v2() && !walletv2_await_receive {
943            Some(client.balance().await?)
944        } else {
945            None
946        };
947
948        let handle = self.pegin_client_no_wait(amount, client).await?;
949
950        if walletv2_await_receive {
951            // `handle` is the event log position from which to wait for the
952            // receive.
953            client.await_receive(&handle).await?;
954        } else if let Some(initial) = initial_balance {
955            // Wait for the balance to increase. We expect slightly less than
956            // `amount` due to mint module fees when creating ecash notes.
957            let expected_balance = initial + (amount * 1000 * 9 / 10);
958            client.await_balance(expected_balance).await?;
959        } else {
960            client.await_deposit(&handle).await?;
961        }
962
963        Ok(())
964    }
965
966    /// Initiates multiple peg-ins to the same federation for the set of
967    /// gateways to save on mining blocks in parallel.
968    pub async fn pegin_gateways(
969        &self,
970        amount: u64,
971        gateways: Vec<&super::gatewayd::Gatewayd>,
972    ) -> Result<()> {
973        let deposit_fees_msat = self.deposit_fees()?.msats;
974        assert_eq!(
975            deposit_fees_msat % 1000,
976            0,
977            "Deposit fees expected to be whole sats in test suite"
978        );
979        let deposit_fees = deposit_fees_msat / 1000;
980        info!(amount, deposit_fees, "Pegging-in gateway funds");
981        let fed_id = self.calculate_federation_id();
982
983        let uses_walletv2 = crate::util::supports_wallet_v2();
984
985        // Gateways record the walletv2 receive events in their payment log
986        // (since v0.11), which lets devimint wait for each deposit to actually
987        // be claimed before polling balances. Reading the log filtered to
988        // those events needs `payment-log --event-kinds` (since v0.10).
989        let walletv2_claim_wait = uses_walletv2
990            && crate::util::GatewayCli::version_or_default().await >= *VERSION_0_10_0_ALPHA;
991
992        // For walletv2, capture initial balances since deposits are auto-claimed
993        // and we need to check balance change rather than absolute balance
994        // (same approach as pegin_client).
995        let mut initial_balances = Vec::new();
996        if uses_walletv2 {
997            for gw in &gateways {
998                let balance = gw
999                    .client()
1000                    .ecash_balance(fed_id.clone())
1001                    .await
1002                    .expect("failed to fetch initial gateway balance");
1003                initial_balances.push(balance);
1004            }
1005        }
1006
1007        let mut gateway_deposit_addrs = Vec::new();
1008        for gw in gateways.clone() {
1009            let pegin_addr = gw.client().get_pegin_addr(&fed_id).await?;
1010            debug!(
1011                gateway = %gw.gw_name,
1012                ln = %gw.ln.ln_type(),
1013                address = %pegin_addr,
1014                amount_sats = amount + deposit_fees,
1015                uses_walletv2,
1016                "Sending gateway pegin"
1017            );
1018            self.bitcoind
1019                .send_to(pegin_addr.clone(), amount + deposit_fees)
1020                .await?;
1021            gateway_deposit_addrs.push(pegin_addr);
1022        }
1023
1024        let pegin_start = Instant::now();
1025        self.bitcoind.mine_blocks(21).await?;
1026        let bitcoind_block_height: u64 = self.bitcoind.get_block_count().await? - 1;
1027        debug!(
1028            bitcoind_block_height,
1029            elapsed_ms = %pegin_start.elapsed().as_millis(),
1030            "Mined gateway pegin blocks"
1031        );
1032
1033        if walletv2_claim_wait {
1034            // Block catch-up and deposit scanning are the slow parts of a
1035            // gateway pegin and have pushed past the default 60s poll budget
1036            // on degraded CI federations, so the claim wait gets a longer
1037            // timeout of its own.
1038            const CLAIM_TIMEOUT: Duration = Duration::from_secs(180);
1039            const PAYMENT_LOG_PAGE_SIZE: usize = 100;
1040
1041            try_join_all(
1042                gateways
1043                    .iter()
1044                    .enumerate()
1045                    .filter(|(_, gw)| gw.gatewayd_version >= *VERSION_0_11_0_ALPHA)
1046                    .map(|(i, gw)| {
1047                        let fed_id = fed_id.clone();
1048                        let gateway_name = gw.gw_name.clone();
1049                        let gateway_ln = gw.ln.ln_type().to_string();
1050                        let deposit_address = gateway_deposit_addrs[i].clone();
1051                        poll_with_timeout("gateway pegin claim", CLAIM_TIMEOUT, move || {
1052                            let fed_id = fed_id.clone();
1053                            let gateway_name = gateway_name.clone();
1054                            let gateway_ln = gateway_ln.clone();
1055                            let deposit_address = deposit_address.clone();
1056                            async move {
1057                                let events = gw
1058                                    .client()
1059                                    .payment_log(
1060                                        &fed_id,
1061                                        &["payment-receive", "payment-receive-update"],
1062                                        PAYMENT_LOG_PAGE_SIZE,
1063                                    )
1064                                    .await
1065                                    .map_err(ControlFlow::Continue)?;
1066
1067                                if !walletv2_receive_claimed(&events, &deposit_address) {
1068                                    return Err(ControlFlow::Continue(anyhow::anyhow!(
1069                                        "Gateway {gateway_name} ({gateway_ln}) has not claimed the deposit to {deposit_address} yet"
1070                                    )));
1071                                }
1072
1073                                debug!(
1074                                    gateway = %gateway_name,
1075                                    ln = %gateway_ln,
1076                                    address = %deposit_address,
1077                                    elapsed_ms = %pegin_start.elapsed().as_millis(),
1078                                    "Walletv2 gateway pegin claimed"
1079                                );
1080
1081                                Ok(())
1082                            }
1083                        })
1084                    }),
1085            )
1086            .await?;
1087        }
1088
1089        try_join_all(gateways.into_iter().enumerate().map(|(i, gw)| {
1090            let initial_balance = if uses_walletv2 {
1091                initial_balances[i]
1092            } else {
1093                0
1094            };
1095            let gateway_name = gw.gw_name.clone();
1096            let gateway_ln = gw.ln.ln_type().to_string();
1097            let gateway_id = gw.gateway_id.clone();
1098            let gateway_index = gw.gateway_index;
1099            let deposit_address = gateway_deposit_addrs[i].clone();
1100            let fed_id = fed_id.clone();
1101            poll("gateway pegin", move || {
1102                let fed_id = fed_id.clone();
1103                let gateway_name = gateway_name.clone();
1104                let gateway_ln = gateway_ln.clone();
1105                let gateway_id = gateway_id.clone();
1106                let deposit_address = deposit_address.clone();
1107                async move {
1108                    let gw_info = gw
1109                        .client()
1110                        .get_info()
1111                        .await
1112                        .map_err(ControlFlow::Continue)?;
1113
1114                    let block_height: u64 = if gw.gatewayd_version < *VERSION_0_10_0_ALPHA {
1115                        gw_info["block_height"]
1116                            .as_u64()
1117                            .expect("Could not parse block height")
1118                    } else {
1119                        gw_info["lightning_info"]["connected"]["block_height"]
1120                            .as_u64()
1121                            .expect("Could not parse block height")
1122                    };
1123
1124                    if bitcoind_block_height != block_height {
1125                        debug!(
1126                            gateway = %gateway_name,
1127                            ln = %gateway_ln,
1128                            bitcoind_block_height,
1129                            gateway_block_height = block_height,
1130                            elapsed_ms = %pegin_start.elapsed().as_millis(),
1131                            "Waiting for gateway pegin block sync"
1132                        );
1133                        return Err(std::ops::ControlFlow::Continue(anyhow::anyhow!(
1134                            "Gateway {gateway_name} ({gateway_id}, index {gateway_index}) block height {block_height} has not reached bitcoind block height {bitcoind_block_height}"
1135                        )));
1136                    }
1137
1138                    let gateway_balance = gw
1139                        .client()
1140                        .ecash_balance(fed_id)
1141                        .await
1142                        .map_err(ControlFlow::Continue)?;
1143
1144                    if uses_walletv2 {
1145                        // Walletv2: check balance increased by approximately
1146                        // the expected amount. Use 90% threshold to account
1147                        // for mintv2 fees (same as pegin_client).
1148                        let expected = initial_balance + (amount * 1000 * 9 / 10);
1149                        debug!(
1150                            gateway = %gateway_name,
1151                            ln = %gateway_ln,
1152                            gateway_balance_msats = gateway_balance,
1153                            expected_msats = expected,
1154                            initial_balance_msats = initial_balance,
1155                            elapsed_ms = %pegin_start.elapsed().as_millis(),
1156                            "Checked walletv2 gateway pegin balance"
1157                        );
1158                        if expected <= gateway_balance {
1159                            Ok(())
1160                        } else {
1161                            Err(ControlFlow::Continue(anyhow::anyhow!(
1162                                "Gateway {gateway_name} ({gateway_id}, index {gateway_index}) balance {gateway_balance} has not reached expected {expected} for deposit address {deposit_address} (initial: {initial_balance})"
1163                            )))
1164                        }
1165                    } else {
1166                        poll_almost_equal!(gateway_balance, amount * 1000)
1167                    }
1168                }
1169            })
1170        }))
1171        .await?;
1172
1173        Ok(())
1174    }
1175
1176    /// Initiates multiple peg-outs from the same federation for the set of
1177    /// gateways and waits for their change to become spendable, sharing the
1178    /// confirmation blocks across all peg-outs.
1179    pub async fn pegout_gateways(
1180        &self,
1181        amount: u64,
1182        gateways: Vec<&super::gatewayd::Gatewayd>,
1183    ) -> Result<()> {
1184        info!(amount, "Pegging-out gateway funds");
1185        let fed_id = self.calculate_federation_id();
1186        let mut peg_outs: BTreeMap<LightningNodeType, (Amount, WithdrawResponse)> = BTreeMap::new();
1187        for gw in gateways.clone() {
1188            let prev_fed_ecash_balance = gw
1189                .client()
1190                .get_balances()
1191                .await?
1192                .ecash_balances
1193                .into_iter()
1194                .find(|fed| fed.federation_id.to_string() == fed_id)
1195                .expect("Gateway has not joined federation")
1196                .ecash_balance_msats;
1197
1198            let pegout_address = self.bitcoind.get_new_address().await?;
1199            let response = gw
1200                .client()
1201                .pegout(fed_id.clone(), amount, pegout_address)
1202                .await?;
1203            peg_outs.insert(gw.ln.ln_type(), (prev_fed_ecash_balance, response));
1204        }
1205        // The gateway returns once the peg-out is accepted, before it is
1206        // necessarily broadcast. Mining first can leave the peg-outs in the
1207        // mempool, with no spendable change for a subsequent withdrawal.
1208        try_join_all(
1209            peg_outs
1210                .values()
1211                .map(|(_, pegout)| self.bitcoind.poll_get_transaction(pegout.txid)),
1212        )
1213        .await?;
1214        self.finalize_mempool_tx().await?;
1215
1216        for gw in gateways.clone() {
1217            let after_fed_ecash_balance = gw
1218                .client()
1219                .get_balances()
1220                .await?
1221                .ecash_balances
1222                .into_iter()
1223                .find(|fed| fed.federation_id.to_string() == fed_id)
1224                .expect("Gateway has not joined federation")
1225                .ecash_balance_msats;
1226
1227            let ln_type = gw.ln.ln_type();
1228            let prev_balance = peg_outs
1229                .get(&ln_type)
1230                .expect("peg out does not exist")
1231                .0
1232                .msats;
1233            let fees = peg_outs
1234                .get(&ln_type)
1235                .expect("peg out does not exist")
1236                .1
1237                .fees;
1238            let total_fee = fees.amount().to_sat() * 1000;
1239            // Walletv2 charges a module fee on top of the on-chain fee:
1240            // 100 sats base + 1% of amount (amount is in msats)
1241            let tolerance = if crate::util::supports_wallet_v2() {
1242                let amount_sats = amount / 1000;
1243                let module_fee_sats = 100 + amount_sats / 100;
1244                module_fee_sats * 1000 + 2000
1245            } else if crate::util::supports_mint_v2() {
1246                4000
1247            } else {
1248                2000
1249            };
1250            crate::util::almost_equal(
1251                after_fed_ecash_balance.msats,
1252                prev_balance - amount - total_fee,
1253                tolerance,
1254            )
1255            .map_err(|e| {
1256                anyhow::anyhow!(
1257                    "new balance did not equal prev balance minus withdraw_amount minus fees: {e}"
1258                )
1259            })?;
1260        }
1261
1262        Ok(())
1263    }
1264
1265    pub fn calculate_federation_id(&self) -> String {
1266        self.client_config()
1267            .unwrap()
1268            .global
1269            .calculate_federation_id()
1270            .to_string()
1271    }
1272
1273    pub async fn await_block_sync(&self) -> Result<u64> {
1274        let finality_delay = self.get_finality_delay()?;
1275        let block_count = self.bitcoind.get_block_count().await?;
1276        let expected = block_count.saturating_sub(finality_delay.into());
1277
1278        if crate::util::supports_wallet_v2() {
1279            // Walletv2 doesn't have `dev wait-block-count`, poll using CLI instead
1280            let client = self.internal_client().await?;
1281            loop {
1282                let value = cmd!(client, "module", "walletv2", "info", "block-count")
1283                    .out_json()
1284                    .await?;
1285                let current: u64 = serde_json::from_value(value)?;
1286                if expected <= current {
1287                    break;
1288                }
1289                fedimint_core::task::sleep_in_test(
1290                    format!("Waiting for consensus block count to reach {expected}"),
1291                    std::time::Duration::from_secs(1),
1292                )
1293                .await;
1294            }
1295        } else {
1296            cmd!(
1297                self.internal_client().await?,
1298                "dev",
1299                "wait-block-count",
1300                expected
1301            )
1302            .run()
1303            .await?;
1304        }
1305
1306        Ok(expected)
1307    }
1308
1309    fn get_finality_delay(&self) -> Result<u32, anyhow::Error> {
1310        // Walletv2's consensus block count trails the backend by a constant
1311        if crate::util::supports_wallet_v2() {
1312            return Ok(fedimint_walletv2_server::BLOCK_COUNT_VOTE_DELAY as u32);
1313        }
1314
1315        let wallet_instance_id = self.module_instance_id_by_kind(&fedimint_wallet_client::KIND)?;
1316        let client_config = &self.client_config()?;
1317        let wallet_cfg = client_config
1318            .modules
1319            .get(&wallet_instance_id)
1320            .context("wallet module not found")?
1321            .clone()
1322            .redecode_raw(&ModuleDecoderRegistry::new([(
1323                wallet_instance_id,
1324                fedimint_wallet_client::KIND,
1325                fedimint_wallet_client::WalletModuleTypes::decoder(),
1326            )]))?;
1327        let wallet_cfg: &WalletClientConfig = wallet_cfg.cast()?;
1328
1329        let finality_delay = wallet_cfg.finality_delay;
1330        Ok(finality_delay)
1331    }
1332
1333    pub async fn await_gateways_registered(&self) -> Result<()> {
1334        // `list-gateways` is an LNv1 concept: gateways register with the LNv1
1335        // module and the client lists them. LNv2 instead addresses gateways
1336        // directly and vets them via an explicit consensus item, so there is
1337        // nothing to poll here when the LNv1 module isn't present. The gateway
1338        // connection itself is awaited separately (via `connect_fed`).
1339        if !crate::util::supports_lnv1() {
1340            return Ok(());
1341        }
1342
1343        let start_time = Instant::now();
1344        debug!(target: LOG_DEVIMINT, "Awaiting LN gateways registration");
1345
1346        poll("gateways registered", || async {
1347            let num_gateways = cmd!(
1348                self.internal_client()
1349                    .await
1350                    .map_err(ControlFlow::Continue)?,
1351                "list-gateways"
1352            )
1353            .out_json()
1354            .await
1355            .map_err(ControlFlow::Continue)?
1356            .as_array()
1357            .context("invalid output")
1358            .map_err(ControlFlow::Break)?
1359            .len();
1360
1361            // After version v0.10.0, the LND gateway will register twice. Once for the HTTP
1362            // server, and once for the iroh endpoint.
1363            let expected_gateways =
1364                if crate::util::Gatewayd::version_or_default().await < *VERSION_0_10_0_ALPHA {
1365                    1
1366                } else {
1367                    2
1368                };
1369
1370            poll_eq!(num_gateways, expected_gateways)
1371        })
1372        .await?;
1373        debug!(target: LOG_DEVIMINT,
1374            elapsed_ms = %start_time.elapsed().as_millis(),
1375            "Gateways registered");
1376        Ok(())
1377    }
1378
1379    /// Waits for a federation quorum and every expected-running peer API.
1380    ///
1381    /// Intentionally stopped peers are absent from `members` and excluded. A
1382    /// successful check establishes API availability, not equal block heights
1383    /// or full synchronization between peers.
1384    pub async fn await_all_peers(&self) -> Result<()> {
1385        let (module_name, endpoint) = if crate::util::supports_wallet_v2() {
1386            ("walletv2", "consensus_block_count")
1387        } else {
1388            ("wallet", "block_count")
1389        };
1390        poll("Waiting for all peers to be online", || async {
1391            cmd!(
1392                self.internal_client()
1393                    .await
1394                    .map_err(ControlFlow::Continue)?,
1395                "dev",
1396                "api",
1397                "--module",
1398                module_name,
1399                endpoint
1400            )
1401            .run()
1402            .await
1403            .map_err(ControlFlow::Continue)?;
1404
1405            query_running_peers(&self.members, |peer_id| async move {
1406                cmd!(
1407                    self.internal_client().await?,
1408                    "dev",
1409                    "api",
1410                    "--peer-id",
1411                    peer_id,
1412                    "--module",
1413                    module_name,
1414                    endpoint
1415                )
1416                .run()
1417                .await
1418            })
1419            .await
1420            .map_err(ControlFlow::Continue)?;
1421
1422            Ok(())
1423        })
1424        .await
1425    }
1426
1427    pub async fn await_peer(&self, peer_id: usize) -> Result<()> {
1428        poll("Waiting for all peers to be online", || async {
1429            cmd!(
1430                self.internal_client()
1431                    .await
1432                    .map_err(ControlFlow::Continue)?,
1433                "dev",
1434                "api",
1435                "--peer-id",
1436                peer_id,
1437                "--module",
1438                "wallet",
1439                "block_count"
1440            )
1441            .run()
1442            .await
1443            .map_err(ControlFlow::Continue)?;
1444            Ok(())
1445        })
1446        .await
1447    }
1448
1449    /// Mines enough blocks to finalize mempool transactions, then waits for
1450    /// federation to process finalized blocks.
1451    ///
1452    /// ex:
1453    ///   tx submitted to mempool at height 100
1454    ///   finality delay = 10
1455    ///   mine finality delay blocks + 1 => new height 111
1456    ///   tx included in block 101
1457    ///   highest finalized height = 111 - 10 = 101
1458    pub async fn finalize_mempool_tx(&self) -> Result<()> {
1459        let finality_delay = self.get_finality_delay()?;
1460        let blocks_to_mine = finality_delay + 1;
1461        self.bitcoind.mine_blocks(blocks_to_mine.into()).await?;
1462        self.await_block_sync().await?;
1463        Ok(())
1464    }
1465
1466    pub async fn mine_then_wait_blocks_sync(&self, blocks: u64) -> Result<()> {
1467        self.bitcoind.mine_blocks(blocks).await?;
1468        self.await_block_sync().await?;
1469        Ok(())
1470    }
1471
1472    pub fn num_members(&self) -> usize {
1473        self.members.len()
1474    }
1475
1476    pub fn member_ids(&self) -> impl Iterator<Item = PeerId> + '_ {
1477        self.members
1478            .keys()
1479            .map(|&peer_id| PeerId::from(peer_id as u16))
1480    }
1481}
1482
1483/// Whether a gateway `payment-log` response contains a successful walletv2
1484/// receive for `deposit_address`.
1485///
1486/// An aborted receive is reprocessed into a new receive operation for the
1487/// same still-unspent deposit, so a single address can have several receive
1488/// events; the deposit is claimed once any of their operations reports a
1489/// `Success` update.
1490fn walletv2_receive_claimed(events: &serde_json::Value, deposit_address: &str) -> bool {
1491    let Some(events) = events.as_array() else {
1492        return false;
1493    };
1494
1495    let is_walletv2 = |event: &serde_json::Value| event["module"]["kind"] == "walletv2";
1496
1497    let receive_operations = events
1498        .iter()
1499        .filter(|event| {
1500            is_walletv2(event)
1501                && event["kind"] == "payment-receive"
1502                && event["payload"]["address"] == deposit_address
1503        })
1504        .map(|event| &event["payload"]["operation_id"])
1505        .collect::<Vec<_>>();
1506
1507    events.iter().any(|event| {
1508        is_walletv2(event)
1509            && event["kind"] == "payment-receive-update"
1510            && event["payload"]["status"] == "Success"
1511            && receive_operations.contains(&&event["payload"]["operation_id"])
1512    })
1513}
1514
1515#[derive(Clone)]
1516pub struct Fedimintd {
1517    _bitcoind: Bitcoind,
1518    process: ProcessHandle,
1519}
1520
1521impl Fedimintd {
1522    pub async fn new(
1523        process_mgr: &ProcessManager,
1524        bitcoind: Bitcoind,
1525        peer_id: usize,
1526        env: &vars::Fedimintd,
1527        fed_name: String,
1528    ) -> Result<Self> {
1529        debug!(target: LOG_DEVIMINT, "Starting fedimintd-{fed_name}-{peer_id}");
1530        let process = process_mgr
1531            .spawn_daemon(
1532                &format!("fedimintd-{fed_name}-{peer_id}"),
1533                cmd!(FedimintdCmd).envs(env.vars()),
1534            )
1535            .await?;
1536
1537        Ok(Self {
1538            _bitcoind: bitcoind,
1539            process,
1540        })
1541    }
1542
1543    pub async fn terminate(self) -> Result<()> {
1544        self.process.terminate().await
1545    }
1546
1547    pub async fn await_terminated(&self) -> Result<()> {
1548        self.process.await_terminated().await
1549    }
1550}
1551
1552pub async fn run_cli_dkg_v2(endpoints: BTreeMap<PeerId, String>) -> Result<()> {
1553    // Parallelize setup status checks
1554    let status_futures = endpoints.values().map(|endpoint| {
1555        let endpoint = endpoint.clone();
1556        async move {
1557            let status = poll("awaiting-setup-status-awaiting-local-params", || async {
1558                crate::util::FedimintCli
1559                    .setup_status(&API_AUTH, &endpoint)
1560                    .await
1561                    .map_err(ControlFlow::Continue)
1562            })
1563            .await
1564            .unwrap();
1565
1566            assert_eq!(status, SetupStatus::AwaitingLocalParams);
1567        }
1568    });
1569    join_all(status_futures).await;
1570
1571    debug!(target: LOG_DEVIMINT, "Setting local parameters...");
1572
1573    // Parallelize setting local parameters
1574    // --federation-size is only supported by fedimint-cli >= 0.11.0-alpha
1575    let federation_size =
1576        if crate::util::FedimintCli::version_or_default().await >= *VERSION_0_11_0_ALPHA {
1577            Some(endpoints.len())
1578        } else {
1579            None
1580        };
1581    let local_params_futures = endpoints.iter().map(|(peer, endpoint)| {
1582        let peer = *peer;
1583        let endpoint = endpoint.clone();
1584        async move {
1585            let info = if peer.to_usize() == 0 {
1586                crate::util::FedimintCli
1587                    .set_local_params_leader(&peer, &API_AUTH, &endpoint, federation_size)
1588                    .await
1589            } else {
1590                crate::util::FedimintCli
1591                    .set_local_params_follower(&peer, &API_AUTH, &endpoint)
1592                    .await
1593            };
1594            info.map(|i| (peer, i))
1595        }
1596    });
1597    let connection_info: BTreeMap<_, _> = try_join_all(local_params_futures)
1598        .await?
1599        .into_iter()
1600        .collect();
1601
1602    debug!(target: LOG_DEVIMINT, "Exchanging peer connection info...");
1603
1604    // Parallelize peer addition - flatten the nested loop into a single parallel
1605    // operation
1606    let add_peer_futures = connection_info.iter().flat_map(|(peer, info)| {
1607        endpoints
1608            .iter()
1609            .filter(move |(p, _)| *p != peer)
1610            .map(move |(_, endpoint)| {
1611                let endpoint = endpoint.clone();
1612                let info = info.clone();
1613                async move {
1614                    crate::util::FedimintCli
1615                        .add_peer(&info, &API_AUTH, &endpoint)
1616                        .await
1617                }
1618            })
1619    });
1620    try_join_all(add_peer_futures).await?;
1621
1622    debug!(target: LOG_DEVIMINT, "Starting DKG...");
1623
1624    // Parallelize DKG start
1625    let start_dkg_futures = endpoints.values().map(|endpoint| {
1626        let endpoint = endpoint.clone();
1627        async move {
1628            crate::util::FedimintCli
1629                .start_dkg(&API_AUTH, &endpoint)
1630                .await
1631        }
1632    });
1633    try_join_all(start_dkg_futures).await?;
1634
1635    Ok(())
1636}
1637
1638#[cfg(test)]
1639mod tests;
1640
1641#[cfg(test)]
1642mod client_config_tests;