//! Wallet creation, registration, and removal on [`PlatformWalletManager`]. use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use dash_spv::chain::CheckpointManager; use dpp::prelude::Identifier; use key_wallet::wallet::initialization::WalletAccountCreationOptions; use key_wallet::wallet::managed_wallet_info::ManagedWalletInfo; use key_wallet::wallet::Wallet; use key_wallet::Network; #[cfg(any(feature = "bls", feature = "eddsa"))] use crate::changeset::ProviderKeyExtendedPubKey; use crate::changeset::{ AccountAddressPoolEntry, AccountRegistrationEntry, ClientWalletStartState, PlatformWalletChangeSet, PlatformWalletPersistence, PrivateContactRequestsPosition, ProviderKeyAccountEntry, WalletMetadataEntry, }; use crate::error::PlatformWalletError; use crate::wallet::core::WalletGeneration; use crate::wallet::mnemonic::parse_mnemonic_any_language; use crate::wallet::platform_wallet::{PlatformWalletInfo, WalletId}; use crate::wallet::PlatformWallet; use super::PlatformWalletManager; /// The error a registration of an already-registered wallet returns. /// /// Built from the upstream variant `insert_wallet` would have produced, so the /// pre-read check and the insert itself are indistinguishable to the caller — /// which of the two answers first is an ordering detail, not a contract. fn already_registered(wallet_id: WalletId) -> PlatformWalletError { PlatformWalletError::WalletAlreadyExists( key_wallet_manager::WalletError::WalletExists(wallet_id).to_string(), ) } /// Test-only rendezvous fired inside [`PlatformWalletManager::remove_wallet_with_teardown`], /// between the inner-manager removal and the public-map removal. /// /// That window is exactly where a concurrent same-id `register_wallet` can /// publish a NEW generation into both maps — the id is free in the inner /// manager from the moment the removal above completes, and nothing gates /// registration. Reproducing it deterministically from outside is not possible: /// the window is bounded by two *different* synchronization domains — the /// inner manager's lock and the public map's `ArcSwap` publication — and a /// test holds no lock that could park the remover between them without also /// stalling the registration's own publish. A rendezvous is therefore the /// only way to pin this ordering without a sleep or a completion-order race. /// /// Compiled under `cfg(test)` only: neither this static nor its call site /// exists in a production build, and it is not part of any public API. #[cfg(test)] pub(crate) type RemoveWalletMidpointHook = Box< dyn Fn(&WalletId) -> std::pin::Pin + Send>> + Send + Sync, >; #[cfg(test)] pub(crate) static REMOVE_WALLET_MIDPOINT_HOOK: std::sync::Mutex> = std::sync::Mutex::new(None); impl PlatformWalletManager

