From 8815da2c04433a1eadcc01c440d1e44a6418559e Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 8 Sep 2026 13:07:55 +0000 Subject: [PATCH 1/4] docs(backend-e2e): fix stale test-module table and workdir description README claimed the persistent workdir is git-rev-keyed (/tmp/dash-evo-e2e-testnet-) and listed only 6 test modules. harness.rs actually uses a fixed base dir name with numbered fallback slots (pick_available_workdir), no git-rev component at all, and main.rs registers 20 modules. Corrected both, and pointed at main.rs as the authoritative module list to keep this table honest going forward. Co-Authored-By: Claude Sonnet 5 --- tests/backend-e2e/README.md | 44 ++++++++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/tests/backend-e2e/README.md b/tests/backend-e2e/README.md index a9535e0d3..feea51361 100644 --- a/tests/backend-e2e/README.md +++ b/tests/backend-e2e/README.md @@ -92,13 +92,15 @@ ctx().await --> OnceCell::get_or_init(BackendTestContext::init) testnet with SPV running - **`framework_wallet_hash`** -- the `WalletSeedHash` of the "bank" wallet used to fund per-test wallets -- **`_workdir`** -- path to a persistent temp directory keyed by git revision - (e.g., `/tmp/dash-evo-e2e-testnet-abc1234`) +- **`_workdir`** -- path to a persistent temp directory (e.g., + `/tmp/dash-evo-e2e-testnet`, or a numbered fallback slot; see "Persistent + workdir" below -- not git-rev-keyed) ### Initialization sequence 1. Initialize tracing subscriber for structured log output. -2. Create a persistent workdir under `/tmp/` keyed by `git rev-parse --short HEAD`. +2. Create a persistent workdir under `/tmp/` (deterministic path, with numbered + fallback slots guarded by a `.lock` file -- see "Persistent workdir" below). 3. Copy `.env.example` into the workdir via `ensure_env_file()`. 4. Create a SQLite database and `AppContext` for `Network::Testnet`, passing the workdir as `data_dir`. 5. Start SPV in light-client mode and wait for peer connections (60s timeout). @@ -110,10 +112,14 @@ ctx().await --> OnceCell::get_or_init(BackendTestContext::init) ### Persistent workdir -The workdir survives across test runs for the same git revision. This means: +The workdir is deterministic, not git-rev-keyed: it's always +`/dash-evo-e2e-testnet` (slot 0), with numbered fallback slots +(`dash-evo-e2e-testnet-1`, `-2`, ...) that `pick_available_workdir` cycles +through via a per-slot `.lock` file when an earlier slot is still locked by +another process (see `framework/harness.rs`). This means: -- The SQLite database is reused, so wallets registered in prior runs are already - present. +- The SQLite database is reused across runs, so wallets registered previously + are already present, regardless of which commit produced them. - The framework wallet registration handles the "already imported" case gracefully. - SPV sync is faster on repeat runs because prior state may be cached. @@ -121,7 +127,7 @@ The workdir survives across test runs for the same git revision. This means: Clean the workdir manually if you need a fresh start: ```bash -rm -rf /tmp/dash-evo-e2e-testnet-* +rm -rf /tmp/dash-evo-e2e-testnet* ``` ## Wallet architecture @@ -182,14 +188,32 @@ Located in `tests/backend-e2e/framework/`: ## Test modules +Registered in `tests/backend-e2e/main.rs` -- that file is the authoritative +list; keep this table in sync when adding or removing a module. + | Module | What it tests | |---|---| -| `spv_wallet` | SPV sync, wallet creation and registration, DB persistence | -| `send_funds` | Core payment between two wallets (send and return) | +| `cleanup_only` | Standalone cleanup -- sweeps orphaned test wallets on init | | `fetch_contract` | Platform contract queries (DashPay, non-existent ID, with descriptions) | | `identity_create` | Identity registration funded from a wallet | -| `register_dpns` | Full flow: identity creation, DPNS name registration, name search verification | +| `identity_masternode_withdraw` | Headless masternode/evonode load + credit withdrawal | | `identity_withdraw` | Identity credit withdrawal to a Core address | +| `register_dpns` | Full flow: identity creation, DPNS name registration, name search verification | +| `send_funds` | Core payment between two wallets (send and return) | +| `spv_wallet` | SPV sync, wallet creation and registration, DB persistence | +| `tx_is_ours` | `is_ours` flag correctness for SPV transactions | +| `identity_cold_boot` | Identity funding on a cold-booted watch-only wallet (scenarios C/D) | +| `spv_reconnect` | SPV reconnect regression (`stop_spv` + `ensure_wallet_backend_and_start_spv`) | +| `core_tasks` | `CoreTask` variants (TC-001 to TC-012) | +| `cross_wallet_topup` | Cross-wallet identity top-up, including spent-lock reuse rejection (#954/#956) | +| `event_bridge_live` | Live `EventBridge` wiring: SPV sync -> `ConnectionStatus` -> frame-loop repaint | +| `identity_in_vault_sign` | TS-SIGN-E2E-01 -- state transition signed by a migrated `InVault` identity key | +| `identity_tasks` | `IdentityTask` variants (TC-020 to TC-030) | +| `shielded_tasks` | `ShieldedTask` variants (TC-074 to TC-083); skippable via `E2E_SKIP_SHIELDED` | +| `token_tasks` | Full token lifecycle: registration, query, mint, burn (TC-045 to TC-065) | +| `wallet_reregistration` | Wallets re-register with upstream SPV so received funds stay visible | +| `wallet_tasks` | `WalletTask` variants (TC-012 to TC-019) | +| `z_broadcast_st_tasks` | `BroadcastStateTransition` (TC-066, TC-067) | ## Writing new tests From c05f3b4446da9b0c8991b29e20d9ec4755cec7f0 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 8 Sep 2026 13:33:31 +0000 Subject: [PATCH 2/4] test(backend-e2e): stop a panicked context init from poisoning its workdir MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `AppContext::new` ends in `SpvProvider::bind_app_context`, which stores a strong `Arc` in a field of that same `AppContext`. The cycle means no `AppContext` is ever dropped, so the `Arc` it owns keeps `det-app.sqlite` registered in the upstream `SqlitePersister` process-wide open-path registry for the life of the process. `OnceCell` does not cache a panicked init, so the next test retries. Until now the retry reopened the same workdir and died with `AlreadyOpen`, burying the first attempt's real failure: a run with an invalid `E2E_WALLET_MNEMONIC` reported the mnemonic error once and `AlreadyOpen` 55 times. - Read and parse `E2E_WALLET_MNEMONIC` before any store is opened, so the most common init failure cannot leave a workdir slot poisoned. - `open_available_workdir` (was `pick_available_workdir`) also opens the app k/v and the secret vault, treating a slot still held open in-process as taken — the same fallback already used for a slot locked by another process. - Cap init attempts at 3 and point at the first failure instead of burning every workdir slot and ending on a misleading "all slots locked". Serial execution stays required, but for unrelated reasons (one shared framework wallet UTXO set, shared fixtures, the cleanup sweep); both constraints are now documented on `CTX`. Co-Authored-By: Claude Opus 5 --- tests/backend-e2e/framework/harness.rs | 211 ++++++++++++++++++------- 1 file changed, 152 insertions(+), 59 deletions(-) diff --git a/tests/backend-e2e/framework/harness.rs b/tests/backend-e2e/framework/harness.rs index 5fcccfab6..cd218a30b 100644 --- a/tests/backend-e2e/framework/harness.rs +++ b/tests/backend-e2e/framework/harness.rs @@ -58,8 +58,36 @@ const FUNDED_WALLET_REGISTRATION_TIMEOUT: Duration = Duration::from_secs(120); /// /// Uses `tokio::sync::OnceCell` so initialization runs inside the shared /// runtime context (via `block_on`) rather than spawning a nested one. +/// `get_or_init` serializes concurrent callers, so parallel test threads never +/// race into `init()` together — but it does not cache a panicked init, so the +/// next test retries from scratch. +/// +/// A retry cannot reuse the failed attempt's workdir. `AppContext::new` ends in +/// `SpvProvider::bind_app_context`, which stores a strong `Arc` +/// inside a field of that same `AppContext` — the resulting cycle means no +/// `AppContext` is ever dropped. Its `Arc` therefore keeps +/// `det-app.sqlite` in the upstream `SqlitePersister` process-wide open-path +/// registry (released only on `Drop`), and reopening it returns `AlreadyOpen`. +/// [`open_available_workdir`] handles this by treating a slot whose stores are +/// still held open as taken, so the real init failure surfaces on the retry +/// instead of a misleading `AlreadyOpen`. +/// +/// None of that is why the suite needs `--test-threads=1`. Serial execution is +/// required because the tests share mutable chain state: one framework wallet's +/// UTXO set (`FUNDING_MUTEX` serializes only the broadcast, not the balance +/// waits), the `SHARED_IDENTITY` fixture, and a cleanup sweep that removes every +/// wallet but the framework one. static CTX: tokio::sync::OnceCell = tokio::sync::OnceCell::const_new(); +/// Init attempts allowed per test process before [`BackendTestContext::init`] +/// stops retrying. A transient failure (SPV peer timeout) can clear on a retry; +/// a standing one (unfunded framework wallet, bad `E2E_WALLET_MNEMONIC`) cannot, +/// and retrying it once per remaining test buries the first, real failure. +const MAX_INIT_ATTEMPTS: usize = 3; + +/// Init attempts made in this process, counted by [`BackendTestContext::init`]. +static INIT_ATTEMPTS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + /// Serializes the UTXO-critical section of `create_funded_test_wallet`. /// /// Only the payment broadcast (UTXO selection → broadcast → UTXO removal) is @@ -88,7 +116,7 @@ static LEAKED_BACKEND: tokio::sync::Mutex< Option>, > = tokio::sync::Mutex::const_new(None); -/// Number of distinct workdir slots `pick_available_workdir` cycles through. +/// Number of distinct workdir slots `open_available_workdir` cycles through. /// The scan wraps modulo this value, so the preferred floor can climb without /// ever emptying the scan range. const MAX_WORKDIR_SLOTS: usize = 10; @@ -96,7 +124,7 @@ const MAX_WORKDIR_SLOTS: usize = 10; /// Preferred starting workdir slot for the next `init()`. Bumped each time a /// panicked init leaks an un-droppable SPV `LockFile`, so the retry prefers a /// fresh directory instead of colliding with the locked one. The scan in -/// [`pick_available_workdir`] wraps modulo [`MAX_WORKDIR_SLOTS`], so even if +/// [`open_available_workdir`] wraps modulo [`MAX_WORKDIR_SLOTS`], so even if /// this floor exceeds the slot count it never exhausts the available slots — a /// freed lower slot is still picked up. static WORKDIR_SLOT_FLOOR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); @@ -183,6 +211,14 @@ async fn register_wallet_with_retry( impl BackendTestContext { async fn init() -> Self { + let attempt = INIT_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1; + assert!( + attempt <= MAX_INIT_ATTEMPTS, + "backend-e2e context init already failed {MAX_INIT_ATTEMPTS} times in this process; \ + not retrying. Fix the first failure reported above (the earliest `harness.rs` panic \ + in this log) — every later test reports this message instead." + ); + // Cancel orphaned SPV tasks from a previous panicked init (if any). if let Some(token) = SPV_CANCEL .lock() @@ -205,7 +241,7 @@ impl BackendTestContext { // clones keep the backend's `Arc` graph alive — so the lock cannot // be reclaimed in-process. Instead, advance the workdir slot so the // retry's SpvRuntime locks a fresh directory (this is exactly what - // `pick_available_workdir`'s slot fallback exists for). + // `open_available_workdir`'s slot fallback exists for). if let Some(stale_backend) = LEAKED_BACKEND.lock().await.take() { tracing::warn!( "Leaked wallet backend from a previous init attempt; \ @@ -230,13 +266,45 @@ impl BackendTestContext { tracing::debug!(".env not loaded ({e}), relying on environment"); } + // E2E_WALLET_MNEMONIC is required. Read and parse it BEFORE any store is + // opened: a bad value here is the most common init failure, and failing + // ahead of `open_available_workdir` keeps the first attempt from leaving + // a workdir slot holding an un-droppable `det-app.sqlite` handle. + let mnemonic_phrase = std::env::var("E2E_WALLET_MNEMONIC").unwrap_or_else(|_| { + panic!( + "E2E_WALLET_MNEMONIC is not set.\n\ + This environment variable is required for backend E2E tests.\n\ + Set it to a BIP-39 mnemonic of a pre-funded testnet wallet.\n\ + Example: E2E_WALLET_MNEMONIC=\"word1 word2 word3 ... word12\"\n\ + You can also add it to the project root .env file." + ); + }); + + let mnemonic = Mnemonic::parse_in(Language::English, &mnemonic_phrase) + .expect("Invalid E2E_WALLET_MNEMONIC"); + let seed = mnemonic.to_seed(""); + let framework_wallet_hash = { + let tmp_wallet = dash_evo_tool::model::wallet::Wallet::new_from_seed( + seed, + Network::Testnet, + None, + None, + ) + .expect("Failed to compute framework wallet hash"); + tmp_wallet.seed_hash() + }; + // Deterministic workdir — always the same path so the database, wallets, // and SPV data persist across runs. If the primary path is locked by // another process, fall back to numbered alternatives (slot 1, 2, ...). let base = std::env::temp_dir().join("dash-evo-e2e-testnet"); let slot_floor = WORKDIR_SLOT_FLOOR.load(std::sync::atomic::Ordering::SeqCst); - let (workdir, lock_file) = pick_available_workdir(&base, slot_floor); - std::fs::create_dir_all(&workdir).expect("Failed to create workdir"); + let WorkdirHandles { + dir: workdir, + lock_file, + app_kv, + secret_store, + } = open_available_workdir(&base, slot_floor); tracing::info!("E2E workdir: {}", workdir.display()); // Ensure .env is present in the workdir (no env var mutation needed). @@ -253,8 +321,6 @@ impl BackendTestContext { let connection_status = Arc::new(ConnectionStatus::new()); let egui_ctx = egui::Context::default(); - let app_kv = AppContext::open_app_kv(&workdir).expect("open app k/v"); - let secret_store = AppContext::open_secret_store(&workdir).expect("open secret store"); let app_context = AppContext::new( workdir.clone(), Network::Testnet, @@ -268,32 +334,6 @@ impl BackendTestContext { ) .expect("Failed to create AppContext for testnet"); - // E2E_WALLET_MNEMONIC is required — read it early so we know which - // wallet to keep before SPV starts. - let mnemonic_phrase = std::env::var("E2E_WALLET_MNEMONIC").unwrap_or_else(|_| { - panic!( - "E2E_WALLET_MNEMONIC is not set.\n\ - This environment variable is required for backend E2E tests.\n\ - Set it to a BIP-39 mnemonic of a pre-funded testnet wallet.\n\ - Example: E2E_WALLET_MNEMONIC=\"word1 word2 word3 ... word12\"\n\ - You can also add it to the project root .env file." - ); - }); - - let mnemonic = Mnemonic::parse_in(Language::English, &mnemonic_phrase) - .expect("Invalid E2E_WALLET_MNEMONIC"); - let seed = mnemonic.to_seed(""); - let framework_wallet_hash = { - let tmp_wallet = dash_evo_tool::model::wallet::Wallet::new_from_seed( - seed, - Network::Testnet, - None, - None, - ) - .expect("Failed to compute framework wallet hash"); - tmp_wallet.seed_hash() - }; - // Purge stale wallets from the persistent DB before SPV starts. // SPV builds a bloom filter for every loaded wallet address — accumulated // test wallets from previous runs cause SPV sync to exceed the 600s timeout. @@ -703,11 +743,25 @@ impl BackendTestContext { } } -/// Pick a deterministic workdir, acquiring an exclusive lock file. +/// A workdir slot with every handle the harness needs to hold exclusively. +struct WorkdirHandles { + dir: PathBuf, + /// Held for the process lifetime; excludes concurrent test *processes*. + lock_file: std::fs::File, + app_kv: Arc, + secret_store: Arc, +} + +/// Open a deterministic workdir, acquiring its lock file and exclusive stores. /// /// Tries the primary path first (`base`), then falls back to `base-1`, `base-2`, -/// etc. up to 10 slots. Each slot has a `.lock` file that is held for the -/// lifetime of the returned `File` handle (via `flock` / `LockFile`). +/// etc. up to [`MAX_WORKDIR_SLOTS`]. A slot is usable only when all three +/// exclusive claims succeed: its `.lock` file (`flock`, excludes other test +/// processes), its app k/v store, and its secret vault. Both stores are +/// single-open-per-process — the k/v via the upstream `SqlitePersister` +/// open-path registry, the vault via an advisory lock — and a panicked `init()` +/// leaks both (see [`CTX`]), so "still open in this process" is exactly as +/// disqualifying as "locked by another process" and is handled the same way. /// /// `slot_floor` is the *preferred* first slot to try — bumped across init /// retries when a panicked predecessor leaked an un-droppable SPV `LockFile`, @@ -720,12 +774,14 @@ impl BackendTestContext { /// This ensures: /// - The same workdir is reused across runs (wallets, SPV data, DB persist) /// - Concurrent test processes get separate workdirs automatically -/// - A retried init after a leaked SPV lock prefers a clean directory, but -/// still recovers a freed lower slot once the leaked floor exceeds the range -fn pick_available_workdir(base: &std::path::Path, slot_floor: usize) -> (PathBuf, std::fs::File) { +/// - A retried init after a leaked lock or store handle lands on a clean +/// directory, but still recovers a freed lower slot +fn open_available_workdir(base: &std::path::Path, slot_floor: usize) -> WorkdirHandles { use std::io::Write; let preferred = slot_floor % MAX_WORKDIR_SLOTS; + let mut last_store_error: Option = None; + for offset in 0..MAX_WORKDIR_SLOTS { let slot = (preferred + offset) % MAX_WORKDIR_SLOTS; let dir = if slot == 0 { @@ -753,34 +809,71 @@ fn pick_available_workdir(base: &std::path::Path, slot_floor: usize) -> (PathBuf }; // Try to acquire an exclusive non-blocking lock - if try_lock_exclusive(&lock_file) { - // Write PID for debugging - let mut f = lock_file; - let _ = f.set_len(0); - let _ = write!(f, "{}", std::process::id()); - let _ = f.flush(); - - if offset > 0 { - tracing::info!( - "Preferred workdir slot {preferred} unavailable, using slot {slot}: {}", + if !try_lock_exclusive(&lock_file) { + tracing::debug!( + "Workdir slot {} locked by another process, trying next...", + dir.display() + ); + continue; + } + + // Both stores refuse a second open, so opening them here is what makes + // a slot leaked by a panicked init unusable rather than fatal. Dropping + // `app_kv` on the vault's error path releases its registry claim. + let app_kv = match AppContext::open_app_kv(&dir) { + Ok(app_kv) => app_kv, + Err(e) => { + tracing::warn!( + "Workdir slot {} has an app k/v still open in this process, trying next: {e}", dir.display() ); - } else if slot != 0 { - tracing::info!("Using preferred workdir slot {slot}: {}", dir.display()); + last_store_error = Some(e.to_string()); + continue; } - return (dir, f); + }; + let secret_store = match AppContext::open_secret_store(&dir) { + Ok(secret_store) => secret_store, + Err(e) => { + tracing::warn!( + "Workdir slot {} has a secret vault still open in this process, trying next: {e}", + dir.display() + ); + last_store_error = Some(e.to_string()); + continue; + } + }; + + // Write PID for debugging + let mut f = lock_file; + let _ = f.set_len(0); + let _ = write!(f, "{}", std::process::id()); + let _ = f.flush(); + + if offset > 0 { + tracing::info!( + "Preferred workdir slot {preferred} unavailable, using slot {slot}: {}", + dir.display() + ); + } else if slot != 0 { + tracing::info!("Using preferred workdir slot {slot}: {}", dir.display()); } - tracing::debug!( - "Workdir slot {} locked by another process, trying next...", - dir.display() - ); + return WorkdirHandles { + dir, + lock_file: f, + app_kv, + secret_store, + }; } panic!( - "All {MAX_WORKDIR_SLOTS} E2E workdir slots are locked. \ - Kill other test processes or remove lock files in {}*", - base.display() + "All {MAX_WORKDIR_SLOTS} E2E workdir slots are unavailable (locked by another process, \ + or still open in this one after a panicked init). Kill other test processes or remove \ + lock files in {}*.{}", + base.display(), + last_store_error + .map(|e| format!(" Last store error: {e}")) + .unwrap_or_default() ); } From 338acf2364fcfb539abed6401b95c51d3f259cf7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 8 Sep 2026 13:33:42 +0000 Subject: [PATCH 3/4] test(backend-e2e): assert the result variants the backend actually returns Five assertions still expected `BackendTaskSuccessResult` variants the tasks under test can no longer produce, so each failed on a correct result. - TC-004 / TC-005 / TC-012 / TC-018 expected `Message` from `CreateRegistrationAssetLock` and `CreateTopUpAssetLock`. Both return only `AssetLockBroadcast { txid }`, which the UI consumes as the broadcast transaction id. A shared `expect_asset_lock_broadcast` helper now asserts the variant and that the txid is a 64-character hex id. - TC-028 handled `LoadedIdentity`, `RegisteredIdentity` and `Message` from `SearchIdentityFromWallet`, none of which it can return; its only success path is `IdentitiesLoaded { count: 1 }`, as sibling TC-029 already asserts. TC-018 now runs past this assertion into the funding gap tracked in #799 and fails there on its confirmation timeout instead. Co-Authored-By: Claude Opus 5 --- tests/backend-e2e/core_tasks.rs | 35 +++++----------------- tests/backend-e2e/framework/task_runner.rs | 19 ++++++++++++ tests/backend-e2e/identity_tasks.rs | 21 ++++++------- tests/backend-e2e/wallet_tasks.rs | 15 +++++----- 4 files changed, 42 insertions(+), 48 deletions(-) diff --git a/tests/backend-e2e/core_tasks.rs b/tests/backend-e2e/core_tasks.rs index aae345a46..911e33247 100644 --- a/tests/backend-e2e/core_tasks.rs +++ b/tests/backend-e2e/core_tasks.rs @@ -2,7 +2,7 @@ use crate::framework::fixtures; use crate::framework::harness::ctx; -use crate::framework::task_runner::run_task; +use crate::framework::task_runner::{expect_asset_lock_broadcast, run_task}; use dash_evo_tool::backend_task::core::{CoreTask, PaymentRecipient, WalletPaymentRequest}; use dash_evo_tool::backend_task::{BackendTask, BackendTaskSuccessResult}; use dash_evo_tool::model::wallet::single_key::SingleKeyWallet; @@ -140,15 +140,8 @@ async fn test_tc004_create_registration_asset_lock() { .await .expect("CreateRegistrationAssetLock should succeed"); - match result { - BackendTaskSuccessResult::Message(msg) => { - tracing::info!("TC-004: asset lock broadcast message: {}", msg); - } - other => panic!( - "TC-004: expected Message from CreateRegistrationAssetLock, got: {:?}", - other - ), - } + let txid = expect_asset_lock_broadcast(result, "TC-004"); + tracing::info!("TC-004: asset lock broadcast in {}", txid); } // TC-005: CreateTopUpAssetLock @@ -181,15 +174,8 @@ async fn test_tc005_create_top_up_asset_lock() { .await .expect("CreateTopUpAssetLock should succeed"); - match result { - BackendTaskSuccessResult::Message(msg) => { - tracing::info!("TC-005: asset lock broadcast message: {}", msg); - } - other => panic!( - "TC-005: expected Message from CreateTopUpAssetLock, got: {:?}", - other - ), - } + let txid = expect_asset_lock_broadcast(result, "TC-005"); + tracing::info!("TC-005: asset lock broadcast in {}", txid); } // TC-006: RecoverAssetLocks — REMOVED (Decision #8: hard-removed; upstream @@ -431,13 +417,6 @@ async fn test_tc012_create_registration_asset_lock_late_added_wallet() { .await .expect("CreateRegistrationAssetLock should succeed for a freshly-added, funded wallet"); - match result { - BackendTaskSuccessResult::Message(msg) => { - tracing::info!("TC-012: asset lock broadcast message: {}", msg); - } - other => panic!( - "TC-012: expected Message from CreateRegistrationAssetLock, got: {:?}", - other - ), - } + let txid = expect_asset_lock_broadcast(result, "TC-012"); + tracing::info!("TC-012: asset lock broadcast in {}", txid); } diff --git a/tests/backend-e2e/framework/task_runner.rs b/tests/backend-e2e/framework/task_runner.rs index 7d3f30f48..35513fc8d 100644 --- a/tests/backend-e2e/framework/task_runner.rs +++ b/tests/backend-e2e/framework/task_runner.rs @@ -132,6 +132,25 @@ pub async fn run_task_with_nonce_retry( Err(last_err.expect("loop always sets last_err before exhausting attempts")) } +/// Assert a task answered with a broadcast asset lock, returning its txid. +/// +/// `CoreTask::CreateRegistrationAssetLock` and `CoreTask::CreateTopUpAssetLock` +/// answer only with [`BackendTaskSuccessResult::AssetLockBroadcast`]; the txid +/// identifies the broadcast funding transaction. `label` names the test case in +/// the panic message. +pub fn expect_asset_lock_broadcast(result: BackendTaskSuccessResult, label: &str) -> String { + match result { + BackendTaskSuccessResult::AssetLockBroadcast { txid } => { + assert!( + txid.len() == 64 && txid.chars().all(|c| c.is_ascii_hexdigit()), + "{label}: AssetLockBroadcast must carry a 64-character hex txid, got: {txid:?}" + ); + txid + } + other => panic!("{label}: expected AssetLockBroadcast, got: {other:?}"), + } +} + // NOTE: `run_task_with_retry` was removed because retrying ConfirmationTimeout // is a workaround for the IS lock relay bug. Tests should fail clearly when // confirmation times out — that surfaces the real issue instead of hiding it. diff --git a/tests/backend-e2e/identity_tasks.rs b/tests/backend-e2e/identity_tasks.rs index 4ad9fd37b..1150637bb 100644 --- a/tests/backend-e2e/identity_tasks.rs +++ b/tests/backend-e2e/identity_tasks.rs @@ -480,18 +480,15 @@ async fn tc_028_search_identity_from_wallet() { .await .expect("TC-028: SearchIdentityFromWallet should not error"); - match &result { - BackendTaskSuccessResult::LoadedIdentity(qi) => { - tracing::info!("TC-028: found identity {:?}", qi.identity.id()); - } - BackendTaskSuccessResult::RegisteredIdentity(qi, _) => { - tracing::info!("TC-028: found identity (registered) {:?}", qi.identity.id()); - } - BackendTaskSuccessResult::Message(msg) => { - tracing::info!("TC-028: no identity at index 0: {}", msg); - } - other => panic!("TC-028: unexpected result: {:?}", other), - } + // The shared identity is registered at index 0, so the search resolves + // exactly one identity and persists it. + assert!( + matches!( + result, + BackendTaskSuccessResult::IdentitiesLoaded { count: 1 } + ), + "TC-028: expected IdentitiesLoaded {{ count: 1 }}, got: {result:?}" + ); } // --- TC-029: SearchIdentitiesUpToIndex --- diff --git a/tests/backend-e2e/wallet_tasks.rs b/tests/backend-e2e/wallet_tasks.rs index c154a8374..46727582a 100644 --- a/tests/backend-e2e/wallet_tasks.rs +++ b/tests/backend-e2e/wallet_tasks.rs @@ -1,7 +1,9 @@ // Tests implemented in Task 2 (WalletTask tests: TC-012 to TC-019) use crate::framework::harness; -use crate::framework::task_runner::{run_task, run_task_with_nonce_retry}; +use crate::framework::task_runner::{ + expect_asset_lock_broadcast, run_task, run_task_with_nonce_retry, +}; use dash_evo_tool::backend_task::core::CoreTask; use dash_evo_tool::backend_task::wallet::WalletTask; use dash_evo_tool::backend_task::{BackendTask, BackendTaskSuccessResult}; @@ -665,13 +667,10 @@ async fn tc_018_fund_platform_address_from_asset_lock() { .await .expect("TC-018: CreateRegistrationAssetLock failed"); - // The task broadcasts the tx and returns a Message (broadcast confirmation). - // The IS lock arrives asynchronously via SPV and populates unused_asset_locks. - assert!( - matches!(create_result, BackendTaskSuccessResult::Message(_)), - "TC-018: expected Message from CreateRegistrationAssetLock, got: {:?}", - create_result - ); + // The task broadcasts the funding tx and answers with its txid. The IS lock + // arrives asynchronously via SPV and populates unused_asset_locks. + let txid = expect_asset_lock_broadcast(create_result, "TC-018"); + tracing::info!("TC-018: asset lock broadcast in {}", txid); // Step 2: Wait for a tracked asset lock with the expected amount and a // ready proof from the upstream `AssetLockManager`. From 068af9e86111c47223125a2720079fe0e06e8e63 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 8 Sep 2026 13:33:58 +0000 Subject: [PATCH 4/4] test(backend-e2e): expect the node-specific not-found error in TC-MN-021 A masternode/evonode load takes a ProTxHash, so a lookup that resolves to no node reports `MasternodeNotFound` rather than the generic `IdentityNotFound` whose "ID or name" copy is wrong for that form (`load_identity.rs`, guarded by the `masternode_not_found_message_is_node_specific` unit test). TC-MN-021 loads with `IdentityType::Evonode` and predates that variant, so it failed on the correct error. Assert `MasternodeNotFound` and that it echoes the ProTxHash that was looked up, which the generic variant cannot carry. Co-Authored-By: Claude Opus 5 --- .../identity_masternode_withdraw.rs | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/tests/backend-e2e/identity_masternode_withdraw.rs b/tests/backend-e2e/identity_masternode_withdraw.rs index da84c90d4..28f945937 100644 --- a/tests/backend-e2e/identity_masternode_withdraw.rs +++ b/tests/backend-e2e/identity_masternode_withdraw.rs @@ -264,7 +264,7 @@ async fn test_mn020_load_wrong_key_rejected() { ); } -// ── TC-MN-021 — identity not found on network → IdentityNotFound ────────────── +// ── TC-MN-021 — node not found on network → MasternodeNotFound ─────────────── #[ignore] #[tokio_shared_rt::test(shared, flavor = "multi_thread", worker_threads = 12)] @@ -272,23 +272,30 @@ async fn test_mn021_load_identity_not_found() { let ctx = ctx().await; // Well-formed but (overwhelmingly) nonexistent 64-hex ProTxHash. - let random_pro_tx = hex::encode([0x42u8; 32]); + const PRO_TX_BYTES: [u8; 32] = [0x42u8; 32]; let task = load_task( - random_pro_tx, + hex::encode(PRO_TX_BYTES), IdentityType::Evonode, None, Some("".to_owned()), None, ); - // No signing key here, but the network fetch fails first with IdentityNotFound. + // No signing key here, but the network fetch fails first. let err = run_task(&ctx.app_context, task) .await .expect_err("a nonexistent ProTxHash must not load"); - assert!( - matches!(err, TaskError::IdentityNotFound), - "expected IdentityNotFound, got: {err:?}" - ); + // A masternode/evonode load reports the node-specific variant, not the + // generic `IdentityNotFound` whose "ID or name" copy is wrong for a + // ProTxHash form, and it echoes the id it looked up. + match err { + TaskError::MasternodeNotFound { identity_id } => assert_eq!( + identity_id.as_bytes(), + &PRO_TX_BYTES, + "MasternodeNotFound must echo the looked-up ProTxHash" + ), + other => panic!("expected MasternodeNotFound, got: {other:?}"), + } } // ── TC-MN-050 — OWNER mode happy path via tool invoke: destination forced to payout