Skip to main content

devimint/
tests.rs

1use std::collections::{BTreeMap, HashSet};
2use std::io::Write;
3use std::ops::ControlFlow;
4use std::path::{Path, PathBuf};
5use std::str::FromStr;
6use std::time::{Duration, Instant};
7use std::{env, ffi};
8
9use anyhow::{Context, Result, anyhow, bail};
10use bitcoin::Txid;
11use clap::Subcommand;
12use fedimint_core::core::OperationId;
13use fedimint_core::encoding::{Decodable, Encodable};
14use fedimint_core::envs::{
15    FM_DISABLE_BASE_FEES_ENV, FM_ENABLE_MODULE_LNV1_ENV, FM_ENABLE_MODULE_LNV2_ENV,
16    FM_ENABLE_MODULE_MINT_ENV, FM_ENABLE_MODULE_MINTV2_ENV, FM_ENABLE_MODULE_WALLET_ENV,
17    FM_ENABLE_MODULE_WALLETV2_ENV, is_env_var_set,
18};
19use fedimint_core::module::registry::ModuleRegistry;
20use fedimint_core::net::api_announcement::SignedApiAnnouncement;
21use fedimint_core::task::block_in_place;
22use fedimint_core::util::backoff_util::aggressive_backoff;
23use fedimint_core::util::{retry, write_overwrite_async};
24use fedimint_core::{Amount, PeerId};
25use fedimint_ln_client::LightningPaymentOutcome;
26use fedimint_ln_client::cli::LnInvoiceResponse;
27use fedimint_ln_server::common::lightning_invoice::Bolt11Invoice;
28use fedimint_lnv2_client::FinalSendOperationState;
29use fedimint_logging::LOG_DEVIMINT;
30use fedimint_testing_core::node_type::LightningNodeType;
31use futures::future::try_join_all;
32use serde_json::json;
33use substring::Substring;
34use tokio::net::TcpStream;
35use tokio::{fs, try_join};
36use tracing::{debug, error, info};
37
38use crate::cli::{CommonArgs, cleanup_on_exit, exec_user_command, setup};
39use crate::envs::{FM_DATA_DIR_ENV, FM_DEVIMINT_RUN_DEPRECATED_TESTS_ENV};
40use crate::federation::Client;
41use crate::util::{LoadTestTool, ProcessManager, almost_equal, poll};
42use crate::version_constants::{
43    VERSION_0_10_0_ALPHA, VERSION_0_11_0_ALPHA, VERSION_0_12_0_ALPHA, VERSION_0_13_0_ALPHA,
44};
45use crate::{DevFed, Gatewayd, LightningNode, Lnd, cmd, dev_fed};
46
47pub struct Stats {
48    pub min: Duration,
49    pub avg: Duration,
50    pub median: Duration,
51    pub p90: Duration,
52    pub max: Duration,
53    pub sum: Duration,
54}
55
56impl std::fmt::Display for Stats {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        write!(f, "min: {:.1}s", self.min.as_secs_f32())?;
59        write!(f, ", avg: {:.1}s", self.avg.as_secs_f32())?;
60        write!(f, ", median: {:.1}s", self.median.as_secs_f32())?;
61        write!(f, ", p90: {:.1}s", self.p90.as_secs_f32())?;
62        write!(f, ", max: {:.1}s", self.max.as_secs_f32())?;
63        write!(f, ", sum: {:.1}s", self.sum.as_secs_f32())?;
64        Ok(())
65    }
66}
67
68pub fn stats_for(mut v: Vec<Duration>) -> Stats {
69    assert!(!v.is_empty());
70    v.sort();
71    let n = v.len();
72    let min = v.first().unwrap().to_owned();
73    let max = v.iter().last().unwrap().to_owned();
74    let median = v[n / 2];
75    let sum: Duration = v.iter().sum();
76    let avg = sum / n as u32;
77    let p90 = v[(n as f32 * 0.9) as usize];
78    Stats {
79        min,
80        avg,
81        median,
82        p90,
83        max,
84        sum,
85    }
86}
87
88pub async fn log_binary_versions() -> Result<()> {
89    let fedimint_cli_version = cmd!(crate::util::get_fedimint_cli_path(), "--version")
90        .out_string()
91        .await?;
92    info!(?fedimint_cli_version);
93    let fedimint_cli_version_hash = cmd!(crate::util::get_fedimint_cli_path(), "version-hash")
94        .out_string()
95        .await?;
96    info!(?fedimint_cli_version_hash);
97    let gateway_cli_version = cmd!(crate::util::get_gateway_cli_path(), "--version")
98        .out_string()
99        .await?;
100    info!(?gateway_cli_version);
101    let gateway_cli_version_hash = cmd!(crate::util::get_gateway_cli_path(), "version-hash")
102        .out_string()
103        .await?;
104    info!(?gateway_cli_version_hash);
105    let fedimintd_version_hash = cmd!(crate::util::FedimintdCmd, "version-hash")
106        .out_string()
107        .await?;
108    info!(?fedimintd_version_hash);
109    let gatewayd_version_hash = cmd!(crate::util::Gatewayd, "version-hash")
110        .out_string()
111        .await?;
112    info!(?gatewayd_version_hash);
113    Ok(())
114}
115
116pub async fn latency_tests(
117    dev_fed: DevFed,
118    r#type: LatencyTest,
119    upgrade_clients: Option<&UpgradeClients>,
120    iterations: usize,
121    assert_thresholds: bool,
122) -> Result<()> {
123    log_binary_versions().await?;
124
125    let DevFed {
126        fed,
127        gw_lnd,
128        gw_ldk,
129        ..
130    } = dev_fed;
131
132    let max_p90_factor = 10.0;
133    let p90_median_factor = 10;
134
135    let client = match upgrade_clients {
136        Some(c) => match r#type {
137            LatencyTest::Reissue => c.reissue_client.clone(),
138            LatencyTest::LnSend => c.ln_send_client.clone(),
139            LatencyTest::LnReceive => c.ln_receive_client.clone(),
140            LatencyTest::FmPay => c.fm_pay_client.clone(),
141            LatencyTest::Restore => bail!("no reusable upgrade client for restore"),
142        },
143        None => fed.new_joined_client("latency-tests-client").await?,
144    };
145
146    let initial_balance_sats = 100_000_000;
147    fed.pegin_client(initial_balance_sats, &client).await?;
148
149    let lnd_gw_id = gw_lnd.gateway_id.clone();
150
151    let gw_lnd = gw_lnd.client();
152    let gw_ldk = gw_ldk.client();
153
154    match r#type {
155        LatencyTest::Reissue => {
156            info!("Testing latency of reissue");
157            let mut reissues = Vec::with_capacity(iterations);
158            let amount_per_iteration_msats =
159                // use a highest 2^-1 amount that fits, to try to use as many notes as possible
160                ((initial_balance_sats * 1000 / iterations as u64).next_power_of_two() >> 1) - 1;
161            for _ in 0..iterations {
162                let notes = cmd!(client, "spend", amount_per_iteration_msats.to_string())
163                    .out_json()
164                    .await?["notes"]
165                    .as_str()
166                    .context("note must be a string")?
167                    .to_owned();
168
169                let start_time = Instant::now();
170                cmd!(client, "reissue", notes).run().await?;
171                reissues.push(start_time.elapsed());
172            }
173            let reissue_stats = stats_for(reissues);
174            println!("### LATENCY REISSUE: {reissue_stats}");
175
176            if assert_thresholds {
177                assert!(reissue_stats.median < Duration::from_secs(10));
178                assert!(reissue_stats.p90 < reissue_stats.median * p90_median_factor);
179                assert!(
180                    reissue_stats.max.as_secs_f64()
181                        < reissue_stats.p90.as_secs_f64() * max_p90_factor
182                );
183            }
184        }
185        LatencyTest::LnSend => {
186            info!("Testing latency of ln send");
187            let mut ln_sends = Vec::with_capacity(iterations);
188            for _ in 0..iterations {
189                let invoice = gw_ldk.create_invoice(1_000_000).await?;
190                let start_time = Instant::now();
191                ln_pay(&client, invoice.to_string(), lnd_gw_id.clone()).await?;
192                gw_ldk
193                    .wait_bolt11_invoice(invoice.payment_hash().consensus_encode_to_vec())
194                    .await?;
195                ln_sends.push(start_time.elapsed());
196
197                if crate::util::supports_lnv2() {
198                    let invoice = gw_lnd.create_invoice(1_000_000).await?;
199
200                    let start_time = Instant::now();
201
202                    lnv2_send(&client, &gw_ldk.address(), &invoice.to_string()).await?;
203
204                    ln_sends.push(start_time.elapsed());
205                }
206            }
207            let ln_sends_stats = stats_for(ln_sends);
208            println!("### LATENCY LN SEND: {ln_sends_stats}");
209
210            if assert_thresholds {
211                assert!(ln_sends_stats.median < Duration::from_secs(10));
212                assert!(ln_sends_stats.p90 < ln_sends_stats.median * p90_median_factor);
213                assert!(
214                    ln_sends_stats.max.as_secs_f64()
215                        < ln_sends_stats.p90.as_secs_f64() * max_p90_factor
216                );
217            }
218        }
219        LatencyTest::LnReceive => {
220            info!("Testing latency of ln receive");
221            let mut ln_receives = Vec::with_capacity(iterations);
222
223            // give lnd some funds
224            let invoice = gw_ldk.create_invoice(10_000_000).await?;
225            ln_pay(&client, invoice.to_string(), lnd_gw_id.clone()).await?;
226
227            for _ in 0..iterations {
228                let invoice = ln_invoice(
229                    &client,
230                    Amount::from_msats(100_000),
231                    "latency-over-lnd-gw".to_string(),
232                    lnd_gw_id.clone(),
233                )
234                .await?
235                .invoice;
236
237                let start_time = Instant::now();
238                gw_ldk
239                    .pay_invoice(
240                        Bolt11Invoice::from_str(&invoice).expect("Could not parse invoice"),
241                    )
242                    .await?;
243                ln_receives.push(start_time.elapsed());
244
245                if crate::util::supports_lnv2() {
246                    let invoice = lnv2_receive(&client, &gw_lnd.address(), 100_000).await?.0;
247
248                    let start_time = Instant::now();
249
250                    gw_ldk.pay_invoice(invoice).await?;
251
252                    ln_receives.push(start_time.elapsed());
253                }
254            }
255            let ln_receives_stats = stats_for(ln_receives);
256            println!("### LATENCY LN RECV: {ln_receives_stats}");
257
258            if assert_thresholds {
259                assert!(ln_receives_stats.median < Duration::from_secs(10));
260                assert!(ln_receives_stats.p90 < ln_receives_stats.median * p90_median_factor);
261                assert!(
262                    ln_receives_stats.max.as_secs_f64()
263                        < ln_receives_stats.p90.as_secs_f64() * max_p90_factor
264                );
265            }
266        }
267        LatencyTest::FmPay => {
268            info!("Testing latency of internal payments within a federation");
269            let mut fm_internal_pay = Vec::with_capacity(iterations);
270            let sender = fed.new_joined_client("internal-swap-sender").await?;
271            fed.pegin_client(10_000_000, &sender).await?;
272            for _ in 0..iterations {
273                let recv = cmd!(
274                    client,
275                    "ln-invoice",
276                    "--amount=1000000msat",
277                    "--description=internal-swap-invoice",
278                    "--force-internal"
279                )
280                .out_json()
281                .await?;
282
283                let invoice = recv["invoice"]
284                    .as_str()
285                    .context("invoice must be string")?
286                    .to_owned();
287                let recv_op = recv["operation_id"]
288                    .as_str()
289                    .context("operation id must be string")?
290                    .to_owned();
291
292                let start_time = Instant::now();
293                cmd!(sender, "ln-pay", invoice, "--force-internal")
294                    .run()
295                    .await?;
296
297                cmd!(client, "await-invoice", recv_op).run().await?;
298                fm_internal_pay.push(start_time.elapsed());
299            }
300            let fm_pay_stats = stats_for(fm_internal_pay);
301
302            println!("### LATENCY FM PAY: {fm_pay_stats}");
303
304            if assert_thresholds {
305                assert!(fm_pay_stats.median < Duration::from_secs(15));
306                assert!(fm_pay_stats.p90 < fm_pay_stats.median * p90_median_factor);
307                assert!(
308                    fm_pay_stats.max.as_secs_f64()
309                        < fm_pay_stats.p90.as_secs_f64() * max_p90_factor
310                );
311            }
312        }
313        LatencyTest::Restore => {
314            info!("Testing latency of restore");
315            let backup_secret = cmd!(client, "print-secret").out_json().await?["secret"]
316                .as_str()
317                .map(ToOwned::to_owned)
318                .unwrap();
319            if !is_env_var_set(FM_DEVIMINT_RUN_DEPRECATED_TESTS_ENV) {
320                info!("Skipping tests, as in previous versions restore was very slow to test");
321                return Ok(());
322            }
323
324            let start_time = Instant::now();
325            let restore_client = Client::create("restore").await?;
326            cmd!(
327                restore_client,
328                "restore",
329                "--mnemonic",
330                &backup_secret,
331                "--invite-code",
332                fed.invite_code()?
333            )
334            .run()
335            .await?;
336            let restore_time = start_time.elapsed();
337
338            println!("### LATENCY RESTORE: {restore_time:?}");
339
340            if assert_thresholds {
341                if crate::util::is_backwards_compatibility_test() {
342                    assert!(restore_time < Duration::from_secs(160));
343                } else {
344                    assert!(restore_time < Duration::from_secs(30));
345                }
346            }
347        }
348    }
349
350    Ok(())
351}
352
353pub async fn lnurl_recovery_test(dev_fed: DevFed) -> Result<()> {
354    let DevFed {
355        fed,
356        gw_lnd,
357        recurringd,
358        ..
359    } = dev_fed;
360
361    const LNURL_AMOUNT: Amount = Amount::from_msats(500_000);
362    const PRE_RECOVERY_RECEIVES: u64 = 3;
363    const POST_RECOVERY_RECEIVES: u64 = 2;
364
365    let receiver = fed.new_joined_client("lnurl-recovery-receiver").await?;
366    if !client_has_module(&receiver, "ln").await? {
367        info!("ln module is not present, skipping LNv1 LNURL recovery test");
368        return Ok(());
369    }
370
371    let payer = fed.new_joined_client("lnurl-recovery-payer").await?;
372    fed.pegin_client(100_000, &payer).await?;
373    fed.pegin_gateways(100_000, vec![&gw_lnd]).await?;
374
375    let lnurl = register_lnv1_lnurl(&receiver, recurringd.api_url().as_str()).await?;
376
377    for invoice_idx in 1..=PRE_RECOVERY_RECEIVES {
378        pay_lnv1_lnurl(&payer, &lnurl, LNURL_AMOUNT, &gw_lnd.gateway_id).await?;
379        let operation_id = await_lnv1_lnurl_invoice(&receiver, invoice_idx).await?;
380        await_lnv1_lnurl_invoice_paid(&receiver, operation_id).await?;
381    }
382
383    let pre_recovery_balance = receiver.balance().await?;
384    let mnemonic = cmd!(receiver, "print-secret").out_json().await?["secret"]
385        .as_str()
386        .context("secret must be a string")?
387        .to_owned();
388
389    let restored = Client::create("lnurl-recovery-restored").await?;
390    restored
391        .restore_federation(fed.invite_code()?, mnemonic)
392        .await?;
393
394    poll(
395        "waiting for LNURL recovery client balance to be restored",
396        || async {
397            let restored_balance = restored.balance().await.map_err(ControlFlow::Break)?;
398            if almost_equal(restored_balance, pre_recovery_balance, 2_000).is_ok() {
399                return Ok(());
400            }
401
402            info!("Waiting for LNURL recovery client balance to be restored");
403            cmd!(restored, "dev", "wait", "1")
404                .out_json()
405                .await
406                .map_err(ControlFlow::Break)?;
407
408            Err(ControlFlow::Continue(anyhow!(
409                "LNURL recovery client balance is not restored yet"
410            )))
411        },
412    )
413    .await?;
414
415    assert!(
416        list_lnv1_lnurl_codes(&restored)
417            .await?
418            .as_object()
419            .context("codes must be an object")?
420            .is_empty(),
421        "LN module recovery should not restore recurring payment code registrations"
422    );
423
424    let restored_lnurl = register_lnv1_lnurl(&restored, recurringd.api_url().as_str()).await?;
425    assert_eq!(
426        restored_lnurl, lnurl,
427        "LNURL registration should be idempotent for a recovered deterministic root key"
428    );
429
430    let mut old_operation_ids = Vec::with_capacity(PRE_RECOVERY_RECEIVES as usize);
431    for invoice_idx in 1..=PRE_RECOVERY_RECEIVES {
432        old_operation_ids.push(await_lnv1_lnurl_invoice(&restored, invoice_idx).await?);
433    }
434
435    for operation_id in &old_operation_ids {
436        assert_lnv1_operation_has_no_outcome(&restored, *operation_id).await?;
437    }
438
439    let post_recovery_balance = restored.balance().await?;
440    let mut post_recovery_operation_ids = Vec::with_capacity(POST_RECOVERY_RECEIVES as usize);
441    for invoice_idx in PRE_RECOVERY_RECEIVES + 1..=PRE_RECOVERY_RECEIVES + POST_RECOVERY_RECEIVES {
442        pay_lnv1_lnurl(&payer, &restored_lnurl, LNURL_AMOUNT, &gw_lnd.gateway_id).await?;
443        let operation_id = await_lnv1_lnurl_invoice(&restored, invoice_idx).await?;
444        await_lnv1_lnurl_invoice_paid(&restored, operation_id).await?;
445        post_recovery_operation_ids.push(operation_id);
446    }
447
448    let expected_final_balance =
449        post_recovery_balance + LNURL_AMOUNT.msats * POST_RECOVERY_RECEIVES;
450    let final_balance = restored.balance().await?;
451    almost_equal(final_balance, expected_final_balance, 2_000).map_err(|error| {
452        anyhow!(
453            "restored client balance {final_balance} did not include post-recovery LNURL receives: {error}"
454        )
455    })?;
456
457    for operation_id in post_recovery_operation_ids {
458        assert_lnv1_recurring_receive_operation_logged(&restored, operation_id).await?;
459    }
460
461    Ok(())
462}
463
464async fn client_has_module(client: &Client, kind: &str) -> Result<bool> {
465    let modules = cmd!(client, "module").out_json().await?;
466    let modules = modules["list"]
467        .as_array()
468        .context("module list must be an array")?;
469
470    Ok(modules
471        .iter()
472        .any(|module| module["kind"].as_str() == Some(kind)))
473}
474
475async fn register_lnv1_lnurl(client: &Client, recurringd_api: &str) -> Result<String> {
476    cmd!(client, "module", "ln", "lnurl", "register", recurringd_api)
477        .out_json()
478        .await?["lnurl"]
479        .as_str()
480        .context("lnurl must be a string")
481        .map(ToOwned::to_owned)
482}
483
484async fn list_lnv1_lnurl_codes(client: &Client) -> Result<serde_json::Value> {
485    Ok(cmd!(client, "module", "ln", "lnurl", "list")
486        .out_json()
487        .await?["codes"]
488        .clone())
489}
490
491async fn pay_lnv1_lnurl(
492    client: &Client,
493    lnurl: &str,
494    amount: Amount,
495    gateway_id: &str,
496) -> Result<()> {
497    let value = cmd!(
498        client,
499        "module",
500        "ln",
501        "pay",
502        lnurl,
503        "--amount",
504        amount.msats,
505        "--gateway-id",
506        gateway_id,
507    )
508    .out_json()
509    .await?;
510    let outcome = serde_json::from_value::<LightningPaymentOutcome>(value)
511        .context("could not deserialize Lightning payment outcome")?;
512    match outcome {
513        LightningPaymentOutcome::Success { .. } => Ok(()),
514        LightningPaymentOutcome::Failure { error_message } => {
515            Err(anyhow!("failed to pay LNURL invoice: {error_message}"))
516        }
517    }
518}
519
520async fn await_lnv1_lnurl_invoice(client: &Client, invoice_idx: u64) -> Result<OperationId> {
521    poll("waiting for LNv1 LNURL invoice operation", || async {
522        cmd!(client, "dev", "wait", "1")
523            .out_json()
524            .await
525            .map_err(ControlFlow::Break)?;
526
527        let invoices = cmd!(client, "module", "ln", "lnurl", "invoices", "0")
528            .out_json()
529            .await
530            .map_err(ControlFlow::Break)?;
531        let Some(operation_id) = invoices["invoices"][invoice_idx.to_string()]["operation_id"]
532            .as_str()
533            .map(ToOwned::to_owned)
534        else {
535            return Err(ControlFlow::Continue(anyhow!(
536                "LNURL invoice index {invoice_idx} not found"
537            )));
538        };
539
540        serde_json::from_value::<OperationId>(json!(operation_id))
541            .map_err(anyhow::Error::from)
542            .map_err(ControlFlow::Break)
543    })
544    .await
545}
546
547async fn await_lnv1_lnurl_invoice_paid(client: &Client, operation_id: OperationId) -> Result<()> {
548    cmd!(
549        client,
550        "module",
551        "ln",
552        "lnurl",
553        "await-invoice-paid",
554        operation_id.fmt_full()
555    )
556    .run()
557    .await
558}
559
560async fn assert_lnv1_operation_has_no_outcome(
561    client: &Client,
562    operation_id: OperationId,
563) -> Result<()> {
564    let operation = get_lnv1_operation_from_log(client, operation_id).await?;
565
566    assert_eq!(
567        operation["operation_kind"].as_str(),
568        Some("ln"),
569        "replayed LNURL invoice operation must be an ln operation"
570    );
571    assert!(
572        operation.get("outcome").is_none(),
573        "replayed pre-recovery LNURL invoice operation should not have a terminal outcome"
574    );
575
576    Ok(())
577}
578
579async fn assert_lnv1_recurring_receive_operation_logged(
580    client: &Client,
581    operation_id: OperationId,
582) -> Result<()> {
583    let operation = get_lnv1_operation_from_log(client, operation_id).await?;
584
585    assert_eq!(
586        operation["operation_kind"].as_str(),
587        Some("ln"),
588        "post-recovery LNURL invoice operation must be an ln operation"
589    );
590    assert!(
591        operation["operation_meta"]["variant"]["recurring_payment_receive"].is_object(),
592        "post-recovery LNURL receive must be logged as recurring_payment_receive"
593    );
594
595    Ok(())
596}
597
598async fn get_lnv1_operation_from_log(
599    client: &Client,
600    operation_id: OperationId,
601) -> Result<serde_json::Value> {
602    let operation_id = operation_id.fmt_full().to_string();
603    let operations = cmd!(client, "list-operations", "--limit", "100")
604        .out_json()
605        .await?;
606    operations["operations"]
607        .as_array()
608        .context("operations must be an array")?
609        .iter()
610        .find(|operation| operation["id"].as_str() == Some(operation_id.as_str()))
611        .cloned()
612        .with_context(|| format!("operation {operation_id} not found"))
613}
614
615#[allow(clippy::struct_field_names)]
616/// Clients reused for upgrade tests
617pub struct UpgradeClients {
618    reissue_client: Client,
619    ln_send_client: Client,
620    ln_receive_client: Client,
621    fm_pay_client: Client,
622}
623
624async fn stress_test_fed(dev_fed: &DevFed, clients: Option<&UpgradeClients>) -> anyhow::Result<()> {
625    use futures::FutureExt;
626
627    // local environments can fail due to latency thresholds, however this shouldn't
628    // cause the upgrade test to fail
629    let assert_thresholds = false;
630
631    // running only one iteration greatly improves the total test time while still
632    // testing the same types of database entries
633    let iterations = 1;
634
635    // skip restore test for client upgrades, since restoring a client doesn't
636    // require a persistent data dir
637    let restore_test = if clients.is_some() {
638        futures::future::ok(()).right_future()
639    } else {
640        latency_tests(
641            dev_fed.clone(),
642            LatencyTest::Restore,
643            clients,
644            iterations,
645            assert_thresholds,
646        )
647        .left_future()
648    };
649
650    // tests are run in sequence so parallelism is controlled using gnu `parallel`
651    // in `upgrade-test.sh`
652    latency_tests(
653        dev_fed.clone(),
654        LatencyTest::Reissue,
655        clients,
656        iterations,
657        assert_thresholds,
658    )
659    .await?;
660
661    latency_tests(
662        dev_fed.clone(),
663        LatencyTest::LnSend,
664        clients,
665        iterations,
666        assert_thresholds,
667    )
668    .await?;
669
670    latency_tests(
671        dev_fed.clone(),
672        LatencyTest::LnReceive,
673        clients,
674        iterations,
675        assert_thresholds,
676    )
677    .await?;
678
679    latency_tests(
680        dev_fed.clone(),
681        LatencyTest::FmPay,
682        clients,
683        iterations,
684        assert_thresholds,
685    )
686    .await?;
687
688    restore_test.await?;
689
690    Ok(())
691}
692
693pub async fn upgrade_tests(process_mgr: &ProcessManager, binary: UpgradeTest) -> Result<()> {
694    match binary {
695        UpgradeTest::Fedimintd { paths } => {
696            if let Some(oldest_fedimintd) = paths.first() {
697                // TODO: Audit that the environment access only happens in single-threaded code.
698                unsafe { std::env::set_var("FM_FEDIMINTD_BASE_EXECUTABLE", oldest_fedimintd) };
699            } else {
700                bail!("Must provide at least 1 binary path");
701            }
702
703            let fedimintd_version = crate::util::FedimintdCmd::version_or_default().await;
704            info!(
705                "running first stress test for fedimintd version: {}",
706                fedimintd_version
707            );
708
709            let mut dev_fed = dev_fed(process_mgr).await?;
710            let client = dev_fed.fed.new_joined_client("test-client").await?;
711            try_join!(stress_test_fed(&dev_fed, None), client.wait_session())?;
712
713            for path in paths.iter().skip(1) {
714                dev_fed.fed.restart_all_with_bin(process_mgr, path).await?;
715
716                // stress test with all peers online
717                try_join!(stress_test_fed(&dev_fed, None), client.wait_session())?;
718
719                let fedimintd_version = crate::util::FedimintdCmd::version_or_default().await;
720                info!(
721                    "### fedimintd passed stress test for version {}",
722                    fedimintd_version
723                );
724            }
725            info!("## fedimintd upgraded all binaries successfully");
726        }
727        UpgradeTest::FedimintCli { paths } => {
728            let set_fedimint_cli_path = |path: &PathBuf| {
729                // TODO: Audit that the environment access only happens in single-threaded code.
730                unsafe { std::env::set_var("FM_FEDIMINT_CLI_BASE_EXECUTABLE", path) };
731                let fm_mint_client: String = format!(
732                    "{fedimint_cli} --data-dir {datadir}",
733                    fedimint_cli = crate::util::get_fedimint_cli_path().join(" "),
734                    datadir = crate::vars::utf8(&process_mgr.globals.FM_CLIENT_DIR)
735                );
736                // TODO: Audit that the environment access only happens in single-threaded code.
737                unsafe { std::env::set_var("FM_MINT_CLIENT", fm_mint_client) };
738            };
739
740            if let Some(oldest_fedimint_cli) = paths.first() {
741                set_fedimint_cli_path(oldest_fedimint_cli);
742            } else {
743                bail!("Must provide at least 1 binary path");
744            }
745
746            let fedimint_cli_version = crate::util::FedimintCli::version_or_default().await;
747            info!(
748                "running first stress test for fedimint-cli version: {}",
749                fedimint_cli_version
750            );
751
752            let dev_fed = dev_fed(process_mgr).await?;
753
754            let wait_session_client = dev_fed.fed.new_joined_client("wait-session-client").await?;
755            let reusable_upgrade_clients = UpgradeClients {
756                reissue_client: dev_fed.fed.new_joined_client("reissue-client").await?,
757                ln_send_client: dev_fed.fed.new_joined_client("ln-send-client").await?,
758                ln_receive_client: dev_fed.fed.new_joined_client("ln-receive-client").await?,
759                fm_pay_client: dev_fed.fed.new_joined_client("fm-pay-client").await?,
760            };
761
762            try_join!(
763                stress_test_fed(&dev_fed, Some(&reusable_upgrade_clients)),
764                wait_session_client.wait_session()
765            )?;
766
767            for path in paths.iter().skip(1) {
768                set_fedimint_cli_path(path);
769                let fedimint_cli_version = crate::util::FedimintCli::version_or_default().await;
770                info!("upgraded fedimint-cli to version: {}", fedimint_cli_version);
771                try_join!(
772                    stress_test_fed(&dev_fed, Some(&reusable_upgrade_clients)),
773                    wait_session_client.wait_session()
774                )?;
775                info!(
776                    "### fedimint-cli passed stress test for version {}",
777                    fedimint_cli_version
778                );
779            }
780            info!("## fedimint-cli upgraded all binaries successfully");
781        }
782        UpgradeTest::Gatewayd {
783            gatewayd_paths,
784            gateway_cli_paths,
785        } => {
786            if let Some(oldest_gatewayd) = gatewayd_paths.first() {
787                // TODO: Audit that the environment access only happens in single-threaded code.
788                unsafe { std::env::set_var("FM_GATEWAYD_BASE_EXECUTABLE", oldest_gatewayd) };
789            } else {
790                bail!("Must provide at least 1 gatewayd path");
791            }
792
793            if let Some(oldest_gateway_cli) = gateway_cli_paths.first() {
794                // TODO: Audit that the environment access only happens in single-threaded code.
795                unsafe { std::env::set_var("FM_GATEWAY_CLI_BASE_EXECUTABLE", oldest_gateway_cli) };
796            } else {
797                bail!("Must provide at least 1 gateway-cli path");
798            }
799
800            let gatewayd_version = crate::util::Gatewayd::version_or_default().await;
801            let gateway_cli_version = crate::util::GatewayCli::version_or_default().await;
802            info!(
803                ?gatewayd_version,
804                ?gateway_cli_version,
805                "running first stress test for gateway",
806            );
807
808            let mut dev_fed = dev_fed(process_mgr).await?;
809            let client = dev_fed.fed.new_joined_client("test-client").await?;
810            try_join!(stress_test_fed(&dev_fed, None), client.wait_session())?;
811
812            for i in 1..gatewayd_paths.len() {
813                info!(
814                    "running stress test with gatewayd path {:?}",
815                    gatewayd_paths.get(i)
816                );
817                let new_gatewayd_path = gatewayd_paths.get(i).expect("Not enough gatewayd paths");
818                let new_gateway_cli_path = gateway_cli_paths
819                    .get(i)
820                    .expect("Not enough gateway-cli paths");
821
822                let gateways = vec![&mut dev_fed.gw_lnd];
823
824                try_join_all(gateways.into_iter().map(|gateway| {
825                    gateway.restart_with_bin(process_mgr, new_gatewayd_path, new_gateway_cli_path)
826                }))
827                .await?;
828
829                dev_fed.fed.await_gateways_registered().await?;
830                try_join!(stress_test_fed(&dev_fed, None), client.wait_session())?;
831                let gatewayd_version = crate::util::Gatewayd::version_or_default().await;
832                let gateway_cli_version = crate::util::GatewayCli::version_or_default().await;
833                info!(
834                    ?gatewayd_version,
835                    ?gateway_cli_version,
836                    "### gateway passed stress test for version",
837                );
838            }
839
840            info!("## gatewayd upgraded all binaries successfully");
841        }
842    }
843    Ok(())
844}
845
846pub async fn cli_tests(dev_fed: DevFed) -> Result<()> {
847    log_binary_versions().await?;
848    let DevFed {
849        bitcoind,
850        lnd,
851        fed,
852        gw_lnd,
853        gw_ldk,
854        ..
855    } = dev_fed;
856
857    let fedimintd_version = crate::util::FedimintdCmd::version_or_default().await;
858
859    let client = fed.new_joined_client("cli-tests-client").await?;
860    let lnd_gw_id = gw_lnd.gateway_id.clone();
861
862    fed.pegin_gateways(10_000_000, vec![&gw_lnd]).await?;
863
864    let iroh_lnd_id = gw_lnd.iroh_gateway_id.clone();
865    let gw_lnd = gw_lnd.client();
866    let gw_ldk = gw_ldk.client();
867
868    let fed_id = fed.calculate_federation_id();
869    let invite = fed.invite_code()?;
870
871    let invite_code = cmd!(client, "dev", "decode", "invite-code", invite.clone())
872        .out_json()
873        .await?;
874
875    let encode_invite_output = cmd!(
876        client,
877        "dev",
878        "encode",
879        "invite-code",
880        format!("--url={}", invite_code["url"].as_str().unwrap()),
881        "--federation_id={fed_id}",
882        "--peer=0"
883    )
884    .out_json()
885    .await?;
886
887    anyhow::ensure!(
888        encode_invite_output["invite_code"]
889            .as_str()
890            .expect("invite_code must be a string")
891            == invite,
892        "failed to decode and encode the client invite code",
893    );
894
895    // Test that LND and LDK can still send directly to each other
896
897    // LND can pay LDK directly
898    info!("Testing LND can pay LDK directly");
899    let invoice = gw_ldk.create_invoice(1_200_000).await?;
900    lnd.pay_bolt11_invoice(invoice.to_string()).await?;
901    gw_ldk
902        .wait_bolt11_invoice(invoice.payment_hash().consensus_encode_to_vec())
903        .await?;
904
905    // LDK can pay LND directly
906    info!("Testing LDK can pay LND directly");
907    let (invoice, payment_hash) = lnd.invoice(1_000_000).await?;
908    gw_ldk
909        .pay_invoice(Bolt11Invoice::from_str(&invoice).expect("Could not parse invoice"))
910        .await?;
911    gw_lnd.wait_bolt11_invoice(payment_hash).await?;
912
913    // # Test the correct descriptor is used
914    let config = cmd!(client, "config").out_json().await?;
915    let guardian_count = config["global"]["api_endpoints"].as_object().unwrap().len();
916    let wallet_module = config["modules"]
917        .as_object()
918        .unwrap()
919        .values()
920        .find(|m| m["kind"].as_str() == Some("wallet"))
921        .expect("wallet module not found");
922    let descriptor = wallet_module["peg_in_descriptor"]
923        .as_str()
924        .unwrap()
925        .to_owned();
926
927    info!("Testing generated descriptor for {guardian_count} guardian federation");
928    if guardian_count == 1 {
929        assert!(descriptor.contains("wpkh("));
930    } else {
931        assert!(descriptor.contains("wsh(sortedmulti("));
932    }
933
934    // # Client tests
935    info!("Testing Client");
936
937    // E-cash tests are v1-specific - skip when MintV2 is enabled
938    if crate::util::supports_mint_v2() {
939        info!("Skipping ecash tests - MintV2 enabled, these tests are v1-specific");
940    } else {
941        // ## reissue e-cash
942        info!("Testing reissuing e-cash");
943        const CLIENT_START_AMOUNT: u64 = 5_000_000_000;
944        const CLIENT_SPEND_AMOUNT: u64 = 1_100_000;
945
946        let initial_client_balance = client.balance().await?;
947        assert_eq!(initial_client_balance, 0);
948
949        fed.pegin_client(CLIENT_START_AMOUNT / 1000, &client)
950            .await?;
951
952        // # Spend from client
953        info!("Testing spending from client");
954        let notes = cmd!(client, "spend", CLIENT_SPEND_AMOUNT)
955            .out_json()
956            .await?
957            .get("notes")
958            .expect("Output didn't contain e-cash notes")
959            .as_str()
960            .unwrap()
961            .to_owned();
962
963        let client_post_spend_balance = client.balance().await?;
964        almost_equal(
965            client_post_spend_balance,
966            CLIENT_START_AMOUNT - CLIENT_SPEND_AMOUNT,
967            10_000,
968        )
969        .unwrap();
970
971        // Test we can reissue our own notes
972        cmd!(client, "reissue", notes).out_json().await?;
973
974        let client_post_spend_balance = client.balance().await?;
975        almost_equal(client_post_spend_balance, CLIENT_START_AMOUNT, 10_000).unwrap();
976
977        let reissue_amount: u64 = 409_600;
978
979        // Ensure that client can reissue after spending
980        info!("Testing reissuing e-cash after spending");
981        let _notes = cmd!(client, "spend", CLIENT_SPEND_AMOUNT)
982            .out_json()
983            .await?
984            .as_object()
985            .unwrap()
986            .get("notes")
987            .expect("Output didn't contain e-cash notes")
988            .as_str()
989            .unwrap();
990
991        let reissue_notes = cmd!(client, "spend", reissue_amount).out_json().await?["notes"]
992            .as_str()
993            .map(ToOwned::to_owned)
994            .unwrap();
995        let client_reissue_amt = cmd!(client, "reissue", reissue_notes)
996            .out_json()
997            .await?
998            .as_u64()
999            .unwrap();
1000        assert_eq!(client_reissue_amt, reissue_amount);
1001
1002        // Ensure that client can reissue via module commands
1003        info!("Testing reissuing e-cash via module commands");
1004        let reissue_notes = cmd!(client, "spend", reissue_amount).out_json().await?["notes"]
1005            .as_str()
1006            .map(ToOwned::to_owned)
1007            .unwrap();
1008        let client_reissue_amt = cmd!(client, "module", "mint", "reissue", reissue_notes)
1009            .out_json()
1010            .await?
1011            .as_u64()
1012            .unwrap();
1013        assert_eq!(client_reissue_amt, reissue_amount);
1014    }
1015
1016    // LND gateway tests
1017    info!("Testing LND gateway");
1018
1019    // OUTGOING: fedimint-cli pays LDK via LND gateway
1020    if let Some(iroh_gw_id) = &iroh_lnd_id
1021        && crate::util::FedimintCli::version_or_default().await >= *VERSION_0_10_0_ALPHA
1022    {
1023        info!("Testing outgoing payment from client to LDK via IROH LND Gateway");
1024
1025        let initial_lnd_gateway_balance = gw_lnd.ecash_balance(fed_id.clone()).await?;
1026        let invoice = gw_ldk.create_invoice(2_000_000).await?;
1027        ln_pay(&client, invoice.to_string(), iroh_gw_id.clone()).await?;
1028        gw_ldk
1029            .wait_bolt11_invoice(invoice.payment_hash().consensus_encode_to_vec())
1030            .await?;
1031
1032        // Assert balances changed by 2_000_000 msat (amount sent) + 0 msat (fee)
1033        let final_lnd_outgoing_gateway_balance = gw_lnd.ecash_balance(fed_id.clone()).await?;
1034        info!(
1035            ?final_lnd_outgoing_gateway_balance,
1036            "Final LND ecash balance after iroh payment"
1037        );
1038        anyhow::ensure!(
1039            almost_equal(
1040                final_lnd_outgoing_gateway_balance - initial_lnd_gateway_balance,
1041                2_000_000,
1042                1_000
1043            )
1044            .is_ok(),
1045            "LND Gateway balance changed by {} on LND outgoing IROH payment, expected 2_000_000",
1046            (final_lnd_outgoing_gateway_balance - initial_lnd_gateway_balance)
1047        );
1048
1049        // Send the funds back over iroh
1050        let recv = ln_invoice(
1051            &client,
1052            Amount::from_msats(2_000_000),
1053            "iroh receive payment".to_string(),
1054            iroh_gw_id.clone(),
1055        )
1056        .await?;
1057        gw_ldk
1058            .pay_invoice(Bolt11Invoice::from_str(&recv.invoice).expect("Could not parse invoice"))
1059            .await?;
1060        let operation_id = recv.operation_id;
1061        cmd!(client, "await-invoice", operation_id.fmt_full())
1062            .run()
1063            .await?;
1064    }
1065
1066    info!("Testing outgoing payment from client to LDK via LND gateway");
1067    let initial_lnd_gateway_balance = gw_lnd.ecash_balance(fed_id.clone()).await?;
1068    let invoice = gw_ldk.create_invoice(2_000_000).await?;
1069    ln_pay(&client, invoice.to_string(), lnd_gw_id.clone()).await?;
1070    let fed_id = fed.calculate_federation_id();
1071    gw_ldk
1072        .wait_bolt11_invoice(invoice.payment_hash().consensus_encode_to_vec())
1073        .await?;
1074
1075    // Assert balances changed by 2_000_000 msat (amount sent) + 0 msat (fee)
1076    let final_lnd_outgoing_gateway_balance = gw_lnd.ecash_balance(fed_id.clone()).await?;
1077    anyhow::ensure!(
1078        almost_equal(
1079            final_lnd_outgoing_gateway_balance - initial_lnd_gateway_balance,
1080            2_000_000,
1081            3_000
1082        )
1083        .is_ok(),
1084        "LND Gateway balance changed by {} on LND outgoing payment, expected 2_000_000",
1085        (final_lnd_outgoing_gateway_balance - initial_lnd_gateway_balance)
1086    );
1087
1088    // INCOMING: fedimint-cli receives from LDK via LND gateway
1089    info!("Testing incoming payment from LDK to client via LND gateway");
1090    let initial_lnd_incoming_client_balance = client.balance().await?;
1091    let recv = ln_invoice(
1092        &client,
1093        Amount::from_msats(1_300_000),
1094        "incoming-over-lnd-gw".to_string(),
1095        lnd_gw_id,
1096    )
1097    .await?;
1098    let invoice = recv.invoice;
1099    gw_ldk
1100        .pay_invoice(Bolt11Invoice::from_str(&invoice).expect("Could not parse invoice"))
1101        .await?;
1102
1103    // Receive the ecash notes
1104    info!("Testing receiving ecash notes");
1105    let operation_id = recv.operation_id;
1106    cmd!(client, "await-invoice", operation_id.fmt_full())
1107        .run()
1108        .await?;
1109
1110    // Only validate balance changes on v0.11 and above because there is a race
1111    // condition in older versions that causes the balances to not match.
1112    let fedimint_cli_version = crate::util::FedimintCli::version_or_default().await;
1113    if fedimint_cli_version >= *VERSION_0_11_0_ALPHA {
1114        // Assert balances changed by 1_300_000 msat
1115        let final_lnd_incoming_client_balance = client.balance().await?;
1116        let final_lnd_incoming_gateway_balance = gw_lnd.ecash_balance(fed_id.clone()).await?;
1117        anyhow::ensure!(
1118            almost_equal(
1119                final_lnd_incoming_client_balance - initial_lnd_incoming_client_balance,
1120                1_300_000,
1121                2_000
1122            )
1123            .is_ok(),
1124            "Client balance changed by {} on LND incoming payment, expected 1_300_000",
1125            (final_lnd_incoming_client_balance - initial_lnd_incoming_client_balance)
1126        );
1127        anyhow::ensure!(
1128            almost_equal(
1129                final_lnd_outgoing_gateway_balance - final_lnd_incoming_gateway_balance,
1130                1_300_000,
1131                2_000
1132            )
1133            .is_ok(),
1134            "LND Gateway balance changed by {} on LND incoming payment, expected 1_300_000",
1135            (final_lnd_outgoing_gateway_balance - final_lnd_incoming_gateway_balance)
1136        );
1137    }
1138
1139    // # Wallet tests
1140    // ## Deposit
1141    info!("Testing client deposit");
1142    let initial_walletng_balance = client.balance().await?;
1143
1144    fed.pegin_client(100_000, &client).await?; // deposit in sats
1145
1146    let post_deposit_walletng_balance = client.balance().await?;
1147
1148    almost_equal(
1149        post_deposit_walletng_balance,
1150        initial_walletng_balance + 100_000_000, // deposit in msats
1151        2_000,
1152    )
1153    .unwrap();
1154
1155    // ## Withdraw
1156    info!("Testing client withdraw");
1157
1158    let initial_walletng_balance = client.balance().await?;
1159
1160    let address = bitcoind.get_new_address().await?;
1161    let withdraw_res = cmd!(
1162        client,
1163        "withdraw",
1164        "--address",
1165        &address,
1166        "--amount",
1167        "50000 sat"
1168    )
1169    .out_json()
1170    .await?;
1171
1172    let txid: Txid = withdraw_res["txid"].as_str().unwrap().parse().unwrap();
1173    let fees_sat = withdraw_res["fees_sat"].as_u64().unwrap();
1174
1175    let tx_hex = bitcoind.poll_get_transaction(txid).await?;
1176
1177    let tx = bitcoin::Transaction::consensus_decode_hex(&tx_hex, &ModuleRegistry::default())?;
1178    assert!(
1179        tx.output
1180            .iter()
1181            .any(|o| o.script_pubkey == address.script_pubkey() && o.value.to_sat() == 50000)
1182    );
1183
1184    let post_withdraw_walletng_balance = client.balance().await?;
1185    let expected_wallet_balance = initial_walletng_balance - 50_000_000 - (fees_sat * 1000);
1186
1187    almost_equal(
1188        post_withdraw_walletng_balance,
1189        expected_wallet_balance,
1190        4_000,
1191    )
1192    .unwrap();
1193
1194    // ## Withdraw everything
1195    //
1196    // `module wallet withdraw --amount all` was added in 0.13.0-alpha; before
1197    // that the module CLI rejected "all" outright.
1198    if fedimint_cli_version >= *VERSION_0_13_0_ALPHA {
1199        info!("Testing client withdraw all");
1200
1201        let pre_sweep_balance = client.balance().await?;
1202        let address = bitcoind.get_new_address().await?;
1203
1204        // Sweeping the whole balance has to leave room for the mint's per-note
1205        // fees on top of the on-chain fee. With base fees enabled (the default)
1206        // a naive `balance - onchain_fee` is underfunded and note selection
1207        // rejects the peg-out.
1208        let sweep_res = cmd!(
1209            client,
1210            "module",
1211            "wallet",
1212            "withdraw",
1213            "--amount",
1214            "all",
1215            "--address",
1216            &address
1217        )
1218        .out_json()
1219        .await?;
1220
1221        let txid: Txid = sweep_res["txid"]
1222            .as_str()
1223            .expect("sweep should return a txid")
1224            .parse()?;
1225
1226        bitcoind.poll_get_transaction(txid).await?;
1227
1228        // A sweep cannot always drain to exactly zero — the fee is stepwise in
1229        // the amount, so a sub-denomination remainder can be left behind — but
1230        // it must move all but a negligible part of the balance.
1231        let post_sweep_balance = client.balance().await?;
1232
1233        assert!(
1234            post_sweep_balance < pre_sweep_balance / 100,
1235            "Sweep left {post_sweep_balance} msats of {pre_sweep_balance} msats behind",
1236        );
1237    }
1238
1239    // # peer-version command
1240    let peer_0_fedimintd_version = cmd!(client, "dev", "peer-version", "--peer-id", "0")
1241        .out_json()
1242        .await?
1243        .get("version")
1244        .expect("Output didn't contain version")
1245        .as_str()
1246        .unwrap()
1247        .to_owned();
1248
1249    assert_eq!(
1250        semver::Version::parse(&peer_0_fedimintd_version)?,
1251        fedimintd_version
1252    );
1253
1254    info!("Checking initial announcements...");
1255
1256    retry(
1257        "Check initial announcements",
1258        aggressive_backoff(),
1259        || async {
1260            // Give the client some time to fetch updates
1261            cmd!(client, "dev", "wait", "1").run().await?;
1262
1263            // # API URL announcements
1264            let initial_announcements =
1265                serde_json::from_value::<BTreeMap<PeerId, SignedApiAnnouncement>>(
1266                    cmd!(client, "dev", "api-announcements",).out_json().await?,
1267                )
1268                .expect("failed to parse API announcements");
1269
1270            if initial_announcements.len() < fed.members.len() {
1271                bail!(
1272                    "Not all announcements ready; got: {}, expected: {}",
1273                    initial_announcements.len(),
1274                    fed.members.len()
1275                )
1276            }
1277
1278            if !initial_announcements
1279                .values()
1280                .all(|announcement| announcement.api_announcement.nonce == 0)
1281            {
1282                bail!("Not all announcements have their initial value");
1283            }
1284            Ok(())
1285        },
1286    )
1287    .await?;
1288
1289    const NEW_API_URL: &str = "ws://127.0.0.1:4242";
1290    let new_announcement = serde_json::from_value::<SignedApiAnnouncement>(
1291        cmd!(
1292            client,
1293            "--our-id",
1294            "0",
1295            "--password",
1296            "pass",
1297            "admin",
1298            "sign-api-announcement",
1299            NEW_API_URL
1300        )
1301        .out_json()
1302        .await?,
1303    )
1304    .expect("Couldn't parse signed announcement");
1305
1306    assert_eq!(
1307        new_announcement.api_announcement.nonce, 1,
1308        "Nonce did not increment correctly"
1309    );
1310
1311    info!("Testing if the client syncs the announcement");
1312    let announcement = poll("Waiting for the announcement to propagate", || async {
1313        cmd!(client, "dev", "wait", "1")
1314            .run()
1315            .await
1316            .map_err(ControlFlow::Break)?;
1317
1318        let new_announcements_peer2 =
1319            serde_json::from_value::<BTreeMap<PeerId, SignedApiAnnouncement>>(
1320                cmd!(client, "dev", "api-announcements",)
1321                    .out_json()
1322                    .await
1323                    .map_err(ControlFlow::Break)?,
1324            )
1325            .expect("failed to parse API announcements");
1326
1327        let announcement = new_announcements_peer2[&PeerId::from(0)]
1328            .api_announcement
1329            .clone();
1330        if announcement.nonce == 1 {
1331            Ok(announcement)
1332        } else {
1333            Err(ControlFlow::Continue(anyhow!(
1334                "Haven't received updated announcement yet; nonce: {}",
1335                announcement.nonce
1336            )))
1337        }
1338    })
1339    .await?;
1340
1341    assert_eq!(
1342        announcement.api_url,
1343        NEW_API_URL.parse().expect("valid URL")
1344    );
1345
1346    Ok(())
1347}
1348
1349pub async fn guardian_metadata_tests(dev_fed: DevFed) -> Result<()> {
1350    use fedimint_api_client::api::{DynGlobalApi, FederationApiExt};
1351    use fedimint_connectors::ConnectorRegistry;
1352    use fedimint_core::PeerId;
1353    use fedimint_core::endpoint_constants::INVITE_CODE_ENDPOINT;
1354    use fedimint_core::invite_code::InviteCode;
1355    use fedimint_core::module::ApiRequestErased;
1356    use fedimint_core::net::guardian_metadata::SignedGuardianMetadata;
1357    use fedimint_core::util::SafeUrl;
1358
1359    log_binary_versions().await?;
1360
1361    let fedimintd_version = crate::util::FedimintdCmd::version_or_default().await;
1362    let fedimint_cli_version = crate::util::FedimintCli::version_or_default().await;
1363
1364    if fedimintd_version < *VERSION_0_11_0_ALPHA || fedimint_cli_version < *VERSION_0_11_0_ALPHA {
1365        info!("Skipping test for too old versions");
1366        return Ok(());
1367    }
1368
1369    let DevFed { fed, .. } = dev_fed;
1370
1371    let client = fed.internal_client().await?;
1372
1373    info!("Checking initial guardian metadata...");
1374
1375    retry(
1376        "Check initial guardian metadata",
1377        aggressive_backoff(),
1378        || async {
1379            // Give the client some time to fetch updates
1380            cmd!(client, "dev", "wait", "1").run().await?;
1381
1382            let initial_metadata =
1383                serde_json::from_value::<BTreeMap<PeerId, SignedGuardianMetadata>>(
1384                    cmd!(client, "dev", "guardian-metadata",).out_json().await?,
1385                )
1386                .expect("failed to parse guardian metadata");
1387
1388            if initial_metadata.len() < fed.members.len() {
1389                bail!(
1390                    "Not all guardian metadata ready; got: {}, expected: {}",
1391                    initial_metadata.len(),
1392                    fed.members.len()
1393                )
1394            }
1395
1396            Ok(())
1397        },
1398    )
1399    .await?;
1400
1401    const TEST_API_URL: &str = "ws://127.0.0.1:5000/";
1402    const TEST_PKARR_ID: &str = "test_pkarr_id_z32";
1403
1404    let new_metadata = serde_json::from_value::<SignedGuardianMetadata>(
1405        cmd!(
1406            client,
1407            "--our-id",
1408            "0",
1409            "--password",
1410            "pass",
1411            "admin",
1412            "sign-guardian-metadata",
1413            "--api-urls",
1414            TEST_API_URL,
1415            "--pkarr-id",
1416            TEST_PKARR_ID
1417        )
1418        .out_json()
1419        .await?,
1420    )
1421    .expect("Couldn't parse signed guardian metadata");
1422
1423    let parsed_metadata = new_metadata.guardian_metadata();
1424
1425    assert_eq!(
1426        parsed_metadata.api_urls.first().unwrap().to_string(),
1427        TEST_API_URL,
1428        "API URL did not match"
1429    );
1430
1431    assert_eq!(
1432        parsed_metadata.pkarr_id_z32, TEST_PKARR_ID,
1433        "Pkarr ID did not match"
1434    );
1435
1436    info!("Testing if the client syncs the guardian metadata");
1437    let metadata = poll("Waiting for the guardian metadata to propagate", || async {
1438        cmd!(client, "dev", "wait", "1")
1439            .run()
1440            .await
1441            .map_err(ControlFlow::Break)?;
1442
1443        let new_metadata_peer0 =
1444            serde_json::from_value::<BTreeMap<PeerId, SignedGuardianMetadata>>(
1445                cmd!(client, "dev", "guardian-metadata",)
1446                    .out_json()
1447                    .await
1448                    .map_err(ControlFlow::Break)?,
1449            )
1450            .expect("failed to parse guardian metadata");
1451
1452        let metadata = new_metadata_peer0[&PeerId::from(0)].guardian_metadata();
1453
1454        if metadata.api_urls.first().unwrap().to_string() == TEST_API_URL {
1455            Ok(metadata.clone())
1456        } else {
1457            Err(ControlFlow::Continue(anyhow!(
1458                "Haven't received updated guardian metadata yet"
1459            )))
1460        }
1461    })
1462    .await?;
1463
1464    assert_eq!(
1465        metadata.pkarr_id_z32, TEST_PKARR_ID,
1466        "Pkarr ID did not propagate correctly"
1467    );
1468
1469    // `invite_code` only honors overridden API URLs since 0.12.0-alpha; skip
1470    // against older fedimintd in backwards-compatibility tests.
1471    if fedimintd_version < *VERSION_0_12_0_ALPHA {
1472        info!("Skipping invite_code endpoint assertion: fedimintd < 0.12.0-alpha");
1473        return Ok(());
1474    }
1475
1476    info!("Checking invite_code endpoint reflects overridden guardian metadata URL...");
1477    // Query peer 0 directly: the client's peer-URL map now points at the fake
1478    // override URL, so `dev api --peer-id 0` would fail to connect.
1479    let peer_id = PeerId::from(0);
1480    let peer0_real_url: SafeUrl = fed
1481        .vars
1482        .get(&0)
1483        .expect("peer 0 vars must exist")
1484        .FM_API_URL
1485        .parse()
1486        .expect("FM_API_URL must be a valid SafeUrl");
1487    let connectors = ConnectorRegistry::build_from_testing_env()?.bind().await?;
1488    let admin_api = DynGlobalApi::new_admin(connectors, peer_id, peer0_real_url, None)?;
1489    let invite: InviteCode = admin_api
1490        .request_single_peer(
1491            INVITE_CODE_ENDPOINT.to_string(),
1492            ApiRequestErased::default(),
1493            peer_id,
1494        )
1495        .await
1496        .expect("invite_code RPC request should succeed");
1497    assert_eq!(
1498        invite.url().to_string(),
1499        TEST_API_URL,
1500        "invite_code endpoint did not reflect overridden guardian metadata URL"
1501    );
1502
1503    Ok(())
1504}
1505
1506pub async fn cli_load_test_tool_test(dev_fed: DevFed) -> Result<()> {
1507    log_binary_versions().await?;
1508    let data_dir = env::var(FM_DATA_DIR_ENV)?;
1509    let load_test_temp = PathBuf::from(data_dir).join("load-test-temp");
1510    dev_fed
1511        .fed
1512        .pegin_client(10_000, dev_fed.fed.internal_client().await?)
1513        .await?;
1514    let invite_code = dev_fed.fed.invite_code()?;
1515    dev_fed
1516        .gw_lnd
1517        .client()
1518        .set_federation_routing_fee(dev_fed.fed.calculate_federation_id(), 0, 0)
1519        .await?;
1520    run_standard_load_test(&load_test_temp, &invite_code).await?;
1521    run_ln_circular_load_test(&load_test_temp, &invite_code).await?;
1522    Ok(())
1523}
1524
1525pub async fn run_standard_load_test(
1526    load_test_temp: &Path,
1527    invite_code: &str,
1528) -> anyhow::Result<()> {
1529    let output = cmd!(
1530        LoadTestTool,
1531        "--archive-dir",
1532        load_test_temp.display(),
1533        "--users",
1534        "1",
1535        "load-test",
1536        "--notes-per-user",
1537        "1",
1538        "--generate-invoice-with",
1539        "ldk-lightning-cli",
1540        "--invite-code",
1541        invite_code
1542    )
1543    .out_string()
1544    .await?;
1545    println!("{output}");
1546    anyhow::ensure!(
1547        output.contains("2 reissue_notes"),
1548        "reissued different number notes than expected"
1549    );
1550    anyhow::ensure!(
1551        output.contains("1 gateway_pay_invoice"),
1552        "paid different number of invoices than expected"
1553    );
1554    Ok(())
1555}
1556
1557pub async fn run_ln_circular_load_test(
1558    load_test_temp: &Path,
1559    invite_code: &str,
1560) -> anyhow::Result<()> {
1561    info!("Testing ln-circular-load-test with 'two-gateways' strategy");
1562    let output = cmd!(
1563        LoadTestTool,
1564        "--archive-dir",
1565        load_test_temp.display(),
1566        "--users",
1567        "1",
1568        "ln-circular-load-test",
1569        "--strategy",
1570        "two-gateways",
1571        "--test-duration-secs",
1572        "2",
1573        "--invite-code",
1574        invite_code
1575    )
1576    .out_string()
1577    .await?;
1578    println!("{output}");
1579    anyhow::ensure!(
1580        output.contains("gateway_create_invoice"),
1581        "missing invoice creation"
1582    );
1583    anyhow::ensure!(
1584        output.contains("gateway_pay_invoice_success"),
1585        "missing invoice payment"
1586    );
1587    anyhow::ensure!(
1588        output.contains("gateway_payment_received_success"),
1589        "missing received payment"
1590    );
1591
1592    info!("Testing ln-circular-load-test with 'partner-ping-pong' strategy");
1593    // Note: invite code isn't required because we already have an archive dir
1594    // Note: test-duration-secs needs to be greater than the timeout for
1595    // discover_api_version_set to work with degraded federations
1596    let output = cmd!(
1597        LoadTestTool,
1598        "--archive-dir",
1599        load_test_temp.display(),
1600        "--users",
1601        "1",
1602        "ln-circular-load-test",
1603        "--strategy",
1604        "partner-ping-pong",
1605        "--test-duration-secs",
1606        "6",
1607        "--invite-code",
1608        invite_code
1609    )
1610    .out_string()
1611    .await?;
1612    println!("{output}");
1613    anyhow::ensure!(
1614        output.contains("gateway_create_invoice"),
1615        "missing invoice creation"
1616    );
1617    anyhow::ensure!(
1618        output.contains("gateway_payment_received_success"),
1619        "missing received payment"
1620    );
1621
1622    info!("Testing ln-circular-load-test with 'self-payment' strategy");
1623    // Note invite code isn't required because we already have an archive dir
1624    let output = cmd!(
1625        LoadTestTool,
1626        "--archive-dir",
1627        load_test_temp.display(),
1628        "--users",
1629        "1",
1630        "ln-circular-load-test",
1631        "--strategy",
1632        "self-payment",
1633        "--test-duration-secs",
1634        "2",
1635        "--invite-code",
1636        invite_code
1637    )
1638    .out_string()
1639    .await?;
1640    println!("{output}");
1641    anyhow::ensure!(
1642        output.contains("gateway_create_invoice"),
1643        "missing invoice creation"
1644    );
1645    anyhow::ensure!(
1646        output.contains("gateway_payment_received_success"),
1647        "missing received payment"
1648    );
1649    Ok(())
1650}
1651
1652pub async fn lightning_gw_reconnect_test(
1653    dev_fed: DevFed,
1654    process_mgr: &ProcessManager,
1655) -> Result<()> {
1656    log_binary_versions().await?;
1657
1658    let DevFed {
1659        bitcoind,
1660        lnd,
1661        fed,
1662        mut gw_lnd,
1663        gw_ldk,
1664        ..
1665    } = dev_fed;
1666
1667    let client = fed
1668        .new_joined_client("lightning-gw-reconnect-test-client")
1669        .await?;
1670
1671    info!("Pegging-in both gateways");
1672    fed.pegin_gateways(99_999, vec![&gw_lnd]).await?;
1673
1674    // Drop other references to LND so that the test can kill it
1675    drop(lnd);
1676
1677    tracing::info!("Stopping LND");
1678    // Verify that the gateway can query the lightning node for the pubkey and alias
1679    assert!(gw_lnd.client().get_info().await.is_ok());
1680
1681    // Verify that after stopping the lightning node, info no longer returns the
1682    // node public key since the lightning node is unreachable.
1683    let ln_type = gw_lnd.ln.ln_type().to_string();
1684    gw_lnd.stop_lightning_node().await?;
1685    let lightning_info = gw_lnd.client().get_info().await?;
1686    if gw_lnd.gatewayd_version < *VERSION_0_10_0_ALPHA {
1687        let lightning_pub_key: Option<String> =
1688            serde_json::from_value(lightning_info["lightning_pub_key"].clone())?;
1689
1690        assert!(lightning_pub_key.is_none());
1691    } else {
1692        let not_connected = lightning_info["lightning_info"].clone();
1693        assert!(not_connected.as_str().expect("ln info is not a string") == "not_connected");
1694    }
1695
1696    // Restart LND
1697    tracing::info!("Restarting LND...");
1698    let new_lnd = Lnd::new(process_mgr, bitcoind.clone()).await?;
1699    gw_lnd.set_lightning_node(LightningNode::Lnd(new_lnd.clone()));
1700
1701    tracing::info!("Retrying info...");
1702    const MAX_RETRIES: usize = 30;
1703    const RETRY_INTERVAL: Duration = Duration::from_secs(1);
1704
1705    for i in 0..MAX_RETRIES {
1706        match do_try_create_and_pay_invoice(&gw_lnd, &client, &gw_ldk).await {
1707            Ok(()) => break,
1708            Err(e) => {
1709                if i == MAX_RETRIES - 1 {
1710                    return Err(e);
1711                }
1712                tracing::debug!(
1713                    "Pay invoice for gateway {} failed with {e:?}, retrying in {} seconds (try {}/{MAX_RETRIES})",
1714                    ln_type,
1715                    RETRY_INTERVAL.as_secs(),
1716                    i + 1,
1717                );
1718                fedimint_core::task::sleep_in_test(
1719                    "paying invoice for gateway failed",
1720                    RETRY_INTERVAL,
1721                )
1722                .await;
1723            }
1724        }
1725    }
1726
1727    info!(target: LOG_DEVIMINT, "lightning_reconnect_test: success");
1728    Ok(())
1729}
1730
1731pub async fn gw_reboot_test(dev_fed: DevFed, process_mgr: &ProcessManager) -> Result<()> {
1732    log_binary_versions().await?;
1733
1734    let DevFed {
1735        bitcoind,
1736        lnd,
1737        fed,
1738        gw_lnd,
1739        gw_ldk,
1740        gw_ldk_second,
1741        ..
1742    } = dev_fed;
1743
1744    let client = fed.new_joined_client("gw-reboot-test-client").await?;
1745    fed.pegin_client(10_000, &client).await?;
1746
1747    // Wait for gateways to sync to chain
1748    let block_height = bitcoind.get_block_count().await? - 1;
1749    try_join!(
1750        async { gw_lnd.client().wait_for_block_height(block_height).await },
1751        async { gw_ldk.client().wait_for_block_height(block_height).await },
1752    )?;
1753
1754    // Drop references to gateways so the test can kill them
1755    let lnd_gateway_id = gw_lnd.gateway_id.clone();
1756    let ldk_gateway_id = gw_ldk.gateway_id.clone();
1757    let gw_ldk_name = gw_ldk.gw_name.clone();
1758    let gw_ldk_port = gw_ldk.gw_port;
1759    let gw_lightning_port = gw_ldk.ldk_port;
1760    let gw_ldk_metrics_port = gw_ldk.metrics_port;
1761    drop(gw_lnd);
1762    drop(gw_ldk);
1763
1764    // Verify that making a payment while the gateways are down does not result in
1765    // funds being stuck
1766    info!("Making payment while gateway is down");
1767    let initial_client_balance = client.balance().await?;
1768    let invoice = gw_ldk_second.client().create_invoice(3000).await?;
1769    ln_pay(&client, invoice.to_string(), lnd_gateway_id.clone())
1770        .await
1771        .expect_err("Expected ln-pay to return error because the gateway is not online");
1772    let new_client_balance = client.balance().await?;
1773    anyhow::ensure!(initial_client_balance == new_client_balance);
1774
1775    // Reboot gateways with the same Lightning node instances
1776    info!("Rebooting gateways...");
1777    let (new_gw_lnd, new_gw_ldk) = try_join!(
1778        Gatewayd::new(process_mgr, LightningNode::Lnd(lnd.clone()), 0),
1779        Gatewayd::new(
1780            process_mgr,
1781            LightningNode::Ldk {
1782                name: gw_ldk_name,
1783                gw_port: gw_ldk_port,
1784                ldk_port: gw_lightning_port,
1785                metrics_port: gw_ldk_metrics_port,
1786            },
1787            1,
1788        )
1789    )?;
1790
1791    let lnd_gateway_id = fedimint_core::secp256k1::PublicKey::from_str(&lnd_gateway_id)?;
1792
1793    poll(
1794        "Waiting for LND Gateway Running state after reboot",
1795        || async {
1796            let lnd_value = new_gw_lnd.client().get_info().await.map_err(ControlFlow::Continue)?;
1797            let reboot_gateway_state: String = serde_json::from_value(lnd_value["gateway_state"].clone()).context("invalid gateway state").map_err(ControlFlow::Break)?;
1798            let reboot_gateway_id = fedimint_core::secp256k1::PublicKey::from_str(&new_gw_lnd.gateway_id).expect("Could not convert public key");
1799
1800            if reboot_gateway_state == "Running" {
1801                info!(target: LOG_DEVIMINT, "LND Gateway restarted, with auto-rejoin to federation");
1802                // Assert that the gateway info is the same as before the reboot
1803                assert_eq!(lnd_gateway_id, reboot_gateway_id);
1804                return Ok(());
1805            }
1806            Err(ControlFlow::Continue(anyhow!("gateway not running")))
1807        },
1808    )
1809    .await?;
1810
1811    let ldk_gateway_id = fedimint_core::secp256k1::PublicKey::from_str(&ldk_gateway_id)?;
1812    poll(
1813        "Waiting for LDK Gateway Running state after reboot",
1814        || async {
1815            let ldk_value = new_gw_ldk.client().get_info().await.map_err(ControlFlow::Continue)?;
1816            let reboot_gateway_state: String = serde_json::from_value(ldk_value["gateway_state"].clone()).context("invalid gateway state").map_err(ControlFlow::Break)?;
1817            let reboot_gateway_id = fedimint_core::secp256k1::PublicKey::from_str(&new_gw_ldk.gateway_id).expect("Could not convert public key");
1818
1819            if reboot_gateway_state == "Running" {
1820                info!(target: LOG_DEVIMINT, "LDK Gateway restarted, with auto-rejoin to federation");
1821                // Assert that the gateway info is the same as before the reboot
1822                assert_eq!(ldk_gateway_id, reboot_gateway_id);
1823                return Ok(());
1824            }
1825            Err(ControlFlow::Continue(anyhow!("gateway not running")))
1826        },
1827    )
1828    .await?;
1829
1830    info!(LOG_DEVIMINT, "gateway_reboot_test: success");
1831    Ok(())
1832}
1833
1834pub async fn do_try_create_and_pay_invoice(
1835    gw_lnd: &Gatewayd,
1836    client: &Client,
1837    gw_ldk: &Gatewayd,
1838) -> anyhow::Result<()> {
1839    // Verify that after the lightning node has restarted, the gateway
1840    // automatically reconnects and can query the lightning node
1841    // info again.
1842    poll("Waiting for info to succeed after restart", || async {
1843        gw_lnd
1844            .client()
1845            .lightning_pubkey()
1846            .await
1847            .map_err(ControlFlow::Continue)?;
1848        Ok(())
1849    })
1850    .await?;
1851
1852    tracing::info!("Creating invoice....");
1853    let invoice = ln_invoice(
1854        client,
1855        Amount::from_msats(1000),
1856        "incoming-over-lnd-gw".to_string(),
1857        gw_lnd.gateway_id.clone(),
1858    )
1859    .await?
1860    .invoice;
1861
1862    match &gw_lnd.ln.ln_type() {
1863        LightningNodeType::Lnd => {
1864            // Pay the invoice using LDK
1865            gw_ldk
1866                .client()
1867                .pay_invoice(Bolt11Invoice::from_str(&invoice).expect("Could not parse invoice"))
1868                .await?;
1869        }
1870        LightningNodeType::Ldk => {
1871            unimplemented!("do_try_create_and_pay_invoice not implemented for LDK yet");
1872        }
1873    }
1874    Ok(())
1875}
1876
1877async fn ln_pay(client: &Client, invoice: String, gw_id: String) -> anyhow::Result<String> {
1878    let value = cmd!(client, "ln-pay", invoice, "--gateway-id", gw_id,)
1879        .out_json()
1880        .await?;
1881    let outcome = serde_json::from_value::<LightningPaymentOutcome>(value)
1882        .expect("Could not deserialize Lightning payment outcome");
1883    match outcome {
1884        LightningPaymentOutcome::Success { preimage } => Ok(preimage),
1885        LightningPaymentOutcome::Failure { error_message } => {
1886            Err(anyhow!("Failed to pay lightning invoice: {error_message}"))
1887        }
1888    }
1889}
1890
1891async fn ln_invoice(
1892    client: &Client,
1893    amount: Amount,
1894    description: String,
1895    gw_id: String,
1896) -> anyhow::Result<LnInvoiceResponse> {
1897    let ln_response_val = cmd!(
1898        client,
1899        "ln-invoice",
1900        "--amount",
1901        amount.msats,
1902        format!("--description='{description}'"),
1903        "--gateway-id",
1904        gw_id,
1905    )
1906    .out_json()
1907    .await?;
1908
1909    let ln_invoice_response: LnInvoiceResponse = serde_json::from_value(ln_response_val)?;
1910
1911    Ok(ln_invoice_response)
1912}
1913
1914async fn lnv2_receive(
1915    client: &Client,
1916    gateway: &str,
1917    amount: u64,
1918) -> anyhow::Result<(Bolt11Invoice, OperationId)> {
1919    Ok(serde_json::from_value::<(Bolt11Invoice, OperationId)>(
1920        cmd!(
1921            client,
1922            "module",
1923            "lnv2",
1924            "receive",
1925            amount,
1926            "--gateway",
1927            gateway
1928        )
1929        .out_json()
1930        .await?,
1931    )?)
1932}
1933
1934async fn lnv2_send(client: &Client, gateway: &String, invoice: &String) -> anyhow::Result<()> {
1935    let send_op = serde_json::from_value::<OperationId>(
1936        cmd!(
1937            client,
1938            "module",
1939            "lnv2",
1940            "send",
1941            invoice,
1942            "--gateway",
1943            gateway
1944        )
1945        .out_json()
1946        .await?,
1947    )?;
1948
1949    let send_state = lnv2_await_send(client, send_op).await?;
1950    assert!(
1951        matches!(send_state, FinalSendOperationState::Success(_)),
1952        "unexpected send state: {send_state:?}"
1953    );
1954
1955    Ok(())
1956}
1957
1958/// Run `await-send` and parse the JSON, tolerating the pre-0.12 CLI output
1959/// shape so this works across the backwards-compatibility test matrix.
1960///
1961/// Pre-0.12 binaries serialize `FinalSendOperationState::Success` as the bare
1962/// string `"Success"` (unit variant); 0.12+ serializes it as `{"Success":
1963/// "<hex preimage>"}` (tuple variant carrying the preimage). Coerce the old
1964/// shape to a synthetic `Success(zero-preimage)` so callers can match
1965/// uniformly regardless of which CLI produced the output.
1966async fn lnv2_await_send(
1967    client: &Client,
1968    send_op: OperationId,
1969) -> anyhow::Result<FinalSendOperationState> {
1970    let raw = cmd!(
1971        client,
1972        "module",
1973        "lnv2",
1974        "await-send",
1975        serde_json::to_string(&send_op)?.substring(1, 65)
1976    )
1977    .out_json()
1978    .await?;
1979
1980    Ok(if raw.as_str() == Some("Success") {
1981        FinalSendOperationState::Success([0; 32])
1982    } else {
1983        serde_json::from_value(raw)?
1984    })
1985}
1986
1987pub async fn reconnect_test(dev_fed: DevFed, process_mgr: &ProcessManager) -> Result<()> {
1988    log_binary_versions().await?;
1989
1990    let DevFed {
1991        bitcoind, mut fed, ..
1992    } = dev_fed;
1993
1994    bitcoind.mine_blocks(110).await?;
1995    fed.await_block_sync().await?;
1996    fed.await_all_peers().await?;
1997
1998    // test a peer missing out on epochs and needing to rejoin
1999    fed.terminate_server(0).await?;
2000    fed.mine_then_wait_blocks_sync(100).await?;
2001
2002    fed.start_server(process_mgr, 0).await?;
2003    fed.mine_then_wait_blocks_sync(100).await?;
2004    fed.await_all_peers().await?;
2005    info!(target: LOG_DEVIMINT, "Server 0 successfully rejoined!");
2006    fed.mine_then_wait_blocks_sync(100).await?;
2007
2008    // now test what happens if consensus needs to be restarted
2009    fed.terminate_server(1).await?;
2010    fed.mine_then_wait_blocks_sync(100).await?;
2011    fed.terminate_server(2).await?;
2012    fed.terminate_server(3).await?;
2013
2014    fed.start_server(process_mgr, 1).await?;
2015    fed.start_server(process_mgr, 2).await?;
2016    fed.start_server(process_mgr, 3).await?;
2017
2018    fed.await_all_peers().await?;
2019
2020    info!(target: LOG_DEVIMINT, "fm success: reconnect-test");
2021    Ok(())
2022}
2023
2024pub async fn recoverytool_test(dev_fed: DevFed) -> Result<()> {
2025    log_binary_versions().await?;
2026
2027    let DevFed { bitcoind, fed, .. } = dev_fed;
2028
2029    let data_dir = env::var(FM_DATA_DIR_ENV)?;
2030    let client = fed.new_joined_client("recoverytool-test-client").await?;
2031
2032    let mut fed_utxos_sats = HashSet::from([12_345_000, 23_456_000, 34_567_000]);
2033    let deposit_fees = fed.deposit_fees()?.msats / 1000;
2034    for sats in &fed_utxos_sats {
2035        // pegin_client automatically adds fees, so we need to counteract that
2036        fed.pegin_client(*sats - deposit_fees, &client).await?;
2037    }
2038
2039    async fn withdraw(
2040        client: &Client,
2041        bitcoind: &crate::external::Bitcoind,
2042        fed_utxos_sats: &mut HashSet<u64>,
2043    ) -> Result<()> {
2044        let withdrawal_address = bitcoind.get_new_address().await?;
2045        let withdraw_res = cmd!(
2046            client,
2047            "withdraw",
2048            "--address",
2049            &withdrawal_address,
2050            "--amount",
2051            "5000 sat"
2052        )
2053        .out_json()
2054        .await?;
2055
2056        let fees_sat = withdraw_res["fees_sat"]
2057            .as_u64()
2058            .expect("withdrawal should contain fees");
2059        let txid: Txid = withdraw_res["txid"]
2060            .as_str()
2061            .expect("withdrawal should contain txid string")
2062            .parse()
2063            .expect("txid should be parsable");
2064        let tx_hex = bitcoind.poll_get_transaction(txid).await?;
2065
2066        let tx = bitcoin::Transaction::consensus_decode_hex(&tx_hex, &ModuleRegistry::default())?;
2067        assert_eq!(tx.input.len(), 1);
2068        assert_eq!(tx.output.len(), 2);
2069
2070        let change_output = tx
2071            .output
2072            .iter()
2073            .find(|o| o.to_owned().script_pubkey != withdrawal_address.script_pubkey())
2074            .expect("withdrawal must have change output");
2075        assert!(fed_utxos_sats.insert(change_output.value.to_sat()));
2076
2077        // Remove the utxo consumed from the withdrawal tx
2078        let total_output_sats = tx.output.iter().map(|o| o.value.to_sat()).sum::<u64>();
2079        let input_sats = total_output_sats + fees_sat;
2080        assert!(fed_utxos_sats.remove(&input_sats));
2081
2082        Ok(())
2083    }
2084
2085    // Initiate multiple withdrawals in a session to verify the recoverytool
2086    // recognizes change outputs
2087    for _ in 0..2 {
2088        withdraw(&client, &bitcoind, &mut fed_utxos_sats).await?;
2089    }
2090
2091    let total_fed_sats = fed_utxos_sats.iter().sum::<u64>();
2092    fed.finalize_mempool_tx().await?;
2093
2094    // We are done transacting and save the current session id so we can wait for
2095    // the next session later on. We already save it here so that if in the meantime
2096    // a session is generated we don't wait for another.
2097    let last_tx_session = client.get_session_count().await?;
2098
2099    info!("Recovering using utxos method");
2100    let output = cmd!(
2101        crate::util::Recoverytool,
2102        "--cfg",
2103        "{data_dir}/fedimintd-default-0",
2104        "utxos",
2105        "--db",
2106        "{data_dir}/fedimintd-default-0/database"
2107    )
2108    .out_json()
2109    .await?;
2110    let outputs = output.as_array().context("expected an array")?;
2111    assert_eq!(outputs.len(), fed_utxos_sats.len());
2112
2113    assert_eq!(
2114        outputs
2115            .iter()
2116            .map(|o| o["amount_sat"].as_u64().unwrap())
2117            .collect::<HashSet<_>>(),
2118        fed_utxos_sats
2119    );
2120    let utxos_descriptors = outputs
2121        .iter()
2122        .map(|o| o["descriptor"].as_str().unwrap())
2123        .collect::<HashSet<_>>();
2124
2125    debug!(target: LOG_DEVIMINT, ?utxos_descriptors, "recoverytool descriptors using UTXOs method");
2126
2127    let descriptors_json = serde_json::value::to_raw_value(&serde_json::Value::Array(vec![
2128        serde_json::Value::Array(
2129            utxos_descriptors
2130                .iter()
2131                .map(|d| {
2132                    json!({
2133                        "desc": d,
2134                        "timestamp": 0,
2135                    })
2136                })
2137                .collect(),
2138        ),
2139    ]))?;
2140    info!("Getting wallet balances before import");
2141    let bitcoin_client = bitcoind.wallet_client().await?;
2142    let balances_before = bitcoin_client.get_balances().await?;
2143    info!("Importing descriptors into bitcoin wallet");
2144    let request = bitcoin_client
2145        .get_jsonrpc_client()
2146        .build_request("importdescriptors", Some(&descriptors_json));
2147    let response = block_in_place(|| bitcoin_client.get_jsonrpc_client().send_request(request))?;
2148    response.check_error()?;
2149    info!("Getting wallet balances after import");
2150    let balances_after = bitcoin_client.get_balances().await?;
2151    let diff = balances_after.mine.immature + balances_after.mine.trusted
2152        - balances_before.mine.immature
2153        - balances_before.mine.trusted;
2154
2155    // We need to wait for a session to be generated to make sure we have the signed
2156    // session outcome in our DB. If there ever is another problem here: wait for
2157    // fedimintd-0 specifically to acknowledge the session switch. In practice this
2158    // should be sufficiently synchronous though.
2159    client.wait_session_outcome(last_tx_session).await?;
2160
2161    // Funds from descriptors should match the fed's utxos
2162    assert_eq!(diff.to_sat(), total_fed_sats);
2163    info!("Recovering using epochs method");
2164
2165    let outputs = cmd!(
2166        crate::util::Recoverytool,
2167        "--cfg",
2168        "{data_dir}/fedimintd-default-0",
2169        "epochs",
2170        "--db",
2171        "{data_dir}/fedimintd-default-0/database"
2172    )
2173    .out_json()
2174    .await?
2175    .as_array()
2176    .context("expected an array")?
2177    .clone();
2178
2179    let epochs_descriptors = outputs
2180        .iter()
2181        .map(|o| o["descriptor"].as_str().unwrap())
2182        .collect::<HashSet<_>>();
2183
2184    // nosemgrep: use-err-formatting
2185    debug!(target: LOG_DEVIMINT, ?epochs_descriptors, "recoverytool descriptors using epochs method");
2186
2187    // Epochs method includes descriptors from spent outputs, so we only need to
2188    // verify the epochs method includes all available utxos
2189    for utxo_descriptor in utxos_descriptors {
2190        assert!(epochs_descriptors.contains(utxo_descriptor));
2191    }
2192    Ok(())
2193}
2194
2195pub async fn guardian_backup_test(dev_fed: DevFed, process_mgr: &ProcessManager) -> Result<()> {
2196    const PEER_TO_TEST: u16 = 0;
2197
2198    log_binary_versions().await?;
2199
2200    let DevFed { mut fed, .. } = dev_fed;
2201
2202    fed.await_all_peers()
2203        .await
2204        .expect("Awaiting federation coming online failed");
2205
2206    let client = fed.new_joined_client("guardian-client").await?;
2207    let old_block_count = cmd!(
2208        client,
2209        "dev",
2210        "api",
2211        "--peer-id",
2212        PEER_TO_TEST.to_string(),
2213        "--module",
2214        "wallet",
2215        "block_count",
2216    )
2217    .out_json()
2218    .await?["value"]
2219        .as_u64()
2220        .expect("No block height returned");
2221
2222    let backup_res = cmd!(
2223        client,
2224        "--our-id",
2225        PEER_TO_TEST.to_string(),
2226        "--password",
2227        "pass",
2228        "admin",
2229        "guardian-config-backup"
2230    )
2231    .out_json()
2232    .await?;
2233    let backup_hex = backup_res["tar_archive_bytes"]
2234        .as_str()
2235        .expect("expected hex string");
2236    let backup_tar = hex::decode(backup_hex).expect("invalid hex");
2237
2238    let data_dir = fed
2239        .vars
2240        .get(&PEER_TO_TEST.into())
2241        .expect("peer not found")
2242        .FM_DATA_DIR
2243        .clone();
2244
2245    fed.terminate_server(PEER_TO_TEST.into())
2246        .await
2247        .expect("could not terminate fedimintd");
2248
2249    std::fs::remove_dir_all(&data_dir).expect("error deleting old datadir");
2250    std::fs::create_dir(&data_dir).expect("error creating new datadir");
2251
2252    let write_file = |name: &str, data: &[u8]| {
2253        let mut file = std::fs::File::options()
2254            .write(true)
2255            .create(true)
2256            .truncate(true)
2257            .open(data_dir.join(name))
2258            .expect("could not open file");
2259        file.write_all(data).expect("could not write file");
2260        file.flush().expect("could not flush file");
2261    };
2262
2263    write_file("backup.tar", &backup_tar);
2264
2265    assert_eq!(
2266        std::process::Command::new("tar")
2267            .arg("-xf")
2268            .arg("backup.tar")
2269            .current_dir(&data_dir)
2270            .spawn()
2271            .expect("error spawning tar")
2272            .wait()
2273            .expect("error extracting archive")
2274            .code(),
2275        Some(0),
2276        "tar failed"
2277    );
2278
2279    // If the backup contains encrypted config (from old fedimintd), write the
2280    // password file so the current fedimintd can read it
2281    if data_dir.join("private.encrypt").exists() {
2282        write_file("password.private", "pass".as_bytes());
2283    }
2284
2285    fed.start_server(process_mgr, PEER_TO_TEST.into())
2286        .await
2287        .expect("could not restart fedimintd");
2288
2289    poll("Peer catches up again", || async {
2290        let block_counts = all_peer_block_count(&client, fed.member_ids())
2291            .await
2292            .map_err(ControlFlow::Continue)?;
2293        let block_count = block_counts[&PeerId::from(PEER_TO_TEST)];
2294
2295        info!("Caught up to block {block_count} of at least {old_block_count} (counts={block_counts:?})");
2296
2297        if block_count < old_block_count {
2298            return Err(ControlFlow::Continue(anyhow!("Block count still behind")));
2299        }
2300
2301        Ok(())
2302    })
2303    .await
2304    .expect("Peer didn't rejoin federation");
2305
2306    Ok(())
2307}
2308
2309async fn peer_block_count(client: &Client, peer: PeerId) -> Result<u64> {
2310    cmd!(
2311        client,
2312        "dev",
2313        "api",
2314        "--peer-id",
2315        peer.to_string(),
2316        "--module",
2317        "wallet",
2318        "block_count",
2319    )
2320    .out_json()
2321    .await?["value"]
2322        .as_u64()
2323        .context("No block height returned")
2324}
2325
2326async fn all_peer_block_count(
2327    client: &Client,
2328    peers: impl Iterator<Item = PeerId>,
2329) -> Result<BTreeMap<PeerId, u64>> {
2330    let mut peer_heights = BTreeMap::new();
2331    for peer in peers {
2332        peer_heights.insert(peer, peer_block_count(client, peer).await?);
2333    }
2334    Ok(peer_heights)
2335}
2336
2337pub async fn cannot_replay_tx_test(dev_fed: DevFed) -> Result<()> {
2338    log_binary_versions().await?;
2339
2340    let DevFed { fed, .. } = dev_fed;
2341
2342    let client = fed.new_joined_client("cannot-replay-client").await?;
2343
2344    const CLIENT_START_AMOUNT: u64 = 10_000_000_000;
2345    const CLIENT_SPEND_AMOUNT: u64 = 5_000_000_000;
2346
2347    let initial_client_balance = client.balance().await?;
2348    assert_eq!(initial_client_balance, 0);
2349
2350    fed.pegin_client(CLIENT_START_AMOUNT / 1000, &client)
2351        .await?;
2352
2353    // Fork client before spending ecash so we can later attempt a double spend
2354    let double_spend_client = client.new_forked("double-spender").await?;
2355
2356    // Spend and reissue all ecash from the client
2357    let notes = cmd!(client, "spend", CLIENT_SPEND_AMOUNT)
2358        .out_json()
2359        .await?
2360        .get("notes")
2361        .expect("Output didn't contain e-cash notes")
2362        .as_str()
2363        .unwrap()
2364        .to_owned();
2365
2366    let client_post_spend_balance = client.balance().await?;
2367    crate::util::almost_equal(
2368        client_post_spend_balance,
2369        CLIENT_START_AMOUNT - CLIENT_SPEND_AMOUNT,
2370        10_000,
2371    )
2372    .unwrap();
2373
2374    cmd!(client, "reissue", notes).out_json().await?;
2375    let client_post_reissue_balance = client.balance().await?;
2376    crate::util::almost_equal(client_post_reissue_balance, CLIENT_START_AMOUNT, 20_000).unwrap();
2377
2378    // Attempt to spend the same ecash from the forked client
2379    let double_spend_notes = cmd!(double_spend_client, "spend", CLIENT_SPEND_AMOUNT)
2380        .out_json()
2381        .await?
2382        .get("notes")
2383        .expect("Output didn't contain e-cash notes")
2384        .as_str()
2385        .unwrap()
2386        .to_owned();
2387
2388    let double_spend_client_post_spend_balance = double_spend_client.balance().await?;
2389    crate::util::almost_equal(
2390        double_spend_client_post_spend_balance,
2391        CLIENT_START_AMOUNT - CLIENT_SPEND_AMOUNT,
2392        10_000,
2393    )
2394    .unwrap();
2395
2396    cmd!(double_spend_client, "reissue", double_spend_notes)
2397        .assert_error_contains("The transaction had an invalid input")
2398        .await?;
2399
2400    let double_spend_client_post_spend_balance = double_spend_client.balance().await?;
2401    crate::util::almost_equal(
2402        double_spend_client_post_spend_balance,
2403        CLIENT_START_AMOUNT - CLIENT_SPEND_AMOUNT,
2404        10_000,
2405    )
2406    .unwrap();
2407
2408    Ok(())
2409}
2410
2411/// Test that client can init even when the federation is down
2412///
2413/// See <https://github.com/fedimint/fedimint/issues/6939>
2414pub async fn test_offline_client_initialization(
2415    dev_fed: DevFed,
2416    _process_mgr: &ProcessManager,
2417) -> Result<()> {
2418    log_binary_versions().await?;
2419
2420    let DevFed { mut fed, .. } = dev_fed;
2421
2422    // Ensure federation is properly initialized and all peers are online
2423    fed.await_all_peers().await?;
2424
2425    // Create and join a client while all servers are online
2426    let client = fed.new_joined_client("offline-test-client").await?;
2427
2428    // Verify client can get info while federation is online
2429    const INFO_COMMAND_TIMEOUT: Duration = Duration::from_secs(5);
2430    let online_info =
2431        fedimint_core::runtime::timeout(INFO_COMMAND_TIMEOUT, cmd!(client, "info").out_json())
2432            .await
2433            .context("Client info command timed out while federation was online")?
2434            .context("Client info command failed while federation was online")?;
2435    info!(target: LOG_DEVIMINT, "Client info while federation online: {:?}", online_info);
2436
2437    // Shutdown all federation servers
2438    info!(target: LOG_DEVIMINT, "Shutting down all federation servers...");
2439    fed.terminate_all_servers().await?;
2440
2441    // Wait a moment to ensure servers are fully shutdown
2442    fedimint_core::task::sleep_in_test("wait for federation shutdown", Duration::from_secs(2))
2443        .await;
2444
2445    // Test that client info command still works with all servers offline
2446    // This should work because client info doesn't require server communication
2447    // for basic federation metadata and local state
2448    info!(target: LOG_DEVIMINT, "Testing client info command with all servers offline...");
2449    let offline_info =
2450        fedimint_core::runtime::timeout(INFO_COMMAND_TIMEOUT, cmd!(client, "info").out_json())
2451            .await
2452            .context("Client info command timed out while federation was offline")?
2453            .context("Client info command failed while federation was offline")?;
2454
2455    info!(target: LOG_DEVIMINT, "Client info while federation offline: {:?}", offline_info);
2456
2457    Ok(())
2458}
2459
2460/// Test that client can detect federation config changes when servers restart
2461/// with new module configurations
2462///
2463/// This test starts a fresh federation, dumps the client config, then stops all
2464/// servers and modifies their configs by adding a new meta module instance. The
2465/// client should detect this configuration change after the servers restart.
2466pub async fn test_client_config_change_detection(
2467    dev_fed: DevFed,
2468    process_mgr: &ProcessManager,
2469) -> Result<()> {
2470    log_binary_versions().await?;
2471
2472    // This test edits the guardians' on-disk config out-of-band and restarts
2473    // them. Since v0.12.0-alpha the private config is stored as plaintext
2474    // `private.json`; older fedimintd only reads the encrypted `private.encrypt`
2475    // format, so the rewritten config would be invisible to it on restart.
2476    let fedimintd_version = crate::util::FedimintdCmd::version_or_default().await;
2477    if fedimintd_version < *VERSION_0_12_0_ALPHA {
2478        info!(
2479            "Skipping test_client_config_change_detection - requires fedimintd v0.12.0-alpha or later"
2480        );
2481        return Ok(());
2482    }
2483
2484    let DevFed { mut fed, .. } = dev_fed;
2485    let peer_ids: Vec<_> = fed.member_ids().collect();
2486
2487    fed.await_all_peers().await?;
2488
2489    let client = fed.new_joined_client("config-change-test-client").await?;
2490
2491    info!(target: LOG_DEVIMINT, "Getting initial client configuration...");
2492    let initial_config = cmd!(client, "config")
2493        .out_json()
2494        .await
2495        .context("Failed to get initial client config")?;
2496
2497    info!(target: LOG_DEVIMINT, "Initial config modules: {:?}", initial_config["modules"].as_object().unwrap().keys().collect::<Vec<_>>());
2498
2499    let data_dir = env::var(FM_DATA_DIR_ENV)?;
2500    let config_dir = PathBuf::from(&data_dir);
2501
2502    // Shutdown all federation servers
2503    //
2504    // In prod. one would probably use a coordinated shutdown, just to be
2505    // careful, but since the change is only adding a new module that does
2506    // not submit CIs without user/admin interaction, there is
2507    // no way for the consensus to diverge.
2508    info!(target: LOG_DEVIMINT, "Shutting down all federation servers...");
2509    fed.terminate_all_servers().await?;
2510
2511    // Wait for servers to fully shutdown
2512    fedimint_core::task::sleep_in_test("wait for federation shutdown", Duration::from_secs(2))
2513        .await;
2514
2515    info!(target: LOG_DEVIMINT, "Modifying server configurations to add new meta module...");
2516    modify_server_configs(&config_dir, &peer_ids).await?;
2517
2518    // Restart all servers with modified configs
2519    info!(target: LOG_DEVIMINT, "Restarting all servers with modified configurations...");
2520    for peer_id in peer_ids {
2521        fed.start_server(process_mgr, peer_id.to_usize()).await?;
2522    }
2523
2524    // Wait for federation to stabilize
2525    info!(target: LOG_DEVIMINT, "Wait for peers to get back up");
2526    fed.await_all_peers().await?;
2527
2528    // Use fedimint-cli dev wait to let the client read the new config in background
2529    info!(target: LOG_DEVIMINT, "Waiting for client to fetch updated configuration...");
2530    cmd!(client, "dev", "wait", "3")
2531        .run()
2532        .await
2533        .context("Failed to wait for client config update")?;
2534
2535    // Test that client switched to the new config
2536    info!(target: LOG_DEVIMINT, "Testing client detection of configuration changes...");
2537    let updated_config = cmd!(client, "config")
2538        .out_json()
2539        .await
2540        .context("Failed to get updated client config")?;
2541
2542    info!(target: LOG_DEVIMINT, "Updated config modules: {:?}", updated_config["modules"].as_object().unwrap().keys().collect::<Vec<_>>());
2543
2544    // Verify that the configuration has changed (new meta module should be present)
2545    let initial_modules = initial_config["modules"].as_object().unwrap();
2546    let updated_modules = updated_config["modules"].as_object().unwrap();
2547
2548    anyhow::ensure!(
2549        updated_modules.len() > initial_modules.len(),
2550        "Expected more modules in updated config. Initial: {}, Updated: {}",
2551        initial_modules.len(),
2552        updated_modules.len()
2553    );
2554
2555    // Check if a new meta module was added
2556    let new_meta_module = updated_modules.iter().find(|(module_id, module_config)| {
2557        module_config["kind"].as_str() == Some("meta") && !initial_modules.contains_key(*module_id)
2558    });
2559
2560    let new_meta_module_id = new_meta_module
2561        .map(|(id, _)| id)
2562        .with_context(|| "Expected to find new meta module in updated configuration")?;
2563
2564    info!(target: LOG_DEVIMINT, "Found new meta module with id: {}", new_meta_module_id);
2565
2566    // Verify client operations still work with the new configuration
2567    info!(target: LOG_DEVIMINT, "Verifying client operations work with new configuration...");
2568    let final_info = cmd!(client, "info")
2569        .out_json()
2570        .await
2571        .context("Client info command failed with updated configuration")?;
2572
2573    info!(target: LOG_DEVIMINT, "Client successfully adapted to configuration changes: {:?}", final_info["federation_id"]);
2574
2575    Ok(())
2576}
2577
2578/// Modify server configuration files to add a new meta module instance
2579async fn modify_server_configs(config_dir: &Path, peer_ids: &[PeerId]) -> Result<()> {
2580    for &peer_id in peer_ids {
2581        modify_single_peer_config(config_dir, peer_id).await?;
2582    }
2583    Ok(())
2584}
2585
2586/// Modify configuration files for a single peer to add a new meta module
2587/// instance
2588async fn modify_single_peer_config(config_dir: &Path, peer_id: PeerId) -> Result<()> {
2589    use fedimint_core::core::ModuleInstanceId;
2590    use fedimint_server::config::io::read_server_config;
2591    use serde_json::Value;
2592
2593    info!(target: LOG_DEVIMINT, %peer_id, "Modifying config for peer");
2594    let peer_dir = config_dir.join(format!("fedimintd-default-{}", peer_id.to_usize()));
2595
2596    // Read consensus config
2597    let consensus_config_path = peer_dir.join("consensus.json");
2598    let consensus_config_content = fs::read_to_string(&consensus_config_path)
2599        .await
2600        .with_context(|| format!("Failed to read consensus config for peer {peer_id}"))?;
2601
2602    let mut consensus_config: Value = serde_json::from_str(&consensus_config_content)
2603        .with_context(|| format!("Failed to parse consensus config for peer {peer_id}"))?;
2604
2605    // Read the private config using the server config reader
2606    let server_config = read_server_config(&peer_dir)
2607        .with_context(|| format!("Failed to read server config for peer {peer_id}"))?;
2608
2609    // Find existing meta module in configs to use as template
2610    let consensus_config_modules = consensus_config["modules"]
2611        .as_object()
2612        .with_context(|| format!("No modules found in consensus config for peer {peer_id}"))?;
2613
2614    // Look for existing meta module to copy its configuration
2615    let existing_meta_consensus = consensus_config_modules
2616        .values()
2617        .find(|module_config| module_config["kind"].as_str() == Some("meta"));
2618
2619    let existing_meta_consensus = existing_meta_consensus
2620        .with_context(|| {
2621            format!("No existing meta module found in consensus config for peer {peer_id}")
2622        })?
2623        .clone();
2624
2625    // Find existing meta module in private config
2626    let existing_meta_instance_id = server_config
2627        .consensus
2628        .modules
2629        .iter()
2630        .find(|(_, config)| config.kind.as_str() == "meta")
2631        .map(|(id, _)| *id)
2632        .with_context(|| {
2633            format!("No existing meta module found in private config for peer {peer_id}")
2634        })?;
2635
2636    let existing_meta_private = server_config
2637        .private
2638        .modules
2639        .get(&existing_meta_instance_id)
2640        .with_context(|| format!("Failed to get existing meta private config for peer {peer_id}"))?
2641        .clone();
2642
2643    // Find the highest existing module ID for the new module
2644    let last_existing_module_id = consensus_config_modules
2645        .keys()
2646        .filter_map(|id| id.parse::<u32>().ok())
2647        .max()
2648        .unwrap_or(0);
2649
2650    let new_module_id = (last_existing_module_id + 1).to_string();
2651    let new_module_instance_id = ModuleInstanceId::from((last_existing_module_id + 1) as u16);
2652
2653    info!(
2654        "Adding new meta module with id {} for peer {} (copying existing meta module config)",
2655        new_module_id, peer_id
2656    );
2657
2658    // Add new meta module to consensus config by copying existing meta module
2659    if let Some(modules) = consensus_config["modules"].as_object_mut() {
2660        modules.insert(new_module_id.clone(), existing_meta_consensus);
2661    }
2662
2663    // Add new meta module to private config
2664    let mut updated_private_config = server_config.private.clone();
2665    updated_private_config
2666        .modules
2667        .insert(new_module_instance_id, existing_meta_private);
2668
2669    // Write back the modified consensus and client configs
2670    let updated_consensus_content = serde_json::to_string_pretty(&consensus_config)
2671        .with_context(|| format!("Failed to serialize consensus config for peer {peer_id}"))?;
2672
2673    write_overwrite_async(&consensus_config_path, updated_consensus_content)
2674        .await
2675        .with_context(|| format!("Failed to write consensus config for peer {peer_id}"))?;
2676
2677    // Write back the modified private config as plaintext JSON
2678    let private_json_path = peer_dir.join("private.json");
2679    let private_config_content = serde_json::to_string_pretty(&updated_private_config)
2680        .with_context(|| format!("Failed to serialize private config for peer {peer_id}"))?;
2681
2682    write_overwrite_async(&private_json_path, private_config_content)
2683        .await
2684        .with_context(|| format!("Failed to write private config for peer {peer_id}"))?;
2685
2686    info!("Successfully modified configs for peer {}", peer_id);
2687    Ok(())
2688}
2689
2690/// Tests the `admin auth` command that stores admin credentials in the client
2691/// database, allowing subsequent admin commands to run without --our-id and
2692/// --password.
2693pub async fn admin_auth_tests(dev_fed: DevFed) -> Result<()> {
2694    log_binary_versions().await?;
2695
2696    let DevFed { fed, .. } = dev_fed;
2697
2698    // Ensure all federation peers are ready before starting the test
2699    // This prevents flaky failures due to Iroh connection timeouts
2700    fed.await_all_peers().await?;
2701
2702    let client = fed.new_joined_client("admin-auth-test-client").await?;
2703
2704    let peer_id = 0;
2705
2706    info!(target: LOG_DEVIMINT, "Testing admin auth command stores credentials");
2707
2708    // First, store the admin credentials using the auth command
2709    // Use --no-verify to skip interactive verification in tests
2710    let auth_result = cmd!(
2711        client,
2712        "--our-id",
2713        &peer_id.to_string(),
2714        "--password",
2715        "pass",
2716        "admin",
2717        "auth",
2718        "--peer-id",
2719        &peer_id.to_string(),
2720        "--password",
2721        "pass",
2722        "--no-verify",
2723        "--force"
2724    )
2725    .out_json()
2726    .await
2727    .context("Admin auth command failed")?;
2728
2729    info!(target: LOG_DEVIMINT, ?auth_result, "Admin auth command completed");
2730
2731    // Verify the response contains expected fields
2732    assert_eq!(
2733        auth_result
2734            .get("peer_id")
2735            .and_then(serde_json::Value::as_u64),
2736        Some(peer_id as u64),
2737        "peer_id in response should match"
2738    );
2739    assert_eq!(
2740        auth_result
2741            .get("status")
2742            .and_then(serde_json::Value::as_str),
2743        Some("saved"),
2744        "status should be 'saved'"
2745    );
2746
2747    info!(target: LOG_DEVIMINT, "Testing that stored credentials are used automatically");
2748
2749    // Now run an admin command WITHOUT --our-id and --password
2750    // It should use the stored credentials automatically
2751    let status_result = cmd!(client, "admin", "status")
2752        .out_json()
2753        .await
2754        .context("Admin status command should succeed with stored credentials")?;
2755
2756    info!(target: LOG_DEVIMINT, ?status_result, "Admin status with stored credentials succeeded");
2757
2758    info!(target: LOG_DEVIMINT, "Testing that --force overwrites existing credentials");
2759
2760    // Test that --force allows overwriting
2761    let auth_result_force = cmd!(
2762        client,
2763        "--our-id",
2764        &peer_id.to_string(),
2765        "--password",
2766        "pass",
2767        "admin",
2768        "auth",
2769        "--peer-id",
2770        &peer_id.to_string(),
2771        "--password",
2772        "pass",
2773        "--no-verify",
2774        "--force"
2775    )
2776    .out_json()
2777    .await
2778    .context("Admin auth force overwrite failed")?;
2779
2780    assert_eq!(
2781        auth_result_force.get("status").and_then(|v| v.as_str()),
2782        Some("saved"),
2783        "Force overwrite should succeed"
2784    );
2785
2786    info!(target: LOG_DEVIMINT, "admin_auth_tests completed successfully");
2787
2788    Ok(())
2789}
2790
2791#[derive(Subcommand)]
2792pub enum LatencyTest {
2793    Reissue,
2794    LnSend,
2795    LnReceive,
2796    FmPay,
2797    Restore,
2798}
2799
2800#[derive(Subcommand)]
2801pub enum UpgradeTest {
2802    Fedimintd {
2803        #[arg(long, trailing_var_arg = true, num_args=1..)]
2804        paths: Vec<PathBuf>,
2805    },
2806    FedimintCli {
2807        #[arg(long, trailing_var_arg = true, num_args=1..)]
2808        paths: Vec<PathBuf>,
2809    },
2810    Gatewayd {
2811        #[arg(long, trailing_var_arg = true, num_args=1..)]
2812        gatewayd_paths: Vec<PathBuf>,
2813        #[arg(long, trailing_var_arg = true, num_args=1..)]
2814        gateway_cli_paths: Vec<PathBuf>,
2815    },
2816}
2817
2818#[derive(Subcommand)]
2819pub enum TestCmd {
2820    /// `devfed` then checks the average latency of reissuing ecash, LN receive,
2821    /// and LN send
2822    LatencyTests {
2823        #[clap(subcommand)]
2824        r#type: LatencyTest,
2825
2826        #[arg(long, default_value = "10")]
2827        iterations: usize,
2828    },
2829    /// `devfed` then kills and restarts most of the Guardian nodes in a 4 node
2830    /// fedimint
2831    ReconnectTest,
2832    /// `devfed` then tests a bunch of the fedimint-cli commands
2833    CliTests,
2834    /// `devfed` then tests guardian metadata functionality
2835    GuardianMetadataTests,
2836    /// `devfed` then calls binary `fedimint-load-test-tool`. See
2837    /// `LoadTestArgs`.
2838    LoadTestToolTest,
2839    /// `devfed` then pegin LND Gateway. Kill the LN node,
2840    /// restart it, rejjoin fedimint and test payments still work
2841    LightningReconnectTest,
2842    /// `devfed` then reboot gateway daemon for both LDK and LND. Test
2843    /// afterward.
2844    GatewayRebootTest,
2845    /// `devfed` then tests if the recovery tool is able to do a basic recovery
2846    RecoverytoolTests,
2847    /// `devfed` then tests LNv1 LNURL receive behavior after client recovery
2848    LnurlRecoveryTest,
2849    /// `devfed` then spawns faucet for wasm tests
2850    WasmTestSetup {
2851        #[arg(long, trailing_var_arg = true, allow_hyphen_values = true, num_args=1..)]
2852        exec: Option<Vec<ffi::OsString>>,
2853    },
2854    /// Restore guardian from downloaded backup
2855    GuardianBackup,
2856    /// `devfed` then tests that spent ecash cannot be double spent
2857    CannotReplayTransaction,
2858    /// Tests that client info commands work when all federation servers are
2859    /// offline
2860    TestOfflineClientInitialization,
2861    /// Tests that client can detect federation config changes when servers
2862    /// restart with new module configurations
2863    TestClientConfigChangeDetection,
2864    /// `devfed` then tests admin auth credential storage
2865    TestAdminAuth,
2866    /// Test upgrade paths for a given binary
2867    UpgradeTests {
2868        #[clap(subcommand)]
2869        binary: UpgradeTest,
2870        #[arg(long)]
2871        lnv2: String,
2872    },
2873}
2874
2875pub async fn handle_command(cmd: TestCmd, common_args: CommonArgs) -> Result<()> {
2876    match cmd {
2877        TestCmd::WasmTestSetup { exec } => {
2878            let (process_mgr, task_group) = setup(common_args).await?;
2879            let main = {
2880                let task_group = task_group.clone();
2881                async move {
2882                    let dev_fed = dev_fed(&process_mgr).await?;
2883                    let gw_lnd = dev_fed.gw_lnd.clone();
2884                    let fed = dev_fed.fed.clone();
2885                    gw_lnd
2886                        .client()
2887                        .set_federation_routing_fee(dev_fed.fed.calculate_federation_id(), 0, 0)
2888                        .await?;
2889                    task_group.spawn_cancellable("faucet", async move {
2890                        if let Err(err) = crate::faucet::run(
2891                            &dev_fed,
2892                            format!("0.0.0.0:{}", process_mgr.globals.FM_PORT_FAUCET),
2893                            process_mgr.globals.FM_PORT_GW_LND,
2894                        )
2895                        .await
2896                        {
2897                            error!("Error spawning faucet: {err}");
2898                        }
2899                    });
2900                    try_join!(fed.pegin_gateways(30_000, vec![&gw_lnd]), async {
2901                        poll("waiting for faucet startup", || async {
2902                            TcpStream::connect(format!(
2903                                "127.0.0.1:{}",
2904                                process_mgr.globals.FM_PORT_FAUCET
2905                            ))
2906                            .await
2907                            .context("connect to faucet")
2908                            .map_err(ControlFlow::Continue)
2909                        })
2910                        .await?;
2911                        Ok(())
2912                    },)?;
2913                    if let Some(exec) = exec {
2914                        exec_user_command(exec).await?;
2915                        task_group.shutdown();
2916                    }
2917                    Ok::<_, anyhow::Error>(())
2918                }
2919            };
2920            cleanup_on_exit(main, task_group).await?;
2921        }
2922        TestCmd::LatencyTests { r#type, iterations } => {
2923            let (process_mgr, _) = setup(common_args).await?;
2924            let dev_fed = dev_fed(&process_mgr).await?;
2925            latency_tests(dev_fed, r#type, None, iterations, true).await?;
2926        }
2927        TestCmd::ReconnectTest => {
2928            let (process_mgr, _) = setup(common_args).await?;
2929            let dev_fed = dev_fed(&process_mgr).await?;
2930            reconnect_test(dev_fed, &process_mgr).await?;
2931        }
2932        TestCmd::CliTests => {
2933            let (process_mgr, _) = setup(common_args).await?;
2934            let dev_fed = dev_fed(&process_mgr).await?;
2935            cli_tests(dev_fed).await?;
2936        }
2937        TestCmd::GuardianMetadataTests => {
2938            let (process_mgr, _) = setup(common_args).await?;
2939            let dev_fed = dev_fed(&process_mgr).await?;
2940            guardian_metadata_tests(dev_fed).await?;
2941        }
2942        TestCmd::LoadTestToolTest => {
2943            // For the load test tool test, explicitly disable mint base fees
2944            unsafe { std::env::set_var(FM_DISABLE_BASE_FEES_ENV, "1") };
2945
2946            let (process_mgr, _) = setup(common_args).await?;
2947            let dev_fed = dev_fed(&process_mgr).await?;
2948            cli_load_test_tool_test(dev_fed).await?;
2949        }
2950        TestCmd::LightningReconnectTest => {
2951            let (process_mgr, _) = setup(common_args).await?;
2952            let dev_fed = dev_fed(&process_mgr).await?;
2953            lightning_gw_reconnect_test(dev_fed, &process_mgr).await?;
2954        }
2955        TestCmd::GatewayRebootTest => {
2956            let (process_mgr, _) = setup(common_args).await?;
2957            let dev_fed = dev_fed(&process_mgr).await?;
2958            gw_reboot_test(dev_fed, &process_mgr).await?;
2959        }
2960        TestCmd::RecoverytoolTests => {
2961            let (process_mgr, _) = setup(common_args).await?;
2962            let dev_fed = dev_fed(&process_mgr).await?;
2963            recoverytool_test(dev_fed).await?;
2964        }
2965        TestCmd::LnurlRecoveryTest => {
2966            let (process_mgr, _) = setup(common_args).await?;
2967            let dev_fed = dev_fed(&process_mgr).await?;
2968            lnurl_recovery_test(dev_fed).await?;
2969        }
2970        TestCmd::GuardianBackup => {
2971            let (process_mgr, _) = setup(common_args).await?;
2972            let dev_fed = dev_fed(&process_mgr).await?;
2973            guardian_backup_test(dev_fed, &process_mgr).await?;
2974        }
2975        TestCmd::CannotReplayTransaction => {
2976            let (process_mgr, _) = setup(common_args).await?;
2977            let dev_fed = dev_fed(&process_mgr).await?;
2978            cannot_replay_tx_test(dev_fed).await?;
2979        }
2980        TestCmd::TestOfflineClientInitialization => {
2981            let (process_mgr, _) = setup(common_args).await?;
2982            let dev_fed = dev_fed(&process_mgr).await?;
2983            test_offline_client_initialization(dev_fed, &process_mgr).await?;
2984        }
2985        TestCmd::TestClientConfigChangeDetection => {
2986            let (process_mgr, _) = setup(common_args).await?;
2987            let dev_fed = dev_fed(&process_mgr).await?;
2988            test_client_config_change_detection(dev_fed, &process_mgr).await?;
2989        }
2990        TestCmd::TestAdminAuth => {
2991            // Check versions early before starting infrastructure
2992            let fedimint_cli_version = crate::util::FedimintCli::version_or_default().await;
2993            let fedimintd_version = crate::util::FedimintdCmd::version_or_default().await;
2994
2995            if fedimint_cli_version < *VERSION_0_11_0_ALPHA
2996                || fedimintd_version < *VERSION_0_11_0_ALPHA
2997            {
2998                info!(target: LOG_DEVIMINT, "Skipping admin_auth_tests - requires v0.11.0-alpha or later");
2999                return Ok(());
3000            }
3001
3002            let (process_mgr, _) = setup(common_args).await?;
3003            let dev_fed = dev_fed(&process_mgr).await?;
3004            admin_auth_tests(dev_fed).await?;
3005        }
3006        TestCmd::UpgradeTests { binary, lnv2 } => {
3007            // TODO: Audit that the environment access only happens in single-threaded code.
3008            unsafe {
3009                std::env::set_var(FM_ENABLE_MODULE_LNV2_ENV, lnv2);
3010                // fedimintd now defaults to the v2 module set; pin the upgrade
3011                // federation to the v1 modules (matching the previous default)
3012                // so upgrade paths starting from older versions stay consistent.
3013                std::env::set_var(FM_ENABLE_MODULE_LNV1_ENV, "1");
3014                std::env::set_var(FM_ENABLE_MODULE_MINT_ENV, "1");
3015                std::env::set_var(FM_ENABLE_MODULE_MINTV2_ENV, "0");
3016                std::env::set_var(FM_ENABLE_MODULE_WALLET_ENV, "1");
3017                std::env::set_var(FM_ENABLE_MODULE_WALLETV2_ENV, "0");
3018            }
3019            let (process_mgr, _) = setup(common_args).await?;
3020            Box::pin(upgrade_tests(&process_mgr, binary)).await?;
3021        }
3022    }
3023    Ok(())
3024}