{ /// Create a PlatformWallet from a BIP39 mnemonic phrase. /// /// The mnemonic's language is auto-detected by trying each /// supported BIP-39 wordlist in turn (see /// [`parse_mnemonic_any_language`]). For passphrase-only flows or /// out-of-band seed material, derive the seed externally and use /// [`Self::create_wallet_from_seed_bytes`]. /// /// `birth_height_override` controls SPV's compact-filter scan /// window for the new wallet. `None` (the default for fresh /// wallets) resolves the birth height from SPV's current /// confirmed header tip, so the scan window is `[H_now, ∞)` and /// anything funded before init is invisible — **but** when SPV is /// not running yet or header state is unavailable (e.g. wallet /// created before the SPV client is started), it falls back to /// the latest network checkpoint height, keeping the scan near /// the chain head instead of rescanning from genesis. `Some(0)` /// always requests a full historical scan from genesis (use /// sparingly — expensive on long-lived chains, but required when /// an address may have received funds before the wallet was first /// registered). `Some(h)` pins the scan start to a specific block /// height, useful when a known funding block is on record. pub async fn create_wallet_from_mnemonic( &self, mnemonic_phrase: &str, network: Network, accounts: WalletAccountCreationOptions, birth_height_override: Option, ) -> Result, PlatformWalletError> { let mnemonic = parse_mnemonic_any_language(mnemonic_phrase) .map_err(|e| PlatformWalletError::WalletCreation(format!("Invalid mnemonic: {}", e)))?; let wallet = Wallet::from_mnemonic(mnemonic, network, accounts).map_err(|e| { PlatformWalletError::WalletCreation(format!( "Failed to create wallet from mnemonic: {}", e )) })?; self.register_wallet(wallet, birth_height_override).await } /// Create a PlatformWallet from raw seed bytes, initialize persisted /// state, register it with the manager and return an `Arc` handle. /// /// See [`Self::create_wallet_from_mnemonic`] for the /// `birth_height_override` semantics. `None` scans from the /// current SPV tip forward when SPV is running, otherwise from /// the latest network checkpoint; `Some(h)` is for callers that need to see funding /// deposited before the wallet was registered (e.g. a long-lived /// bank address pre-funded with testnet duffs). pub async fn create_wallet_from_seed_bytes( &self, network: Network, // By reference: the named stack copy we hold of the master secret is // wrapped in `Zeroizing` and scrubbed on drop. (`[u8; 64]` is `Copy`, // so a transient by-value copy still // crosses into key-wallet's `from_seed_bytes`, which consumes it into // its own zeroizing `Seed`; fully eliminating that residual copy // needs `from_seed_bytes` to take `&[u8; 64]` upstream in key-wallet.) seed_bytes: &[u8; 64], accounts: WalletAccountCreationOptions, birth_height_override: Option, ) -> Result, PlatformWalletError> { let seed = zeroize::Zeroizing::new(*seed_bytes); let wallet = Wallet::from_seed_bytes(*seed, network, accounts).map_err(|e| { PlatformWalletError::WalletCreation(format!( "Failed to create wallet from seed bytes: {}", e )) })?; self.register_wallet(wallet, birth_height_override).await } /// Register a pre-built `Wallet` with the manager: insert into the /// `WalletManager`, build a `PlatformWallet` handle, load persisted /// state, and return an `Arc` to the managed wallet. /// /// `birth_height_override` flows through to both the in-memory /// `ManagedWalletInfo` sync checkpoint and the persisted /// `WalletMetadataEntry` so the SPV scan window is consistent /// across restarts. See [`Self::create_wallet_from_mnemonic`] for /// the contract. #[allow(clippy::type_complexity)] async fn register_wallet( &self, mut wallet: Wallet, birth_height_override: Option, ) -> Result, PlatformWalletError> { // NOTE: the wallet id is NETWORK-SCOPED by construction. // `Wallet::from_mnemonic` / `from_seed_bytes` now stamp a // network-scoped id (key-wallet folds a domain-tagged, // wire-stable network byte into the digest), so the same // mnemonic yields a DISTINCT id per network. That makes every // downstream `walletId`-keyed structure network-correct by // construction — no per-network disambiguation needed in the // persistence layer, and network-blind child tables (UTXOs, // asset locks, platform addresses) cannot cross-feed // between a mnemonic's per-network wallets. The watch-only // restore path (`Wallet::new_external_signable`) reuses the // persisted id verbatim, so it stays self-consistent across // launches. // Birth height resolution: explicit override wins; otherwise fall back // to SPV's confirmed header tip (default for fresh wallets — they only // need to see funding from now on). Before SPV has synced any headers // the tip is 0, so a brand-new wallet created at startup would otherwise // anchor at genesis and rescan the whole chain. Fall back to the latest // hardcoded checkpoint instead, keeping the scan near the chain head. let birth_height: u32 = match birth_height_override { Some(h) => h, None => { let tip = self .spv_manager .sync_progress() .await .and_then(|p| p.headers().ok().map(|h| h.tip_height())) .unwrap_or(0); if tip > 0 { tip } else { CheckpointManager::for_network(self.sdk.network) .checkpoints() .last() .map(|checkpoint| checkpoint.height()) .unwrap_or(0) } } }; // `mut` so the platform-node (Ed25519) pool can be populated in // place below, BEFORE the address-pool snapshot is taken. let mut wallet_info = ManagedWalletInfo::from_wallet(&wallet, birth_height); // The id this wallet is about to occupy. Computed HERE — before // `downgrade_to_external_signable` below flips the wallet type, and // before `wallet` is moved into `insert_wallet` — because the // generation must be born already holding this wallet's fence map. // // A registration under an id a previous generation held is exactly the // remove-and-recreate case: that generation's pending-spend fences // protect signed transactions that are still valid and still relayable, // so the replacement inherits them rather than starting clean. A first // registration finds no entry and gets an empty map. let registration_wallet_id = wallet.compute_wallet_id(); let generation = Arc::new(WalletGeneration::with_fences( self.in_broadcast_fences_for(®istration_wallet_id), )); // Snapshot per-account xpubs and address-pool entries BEFORE // the wallet / managed-info are moved into insert_wallet. The // persister sees everything needed to rebuild the wallet // external-signable (via `Wallet::new_external_signable`) plus populate // SwiftData's address table on next launch. let account_specs: Vec<( key_wallet::account::AccountType, key_wallet::bip32::ExtendedPubKey, )> = wallet .accounts .all_accounts() .iter() .map(|a| (a.account_type, a.account_xpub)) .collect(); // Provider key-material accounts (BLS operator keys / EdDSA // platform-node keys) live in dedicated `Option` fields on the // `AccountCollection` that `all_accounts()` deliberately // excludes, so snapshot them separately. They carry a // non-secp256k1 extended public key; the persister bincode- // encodes it and the restore path rebuilds them watch-only. #[allow(unused_mut)] let mut provider_key_account_registrations: Vec = Vec::new(); #[cfg(feature = "bls")] if let Some(bls) = wallet .accounts .bls_account_of_type(key_wallet::account::AccountType::ProviderOperatorKeys) { provider_key_account_registrations.push(ProviderKeyAccountEntry { account_type: key_wallet::account::AccountType::ProviderOperatorKeys, extended_public_key: ProviderKeyExtendedPubKey::Bls(bls.bls_public_key.clone()), }); } #[cfg(feature = "eddsa")] if let Some(eddsa) = wallet .accounts .eddsa_account_of_type(key_wallet::account::AccountType::ProviderPlatformKeys) { // Pre-derive a fixed batch of platform-node public keys while // the wallet is still seed-bearing (`downgrade_to_external_signable` // hasn't run yet). Ed25519/SLIP-10 is hardened-only, so this // pool can never be extended later from the watch-only restore — // populating the managed pool now lets those keys ride the // normal typed-address persistence pipeline (persisted as // `PublicKeyType::EdDSA` core-address rows, rehydrated on load // by `restore_core_address_pools`) so the Node Keys screen lists // them from persistence with no keychain prompt. A derivation // failure here is non-fatal: fall back to an empty batch (the UI // then uses its resolver-based "Load Keys" path) rather than // aborting the whole wallet registration. let derived_platform_node_keys = crate::wallet::provider_key_at_index::derive_platform_node_public_keys( &wallet, wallet.network, crate::wallet::provider_key_at_index::PLATFORM_NODE_KEY_PREDERIVE_COUNT, ) .unwrap_or_else(|e| { tracing::warn!( error = %e, "failed to pre-derive platform-node keys at registration; \ the Node Keys screen will fall back to the resolver path" ); Vec::new() }); // Populate the managed platform-node pool in place, BEFORE the // address-pool snapshot below reads `all_managed_accounts()`, so // the EdDSA keys are captured as typed core-address rows. A // population failure is non-fatal for the same reason the // derivation failure above is. if let Err(e) = crate::wallet::provider_key_at_index::populate_platform_node_pool( &mut wallet_info, &derived_platform_node_keys, wallet.network, ) { tracing::warn!( error = %e, "failed to populate the managed platform-node pool at registration; \ the Node Keys screen will fall back to the resolver path" ); } provider_key_account_registrations.push(ProviderKeyAccountEntry { account_type: key_wallet::account::AccountType::ProviderPlatformKeys, extended_public_key: ProviderKeyExtendedPubKey::EdDSA( eddsa.ed25519_public_key.clone(), ), }); } // Snapshot core (BIP44/CoinJoin/identity/provider/DashPay) // address pools. PlatformPayment accounts live in a separate // collection on `ManagedWalletInfo` and are handled below. let mut address_snapshots: Vec<( key_wallet::account::AccountType, Vec<( key_wallet::managed_account::address_pool::AddressPoolType, Vec, )>, )> = wallet_info .all_managed_accounts() .iter() .map(|managed| { // `all_managed_accounts()` returns `ManagedAccountRef`; // the upstream split made `managed_account_type` a // delegating method (it was a field on the pre-split // unified `ManagedCoreAccount`). let account_type = managed.managed_account_type().to_account_type(); let pools = managed .managed_account_type() .address_pools() .iter() .map(|pool| { let infos: Vec = pool.addresses.values().cloned().collect(); (pool.pool_type, infos) }) .collect(); (account_type, pools) }) .collect(); // Platform payment (DIP-17) accounts sit in their own // collection and each owns a single `AddressPool`. Snapshot // them here so the Storage Explorer can show them under the // PlatformPayment account row alongside core pools. for managed in wallet_info.all_platform_payment_managed_accounts() { let account_type = key_wallet::account::AccountType::PlatformPayment { account: managed.account, key_class: managed.key_class, }; let pool = &managed.addresses; let infos: Vec = pool.addresses.values().cloned().collect(); address_snapshots.push((account_type, vec![(pool.pool_type, infos)])); } // Network-INDEPENDENT group id, snapshotted BEFORE `wallet` is // moved into `insert_wallet` below. The per-network `wallet_id` // differs per network for the same seed (see the scoping note // above); this digest deliberately omits the network byte // (`None`), so every network's wallet for one seed shares it and // the persister can group a seed's sibling-network rows by it. // Watch-only / external-signable wallets carry no root key, so // there's nothing to hash — fall back to the scoped `wallet_id` // (a group of one). let wallet_group_id = wallet .root_extended_pub_key_cow() .map(|root| Wallet::compute_wallet_id_from_root_extended_pub_key(&root, None)) .unwrap_or(wallet.wallet_id); let mut platform_info = PlatformWalletInfo { observed_input_conflicts: Default::default(), finalized_spends: Default::default(), core_wallet: wallet_info, generation: Arc::clone(&generation), identity_manager: crate::wallet::identity::IdentityManager::new(), tracked_asset_locks: std::collections::BTreeMap::new(), dpns_name_states: std::collections::BTreeMap::new(), dashpay_backfill: Default::default(), rewind_barrier: Default::default(), }; wallet.downgrade_to_external_signable(); // Answer a duplicate registration before the read below, not after. // Re-registering an existing wallet is a benign no-op the FFI / Swift // call sites rely on, and it must stay one: a busy backend would // otherwise turn it into a persister error that invites the caller to // retry an operation that had nothing to do. `insert_wallet` stays the // authority — this only decides which answer the caller gets first, so // a wallet registered between the two checks still collides there. { let wm = self.wallet_manager.read().await; if wm.get_wallet_info(®istration_wallet_id).is_some() { return Err(already_registered(registration_wallet_id)); } } // Read the persisted state BEFORE the wallet exists anywhere the // wallet-event producer can see it. // // The ordering is load-bearing, and the write it protects against is // not one this function makes. An exhausted transient read reports // `PersisterLoad(Transient)`, which tells the caller nothing was // mutated and the registration is safe to re-issue. But // `insert_wallet` publishes the wallet into the shared // `WalletManager`, and the SPV filter loop scans under that same lock: // a wallet whose `synced_height` is behind the chain is picked up by // the next batch, whose matches and watermark advance travel the // lossless channel to the wallet-event adapter and land in `store()`. // Registering first therefore lets a durable write precede the promise // that none happened — and the exhausting read is the slow case, so // the producer has the most time to commit exactly when the promise is // about to be made. Reading first leaves nothing for it to write. // // The caller owns retry policy for both this read and the `store` // further down. // // The whole per-wallet map is carried across `insert_wallet` rather // than sliced here: the authoritative id is the one that call returns, // and it is deliberately not assumed equal to `registration_wallet_id` // (see the divergence branch below). // // The same read also yields what the host holds for every persisted // wallet: a registration that recreates a wallet the host already has // must measure durable writes against the host's cursor, not the one // it just built, and keeps the host's DashPay backfill record for the // receival accounts it holds (see the seed below). // // And the private contact request scan state records the host kept // marked for this id, its wallet's identities' or those kept after the // wallet's removal: a private payment one stands for may still // execute, while the identity is added afresh, with no reservation or // record of it. Each such identity is held as it is added, before it // can send or accept, in every build. let load_persister: Arc = Arc::clone(&self.persister) as _; let (mut persisted_platform_addresses, mut host_wallets, retained_markers) = match super::run_blocking_load(move || load_persister.load()).await { Ok(crate::changeset::ClientStartState { platform_addresses, wallets, retained_private_contact_scan_states, .. }) => { let retained_markers = retained_private_payment_markers( registration_wallet_id, &wallets, &retained_private_contact_scan_states, ); ( platform_addresses, wallets .into_iter() .map(|(id, state)| { ( id, ( state.wallet_info.metadata.synced_height, state.dashpay_backfill, ), ) }) .collect::>(), retained_markers, ) } Err(e) => { tracing::error!( wallet_id = %hex::encode(registration_wallet_id), transient = e.is_transient(), error = %e, "failed to load persisted wallet state; \ registration aborted before the wallet was registered" ); return Err(PlatformWalletError::from_load_failure(e)); } }; // Insert into WalletManager. A duplicate (same network-scoped // wallet id already registered) surfaces as the typed // `WalletAlreadyExists` so the create FFI / Swift call sites can // treat re-registering an existing wallet as a benign no-op // instead of substring-matching the error text. Everything else // stays `WalletCreation`. // // The durable cursor is seeded in the same scope as the insert, under // the cursor lock taken first (its order: cursor lock, then manager). // The insert makes the wallet visible to the scanner and the event // adapter; seeding after it would let an adapter commit or a // reconcile record a newer durable height first, only for the seed to // overwrite it with the creation one. // // A registration can recreate a wallet the host already holds (the // same seed added again on a fresh manager). The host keeps that // row's cursor — registration writes no core cursor, and a host // preserves `syncedHeight` on the metadata upsert — so the seed is // the host's cursor, not the freshly built one. The snapshot above // was read before this lock, and a same-id predecessor still // registered then may have had a commit accepted since — or a whole // same-id registration may have come and gone, creating the row the // snapshot did not see. The entry those writes left in // `DurableCursors` is what the host holds now, so it wins over the // snapshot, row or no row. When the built cursor is lower than the // host's, the wallet is in effect reset in memory only: that reset is // owed to the host like any other, in this wallet's inherited epoch, // and the next DashPay backfill record round carries it, so coverage // never reaches disk beside the host's higher cursor // (dashpay/platform#4302 review). // // The host's record is kept only for the receival accounts the // recreated wallet actually holds — none, when it is built from the // seed. Coverage for an account that is absent while this wallet // scans is not coverage: the scan does not watch the account's // scripts, and the account-generation guard only stops batches still // in flight, not an advance already committed. The host still holds // the old record and the account rows, and would restore both beside // this wallet's advanced cursor after a crash — so the filtered // record is stored BEFORE the wallet is published to the scanner. // Those accounts re-arm when they are registered, at the cost of one // more backfill. // // Whether the snapshot held anything to prune is not the whole test, // because the snapshot is older than the lock: a same-id registration // can have been published after it, established a receival account, // stored that account's coverage and been removed again, all before // this one publishes. Nothing in this snapshot shows that coverage. // An entry in `DurableCursors` is what tells: every publication leaves // one and removal keeps it. So with an entry present the host's // record is replaced with the one this wallet carries, whatever the // snapshot showed (`settle_published_backfill`). The duplicate check // runs first, so a wallet still registered under this id never has // its record overwritten; every publisher holds the cursor lock, so // none can appear between that check and the insert. platform_info .identity_manager .retain_private_payment_markers(retained_markers); let created_cursor = platform_info.core_wallet.metadata.synced_height; let (snapshot_cursor, mut host_backfill) = match host_wallets.remove(®istration_wallet_id) { Some((cursor, record)) => (Some(cursor), record), None => (None, Default::default()), }; let dropped = super::retain_coverage_for_held_accounts( &mut host_backfill, &platform_info.core_wallet, ); let wallet_id = { let mut durable_cursors = self.durable_cursors.lock().await; if self .wallet_manager .read() .await .get_wallet_info(®istration_wallet_id) .is_some() { return Err(already_registered(registration_wallet_id)); } let host_backfill = self.settle_published_backfill( &mut durable_cursors, registration_wallet_id, host_backfill, dropped, created_cursor, snapshot_cursor.unwrap_or(created_cursor), )?; let mut wm = self.wallet_manager.write().await; let wallet_id = wm .insert_wallet(wallet, platform_info) .map_err(|e| match e { key_wallet_manager::WalletError::WalletExists(id) => already_registered(id), other => PlatformWalletError::WalletCreation(format!( "Failed to register wallet in WalletManager: {}", other )), })?; let host_cursor = durable_cursors .get(&wallet_id) .map(|entry| entry.height) .or(snapshot_cursor) .unwrap_or(created_cursor); self.inherit_rewind_barrier(&mut wm, &wallet_id); if let Some(info) = wm.get_wallet_info_mut(&wallet_id) { info.dashpay_backfill = host_backfill; if created_cursor < host_cursor { let epoch = info.rewind_barrier.epoch(); info.dashpay_backfill.owe_cursor(created_cursor, epoch); } } durable_cursors .entry(wallet_id) .or_insert(crate::changeset::DurableCursor::at(host_cursor)); wallet_id }; // `insert_wallet` recomputes the id from the (now external-signable) // wallet. The two agree by construction — the downgrade flips only the // wallet TYPE, and the type's own branch returns the same stamped // network-scoped digest — but the fence map is safety state, so a // divergence must not silently key it under an id nothing will look up. // Alias the same `Arc` under the authoritative id instead: one map, // reachable either way. debug_assert_eq!( wallet_id, registration_wallet_id, "the registered wallet id must match the id the fence map was keyed by" ); if wallet_id != registration_wallet_id { tracing::error!( registered = %hex::encode(wallet_id), fenced_as = %hex::encode(registration_wallet_id), "wallet id changed across registration; aliasing the in-broadcast \ fence map under both" ); let fences = self.in_broadcast_fences_for(®istration_wallet_id); self.in_broadcast_fences .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .insert(wallet_id, fences); } // Now that the authoritative id is known, take this wallet's slice of // the snapshot read above and drop the rest. let persisted_platform_addresses = persisted_platform_addresses.remove(&wallet_id); // Emit metadata + per-account xpubs + per-pool address // snapshots to the persister so the watch-only restore path // has everything it needs on next launch. The whole // registration round travels as a single // [`PlatformWalletChangeSet`] through the canonical `store` // entry point — backends (FFI, SQLite, in-memory) see one // atomic round rather than three side-channel calls. // // This round is the only record a wallet can be rebuilt // watch-only from on next launch, so it is load-bearing: a // `store` error rolls back the in-memory insert and aborts // registration — same shape as the `load_persisted` / // `initialize_from_persisted` failure paths below. // `birth_height` was resolved at the top of `register_wallet` // and seeded into `ManagedWalletInfo`; reuse it here so the // persisted `WalletMetadataEntry` agrees with the in-memory // sync checkpoint. let mut registration_changeset = PlatformWalletChangeSet { wallet_metadata: Some(WalletMetadataEntry { network: self.sdk.network, wallet_group_id, birth_height, }), account_registrations: account_specs .iter() .map(|(account_type, account_xpub)| AccountRegistrationEntry { account_type: *account_type, account_xpub: *account_xpub, }) .collect(), provider_key_account_registrations, ..Default::default() }; // Every account type contributes at least one pool (external, // or a single `Absent` pool for degenerate types); Standard // accounts contribute two. Ordering within a pool is by // derivation index via `BTreeMap::values`. Empty pools are // dropped here so the FFI receiver can match the previous // "skip empty pools" semantics without re-deciding it. for (account_type, pools) in &address_snapshots { for (pool_type, infos) in pools { if infos.is_empty() { continue; } registration_changeset .account_address_pools .push(AccountAddressPoolEntry { account_type: *account_type, pool_type: *pool_type, addresses: infos.clone(), }); } } // `store` is not retried here: the caller receives the typed, // kind-classified `PersistenceError` and decides. if let Err(e) = self.persister.store(wallet_id, registration_changeset) { tracing::error!( wallet_id = %hex::encode(wallet_id), transient = e.is_transient(), error = %e, "failed to persist wallet registration changeset" ); let mut wm = self.wallet_manager.write().await; if let Err(remove_err) = self.remove_from_wallet_manager(&mut wm, &wallet_id) { tracing::warn!( wallet_id = %hex::encode(wallet_id), error = %remove_err, "rollback: remove_wallet failed while unwinding a failed wallet registration" ); } return Err(PlatformWalletError::from_store_failure(&*self.persister, e)); } // Build the PlatformWallet handle. let broadcaster = Arc::new(crate::broadcaster::SpvBroadcaster::new(Arc::clone( &self.spv_manager, ))); let persister_dyn: Arc = Arc::clone(&self.persister) as _; let platform_wallet = PlatformWallet::new( Arc::clone(&self.sdk), wallet_id, Arc::clone(&self.wallet_manager), generation, Arc::clone(&self.lock_notify), persister_dyn, broadcaster, Arc::clone(&self.sync_fault), Arc::clone(&self.durable_cursors), ); // Restore the platform-address provider from the slice read above — // the only area wired up today. `from_persisted` skips the live // `AddressPool` scan `initialize` would otherwise do. Per-wallet // UTXOs / unused asset locks ship in the snapshot but don't have an // active restore path yet. // // A bare `?` here would leave the wallet half-registered exactly as on // the read path above, so this too rolls the insert back before // bailing. Unlike that path, the registration write has already // landed: `PersisterRestore` says so, and promises no re-issue. if let Some(persisted) = persisted_platform_addresses { if let Err(e) = platform_wallet .platform() .initialize_from_persisted(persisted) .await { tracing::error!( wallet_id = %hex::encode(wallet_id), error = %e, "failed to restore persisted platform-address state" ); let mut wm = self.wallet_manager.write().await; if let Err(remove_err) = self.remove_from_wallet_manager(&mut wm, &wallet_id) { tracing::warn!( wallet_id = %hex::encode(wallet_id), error = %remove_err, "rollback: remove_wallet failed while unwinding a failed wallet setup" ); } // Wrap the already-typed error rather than stringify it, so // its concrete variant and source chain survive. return Err(PlatformWalletError::from_restore_failure(e)); } } else { platform_wallet.platform().initialize().await; } let platform_wallet = Arc::new(platform_wallet); // Before the wallet is published: hold or restore its private // payments (`PlatformWalletManager::hold_or_restore_private_payments`). #[cfg(feature = "shielded")] self.hold_or_restore_private_payments(&platform_wallet) .await; // Register the PlatformWallet handle. `rcu` publishes a new map // snapshot; the closure can rerun under a concurrent-writer // retry, so it must stay pure map manipulation. self.wallets.rcu(|wallets| { let mut wallets = std::collections::BTreeMap::clone(wallets); wallets.insert(wallet_id, Arc::clone(&platform_wallet)); wallets }); // A store configured since the check above restored the wallets it // found published, which this one was not yet. #[cfg(feature = "shielded")] self.restore_private_payments_configured_since(&platform_wallet) .await; // Re-seed the lock-free balance atomic from the wallet's inner // balance now that the wallet is in `self.wallets`. // // A wallet added while SPV is already synced (e.g. importing an // existing mnemonic with `birth_height = 0`) has its historical // funds backfilled by an SPV rescan. `insert_wallet` does not // request that rescan — it only publishes the wallet into the shared // `WalletManager`; the SPV filter loop reads that same map, finds a // wallet whose `synced_height` is behind the chain, and scans it on // its next batch. That backfill can therefore complete — emitting the // `BlockProcessed` event that carries the post-backfill balance — // *before* this wallet lands in `self.wallets`, so // `BalanceUpdateHandler` drops those events (the wallet isn't in // the map yet) and the atomic stays at zero even though the inner // `ManagedWalletInfo` balance is correct. Mirror the inner balance // into the atomic here (as `manager::load` does for restored // wallets); any later block events are applied normally now that // the wallet is mapped. // // Last writer wins between this seed and the handler: if SPV // processes another block between the read below and the `set`, the // atomic briefly goes back to the older totals. The next // balance-bearing event corrects it, and during the rescan this // exists for those arrive continuously. { let wm = self.wallet_manager.read().await; if let Some(info) = wm.get_wallet_info(&wallet_id) { let b = &info.core_wallet.balance; platform_wallet.balance().set( b.confirmed(), b.unconfirmed(), b.immature(), b.locked(), ); } } // Registration deliberately runs no identity discovery. The wallet // was downgraded to external-signable above, so the resident-key // scan (`identity().discover(..)`) cannot derive its first auth key and // fails before ever reaching Platform — all it did here was wait on // the wallet-manager lock twice, spend one host persistence round // and leave a spurious "scan incomplete at index 0" verdict behind // (on a host whose persister commit was in flight, that wait // stretched a wallet import to minutes). Discovery belongs to the // host's startup sequence (`start_wallet_subsystems`: budgeted, // master key resolved on demand) or to an explicit // `identity().discover_from_master(..)`. Ok(platform_wallet) } /// Remove a wallet from the manager. /// /// Runs under the removed generation's lifecycle gate — see /// [`remove_wallet_with_teardown`](Self::remove_wallet_with_teardown), of /// which this is the no-extra-teardown case. pub async fn remove_wallet( &self, wallet_id: &WalletId, ) -> Result, PlatformWalletError> { self.remove_wallet_with_teardown(wallet_id, |_| {}).await } /// Remove a wallet from the manager and run `tear_down` on the removed /// wallet — both under that generation's exclusive lifecycle gate, as one /// linearization point. /// /// # Why the gate lives here rather than in the caller /// /// Removing the generation and tearing down the deferred state that names it /// (the [`SignedPaymentRegistry`](crate::SignedPaymentRegistry) tokens and /// the FFI's finalized-transaction handles) must be indivisible. If they are /// two steps, a retained handle can broadcast in the gap: the removal's own /// `.await`s (shielded-coordinator and identity-sync unregistration) sit /// inside it, `CoreWallet::is_same_generation` passes for a removed /// generation (a removed generation matches itself), and the reservation age /// guard is disabled once `last_processed_height` returns `None`. So a /// payment for a wallet the host already deleted reaches the network. /// /// Taking the gate *inside* this method rather than leaving it to the caller /// is deliberate: `PlatformWalletManager` is public and `SignedPaymentRegistry` /// is re-exported, so a direct Rust embedder that never goes through the FFI /// would otherwise remove wallets with no exclusion at all, and could /// interleave between a payment operation's liveness check and its register /// or network action. `tear_down` is the hook that lets the FFI layer sweep /// its own process-global handle storages inside the same critical section /// without the gate ever being optional. /// /// `tear_down` is synchronous by design — it runs while the gate is held, and /// every sweep it needs (`remove_entries_for_wallet`, /// `HandleStorage::remove_matching`) is a synchronous map retain. /// /// ## Lock ordering /// /// The generation gate is always taken BEFORE the manager locks. The lookup /// that finds the gate takes `wallets` briefly and **drops it before** /// awaiting the gate, so no manager lock is ever held across a gate /// acquisition; payment operations likewise take the gate and only then await /// the manager. The order is total, so the two cannot deadlock. /// /// ## Removal is by generation identity, not by key /// /// The gate excludes *payment operations on this generation*. It does not /// exclude a fresh **registration** under the same `wallet_id`: /// [`register_wallet`](Self::register_wallet) mints its own /// [`WalletGeneration`] and takes no gate at all, by design — a create must /// never queue behind an unrelated wallet's teardown. /// /// So once this method has removed generation G1 from the inner /// `wallet_manager`, the id is free and a concurrent registration can publish /// a *different* generation G2 into both maps before this method reaches its /// own `self.wallets` removal — the two removals are separately synchronized, with /// no happens-before edge between them and the registration. Removing by key /// there would take G2 out of the public map (leaving it registered in the /// inner manager, invisible and unremovable) and hand G2 to `tear_down`, /// which would sweep G2's registry tokens and V2 handles while holding only /// G1's gate — i.e. with G2's payment operations *not* excluded, which is the /// exact property this gate exists to provide. /// /// The `Arc` validated under the gate is therefore retained, /// and the public-map entry is removed only while it still names that same /// generation. Both maps, the returned handle and the `tear_down` argument /// then all name that one generation. The one remaining id-keyed step is /// the shielded coordinator detach below, which has no generation concept /// at all; a generation that has just been registered has not run /// `bind_shielded` yet, so it holds no coordinator entry to detach. /// /// The inner-manager removal needs no such check: G1 can only leave /// `wallet_manager` through this method (which requires G1's gate, held here) /// or through a registration/load rollback for an insert that could not have /// happened while G1 occupied the id — so while the gate is held and before /// the removal below, the inner entry is still G1 by construction. pub async fn remove_wallet_with_teardown( &self, wallet_id: &WalletId, tear_down: F, ) -> Result, PlatformWalletError> where F: FnOnce(&Arc), { // Find the generation registered under `wallet_id` and take ITS gate. // Re-validated after acquisition because the wallet could have been // removed and re-created under the same id while we waited: in that case // we hold the OLD generation's gate, which excludes nothing relevant to // the new one, so retry against the generation that is actually current. // // The validated handle is carried out of the loop: it is both what this // call returns and tears down, and the identity every mutation below is // matched against. let (removed, _teardown) = loop { let candidate = { let wallets = self.wallets.load(); match wallets.get(wallet_id) { None => { return Err(PlatformWalletError::WalletNotFound(hex::encode(wallet_id))) } Some(wallet) => Arc::clone(wallet), } }; let guard = candidate.generation().teardown_guard().await; let still_current = { let wallets = self.wallets.load(); wallets .get(wallet_id) .is_some_and(|wallet| Arc::ptr_eq(wallet.generation(), candidate.generation())) }; if still_current { break (candidate, guard); } // Drop this generation's guard and re-resolve. drop(guard); }; let generation = Arc::clone(removed.generation()); // Every ID-keyed side-registry teardown below runs BEFORE the inner // wallet-manager removal frees `wallet_id`. The side registries // (shielded coordinator, identity-sync rows) are keyed by wallet / // identity id, not by generation, so an unregister that ran after the // id was freed could delete state a concurrent same-id registration // (G2) had just installed. The inner manager's `insert_wallet` is the // create path's commit point — a same-id create fails with // `WalletAlreadyExists` until the removal below — so completing all // id-keyed cleanup first makes the window unreachable rather than // merely narrow. let owned_identity_ids: Vec = { let wm = self.wallet_manager.read().await; match wm.get_wallet_info(wallet_id) { Some(info) => info .identity_manager .wallet_identities .get(wallet_id) .map(|inner| { use dpp::identity::accessors::IdentityGettersV0; inner .values() .map(|managed| managed.identity.id()) .collect() }) .unwrap_or_default(), None => Vec::new(), } }; // Detach the wallet's shielded state from the network // coordinator. After the Phase-2b refactor the coordinator // owns the per-`SubwalletId` viewing-key registry and the // per-wallet `WalletPersister`; without this call a deleted // wallet's shielded notes keep getting fetched, // trial-decrypted, and re-persisted through the stale // persister on the next `coordinator.sync()` pass — // resurrecting private shielded history on disk after the // host believed the wallet was gone. Drops the registry + // persister entries and the per-subwallet store state. // // The handle is marked detached first: a caller that resolved // this wallet before the removal can still be inside a bind // (the seed-backed path resolves a mnemonic through the host, // so it may take arbitrarily long), and its registration would // otherwise land after the unregister below and resurrect // exactly the state this call exists to drop. The flag is read // inside the coordinator's install transaction, which the // unregister also takes, so the two cannot interleave. // Unconditional: a removal with no coordinator yet has nothing // to unregister, but the handle must still be barred from // binding onto one a later `configure_shielded` installs. #[cfg(feature = "shielded")] removed.mark_shielded_detached(); #[cfg(feature = "shielded")] if let Some(coordinator) = self.shielded_coordinator().await { coordinator.unregister_wallet(*wallet_id).await; } for identity_id in &owned_identity_ids { self.identity_sync_manager .unregister_identity(identity_id) .await; } // Only now free the id in the inner manager — the LAST id-keyed step. // An identity registered on this wallet after the snapshot above (a // host racing an identity add against its own removal) is left as a // stale sync row rather than unregistered post-removal, because a // post-removal unregister-by-id would reopen the very window this // ordering closes for a same-id recreation's rows. Surface it instead. { let mut wm = self.wallet_manager.write().await; let late_identity_count = wm .get_wallet_info(wallet_id) .and_then(|info| info.identity_manager.wallet_identities.get(wallet_id)) .map(|inner| inner.len()) .unwrap_or(0) .saturating_sub(owned_identity_ids.len()); if late_identity_count > 0 { tracing::warn!( wallet_id = %hex::encode(wallet_id), late_identity_count, "remove_wallet: identities were added while the wallet was being removed; \ their identity-sync rows are left for the next launch to reconcile" ); } // The reconcile schedule is keyed by id too: forget it while this // generation still holds the id, so a same-id wallet added later // is reconciled at once rather than waiting out this one's // cadence, and no successor's checkpoint or claim is touched. A // run in flight is marked forgotten and records nothing; one // claimed from here on finds the wallet gone at its gate. self.forget_txo_reconcile(wallet_id); if let Err(e) = self.remove_from_wallet_manager(&mut wm, wallet_id) { tracing::warn!( wallet_id = %hex::encode(wallet_id), error = %e, "remove_wallet: inner wallet-manager removal failed (state may be inconsistent)" ); } } // Test-only rendezvous: the window a concurrent same-id registration can // publish a new generation into. Sits AFTER every id-keyed unregister, // so state a midpoint recreation installs is never torn down by this // removal. See `REMOVE_WALLET_MIDPOINT_HOOK`. #[cfg(test)] { let pending = REMOVE_WALLET_MIDPOINT_HOOK .lock() .expect("remove-wallet midpoint hook mutex") .as_ref() .map(|hook| hook(wallet_id)); if let Some(rendezvous) = pending { rendezvous.await; } } // Remove the public-map entry only while it still names the generation // validated under the gate. A concurrent same-id registration could have // published a NEW generation here in the window since the inner removal // above freed the id (see the "Removal is by generation identity" note on // this method); removing by key would evict that live wallet and hand it // to `tear_down` under the wrong gate. { // `rcu` keeps the generation check and the removal atomic: the // closure sees the map the CAS will replace, and a concurrent // publication retries the whole closure against the new map. // The `Cell` therefore ends up holding the verdict of the // attempt that actually committed. let entry_is_ours = std::cell::Cell::new(false); self.wallets.rcu(|wallets| { let ours = wallets .get(wallet_id) .is_some_and(|wallet| Arc::ptr_eq(wallet.generation(), &generation)); entry_is_ours.set(ours); if ours { let mut next = std::collections::BTreeMap::clone(wallets); next.remove(wallet_id); Arc::new(next) } else { // Not ours: publish the map unchanged. Arc::clone(wallets) } }); if !entry_is_ours.get() { tracing::warn!( wallet_id = %hex::encode(wallet_id), "remove_wallet: a new generation was registered under this id while the \ previous one was being removed; leaving the new registration in place" ); } } // Still under the generation's teardown gate: any deferred state naming // this generation is dropped in the same critical section as the removal // itself, so no payment operation can observe the wallet as live and then // act on it after this returns. tear_down(&removed); Ok(removed) } } /// The identities of `wallet_id` whose private contact request scan state /// record the host kept marked /// (`PrivateContactRequestsPosition::private_payments_unresolved`): those of /// its own identities, when the host still holds the wallet, and those it kept /// after the wallet's removal /// (`ClientStartState::retained_private_contact_scan_states`). pub(super) fn retained_private_payment_markers( wallet_id: WalletId, wallets: &BTreeMap, retained: &BTreeMap>, ) -> BTreeSet { let held = wallets .get(&wallet_id) .into_iter() .flat_map(|state| state.identity_manager.wallet_identities.values()) .flat_map(|identities| identities.values()) .filter(|managed| managed.dashpay().private_payments_unresolved()) .map(|managed| managed.id()); let kept = retained .get(&wallet_id) .into_iter() .flat_map(|records| records.iter()) .filter(|(_, record)| record.private_payments_unresolved) .map(|(owner, _)| *owner); held.chain(kept).collect() } #[cfg(test)] mod scoped_wallet_id_tests { use key_wallet::mnemonic::Mnemonic; use key_wallet::wallet::initialization::WalletAccountCreationOptions; use key_wallet::wallet::Wallet; use key_wallet::Network; // Canonical all-`abandon` BIP-39 test vector. Deterministic, so the // ids below are reproducible across runs. const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon \ abandon abandon abandon abandon abandon about"; fn wallet_id_for(network: Network) -> [u8; 32] { let mnemonic = Mnemonic::from_phrase(TEST_MNEMONIC).expect("valid test mnemonic"); let wallet = Wallet::from_mnemonic(mnemonic, network, WalletAccountCreationOptions::Default) .expect("wallet construction"); // This is the id the manager keys on (insert_wallet returns it, // the create FFI hands it to Swift) — exercises the same // construction path `create_wallet_from_mnemonic` uses. wallet.wallet_id } /// The network-INDEPENDENT group id `register_wallet` computes and /// persists onto every per-network row, so the iOS Wallet Info /// "Networks" section can group a seed's sibling-network wallets. /// Mirrors the `register_wallet` derivation exactly. fn wallet_group_id_for(network: Network) -> [u8; 32] { let mnemonic = Mnemonic::from_phrase(TEST_MNEMONIC).expect("valid test mnemonic"); let wallet = Wallet::from_mnemonic(mnemonic, network, WalletAccountCreationOptions::Default) .expect("wallet construction"); wallet .root_extended_pub_key_cow() .map(|root| Wallet::compute_wallet_id_from_root_extended_pub_key(&root, None)) .unwrap_or(wallet.wallet_id) } /// The same mnemonic must yield a DISTINCT wallet id on each network. /// This is the property the whole per-network persistence model now /// relies on (rust-dashcore #793: network-scoped id by default). #[test] fn same_mnemonic_yields_distinct_ids_per_network() { let mainnet = wallet_id_for(Network::Mainnet); let testnet = wallet_id_for(Network::Testnet); let devnet = wallet_id_for(Network::Devnet); let regtest = wallet_id_for(Network::Regtest); let all = [mainnet, testnet, devnet, regtest]; for i in 0..all.len() { for j in (i + 1)..all.len() { assert_ne!( all[i], all[j], "wallet ids for two different networks must differ \ (index {i} vs {j}) — scoped-id regression" ); } } } /// Re-deriving the same (mnemonic, network) must be stable, otherwise /// the watch-only restore path (which reuses the persisted id) would /// drift across launches. #[test] fn same_mnemonic_same_network_is_stable() { for network in [ Network::Mainnet, Network::Testnet, Network::Devnet, Network::Regtest, ] { assert_eq!( wallet_id_for(network), wallet_id_for(network), "wallet id must be stable across re-derivation for {network:?}" ); } } /// The group id must be network-INDEPENDENT: the same seed yields /// the SAME group id on every network (this is what lets the Wallet /// Info "Networks" section discover a seed's sibling-network rows /// now that the scoped `walletId` differs per network). It must also /// differ from the scoped id, or grouping would collapse back into /// the per-network id and find nothing. #[test] fn group_id_is_network_independent_and_differs_from_scoped_id() { let g_main = wallet_group_id_for(Network::Mainnet); let g_test = wallet_group_id_for(Network::Testnet); let g_dev = wallet_group_id_for(Network::Devnet); let g_reg = wallet_group_id_for(Network::Regtest); // Same seed → identical group id across every network. assert_eq!(g_main, g_test, "group id must not depend on network"); assert_eq!(g_main, g_dev, "group id must not depend on network"); assert_eq!(g_main, g_reg, "group id must not depend on network"); // …but the group id is NOT the scoped id (else grouping siblings // by it would degenerate to the per-network id and miss them). assert_ne!( g_main, wallet_id_for(Network::Mainnet), "group id must differ from the network-scoped id" ); } } #[cfg(test)] mod register_wallet_duplicate_tests { use std::sync::{Arc, Mutex}; use key_wallet::mnemonic::Mnemonic; use key_wallet::wallet::initialization::WalletAccountCreationOptions; use key_wallet::Network; use crate::changeset::{ ClientStartState, PersistenceError, PlatformWalletChangeSet, PlatformWalletPersistence, }; use crate::error::PlatformWalletError; use crate::events::{EventHandler, PlatformEventHandler}; use crate::wallet::platform_wallet::WalletId; use crate::PlatformWalletManager; // Canonical all-`abandon` BIP-39 test vector. const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon \ abandon abandon abandon abandon abandon about"; /// No-op persister: lifecycle tests don't need the real persistence /// pipeline, just a handle satisfying the constructor. struct NoopPersister; impl PlatformWalletPersistence for NoopPersister { fn store( &self, _wallet_id: WalletId, _changeset: PlatformWalletChangeSet, ) -> Result<(), PersistenceError> { Ok(()) } fn flush(&self, _wallet_id: WalletId) -> Result<(), PersistenceError> { Ok(()) } fn load(&self) -> Result { Ok(ClientStartState::default()) } } struct NoopEventHandler; impl EventHandler for NoopEventHandler {} impl PlatformEventHandler for NoopEventHandler {} /// Persister that records every store round so a test can assert on /// exactly what registration hands the host. #[derive(Default)] struct RecordingPersister { stores: Mutex>, } impl PlatformWalletPersistence for RecordingPersister { fn store( &self, wallet_id: WalletId, changeset: PlatformWalletChangeSet, ) -> Result<(), PersistenceError> { self.stores.lock().unwrap().push((wallet_id, changeset)); Ok(()) } fn flush(&self, _wallet_id: WalletId) -> Result<(), PersistenceError> { Ok(()) } fn load(&self) -> Result { Ok(ClientStartState::default()) } } /// Registration must not run (or record) an identity scan: the wallet /// is downgraded to external-signable before it could, so the scan /// never reached Platform — it only left a spurious "incomplete at /// index 0" verdict and one extra host persistence round behind. /// Against the pre-fix `register_wallet` both assertions fail. #[tokio::test] async fn register_wallet_records_no_identity_scan_verdict() { let sdk = Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk")); let persister = Arc::new(RecordingPersister::default()); let event_handler: Arc = Arc::new(NoopEventHandler); let manager = Arc::new(PlatformWalletManager::new( sdk, Arc::clone(&persister), event_handler, )); let seed_bytes = Mnemonic::from_phrase(TEST_MNEMONIC) .expect("valid test mnemonic") .to_seed(""); let wallet = manager .create_wallet_from_seed_bytes( Network::Testnet, &seed_bytes, WalletAccountCreationOptions::Default, Some(0), ) .await .expect("create should succeed"); // Read the verdict out before the await below (no std guard across it). let persisted_no_scan = persister .stores .lock() .unwrap() .iter() .all(|(_, cs)| cs.identity_scan_state.is_none() && cs.identities.is_none()); assert!( persisted_no_scan, "registration must not persist an identity-scan verdict or identities" ); let wm = wallet.wallet_manager().read().await; let info = wm .get_wallet_info(&wallet.wallet_id()) .expect("wallet info"); assert!( !info .identity_manager .identity_scan_is_incomplete(&wallet.wallet_id()), "registration must not leave an incomplete-scan verdict behind" ); } /// Build a manager wired to a no-op persister over a mock SDK. The /// duplicate-create path under test never reaches the network: /// registration runs no identity discovery, so the first `create` /// returns `Ok` without a query, and the second fails at /// `WalletManager::insert_wallet` before any. fn make_manager() -> Arc> { let sdk = Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk")); let persister = Arc::new(NoopPersister); let event_handler: Arc = Arc::new(NoopEventHandler); Arc::new(PlatformWalletManager::new(sdk, persister, event_handler)) } /// Registering the SAME wallet (same mnemonic/seed + network) twice /// must surface the typed `WalletAlreadyExists` on the second call — /// NOT `WalletCreation`. This exercises the real producer path /// (`register_wallet` → `WalletManager::insert_wallet` → /// `WalletError::WalletExists` mapping) end-to-end; the prior /// isolated FFI-mapper test missed that nothing ever constructed /// `WalletAlreadyExists` on the create path. #[tokio::test] async fn duplicate_register_wallet_returns_wallet_already_exists() { let manager = make_manager(); let network = Network::Testnet; let mnemonic = Mnemonic::from_phrase(TEST_MNEMONIC).expect("valid test mnemonic"); let seed_bytes = mnemonic.to_seed(""); // First registration succeeds. `Some(0)` skips the SPV-tip // birth-height lookup so the test never consults SPV. manager .create_wallet_from_seed_bytes( network, &seed_bytes, WalletAccountCreationOptions::Default, Some(0), ) .await .expect("first create should succeed"); // Second registration of the identical (seed, network) wallet // collides on the network-scoped wallet id inside // `WalletManager::insert_wallet`. let err = manager .create_wallet_from_seed_bytes( network, &seed_bytes, WalletAccountCreationOptions::Default, Some(0), ) .await .expect_err("second create of the same wallet must fail"); assert!( matches!(err, PlatformWalletError::WalletAlreadyExists(_)), "duplicate create must map to WalletAlreadyExists, got: {err:?}" ); } /// Removing a wallet keeps its rewind barrier's state, and a same-id /// registration inherits it in the critical section that publishes it: /// advances the removed wallet emitted cannot be stored against its /// successor, and the successor's account generation starts past the /// predecessor's, so no filter batch scanned against the predecessor's /// account set is certified for it (dashpay/platform#4302 review). #[tokio::test] async fn a_same_id_registration_inherits_the_removed_wallets_barrier() { use key_wallet::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; let manager = make_manager(); let network = Network::Testnet; let mnemonic = Mnemonic::from_phrase(TEST_MNEMONIC).expect("valid test mnemonic"); let seed_bytes = mnemonic.to_seed(""); let create = |manager: Arc>| { let seed_bytes = seed_bytes.clone(); async move { manager .create_wallet_from_seed_bytes( network, &seed_bytes, WalletAccountCreationOptions::Default, Some(0), ) .await } }; let wallet_id = create(Arc::clone(&manager)) .await .expect("first create") .wallet_id(); let predecessor_generation = { // Three advances emitted and not yet drained by the adapter, and // a receival account registered. let mut wm = manager.wallet_manager.write().await; let info = wm.get_wallet_info_mut(&wallet_id).expect("info"); for _ in 0..3 { info.rewind_barrier.note_emitted(); } info.rewind_barrier.arm(); info.rewind_barrier.note_account_registered(); WalletInfoInterface::account_generation(info) }; manager.remove_wallet(&wallet_id).await.expect("remove"); assert_eq!( manager.durable_cursors.retired()[&wallet_id].in_flight, 3, "removal retires the barrier under the id" ); create(Arc::clone(&manager)).await.expect("second create"); assert!( manager.durable_cursors.retired().get(&wallet_id).is_none(), "the successor took the retired state over" ); let wm = manager.wallet_manager.read().await; let info = wm.get_wallet_info(&wallet_id).expect("published"); let retired = info.rewind_barrier.retire(0); assert_eq!( retired.in_flight, 3, "the predecessor's queued advances are carried" ); assert!(retired.epoch > 1, "the epoch moves past the predecessor's"); assert!( WalletInfoInterface::account_generation(info) > predecessor_generation, "the successor's account generation starts past the predecessor's" ); } /// The durable cursor is seeded in the critical section that publishes /// the wallet. Published first and seeded after, an adapter commit or a /// reconcile could record a newer durable height in between and the seed /// would overwrite it with the creation one. While the cursor lock is /// held the registration must not publish the wallet at all, and once it /// does, an entry an earlier same-id registration left is what the host /// holds now, so it is kept and the lower created cursor is owed to it. #[tokio::test] async fn a_wallet_is_published_and_its_durable_cursor_seeded_in_one_step() { let manager = make_manager(); let network = Network::Testnet; let mnemonic = Mnemonic::from_phrase(TEST_MNEMONIC).expect("valid test mnemonic"); let seed_bytes = mnemonic.to_seed(""); let create = |manager: Arc>| { let seed_bytes = seed_bytes.clone(); async move { manager .create_wallet_from_seed_bytes( network, &seed_bytes, WalletAccountCreationOptions::Default, Some(0), ) .await } }; let wallet_id = create(Arc::clone(&manager)) .await .expect("first create") .wallet_id(); manager.remove_wallet(&wallet_id).await.expect("remove"); let mut gate = manager.durable_cursors.lock().await; // What a removed registration might leave behind. gate.insert(wallet_id, crate::changeset::DurableCursor::at(777)); let registering = tokio::spawn(create(Arc::clone(&manager))); tokio::time::sleep(std::time::Duration::from_millis(100)).await; assert!( manager .wallet_manager .read() .await .get_wallet_info(&wallet_id) .is_none(), "no wallet may become visible while the durable-cursor lock is held" ); drop(gate); registering.await.expect("join").expect("second create"); let created_cursor = { use key_wallet::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; manager .wallet_manager .read() .await .get_wallet_info(&wallet_id) .expect("published") .core_wallet .synced_height() }; assert_eq!( manager .durable_cursors .lock() .await .get(&wallet_id) .map(|cursor| cursor.height), Some(777), "the entry the earlier registration left is what the host holds" ); assert!(created_cursor < 777); assert_eq!( manager .wallet_manager .read() .await .get_wallet_info(&wallet_id) .expect("published") .dashpay_backfill .unpersisted_cursor, Some(created_cursor), "the lower created cursor is owed" ); } /// PENDING-SPEND PROTECTION MUST SURVIVE WALLET RECREATION. /// /// If the in-broadcast fence lived in the `WalletGeneration` itself, it /// would be not merely process-local but *generation*-local. Removing a /// wallet and re-creating it under the same id mints a fresh generation, /// and the fence map would go with the old one — while the signed /// transaction it protects stays perfectly valid and can still be relayed /// by a DAPI endpoint or a peer that retained it. The re-created wallet /// would restore the persisted UTXO with neither the fence nor key-wallet's /// memory-only reservation holding it, and could sign a conflicting spend /// of the very same outpoint. /// /// Fences are therefore keyed by WALLET, not by generation: a generation /// that replaces another under the same id inherits its predecessor's /// pending-spend fences, and they are retired by the same evidence as ever — /// an observed spend — not by the replacement. /// /// Without wallet-keyed fences the re-created wallet reports no conflict /// at all. #[tokio::test] async fn a_recreated_wallet_inherits_the_pending_fences_of_the_generation_it_replaces() { use dashcore::{OutPoint, ScriptBuf, Transaction, TxIn, Txid, Witness}; let manager = make_manager(); let network = Network::Testnet; let seed_bytes = Mnemonic::from_phrase(TEST_MNEMONIC) .expect("valid test mnemonic") .to_seed(""); let wallet = manager .create_wallet_from_seed_bytes( network, &seed_bytes, WalletAccountCreationOptions::Default, Some(0), ) .await .expect("first create should succeed"); let wallet_id = wallet.wallet_id(); // One dispatch that reached the network and has NOT been observed // spent — the state that must outlive the generation holding it. let funded = OutPoint { txid: Txid::from_slice(&[0x7E; 32]).expect("valid txid"), vout: 0, }; let tx = Transaction { version: 2, lock_time: 0, input: vec![TxIn { previous_output: funded, script_sig: ScriptBuf::new(), sequence: 0xffff_ffff, witness: Witness::new(), }], output: Vec::new(), special_transaction_payload: None, }; wallet .generation() .pin_in_broadcast(&tx) .settle_pending_spend(); assert_eq!( wallet.generation().in_broadcast_conflict(&tx), Some(funded), "the dispatching wallet must fence its own pending spend" ); // Remove and re-create under the same id — the host-visible // "delete and restore this wallet" round trip. manager.remove_wallet(&wallet_id).await.expect("remove"); let recreated = manager .create_wallet_from_seed_bytes( network, &seed_bytes, WalletAccountCreationOptions::Default, Some(0), ) .await .expect("re-create should succeed"); assert_eq!( recreated.wallet_id(), wallet_id, "the re-created wallet must occupy the same id" ); assert_eq!( recreated.generation().in_broadcast_conflict(&tx), Some(funded), "a wallet re-created under the same id must inherit the pending-spend \ fence of the generation it replaced — the signed transaction that \ fence protects is still valid and still relayable" ); } /// The inheritance above is per WALLET, not global: one wallet's dispatch /// must never fence another wallet's inputs. #[tokio::test] async fn fences_do_not_leak_between_different_wallets() { use dashcore::{OutPoint, ScriptBuf, Transaction, TxIn, Txid, Witness}; let manager = make_manager(); let seed_bytes = Mnemonic::from_phrase(TEST_MNEMONIC) .expect("valid test mnemonic") .to_seed(""); // Same seed, DIFFERENT networks — key-wallet stamps a network-scoped // id, so these are two distinct wallets in one manager. let first = manager .create_wallet_from_seed_bytes( Network::Testnet, &seed_bytes, WalletAccountCreationOptions::Default, Some(0), ) .await .expect("testnet create"); let second = manager .create_wallet_from_seed_bytes( Network::Devnet, &seed_bytes, WalletAccountCreationOptions::Default, Some(0), ) .await .expect("devnet create"); assert_ne!(first.wallet_id(), second.wallet_id()); let funded = OutPoint { txid: Txid::from_slice(&[0x7F; 32]).expect("valid txid"), vout: 0, }; let tx = Transaction { version: 2, lock_time: 0, input: vec![TxIn { previous_output: funded, script_sig: ScriptBuf::new(), sequence: 0xffff_ffff, witness: Witness::new(), }], output: Vec::new(), special_transaction_payload: None, }; first .generation() .pin_in_broadcast(&tx) .settle_pending_spend(); assert_eq!( second.generation().in_broadcast_conflict(&tx), None, "a different wallet's fence must not block this one's builds" ); } } #[cfg(test)] mod persister_error_tests { //! Registration and discovery persistence: caller-owned retry policy, //! typed error propagation, and log-level policy. use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use key_wallet::mnemonic::Mnemonic; use key_wallet::wallet::initialization::WalletAccountCreationOptions; use key_wallet::Network; use tracing::Level; use zeroize::Zeroizing; use crate::changeset::{ ClientStartState, PersistenceError, PersistenceErrorKind, PlatformWalletChangeSet, PlatformWalletPersistence, }; use crate::error::PlatformWalletError; use crate::events::PlatformEventHandler; use crate::test_support::NoopTestEventHandler; use crate::wallet::platform_wallet::WalletId; use crate::PlatformWalletManager; // Canonical all-`abandon` BIP-39 test vector. const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon \ abandon abandon abandon abandon abandon about"; fn transient() -> PersistenceError { PersistenceError::backend_with_kind( PersistenceErrorKind::Transient, "simulated SQLITE_BUSY", ) } fn fatal() -> PersistenceError { PersistenceError::backend_with_kind(PersistenceErrorKind::Fatal, "simulated corruption") } use crate::test_support::tracing_capture::{RecordedEvents, RecordingGuard}; /// Persister with scripted `store` / `flush` / `load` outcomes. /// Registration and explicit discovery writes are counted separately. #[derive(Default)] struct FaultyPersister { /// Stores of the registration changeset. registration_store_calls: AtomicUsize, /// Stores of the verdict published by explicit identity discovery. scan_verdict_store_calls: AtomicUsize, /// Never scripted to fail: a `store` failure is never retried through /// it, so every assertion expects 0. flush_calls: AtomicUsize, load_calls: AtomicUsize, store_transient: bool, store_fatal: bool, /// Leading scan-verdict `store` calls that fail transiently. scan_verdict_store_transient_failures: usize, scan_verdict_store_fatal: bool, /// Leading `load` calls that fail transiently. load_transient_failures: usize, load_fatal: bool, /// Model a buffering backend that keeps the failed changeset for its /// own later retry, so re-issuing it would merge it twice. retains_failed_changeset: bool, } impl PlatformWalletPersistence for FaultyPersister { fn store_transient_is_reissuable(&self) -> bool { !self.retains_failed_changeset } fn store( &self, _wallet_id: WalletId, changeset: PlatformWalletChangeSet, ) -> Result<(), PersistenceError> { // `merge` can fold a registration write and a scan verdict into // one round, so both counters increment; letting the first match // win would reintroduce the batching dependency. let registration = changeset .wallet_metadata .is_some() .then(|| self.registration_store_calls.fetch_add(1, Ordering::SeqCst)); let verdict = changeset .identity_scan_state .is_some() .then(|| self.scan_verdict_store_calls.fetch_add(1, Ordering::SeqCst)); // Registration faults take precedence in a combined changeset. if registration.is_some() { if self.store_fatal { return Err(fatal()); } if self.store_transient { return Err(transient()); } } if let Some(n) = verdict { if self.scan_verdict_store_fatal { return Err(fatal()); } if n < self.scan_verdict_store_transient_failures { return Err(transient()); } } Ok(()) } fn flush(&self, _wallet_id: WalletId) -> Result<(), PersistenceError> { self.flush_calls.fetch_add(1, Ordering::SeqCst); Ok(()) } fn load(&self) -> Result { let n = self.load_calls.fetch_add(1, Ordering::SeqCst); if self.load_fatal { return Err(fatal()); } if n < self.load_transient_failures { return Err(transient()); } Ok(ClientStartState::default()) } } fn make_manager( persister: Arc, ) -> Arc> { let sdk = Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk")); let event_handler: Arc = Arc::new(NoopTestEventHandler); Arc::new(PlatformWalletManager::new(sdk, persister, event_handler)) } fn seed_bytes() -> Zeroizing<[u8; 64]> { Mnemonic::from_phrase(TEST_MNEMONIC) .expect("valid test mnemonic") .to_seed("") } /// `Some(0)` skips the SPV-tip birth-height lookup. async fn register( manager: &PlatformWalletManager, ) -> Result<(), PlatformWalletError> { manager .create_wallet_from_seed_bytes( Network::Testnet, &seed_bytes(), WalletAccountCreationOptions::Default, Some(0), ) .await .map(|_| ()) } /// Surfaces on the first attempt, and rolls the in-memory insert back. #[tokio::test] async fn transient_store_failure_surfaces_as_persister_store_without_retry() { let persister = Arc::new(FaultyPersister { store_transient: true, ..Default::default() }); let manager = make_manager(Arc::clone(&persister)); let err = register(&manager) .await .expect_err("a transient store failure must abort registration, not retry it"); match err { PlatformWalletError::PersisterStore(pe) => assert!( pe.is_transient(), "a transient store failure must keep its transient classification" ), other => panic!("expected PersisterStore, got {other:?}"), } assert_eq!(persister.registration_store_calls.load(Ordering::SeqCst), 1); assert_eq!( persister.flush_calls.load(Ordering::SeqCst), 0, "store is never retried via flush" ); assert_eq!( persister.scan_verdict_store_calls.load(Ordering::SeqCst), 0, "an aborted registration never reaches the discovery scan" ); assert!( manager.wallet_ids().await.is_empty(), "a failed store must roll back the in-memory wallet insert" ); } /// A persister that keeps the failed changeset buffered for its own retry /// (the canonical SQLite backend does exactly this) must never reach the /// caller as retryable: re-issuing the changeset would merge it into the /// retained copy, and changeset vectors merge by appending. #[tokio::test] async fn transient_store_failure_is_downgraded_without_a_reissue_attestation() { let persister = Arc::new(FaultyPersister { store_transient: true, retains_failed_changeset: true, ..Default::default() }); let manager = make_manager(Arc::clone(&persister)); let err = register(&manager) .await .expect_err("a transient store failure must abort registration"); match err { PlatformWalletError::PersisterStore(pe) => assert!( !pe.is_transient(), "a persister that retains the failed changeset must not invite a re-issue" ), other => panic!("expected PersisterStore, got {other:?}"), } } /// A fatal `store` failure fails fast, keeping its classification. #[tokio::test] async fn fatal_store_failure_fails_fast_without_retry() { let persister = Arc::new(FaultyPersister { store_fatal: true, ..Default::default() }); let manager = make_manager(Arc::clone(&persister)); let err = register(&manager) .await .expect_err("a fatal store must abort registration"); match err { PlatformWalletError::PersisterStore(pe) => assert!( !pe.is_transient(), "a fatal store must carry non-transient classification" ), other => panic!("expected PersisterStore, got {other:?}"), } assert_eq!(persister.registration_store_calls.load(Ordering::SeqCst), 1); assert_eq!( persister.flush_calls.load(Ordering::SeqCst), 0, "a fatal store must not be retried via flush" ); assert_eq!( persister.scan_verdict_store_calls.load(Ordering::SeqCst), 0, "an aborted registration never reaches the discovery scan" ); } /// A transient `load` is classified and left to the caller to retry. #[tokio::test] async fn transient_load_failure_surfaces_without_retry() { let persister = Arc::new(FaultyPersister { load_transient_failures: 1, ..Default::default() }); let manager = make_manager(Arc::clone(&persister)); let err = register(&manager) .await .expect_err("a transient load failure must reach the caller"); match err { PlatformWalletError::PersisterLoad(source) => assert!(source.is_transient()), other => panic!("expected transient PersisterLoad, got {other:?}"), } assert_eq!(persister.registration_store_calls.load(Ordering::SeqCst), 0); assert_eq!(persister.flush_calls.load(Ordering::SeqCst), 0); assert_eq!(persister.load_calls.load(Ordering::SeqCst), 1); assert_eq!( persister.scan_verdict_store_calls.load(Ordering::SeqCst), 0, "an aborted registration must not publish the identity-scan verdict" ); } #[tokio::test] async fn fatal_load_failure_surfaces_as_persister_load() { let persister = Arc::new(FaultyPersister { load_fatal: true, ..Default::default() }); let manager = make_manager(Arc::clone(&persister)); let err = register(&manager) .await .expect_err("a fatal load must abort registration"); match err { PlatformWalletError::PersisterLoad(pe) => assert!(!pe.is_transient()), other => panic!("expected PersisterLoad, got {other:?}"), } assert_eq!( persister.load_calls.load(Ordering::SeqCst), 1, "a fatal load must not be retried" ); } /// Nothing the wallet-event producer can persist may exist before the /// registration read runs. /// /// A transient read reports `PersisterLoad(Transient)` — FFI code 49 — /// after one attempt. This promises the host nothing was mutated and the /// registration is safe to re-issue. /// Registering the wallet in `WalletManager` first breaks that promise /// without any code in this function writing anything: the SPV filter loop /// reads the same lock, sees a wallet whose `synced_height` is behind the /// chain, and its scan emits the events that the wallet-event adapter /// commits through `store()`. /// /// Standing in for SPV from inside `load()` is what makes this /// deterministic rather than a race: the probe plays the part of a filter /// batch committing mid-read, then waits for the write it caused. No caller /// holds the wallet-manager lock across the read, and the probe releases /// its own guard before waiting. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_registration_read_precedes_any_wallet_the_event_producer_can_see() { use std::sync::atomic::AtomicBool; use std::sync::{OnceLock, Weak}; use tokio::sync::RwLock; use crate::wallet::platform_wallet::PlatformWalletInfo; use key_wallet_manager::{WalletInterface, WalletManager}; /// Fails every `load` transiently, and while doing so acts as the SPV /// filter loop: any wallet already visible in the manager gets a /// watermark advance, which reaches the persister through the live /// wallet-event adapter. struct SpvRacingPersister { wallet_manager: OnceLock>>>, store_calls: AtomicUsize, wallet_visible_during_load: AtomicBool, /// Flipped for the second phase: the backend recovers and the /// caller's retry must go through. healthy: AtomicBool, } impl PlatformWalletPersistence for SpvRacingPersister { fn store( &self, _wallet_id: WalletId, _changeset: PlatformWalletChangeSet, ) -> Result<(), PersistenceError> { self.store_calls.fetch_add(1, Ordering::SeqCst); Ok(()) } fn flush(&self, _wallet_id: WalletId) -> Result<(), PersistenceError> { Ok(()) } fn load(&self) -> Result { let manager = self .wallet_manager .get() .and_then(Weak::upgrade) .expect("the probe is wired to the manager before any registration"); // On the blocking pool, and no caller holds this lock across // the call, so blocking on it here cannot deadlock. let emitted = { let mut wallet_manager = manager.blocking_write(); match wallet_manager.get_all_wallet_infos().keys().next().copied() { Some(wallet_id) => { self.wallet_visible_during_load .store(true, Ordering::SeqCst); // What a committed filter batch does to a wallet // that was behind the chain. wallet_manager.update_wallet_synced_height(&wallet_id, 1_000); true } None => false, } }; // Guard released above: give the write this read provoked time // to actually land, so the assertions below observe a // committed store rather than a lost race. if emitted { let deadline = std::time::Instant::now() + Duration::from_secs(5); while self.store_calls.load(Ordering::SeqCst) == 0 && std::time::Instant::now() < deadline { std::thread::sleep(Duration::from_millis(10)); } } if self.healthy.load(Ordering::SeqCst) { Ok(ClientStartState::default()) } else { Err(transient()) } } } let persister = Arc::new(SpvRacingPersister { wallet_manager: OnceLock::new(), store_calls: AtomicUsize::new(0), wallet_visible_during_load: AtomicBool::new(false), healthy: AtomicBool::new(false), }); let sdk = Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk")); let event_handler: Arc = Arc::new(NoopTestEventHandler); let manager = PlatformWalletManager::new(sdk, Arc::clone(&persister), event_handler); let _ = persister .wallet_manager .set(Arc::downgrade(&manager.wallet_manager)); let seed = Mnemonic::from_phrase(TEST_MNEMONIC) .expect("valid test mnemonic") .to_seed(""); let err = manager .create_wallet_from_seed_bytes( Network::Testnet, &seed, WalletAccountCreationOptions::Default, // `Some(0)` skips the SPV-tip lookup: the birth height is not // what puts the wallet behind the chain here, the probe is. Some(0), ) .await .expect_err("a transient load failure must abort registration"); match err { PlatformWalletError::PersisterLoad(pe) => assert!( pe.is_transient(), "a transient load keeps its transient classification" ), other => panic!("expected PersisterLoad, got {other:?}"), } assert_eq!( persister.store_calls.load(Ordering::SeqCst), 0, "a failed read reports that nothing was mutated, so nothing may \ have reached the persister before it — including writes this \ function never makes itself" ); assert!( !persister.wallet_visible_during_load.load(Ordering::SeqCst), "the registration read must run before the wallet is visible in \ WalletManager: the SPV filter loop reads that map, and a wallet \ it can see is a wallet it can produce persistable events for" ); // The caller takes the retry the error invited. It can only succeed if // the aborted attempt left no wallet behind — a registration that // returned before publishing one has nothing to collide with. persister.healthy.store(true, Ordering::SeqCst); manager .create_wallet_from_seed_bytes( Network::Testnet, &seed, WalletAccountCreationOptions::Default, Some(0), ) .await .expect("the retry a transient read invites must succeed"); assert!( !persister.wallet_visible_during_load.load(Ordering::SeqCst), "the retry's read must also precede its own registration" ); } /// A transient `load` failure must leave nothing on disk to double-write. /// /// `PersisterLoad(Transient)` crosses the C ABI as code 49, which tells the /// host nothing was mutated and a later retry is safe. The only /// caller-visible operation to retry is the registration itself, so with /// the read ordered after the registration write that retry appends the /// append-only changeset a second time. #[tokio::test] async fn a_transient_load_failure_leaves_the_registration_unwritten() { let persister = Arc::new(FaultyPersister { load_transient_failures: 1, ..Default::default() }); let manager = make_manager(Arc::clone(&persister)); let err = register(&manager) .await .expect_err("a transient load failure must abort registration"); match err { PlatformWalletError::PersisterLoad(pe) => assert!( pe.is_transient(), "a transient load keeps its transient classification" ), other => panic!("expected PersisterLoad, got {other:?}"), } assert_eq!(persister.load_calls.load(Ordering::SeqCst), 1); assert_eq!( persister.registration_store_calls.load(Ordering::SeqCst), 0, "a failed read must run before the registration write: \ its error promises the caller nothing was mutated, and the retry \ it invites is the registration" ); // The caller takes that invitation. register(&manager) .await .expect("the retry a transient load failure invites must succeed"); assert_eq!( persister.registration_store_calls.load(Ordering::SeqCst), 1, "the retried registration must be the FIRST write of the changeset" ); } /// A seedless scan fails locally, publishes its verdict, and never queries Platform. async fn discover_without_resident_seed(manager: &PlatformWalletManager) { let wallet = manager .create_wallet_from_seed_bytes( Network::Testnet, &seed_bytes(), WalletAccountCreationOptions::Default, Some(0), ) .await .expect("registration succeeds without running discovery"); assert!(!wallet.state().await.wallet().has_seed()); assert_eq!( manager .persister .scan_verdict_store_calls .load(Ordering::SeqCst), 0 ); let error = wallet .identity() .discover(crate::wallet::identity::network::IdentityDiscoveryOptions { start_index: Some(0), gap_limit: 1, }) .await .expect_err("discovery requires resident key material"); assert!( matches!(error, PlatformWalletError::InvalidIdentityData(_)), "the verdict store failure must not mask the discovery failure: {error:?}" ); let wm = manager.wallet_manager.read().await; let wallet_id = wallet.wallet_id(); let verdict = wm .get_wallet_info(&wallet_id) .expect("wallet info") .identity_manager .identity_scan_state(&wallet_id) .expect("failed persistence must not discard the in-memory verdict"); assert!(!verdict.complete); assert_eq!(verdict.failed_indices, vec![0]); } /// A transient verdict-store failure is logged once, without retrying the write. #[tokio::test] async fn transient_scan_verdict_store_failure_is_logged_not_retried() { let persister = Arc::new(FaultyPersister { scan_verdict_store_transient_failures: 1, ..Default::default() }); let manager = make_manager(Arc::clone(&persister)); let recorder = RecordedEvents::default(); let _guard = RecordingGuard::install(recorder.clone()); discover_without_resident_seed(&manager).await; assert_eq!( persister.scan_verdict_store_calls.load(Ordering::SeqCst), 1, "the verdict store is attempted once, never retried" ); assert_eq!(persister.flush_calls.load(Ordering::SeqCst), 0); let events = recorder.entries(); assert!( events.iter().any(|(level, msg)| *level == Level::WARN && msg.contains("identity-scan verdict could not be persisted")), "an unpersisted scan verdict must be logged at warn: {events:?}" ); assert!( !events .iter() .any(|(level, msg)| *level == Level::ERROR && msg.contains("identity-scan verdict")), "a scan-verdict store failure must not log at error: {events:?}" ); } #[tokio::test] async fn fatal_scan_verdict_store_failure_does_not_mask_discovery_failure() { let persister = Arc::new(FaultyPersister { scan_verdict_store_fatal: true, ..Default::default() }); let manager = make_manager(Arc::clone(&persister)); discover_without_resident_seed(&manager).await; assert_eq!(persister.scan_verdict_store_calls.load(Ordering::SeqCst), 1); assert_eq!(persister.flush_calls.load(Ordering::SeqCst), 0); } /// The typed variants preserve retry classification, allow structural /// matching, and keep the `#[source]` chain. /// /// Also pins each constructor to the operation it names — the reason no /// blanket `From` exists: only the call site knows /// whether a load, a store or a flush produced the value, so an inferred /// conversion would report failed writes as failed reads. #[test] fn typed_variants_preserve_classification_matching_and_source() { use std::error::Error; let attesting = FaultyPersister { retains_failed_changeset: false, ..Default::default() }; let store_err = PlatformWalletError::from_store_failure(&attesting, transient()); match &store_err { PlatformWalletError::PersisterStore(pe) => assert!(pe.is_transient()), other => panic!("expected PersisterStore, got {other:?}"), } assert!( store_err.source().is_some(), "PersisterStore must expose its PersistenceError source" ); // The narrowing keeps the chain: a caller that downcasts for detail // still gets it, it is only told not to re-issue. let retaining = FaultyPersister { retains_failed_changeset: true, ..Default::default() }; let narrowed = PlatformWalletError::from_store_failure(&retaining, transient()); match &narrowed { PlatformWalletError::PersisterStore(pe) => assert!(!pe.is_transient()), other => panic!("expected PersisterStore, got {other:?}"), } assert!(narrowed.source().is_some()); let load_err = PlatformWalletError::from_load_failure(fatal()); match &load_err { PlatformWalletError::PersisterLoad(pe) => assert!(!pe.is_transient()), other => panic!("expected PersisterLoad, got {other:?}"), } assert!(load_err.source().is_some()); // Structural matching must recover the concrete inner variant. let restore_err = PlatformWalletError::from_restore_failure(PlatformWalletError::WalletLocked); assert!(restore_err.source().is_some()); match restore_err { PlatformWalletError::PersisterRestore(inner) => { assert!(matches!(*inner, PlatformWalletError::WalletLocked)); } other => panic!("expected PersisterRestore, got {other:?}"), } // Both take the SAME input type, so only the call site distinguishes // them and a mix-up is silent. assert!( matches!( PlatformWalletError::from_store_failure(&attesting, fatal()), PlatformWalletError::PersisterStore(_) ), "a failed store must never be reported as a failed load" ); assert!( matches!( PlatformWalletError::from_load_failure(fatal()), PlatformWalletError::PersisterLoad(_) ), "a failed load must never be reported as a failed store" ); } } /// Removal versus a same-id re-registration that lands *during* the removal. /// /// The invariant: `remove_wallet_with_teardown` removes, returns and tears down /// exactly the wallet generation it validated under that generation's lifecycle /// gate — never a different generation that appeared under the same /// `wallet_id` while the removal was in progress. #[cfg(test)] mod remove_versus_recreate_tests { use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use key_wallet::mnemonic::Mnemonic; use key_wallet::wallet::initialization::WalletAccountCreationOptions; use key_wallet::Network; use super::REMOVE_WALLET_MIDPOINT_HOOK; use crate::test_support::test_platform_wallet_manager; use crate::wallet::core::WalletGeneration; use crate::wallet::identity::state::managed_identity::ManagedIdentity; use crate::wallet::PlatformWallet; use dpp::identity::Identity; use dpp::prelude::Identifier; /// The identity id the scenario threads through both generations: G1 owns /// it (so the removal's id-keyed unregister names it), and the midpoint /// recreation re-registers it as G2's — the row the old ordering deleted. const SHARED_IDENTITY_ID: [u8; 32] = [0x1D; 32]; /// The mnemonic `test_platform_wallet_manager` builds its wallet from, so /// re-registering from the same seed collides on the same network-scoped /// `wallet_id` — which is the whole point of the scenario. const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon \ abandon abandon abandon abandon abandon about"; /// Clears [`REMOVE_WALLET_MIDPOINT_HOOK`] on drop, including on panic, so a /// failing assertion can never leave the hook armed for another test in the /// same binary. struct MidpointHookGuard; impl Drop for MidpointHookGuard { fn drop(&mut self) { if let Ok(mut slot) = REMOVE_WALLET_MIDPOINT_HOOK.lock() { *slot = None; } } } /// Requirement: a wallet generation registered while a removal is in flight /// must survive that removal — in BOTH maps — and the removal must return /// and tear down the generation it actually validated. /// /// Deterministic by construction: the re-registration runs from a rendezvous /// fired inside the removal, in the exact window between the inner-manager /// removal and the public-map removal, so there is no completion order to /// race and no sleep. The registration itself is the real /// `create_wallet_from_seed_bytes` → `register_wallet` path, publishing into /// the inner `WalletManager` and then `self.wallets` in the production /// order. /// /// Why that window is reachable in production: the removal frees the id in /// the inner manager and only then acquires `self.wallets` — two separately /// locked stages with no happens-before edge to a concurrent registration, /// which takes no lifecycle gate at all (it mints its own generation). A /// remover descheduled in that gap resumes into a map that already names the /// new generation. /// /// Before the fix the removal took the public-map entry by KEY: it evicted /// the freshly registered generation — leaving it registered in the inner /// manager but invisible and unremovable through `self.wallets` — returned /// it to the caller, and handed it to `tear_down`, which sweeps that /// generation's registry tokens and V2 finalized-transaction handles while /// holding only the OLD generation's gate. The new generation's in-flight /// payment operations were therefore not excluded, which is the one property /// the gate exists to provide. #[tokio::test] async fn removal_leaves_a_generation_registered_during_it_intact() { let (manager, wallet_id) = test_platform_wallet_manager().await; let original = manager .get_wallet(&wallet_id) .await .expect("fixture wallet is registered"); // Give G1 an owned identity + its identity-sync row, so the removal's // id-keyed unregister has a real target — the state class a same-seed // recreation re-registers under the identical identity id. let identity_id = Identifier::new(SHARED_IDENTITY_ID); { let mut wm = manager.wallet_manager.write().await; let info = wm .get_wallet_info_mut(&wallet_id) .expect("fixture wallet info"); let identity = Identity::new_with_id_and_keys( identity_id, Default::default(), dpp::version::PlatformVersion::latest(), ) .expect("bare test identity"); info.identity_manager .wallet_identities .entry(wallet_id) .or_default() .insert(0, ManagedIdentity::new(identity, 0)); } manager .identity_sync_manager .register_identity(identity_id, []) .await; // Filled by the rendezvous with the generation the re-registration // publishes, so the assertions can name it rather than infer it. let recreated: Arc>>> = Arc::new(Mutex::new(None)); let _hook_guard = MidpointHookGuard; { let manager_for_hook = Arc::clone(&manager); let recreated_slot = Arc::clone(&recreated); // One-shot: the re-registration must not recurse into a later // removal, and no other test in this binary may see the hook. let fired = AtomicBool::new(false); *REMOVE_WALLET_MIDPOINT_HOOK .lock() .expect("midpoint hook mutex") = Some(Box::new(move |id| { let already_fired = fired.swap(true, Ordering::SeqCst); let manager = Arc::clone(&manager_for_hook); let recreated_slot = Arc::clone(&recreated_slot); let id = *id; Box::pin(async move { if already_fired { return; } let mnemonic = Mnemonic::from_phrase(TEST_MNEMONIC).expect("valid test mnemonic"); let seed_bytes = mnemonic.to_seed(""); // The real registration path: inner `WalletManager` first, // then `self.wallets`. `Some(0)` skips the SPV-tip lookup. let wallet = manager .create_wallet_from_seed_bytes( Network::Testnet, &seed_bytes, WalletAccountCreationOptions::Default, Some(0), ) .await .expect( "the id is free in the inner manager at this point, so a same-seed \ re-registration must succeed", ); assert_eq!(wallet.wallet_id(), id, "the fixture seeds must collide"); // G2 re-registers the SAME identity (same seed derives the // same identities) — the id-keyed sync row the old teardown // ordering deleted after the midpoint. manager .identity_sync_manager .register_identity(Identifier::new(SHARED_IDENTITY_ID), []) .await; // G2 starts a reconcile run that is still in flight when // the removal finishes. assert!( manager .txo_reconciler() .claim_without_gate(&id, 0) .is_some(), "the recreated wallet holds no run yet" ); *recreated_slot.lock().expect("recreated slot") = Some(wallet); }) })); } // Capture what teardown was actually handed. let torn_down: Arc>>> = Arc::new(Mutex::new(None)); let torn_down_slot = Arc::clone(&torn_down); let removed = manager .remove_wallet_with_teardown(&wallet_id, move |wallet| { *torn_down_slot.lock().expect("torn-down slot") = Some(Arc::clone(wallet.generation())); }) .await .expect("removal of the validated generation succeeds"); let recreated = recreated .lock() .expect("recreated slot") .clone() .expect("the rendezvous must have re-registered the wallet"); assert!( !Arc::ptr_eq(original.generation(), recreated.generation()), "the fixture must produce two distinct generations under one wallet id" ); // 1. The removal returns the generation it validated under the gate. assert!( Arc::ptr_eq(removed.generation(), original.generation()), "remove_wallet_with_teardown returned a generation it never validated — it took the \ public-map entry by key and got the generation registered during the removal" ); // 2. …and tears down that same generation. Sweeping the other one here // would run without holding ITS gate, so its in-flight payment // operations would not be excluded. let torn_down = torn_down .lock() .expect("torn-down slot") .clone() .expect("tear_down must have run"); assert!( Arc::ptr_eq(&torn_down, original.generation()), "tear_down was handed a generation whose lifecycle gate this removal does not hold" ); // 3. The generation registered during the removal is still published. let still_registered = manager .get_wallet(&wallet_id) .await .expect("a wallet registered during a removal must remain in the public map"); assert!( Arc::ptr_eq(still_registered.generation(), recreated.generation()), "the public map must still name the generation the registration published" ); // 4. …and both maps agree about it: `is_current_generation` compares the // handle against the inner `WalletManager`, so this fails if the // removal evicted it from one map only. assert!( recreated.core().is_current_generation().await, "the re-registered generation must be live in both the inner manager and the public \ map — evicting it from one leaves an invisible, unremovable wallet" ); // 5. The removed generation is gone. assert!( !original.core().is_current_generation().await, "the validated generation must be gone from the inner manager" ); // 6. The id-keyed side-registry state the recreation installed // survived. Every id-keyed unregister ran BEFORE the inner removal // freed the wallet id, so it could only touch G1's rows — with the // old ordering (unregisters after the midpoint) this row was // deleted out from under the live G2. assert!( manager .identity_sync_manager .is_identity_registered(&identity_id) .await, "the removal's id-keyed unregister deleted the identity-sync row the recreated \ generation registered mid-removal" ); // 7. So did G2's reconcile run: the removal forgot G1's schedule // while G1 still held the id, so G2's in-flight claim is not // marked forgotten and the page it applies moves its checkpoint. let reconciler = manager.txo_reconciler(); let (_, held) = match reconciler.heal_page_held(&wallet_id, 0).await { Some(crate::manager::txo_reconcile::TxoReconcileRead::Page(page, held)) => (page, held), other => panic!("G2's claim must still read a heal page, got {other:?}"), }; drop(held); reconciler.heal_page_applied(&wallet_id); reconciler.finish( &wallet_id, crate::manager::txo_reconcile::TxoReconcileFinish::Ran, ); let next = reconciler .claim_without_gate(&wallet_id, 0) .expect("the run finished"); assert_ne!( next.start, crate::manager::txo_reconcile::TxoReconcileStart::Heal { resumed: false }, "the removal forgot the recreated wallet's in-flight run, so its applied page was \ not kept" ); reconciler.finish( &wallet_id, crate::manager::txo_reconcile::TxoReconcileFinish::NotRun, ); } }