Skip to main content

devimint/
tests.rs

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