//! Multi-wallet manager with SPV coordination. pub mod accessors; pub mod dashpay_sync; pub mod dpns_sync; pub mod identity_sync; mod load; #[cfg(test)] pub(crate) use load::pool_validations_on_this_thread; mod persistence_load; pub mod platform_address_sync; #[cfg(feature = "shielded")] pub mod shielded_sync; #[cfg(feature = "spv-context")] mod spv_quorums; #[cfg(feature = "spv-context")] pub use spv_quorums::claim_spv_quorum_lease; pub mod startup; pub mod txo_reconcile; mod wallet_lifecycle; pub(crate) use persistence_load::run_blocking_load; use std::collections::BTreeMap; use std::sync::Arc; use std::time::Duration; use dash_async::{ShutdownReport, ThreadRegistry, WorkerConfig, WorkerStatus, DEFAULT_JOIN_BUDGET}; use tokio::sync::{Notify, RwLock}; use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; use dpp::prelude::Identifier; use key_wallet::wallet::ManagedWalletInfo; use key_wallet_manager::WalletManager; use crate::changeset::{ persists_backfill_coverage, spawn_wallet_event_adapter_with_durable_cursors, CoreChangeSet, DashPayBackfillRecord, DurableCursor, DurableCursors, PlatformWalletChangeSet, PlatformWalletPersistence, }; use crate::error::PlatformWalletError; use crate::events::{PlatformEventHandler, PlatformEventManager}; use crate::manager::dashpay_sync::DashPaySyncManager; use crate::manager::dpns_sync::DpnsSyncManager; use crate::manager::identity_sync::IdentitySyncManager; use crate::manager::platform_address_sync::PlatformAddressSyncManager; #[cfg(feature = "shielded")] use crate::manager::shielded_sync::ShieldedSyncManager; use crate::manager::txo_reconcile::TxoReconcileSchedule; use crate::spv::SpvRuntime; use crate::wallet::asset_lock::LockNotifyHandler; use crate::wallet::core::{BalanceUpdateHandler, SpendObservationHandler}; use crate::wallet::identity::network::DashPayPaymentHandler; use crate::wallet::persister::WalletPersister; use crate::wallet::platform_wallet::{PlatformWalletInfo, WalletId}; #[cfg(feature = "shielded")] use crate::wallet::shielded::balance_emitter::spawn_balance_emitter; #[cfg(feature = "shielded")] use crate::wallet::shielded::{NetworkShieldedCoordinator, ShieldedBalanceUpdate}; use crate::wallet::PlatformWallet; /// Registry key identifying each background worker the manager joins at /// shutdown. /// /// The four periodic sync coordinators run their `!Send` loops on OS /// threads the shared [`ThreadRegistry`] spawns and owns end to end: it /// installs each loop's cancellation token, and /// [`shutdown`](PlatformWalletManager::shutdown) cancels and joins them — /// surfacing a panicked loop — before the host drops the tokio runtime. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum WalletWorker { /// Platform-address (BLAST / DIP-17) balance sync coordinator. PlatformAddressSync, /// Per-identity token-state sync coordinator. IdentitySync, /// DashPay (contact requests + profiles) sync coordinator. DashPaySync, /// DPNS username-marketplace sync coordinator. DpnsSync, /// Shielded (Orchard) note sync coordinator. ShieldedSync, /// SPV runtime — the network event source feeding every persister- /// visible wallet event. Not a registry worker: `SpvRuntime::stop` /// owns its teardown task and bounds only the wait for it, and /// [`shutdown`](PlatformWalletManager::shutdown) folds the stop /// outcome into the report so a failed SPV stop can never hide /// behind a clean coordinator join. Spv, /// DashPay payment-hook tasks spawned by `DashPayPaymentHandler` in /// response to SPV wallet events. Not a registry worker: the /// handler's own tracker closes admission and joins the admitted /// tasks; its drain outcome is folded into the report because those /// tasks clone the FFI persister and can fire host callbacks. DashPayPayments, /// The wallet-event adapter task — the sink coordinator stores feed /// into. Not a registry worker: joined by /// [`shutdown`](PlatformWalletManager::shutdown) under a bounded /// budget, with the live handle re-parked on timeout so a destroy /// retry can re-join it. EventAdapter, /// The shielded balance emitter task, which pushes each wallet's local /// shielded balance state to the event handlers whenever it changes. Not /// a registry worker: a tokio task spawned by `configure_shielded`, /// cancelled and joined by [`shutdown`](PlatformWalletManager::shutdown) /// under a bounded budget. Its handle stays owned until a join completes, /// so a later `shutdown` on the same manager re-joins a straggler (an FFI /// `destroy` removes the handle before it shuts down, so a repeated /// destroy cannot; there the host context lives until `release_fn` runs, /// after the straggler ends). It fires host callbacks, so a straggler is /// reported non-clean. ShieldedBalanceEmitter, } // `dash_async::RegistryKey` is a blanket impl over // `Copy + Ord + Eq + Debug + Send + Sync + 'static`, which the derives above // satisfy — no explicit impl needed. /// Deadline for a coordinator `quiesce()` drain — how long we wait for an /// in-flight pass (its `is_syncing` slot) to fall before giving up and /// reporting the coordinator non-clean. Without a bound, a pass wedged in /// a network / persister / host-callback await blocks `shutdown()` (and /// therefore the FFI's `destroy`) forever, *before* the registry's /// per-worker join budget ever gets a chance to run. A timed-out drain is /// surfaced as [`WorkerStatus::Timeout`](dash_async::WorkerStatus::Timeout) /// so `all_clean()` fails and the host keeps its callback context alive. pub(crate) const COORDINATOR_DRAIN_BUDGET: Duration = Duration::from_secs(10); /// How often a running sync loop re-checks a latched gate while the pass /// a timed-out drain gave up on still holds `is_syncing`. The loop cannot /// run a pass behind that one anyway, so instead of sleeping its normal /// interval (up to 60 s) it polls the slot at this cadence and resumes /// within about a second of the wedged pass draining. pub(crate) const LATCHED_RETRY_INTERVAL: Duration = Duration::from_secs(1); /// Deadline for draining the DashPay payment-hook tasks at shutdown. /// After it lapses each straggler is aborted and given /// [`PAYMENT_ABORT_GRACE`] to confirm termination; anything still alive /// is kept tracked and reported non-clean. pub(crate) const PAYMENT_DRAIN_BUDGET: Duration = Duration::from_secs(10); /// Post-abort confirmation grace for one payment-hook task. An abort only /// takes effect at the task's next await point, so a task stuck inside a /// synchronous persister call cannot be interrupted — after this grace it /// is left tracked (for a retry to re-join) and reported non-clean. pub(crate) const PAYMENT_ABORT_GRACE: Duration = Duration::from_secs(1); /// Deadline for joining the wallet-event adapter task at shutdown. The /// adapter exits promptly on cancellation; the bound exists so a persister /// `store` it is blocked in cannot hang `destroy`. On timeout the live /// handle is re-parked so a destroy retry re-joins it, and the report /// carries [`WorkerStatus::Timeout`](dash_async::WorkerStatus::Timeout). const EVENT_ADAPTER_JOIN_BUDGET: Duration = Duration::from_secs(10); /// Deadline for joining the shielded balance emitter at shutdown. The emitter /// observes its cancellation at every await, including the wait for a store a /// scan holds, so only a host callback it is inside can hold it up; the bound /// keeps such a callback from hanging `destroy`. The handle stays in its slot /// until a join completes, so a timeout or a dropped `shutdown` future leaves /// it for a later `shutdown` on the same manager to re-join, and the report /// carries [`WorkerStatus::Timeout`](dash_async::WorkerStatus::Timeout). The /// FFI context of a straggler stays alive until `release_fn` runs, which is /// after the straggler ends. #[cfg(feature = "shielded")] const SHIELDED_BALANCE_EMITTER_JOIN_BUDGET: Duration = Duration::from_secs(10); /// RAII holder for a coordinator's `is_syncing` slot: clears the flag on /// drop, **including panic unwind out of a pass body**. Every pass must /// hold one of these instead of storing `false` manually — a panicking /// pass that leaves `is_syncing` latched would wedge `quiesce()`'s drain /// until its budget lapses on every subsequent teardown. pub(crate) struct SyncSlotGuard<'a>(pub(crate) &'a std::sync::atomic::AtomicBool); impl Drop for SyncSlotGuard<'_> { fn drop(&mut self) { self.0.store(false, std::sync::atomic::Ordering::Release); } } /// Sync-pass admission gate shared by all four coordinators. /// /// A pass claims its coordinator's `is_syncing` slot and then checks this /// gate; when the gate is closed it releases the slot and bails without /// touching any state. The gate is what turns "no pass is in flight right /// now" into "no pass is in flight *and none can start*", which is the /// barrier Clear / reset / shutdown need before they mutate or free the /// state a pass would touch. /// /// Four independent reasons close it, deliberately kept apart: /// - an active drain ([`drain_pass`]) — the drain **counts as a holder /// from its first instruction**, so overlapping drains keep the gate /// shut for each other (see the race note on [`GateBookkeeping::holds`]), /// - a live [`QuiesceGuard`] holder — a caller that drained and is still /// mutating; the gate reopens when the last hold drops, /// - the latch — a drain that timed out leaves the gate stuck closed with /// no holder, so the wedged pass cannot be followed by a fresh one; the /// next *successful* drain clears it, as does a loop (re)start once the /// wedged pass has released `is_syncing` /// ([`reopen_if_drained`](Self::reopen_if_drained)), /// - [`seal`](Self::seal) — terminal, set by /// [`shutdown`](PlatformWalletManager::shutdown); never reopens, so a /// direct `sync_now` that was already dispatched on a host thread /// cannot start a fresh pass after the drain concluded and the FFI /// freed the callback context. #[derive(Default)] pub(crate) struct QuiesceGate { /// The single flag every pass reads — one atomic load on the hot path /// instead of taking `bookkeeping`. Only ever written while holding /// that lock, so it is always consistent with the state below. closed: std::sync::atomic::AtomicBool, /// Serializes every transition. Without it, a guard dropping (reopen) /// can interleave with another caller closing + taking a hold, and the /// stale reopen wins — leaving admission open under a live holder. /// Held for a handful of instructions and never across an `.await`. bookkeeping: std::sync::Mutex, } #[derive(Default)] struct GateBookkeeping { /// Live [`QuiesceGuard`]s — including every drain still in flight, /// which takes its hold at [`drain_pass`] entry rather than after its /// final `is_syncing` observation. The early hold is load-bearing: /// were a drain not counted until it finished, a concurrent holder's /// drop could reopen the gate in the window between the drain's last /// `is_syncing` load and its own hold, letting a direct sync claim /// the slot and pass the gate check — and the drain would then return /// "success" to a caller about to wipe state under that live pass. holds: usize, /// A drain timed out with the pass still holding `is_syncing`; keeps /// the gate closed with no holder until a later drain succeeds. latched: bool, /// Terminal close. Wins over everything. sealed: bool, } impl GateBookkeeping { fn should_close(&self) -> bool { self.sealed || self.latched || self.holds > 0 } } impl QuiesceGate { /// Whether new sync passes are currently barred. pub(crate) fn is_closed(&self) -> bool { self.closed.load(std::sync::atomic::Ordering::Acquire) } fn bookkeeping(&self) -> std::sync::MutexGuard<'_, GateBookkeeping> { // The critical sections are straight-line counter updates that // cannot panic, so the lock cannot actually be poisoned. self.bookkeeping .lock() .expect("quiesce gate mutex poisoned") } /// Recompute the hot-path flag from the bookkeeping — the ONLY writer /// of `closed`, always under the lock. fn publish_locked(&self, bookkeeping: &GateBookkeeping) { self.closed.store( bookkeeping.should_close(), std::sync::atomic::Ordering::Release, ); } /// Take a hold, closing the gate. Called at [`drain_pass`] entry (the /// drain itself is a holder) — there is no close-without-hold except /// the timeout latch and the seal. fn hold(&self) -> QuiesceGuard<'_> { let mut bookkeeping = self.bookkeeping(); bookkeeping.holds += 1; self.publish_locked(&bookkeeping); QuiesceGuard(self) } /// A drain observed the pass fully drained while holding the gate: /// clear any latch left by a previously timed-out drain. The caller /// still holds its guard, so the gate stays closed until that drops. fn drain_succeeded(&self) { let mut bookkeeping = self.bookkeeping(); bookkeeping.latched = false; self.publish_locked(&bookkeeping); } /// A drain gave up with the pass still holding `is_syncing`: latch the /// gate closed so dropping the drain's own hold cannot reopen it. fn latch_closed(&self) { let mut bookkeeping = self.bookkeeping(); bookkeeping.latched = true; self.publish_locked(&bookkeeping); } /// Clear the timeout latch if the pass it guarded has since drained. /// /// Called by a coordinator's `start()` and by its loop before each /// pass. Without it, a `quiesce` that timed out (the host saw /// `ErrorShutdownIncomplete`) leaves the latch set until *another* /// drain succeeds — and a plain restart never drains, so the new loop /// reports running while every pass bails on the closed gate. Called /// by `start()`, by the one-shot `sync_now` / per-wallet entry points /// before they claim the slot, and by the running loop after each /// pass to pick its cadence, so a stale latch never outlives the pass /// it guarded. /// /// Keeps the latch's guarantee: while `is_syncing` is still held, the /// wedged pass is the only thing that can hold it (a latched gate makes /// every new pass bail right after its CAS), so the gate stays closed /// until that pass is gone. A live hold or the seal still closes the /// gate regardless of the latch. /// /// Returns `true` when no latch remains after the call. fn reopen_if_drained(&self, is_syncing: &std::sync::atomic::AtomicBool) -> bool { let mut bookkeeping = self.bookkeeping(); if bookkeeping.latched && !is_syncing.load(std::sync::atomic::Ordering::Acquire) { bookkeeping.latched = false; } self.publish_locked(&bookkeeping); !bookkeeping.latched } /// Drop a hold, reopening the gate only if nothing else closes it. fn release(&self) { let mut bookkeeping = self.bookkeeping(); bookkeeping.holds = bookkeeping.holds.saturating_sub(1); self.publish_locked(&bookkeeping); } /// Close the gate permanently. Used by manager shutdown, after which /// no pass may ever start again on this manager instance. pub(crate) fn seal(&self) { let mut bookkeeping = self.bookkeeping(); bookkeeping.sealed = true; self.publish_locked(&bookkeeping); } } /// RAII hold on a closed [`QuiesceGate`]: keeps new passes barred for as /// long as the holder is mutating state a pass would touch, and reopens /// the gate on drop — including `?` early-return and panic unwind. /// /// Without this, `quiesce()` reopened the gate the instant it returned, so /// `clear_shielded` / `reset_platform_address_sync_state` ran their wipe /// with admission already re-opened: a direct `sync_now` on a host thread /// could snapshot pre-wipe state and re-persist it right after the wipe. #[must_use = "dropping the guard immediately reopens sync admission, which defeats the barrier"] pub(crate) struct QuiesceGuard<'a>(&'a QuiesceGate); impl Drop for QuiesceGuard<'_> { fn drop(&mut self) { self.0.release(); } } /// Shared drain body behind every coordinator's `quiesce*` family: take a /// hold on the gate so no new pass can start, cancel the loop, then wait /// for the in-flight pass (if any) to release `is_syncing`. /// /// `is_syncing` is held across a pass's persister / host-callback fan-out, /// so its falling edge *with the gate closed* is a sound "fully drained, /// nothing more will fire" signal. The hold is taken at ENTRY — before the /// first `is_syncing` observation — so the gate is closed continuously /// from here to the returned guard's drop, and no concurrent holder's /// release can open an admission window mid-drain (the race a /// close-then-hold-at-the-end sequence has). /// /// Returns a [`QuiesceGuard`] that keeps the gate closed until it drops. /// Returns `None` when the pass was still holding `is_syncing` at the /// deadline; the gate is latched closed on that path (the wedged pass /// must not be followed by a fresh one — a later successful drain clears /// the latch) and the caller must fail closed. pub(crate) async fn drain_pass<'a>( gate: &'a QuiesceGate, is_syncing: &std::sync::atomic::AtomicBool, stop: impl FnOnce(), budget: Duration, ) -> Option> { let guard = gate.hold(); stop(); let deadline = tokio::time::Instant::now() + budget; while is_syncing.load(std::sync::atomic::Ordering::Acquire) { if tokio::time::Instant::now() >= deadline { // Latch BEFORE the guard drops so there is no instant in // which the gate is open on the timeout path. gate.latch_closed(); drop(guard); return None; } tokio::time::sleep(Duration::from_millis(20)).await; } gate.drain_succeeded(); Some(guard) } /// Base [`WorkerConfig`] each coordinator starts its loop thread with — the /// registry's default managed-join budget ([`DEFAULT_JOIN_BUDGET`]) so a /// wedged loop pass surfaces as /// [`WorkerStatus::Timeout`](dash_async::WorkerStatus::Timeout) instead of /// hanging shutdown forever, and the platform default OS-thread stack. A /// coordinator that needs a deeper stack (e.g. DashPay's GroveDB proof /// descent) overrides `stack_size` on top of this. pub(crate) fn coordinator_worker_config() -> WorkerConfig { WorkerConfig { join_budget: DEFAULT_JOIN_BUDGET, stack_size: None, } } /// Multi-wallet coordinator with SPV sync and event handling. /// /// Events are dispatched through [`PlatformEventManager`] to all registered /// [`PlatformEventHandler`]s by reference (no cloning). pub struct PlatformWalletManager { pub(super) sdk: Arc, pub(super) wallet_manager: Arc>>, /// Map of registered wallets. Held in an `Arc` so the /// `BalanceUpdateHandler` can hold a clone and look up wallets to /// update their lock-free balance atomics from event-handler /// context, without touching the SPV-contended `wallet_manager` /// lock. /// /// An [`arc_swap::ArcSwap`] rather than a lock: readers take a /// wait-free snapshot that can never fail or block, which the /// balance handler depends on — the event bus neither retries nor /// coalesces, so a snapshot dropped during a lifecycle write would /// be lost for good (see `BalanceUpdateHandler`). Writers are the /// rare manager lifecycle paths (create/remove/load) and publish /// via `rcu`. That closure can run more than once under a /// concurrent-writer retry, and only the invocation whose /// compare-and-swap succeeds is published — so captured state it /// writes must be OVERWRITTEN per attempt, never accumulated across /// them. `remove_wallet`'s generation verdict and the load rollback's /// reclaimed-id list both rely on exactly that: each attempt recomputes /// its answer from the map the closure was handed, which is the same /// map the CAS compares against. pub(super) wallets: Arc>>>, /// Notified on InstantLock / ChainLock events for `AssetLockManager` waiters. pub(super) lock_notify: Arc, pub(super) spv_manager: Arc, /// Periodic platform-address (BLAST) balance sync coordinator. /// Not auto-started — call `start` after wallets are registered. pub(super) platform_address_sync_manager: Arc, /// Periodic per-identity token state sync coordinator. Refreshes /// the per-(identity, token) balance cache on every registered /// wallet. Not auto-started — call `start` after wallets are /// registered. See [`IdentitySyncManager`]. pub(super) identity_sync_manager: Arc>, /// Periodic DashPay sync coordinator. Drives `dashpay_sync()` /// (contact requests + profiles) on **every** registered wallet /// each sweep — wallet-driven, not token-registry-driven, so /// DashPay-only identities are never skipped. Shares the same /// `wallets` map as [`PlatformAddressSyncManager`]. Not /// auto-started — call `start` after wallets are registered. See /// [`DashPaySyncManager`]. pub(super) dashpay_sync_manager: Arc, /// Periodic DPNS username-marketplace sync coordinator. Drives /// `sync_dpns_marketplace()` (owned-name sale state + departure /// detection) on **every** registered wallet each sweep; shares the /// same `wallets` map as [`DashPaySyncManager`]. Not auto-started — /// call `start` after wallets are registered. See [`DpnsSyncManager`]. pub(super) dpns_sync_manager: Arc, /// Tracks asynchronous payment hooks so manager shutdown can close /// admission and drain every task before host callback contexts are freed. pub(super) dashpay_payment_handler: Arc, /// Periodic shielded (Orchard) note sync coordinator (spends are /// detected during the note scan, no separate nullifier pass). /// Iterates every wallet that has been bound via /// [`PlatformWallet::bind_shielded`](crate::wallet::PlatformWallet::bind_shielded); /// unbound wallets are skipped silently. Not auto-started — call /// `start` after wallets are registered. #[cfg(feature = "shielded")] pub(super) shielded_sync_manager: Arc, /// Network-scoped shielded coordinator. `None` until /// `configure_shielded` opens the per-network SQLite tree; /// once `Some`, every wallet's `bind_shielded` reuses the /// same `Arc>` (held inside /// the coordinator) so there's exactly one SQLite handle per /// network manager. Phase 2 will move the sync loop here /// from the per-wallet `ShieldedSyncManager` iteration; Phase /// 4 deletes `ShieldedWallet` outright and the coordinator /// owns the spend surface too. #[cfg(feature = "shielded")] pub(super) shielded_coordinator: Arc>>>, /// Cancellation token + join handle of the shielded balance emitter /// `configure_shielded` spawns for the coordinator. The token is never /// replaced: [`shutdown`](Self::shutdown) cancels it for good, and /// `configure_shielded` spawns nothing once it is cancelled. A spawn /// stores its handle under the same mutex `shutdown` takes it from after /// cancelling, so no emitter can start behind a shutdown. #[cfg(feature = "shielded")] pub(super) shielded_balance_emitter_cancel: CancellationToken, #[cfg(feature = "shielded")] pub(super) shielded_balance_emitter_join: tokio::sync::Mutex>>, /// Notified when `shutdown` starts waiting for the emitter's join, so a /// test can drop a `shutdown` future at exactly that point. #[cfg(all(test, feature = "shielded"))] pub(crate) shielded_balance_emitter_join_reached: Notify, /// Shared `PlatformEventManager` — held on the manager so /// `configure_shielded` can install a per-chunk progress handler /// onto the freshly-created `NetworkShieldedCoordinator` that /// forwards into `on_shielded_sync_progress`. Sub-managers /// (`SpvRuntime`, `PlatformAddressSyncManager`, etc.) hold their /// own clones already, so `configure_shielded` is the only /// production reader of this retained handle — hence it is gated to /// `shielded`, plus `test` so the handler-wiring test can dispatch /// an event through the manager's own fan-out. #[cfg(any(test, feature = "shielded"))] pub(super) event_manager: Arc, pub(super) persister: Arc

, /// Tracked (wallet-independent) masternodes for this manager's /// network, keyed by wire proTxHash, plus the per-node gates that /// serialize their refreshes. Hydrated from the persister at /// `load_from_persistor`; every mutation writes the whole set back /// (see `masternode::tracked`). pub(crate) tracked_masternodes: std::sync::Arc, /// Cancellation token + join handle for the wallet-event adapter /// task. Held so [`shutdown`] can stop it cleanly when the manager /// is torn down. pub(super) event_adapter_cancel: CancellationToken, pub(super) event_adapter_join: tokio::sync::Mutex>>, /// Shared lifecycle registry for the periodic coordinator threads. /// Each coordinator spawns its loop through `registry.start_thread` at /// `start`, handing the registry ownership of the OS thread and its /// cancellation token; [`shutdown`](Self::shutdown) cancels, joins, and /// reports per-worker terminal status. pub(super) registry: Arc>, /// Host-visible hard sync-fault latch. Set /// (and never cleared for this manager instance's lifetime) by the /// wallet-event adapter the first time it freezes a durable watermark /// after a persistence `store()` rejection — the one remaining fault /// trigger; the lossless persistence channel cannot drop or lag events. /// Poll via [`Self::sync_fault_detected`] to surface a "verification /// failed / rescan pending" state rather than re-freezing silently on /// the next launch. pub(super) sync_fault: Arc, /// The durable sync cursor each wallet's host last accepted, shared by /// the wallet-event adapter and the DashPay rescan reconcile — the lock /// that orders their cursor writes. See [`DurableCursors`]. pub(super) durable_cursors: DurableCursors, /// Per-WALLET in-broadcast fence maps, handed to every /// [`WalletGeneration`](crate::wallet::core::WalletGeneration) registered /// under each id. /// /// A fence describes a signed transaction that may be live on the network. /// That fact outlives the wallet *instance* that dispatched it: if removing /// a wallet and re-creating it under the same id minted a generation with /// an empty map, the re-created wallet would restore the persisted UTXO /// with nothing holding it — not the fence, not key-wallet's memory-only /// reservation — and could sign a conflicting spend of an outpoint the /// original transaction still spends. Keying the map here makes the /// replacement inherit it. /// /// **Deliberately never pruned.** A removed wallet's entry stays, because a /// removal is exactly when the protection must survive; dropping it on /// removal would reopen the recreate-after-remove hazard this exists to /// close. Growth is bounded by the number of distinct wallet ids /// this process has registered, and each entry reaps its own cleared rows /// on read. /// /// A `std::sync::Mutex`: touched only at wallet registration and load, for /// one map lookup, and never held across an await. pub(super) in_broadcast_fences: std::sync::Mutex< std::collections::BTreeMap>, >, /// The SDK provider slot this manager serves SPV quorum keys into, held /// from [`Self::serve_spv_quorums`] until [`Self::shutdown`]. #[cfg(feature = "spv-context")] pub(super) spv_quorum_lease: std::sync::Mutex>, /// The host TXO-store reconcile's steady-state edge, runs in flight and /// per-wallet cadence — see [`txo_reconcile`]. A `std::sync::Mutex`, /// never held across an await. pub(super) txo_reconcile_schedule: Arc>, } /// Keep `record`'s coverage only for the DashPay receival accounts `core` /// actually holds, and report whether anything was dropped. /// /// Coverage vouches that an account's scripts were watched; for an account /// the published wallet does not hold, nothing watches them, and a scan the /// wallet commits before the account is registered again would sit inside /// coverage that never saw it. Both publish paths apply this before /// [`PlatformWalletManager::settle_published_backfill`], which replaces the /// host's record when it reports a drop. Dropping the last entry also drops /// the extent: nothing is left for it to describe. pub(crate) fn retain_coverage_for_held_accounts( record: &mut DashPayBackfillRecord, core: &ManagedWalletInfo, ) -> bool { let held: Vec<(Identifier, Identifier, u32)> = core .accounts .dashpay_receival_accounts .keys() .map(|key| { ( Identifier::from(key.user_identity_id), Identifier::from(key.friend_identity_id), key.index, ) }) .collect(); let dropped = record.retain(|owner, contact, index| held.contains(&(*owner, *contact, index))); if dropped && record.is_empty() { *record = DashPayBackfillRecord::default(); } dropped } impl PlatformWalletManager

{ /// Create a new PlatformWalletManager. /// /// `app_handler` receives all SPV and platform events by reference. /// Internally, a `LockNotifyHandler` is also registered to wake /// `AssetLockManager` async waiters on lock events. /// /// The count of `persister`'s flushes per wallet id belongs to the /// backend instance, not to this manager, and lives as long as the /// instance does: every handle made over it counts there, so a flush /// through a handle an earlier manager gave out that drops the backend's /// buffer is seen by this manager and its wallets /// (`WalletPersister::new`). /// /// The order of durable cursor writes ([`DurableCursors`]) is still kept /// per manager, so two managers that both sync wallets over one backend /// instance are not supported. A host that replaces its manager gives /// the new one its own backend instance, as the FFI does, or stops the /// earlier manager first. pub fn new( sdk: Arc, persister: Arc

, app_handler: Arc, ) -> Self { // Take the manager's lossless, unbounded persistence receiver BEFORE // the manager is wrapped in the shared `Arc` and handed to any // producer. A broadcast subscription would drop events emitted during // startup; an `mpsc::UnboundedReceiver` buffers them instead, so // there is no subscribe-before-publish race and — being unbounded — // it can never `Lagged` and freeze the durable sync watermark. The // receiver is taken here, once, and moved into the adapter task below. let mut wallet_manager_inner = WalletManager::new(sdk.network); let event_receiver = wallet_manager_inner .take_persistence_receiver() .expect("persistence receiver is available exactly once on a fresh WalletManager"); let wallet_manager = Arc::new(RwLock::new(wallet_manager_inner)); let wallets = Arc::new(arc_swap::ArcSwap::from_pointee( std::collections::BTreeMap::new(), )); let lock_notify = Arc::new(Notify::new()); // Shared registry that owns the coordinators' loop-thread join // handles for a clean, panic-aware shutdown join. let registry = ThreadRegistry::::new(); // Host-visible hard sync-fault latch. The // adapter raises it the first time it freezes a durable watermark. let sync_fault = Arc::new(std::sync::atomic::AtomicBool::new(false)); let durable_cursors = DurableCursors::default(); // Spawn the wallet-event adapter that translates upstream // `WalletEvent`s into `CoreChangeSet`s and forwards them to // the persister. let event_adapter_cancel = CancellationToken::new(); let event_adapter_join = spawn_wallet_event_adapter_with_durable_cursors( Arc::clone(&wallet_manager), Arc::downgrade(&persister), event_receiver, Arc::clone(&sync_fault), Arc::clone(&durable_cursors), event_adapter_cancel.clone(), ); // Build handler list: app handler + internal handlers. // BalanceUpdateHandler holds a clone of the wallets map (a // wait-free `ArcSwap`, separate from the wallet_manager lock) // so it can look up PlatformWallets and write to their // lock-free balance atomics from broadcast-handler context // without contending with SPV's write lock — and without any // window in which a lifecycle write could make the lookup fail. let lock_handler = Arc::new(LockNotifyHandler::new(Arc::clone(&lock_notify))); let balance_handler = Arc::new(BalanceUpdateHandler::new(Arc::clone(&wallets))); // SpendObservationHandler releases in-broadcast input fences when the // wallet observes the fenced outpoints spent — the evidence that ends // the fence a dispatch installs. It takes the // same `wallets` map, and for the same lock reason as the balance // handler: the event fires inside SPV's block-processing write section, // so the generation cannot be resolved through the wallet-manager lock. let spend_observation_handler = Arc::new(SpendObservationHandler::new(Arc::clone(&wallets))); // DashPayPaymentHandler records incoming DashPay payments and // confirms sent ones off the wallet-event fan-out, keeping that // domain logic out of the generic core-changeset bridge. It holds // the wallet-manager (for the in-memory payment state it mutates) // and the persister (to write the resulting payment rows). let dashpay_payment_handler = Arc::new(DashPayPaymentHandler::new( Arc::clone(&wallet_manager), Arc::clone(&persister) as Arc, )); let event_manager = Arc::new(PlatformEventManager::new(vec![ app_handler, lock_handler, balance_handler, spend_observation_handler, Arc::clone(&dashpay_payment_handler) as Arc, ])); let spv = Arc::new(SpvRuntime::new( Arc::clone(&wallet_manager), Arc::clone(&event_manager), )); let platform_address_sync = Arc::new(PlatformAddressSyncManager::new( Arc::clone(&wallets), Arc::clone(&event_manager), Arc::clone(®istry), )); let identity_sync = Arc::new(IdentitySyncManager::new( Arc::clone(&sdk), Arc::clone(&persister), Arc::clone(®istry), )); // DashPay sync shares the `wallets` map (not the token // registry) so DashPay-only identities sync on every sweep. let dashpay_sync = Arc::new(DashPaySyncManager::new( Arc::clone(&wallets), Arc::clone(®istry), )); // DPNS marketplace sync also sweeps the `wallets` map; it takes // the event manager to dispatch its pass-completion event. let dpns_sync = Arc::new(DpnsSyncManager::new( Arc::clone(&wallets), Arc::clone(®istry), Arc::clone(&event_manager), )); #[cfg(feature = "shielded")] let shielded_coordinator: Arc< RwLock>>, > = Arc::new(RwLock::new(None)); #[cfg(feature = "shielded")] let shielded_sync = Arc::new(ShieldedSyncManager::new( Arc::clone(&event_manager), Arc::clone(&shielded_coordinator), Arc::clone(®istry), )); Self { sdk, wallet_manager, wallets, lock_notify, spv_manager: spv, platform_address_sync_manager: platform_address_sync, identity_sync_manager: identity_sync, dashpay_sync_manager: dashpay_sync, dpns_sync_manager: dpns_sync, dashpay_payment_handler, #[cfg(feature = "shielded")] shielded_sync_manager: shielded_sync, #[cfg(feature = "shielded")] shielded_coordinator, #[cfg(feature = "shielded")] shielded_balance_emitter_cancel: CancellationToken::new(), #[cfg(feature = "shielded")] shielded_balance_emitter_join: tokio::sync::Mutex::new(None), #[cfg(all(test, feature = "shielded"))] shielded_balance_emitter_join_reached: Notify::new(), #[cfg(any(test, feature = "shielded"))] event_manager, persister, tracked_masternodes: std::sync::Arc::new(Default::default()), event_adapter_cancel, event_adapter_join: tokio::sync::Mutex::new(Some(event_adapter_join)), registry, sync_fault, durable_cursors, in_broadcast_fences: std::sync::Mutex::new(std::collections::BTreeMap::new()), #[cfg(feature = "spv-context")] spv_quorum_lease: std::sync::Mutex::new(None), txo_reconcile_schedule: Arc::default(), } } /// Remove `wallet_id` from the inner manager, keeping its rewind /// barrier's state under the id in the shared [`DurableCursors`] for a /// successor registered under the same id (see /// [`Self::inherit_rewind_barrier`]) — and for the adapter, which drops /// the removed wallet's advances while nothing holds the id and counts /// them off this state as it does. Called under the manager write lock, /// which is what makes the hand-off atomic against the adapter. pub(super) fn remove_from_wallet_manager( &self, wm: &mut WalletManager, wallet_id: &WalletId, ) -> Result<(), key_wallet_manager::WalletError> { use key_wallet::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; let (_, info) = wm.remove_wallet(wallet_id)?; let retiring = info .rewind_barrier .retire(WalletInfoInterface::account_generation(&info)); let mut retired = self.durable_cursors.retired(); let entry = retired.entry(*wallet_id).or_default(); entry.in_flight = entry.in_flight.saturating_add(retiring.in_flight); entry.epoch = entry.epoch.max(retiring.epoch); entry.account_generation = entry.account_generation.max(retiring.account_generation); Ok(()) } /// Settle the host's DashPay backfill record for a wallet about to be /// published under `wallet_id`, holding the durable-cursor lock /// (`durable_cursors`), and return the record the wallet carries in /// memory. /// /// `record` is what the wallet would carry — its snapshot's record, /// already filtered to the receival accounts it holds — and `own_cursor` /// the scan cursor it starts from. `snapshot_cursor` is the host cursor /// the pre-lock snapshot saw; an entry in `durable_cursors` wins over it. /// `dropped` says the filter removed coverage from the snapshot's record. /// /// The host's record is replaced, before the wallet is visible to the /// scanner, when it may disagree with what the wallet carries: /// - the filter dropped coverage for accounts this wallet does not hold; /// - an entry shows a same-id wallet was published in this process — it /// may have stored or invalidated coverage after the snapshot was read; /// - the backend cannot hold the record durably and the snapshot held one. /// /// A replacement that puts coverage on the host while this wallet's cursor /// is below the host's carries that cursor, as a rewind, in the same /// round. Otherwise a crash right after it would restore the coverage /// beside a cursor the wallet never scanned up to with those accounts /// watched. The entry follows the cursor only once the round is /// committed, so a lower cursor owed later is measured against it. /// /// A backend that cannot hold the record durably /// ([`persists_backfill_coverage`](crate::changeset::persists_backfill_coverage): /// not inline, or not atomic) gets no record at all, the same as the /// rescan sweep gives it: only an empty one is written — committed with a /// `flush` where `store` only buffers — before the wallet is published, /// so a record an earlier run left cannot outlive this one. That flush is /// trusted as a wallet's handle trusts its own /// ([`WalletPersister::store_durably`]): not when another flush of the /// wallet id's records may have taken the empty record and failed, in /// which case the wallet is not published. #[allow(clippy::too_many_arguments)] pub(super) fn settle_published_backfill( &self, durable_cursors: &mut BTreeMap, wallet_id: WalletId, record: DashPayBackfillRecord, dropped: bool, own_cursor: u32, snapshot_cursor: u32, ) -> Result { let durable = persists_backfill_coverage(&*self.persister); let predecessor = durable_cursors.contains_key(&wallet_id); let held_on_host = !record.is_empty() || dropped; let record = if durable { record } else { DashPayBackfillRecord::default() }; // A backend that cannot hold the record durably never had one // written by this process, so only a record it handed back can need // invalidating; one that can is replaced when the snapshot's record // may disagree with what the wallet carries. let replace = if durable { dropped || predecessor } else { held_on_host }; if !replace { return Ok(record); } let host_cursor = durable_cursors .get(&wallet_id) .map_or(snapshot_cursor, |entry| entry.height); let cursor = (!record.is_empty() && own_cursor < host_cursor).then_some(own_cursor); tracing::info!( wallet_id = %hex::encode(wallet_id), covered = record.covered().len(), dropped, predecessor, durable, cursor = ?cursor, "the host's DashPay backfill record is replaced with the one this wallet \ carries before the wallet is published" ); let changeset = PlatformWalletChangeSet { core: cursor.map(|cursor| CoreChangeSet { synced_height: Some(cursor), synced_height_is_rewind: true, ..CoreChangeSet::default() }), dashpay_backfill: Some(record.clone()), ..PlatformWalletChangeSet::default() }; // Stored as a handle of the wallet stores a record it then acts on // (`WalletPersister::store_durably`), in the wallet id's flush ledger, // where every flush of its records is counted. A flush that fails for // good here drops what a handle of an earlier wallet under the id // still had buffered, and that handle learns of it from the ledger. // And a flush that succeeds here is not trusted by itself: a flush // by such a handle may have taken the replacement first and failed, // which the ledger shows, and the wallet is then not published. let persister = WalletPersister::new( wallet_id, Arc::clone(&self.persister) as Arc, ); persister.store_durably(changeset).map_err(|not_durable| { tracing::error!( wallet_id = %hex::encode(wallet_id), error = %not_durable, "the replaced DashPay backfill record is not known to be on the host; \ the wallet was not published" ); persister.classify_not_durable(not_durable) })?; if let Some(cursor) = cursor { durable_cursors.insert(wallet_id, DurableCursor::at(cursor)); } Ok(record) } /// Hand a newly published wallet the barrier state a removed wallet of /// the same id left behind, so advances that wallet emitted — still /// queued in, or already projected by, the shared adapter — are dropped /// rather than stored against the new wallet's scan. Called inside the /// critical section that publishes the wallet. pub(super) fn inherit_rewind_barrier( &self, wm: &mut WalletManager, wallet_id: &WalletId, ) { let retired = self.durable_cursors.retired().remove(wallet_id); if let (Some(retired), Some(info)) = (retired, wm.get_wallet_info_mut(wallet_id)) { info.rewind_barrier.inherit(retired); } } /// The in-broadcast fence map for `wallet_id`, creating it on first use. /// /// Every [`WalletGeneration`](crate::wallet::core::WalletGeneration) this /// manager mints for a wallet is built from this, so a generation that /// replaces another under the same id inherits its pending-spend fences — /// see the [`in_broadcast_fences`](Self#structfield.in_broadcast_fences) /// field docs. pub(super) fn in_broadcast_fences_for( &self, wallet_id: &WalletId, ) -> Arc { Arc::clone( self.in_broadcast_fences .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .entry(*wallet_id) .or_default(), ) } /// Whether the wallet-event adapter has frozen a durable sync /// watermark this manager's lifetime. /// /// Returns `true` once — and stays `true` for THIS manager instance's /// lifetime (a destroyed-and-recreated manager starts unlatched) — /// after a persistence `store()` was rejected, the only fault trigger: /// the lossless persistence channel cannot drop or lag events. A latch /// means the /// persisted `syncedHeight` is deliberately held behind the chain tip /// for the affected wallet and a rescan is pending on the next launch. /// Integrators poll this to /// surface a hard "verification failed / rescan pending" state instead /// of the fault being visible only in error logs. It is intentionally /// a coarse, latch-once, all-or-nothing signal (the per-wallet vs. /// global scoping lives inside the adapter); a host that needs /// per-wallet granularity should re-derive it from the persisted /// watermark vs. chain tip. pub fn sync_fault_detected(&self) -> bool { self.sync_fault.load(std::sync::atomic::Ordering::Relaxed) } /// Configure network-scoped shielded support. Opens the /// per-network commitment-tree SQLite file at `db_path` and /// installs a [`NetworkShieldedCoordinator`] that every /// subsequent `PlatformWallet::bind_shielded` will share. /// /// Must be called before any wallet's `bind_shielded` — /// per-wallet bind looks up the coordinator from the manager /// and errors out if it hasn't been configured. /// /// Once the store is open, restores the reservations of the unconfirmed /// private contact request payments of every wallet the manager holds /// whose public contact requests a load or a re-creation held for them, /// or whose id the store's journal keeps payments of, with no keys /// ([`Self::restore_private_contact_payment_holds`]). Call it right after /// [`Self::load_from_persistor`] for a wallet that bound a shielded /// account before: until then, its public contact requests are refused /// with [`PlatformWalletError::PrivateContactPaymentsNotRestored`]. /// /// Subsequent calls with the **same** `db_path` are a no-op /// (configuration is idempotent at the path level). A second /// call with a **different** path returns /// `ShieldedNotConfigured` — the SQLite handle is opened /// once per manager and can't be repointed at a different /// file mid-flight. (Design-doc choice (c): the path is a /// manager-level concern, not per-wallet.) #[cfg(feature = "shielded")] pub async fn configure_shielded( &self, db_path: impl AsRef, ) -> Result<(), crate::error::PlatformWalletError> { use crate::wallet::shielded::{FileBackedShieldedStore, NetworkShieldedCoordinator}; let db_path: std::path::PathBuf = db_path.as_ref().to_path_buf(); let mut slot = self.shielded_coordinator.write().await; if let Some(existing) = slot.as_ref() { if existing.db_path() == db_path.as_path() { let existing = Arc::clone(existing); drop(slot); // A repeat call, on the main thread of a host binding again: // a scan may hold the store, so nothing waits on it. self.restore_private_payments_without_waiting(&existing, false) .await; return Ok(()); } return Err(crate::error::PlatformWalletError::ShieldedStoreError( format!( "shielded already configured at {} — refusing to repoint at {}", existing.db_path().display(), db_path.display(), ), )); } // The store opens (and creates if missing) the SQLite // file synchronously. 100 = shardtree's max retained // checkpoints; matches the prior per-wallet default at // `PlatformWallet::bind_shielded`. let store = FileBackedShieldedStore::open_path(&db_path, 100) .map_err(crate::error::PlatformWalletError::from)?; let coordinator = Arc::new(NetworkShieldedCoordinator::new( Arc::clone(&self.sdk), self.sdk.network, db_path, store, )); // Bridge sync-internal chunk progress (~every 2048 notes) // into the public `PlatformEventHandler::on_shielded_sync_progress` // event so UI clients can render a live counter / progress // bar during long cold syncs. Cheap closure — just forwards // two u64s to the event manager. let event_manager_for_progress = Arc::clone(&self.event_manager); coordinator.install_progress_handler(Some(Arc::new( move |cumulative_scanned: u64, block_height: u64| { event_manager_for_progress .on_shielded_sync_progress(cumulative_scanned, block_height); }, ))); // Bridge sync-internal tree-commit progress (once per // committed batch) into the public // `PlatformEventHandler::on_shielded_tree_progress` event — the // second "checked / committed-to-tree" signal, distinct from // the "downloaded" counter above. `leaves_committed` is the // cumulative tree leaf count; `total_target` is the on-chain // MMR total (0 ⇒ indeterminate). Lets UI clients render a dual // ProgressView ("downloaded" vs "checked") during cold syncs. let event_manager_for_tree_progress = Arc::clone(&self.event_manager); coordinator.install_tree_progress_handler(Some(Arc::new( move |leaves_committed: u64, total_target: u64| { event_manager_for_tree_progress .on_shielded_tree_progress(leaves_committed, total_target); }, ))); // Push every wallet's local balance state to the event handlers // whenever it changes (`on_shielded_balance_changed`). Spawned under // the join mutex and only while shutdown has not cancelled the // token, so `shutdown` always finds the handle it has to join. { let mut join = self.shielded_balance_emitter_join.lock().await; if self.shielded_balance_emitter_cancel.is_cancelled() { tracing::warn!( "shielded configured after shutdown; no balance updates are emitted" ); } else { let event_manager_for_balance = Arc::clone(&self.event_manager); *join = Some(spawn_balance_emitter( Arc::clone(&coordinator), Arc::new(move |update: &ShieldedBalanceUpdate| { event_manager_for_balance.on_shielded_balance_changed(update); }), self.shielded_balance_emitter_cancel.clone(), )); } } *slot = Some(Arc::clone(&coordinator)); drop(slot); self.restore_private_contact_payment_holds(&coordinator) .await; Ok(()) } /// Restore from `coordinator`'s store, just opened, with no keys, the /// reservations of the unconfirmed private contact request payments of /// every wallet this manager holds whose contact requests wait for them, /// or whose id the store's journal keeps payments of /// ([`PlatformWallet::restore_private_contact_payments`]): a wallet /// published before the store was configured with a persister that keeps /// the private scan state, one loaded after binding a shielded account in /// an earlier process, one with an identity marking a private payment that /// may be unresolved ([`PlatformWallet::private_payments_held`]), or one /// whose id another process journaled payments under. Nothing else holds a /// store just opened, so this waits for nothing long. A wallet whose /// restoration fails stays held, until a bind, a contact request's own /// retry or a later call restores it. #[cfg(feature = "shielded")] pub(crate) async fn restore_private_contact_payment_holds( &self, coordinator: &Arc, ) { let wallets: Vec> = self.wallets.load().values().cloned().collect(); for wallet in wallets { if !wallet.private_payments_held().await && !coordinator.may_journal_private_payments_of(wallet.wallet_id()) { continue; } if let Err(error) = wallet.restore_private_contact_payments(coordinator).await { tracing::warn!( wallet_id = %hex::encode(wallet.wallet_id()), %error, "unconfirmed private contact request payments not restored; the wallet's \ contact requests stay held until a restoration succeeds" ); } } } /// [`Self::restore_private_contact_payment_holds`] for a store configured /// before, which a shielded scan may hold for minutes: none waits on the /// store ([`PlatformWallet::restore_private_payments_or_defer`]), a busy /// store deferring it to a task, the wallet held until it runs. The /// wallets still held are restored, and with `journaled_too` those whose /// id the journal may keep payments of /// (`NetworkShieldedCoordinator::may_journal_private_payments_of`, a busy /// store counting as may): a load passes it, a repeat configure does not, /// so a configure during a scan holds no wallet that was not held. #[cfg(feature = "shielded")] pub(crate) async fn restore_private_payments_without_waiting( &self, coordinator: &Arc, journaled_too: bool, ) { let wallets: Vec> = self.wallets.load().values().cloned().collect(); for wallet in wallets { if wallet.private_payments_held().await || (journaled_too && coordinator.may_journal_private_payments_of(wallet.wallet_id())) { wallet.restore_private_payments_or_defer(coordinator).await; } } } /// Before `wallet` is published: hold its contact requests until its /// private payments are restored, or restore them now. The shielded /// store's journal outlives a wallet's removal and a process's end, so a /// wallet created or loaded under an id may have payments that may still /// execute, which no marker shows and only the journal does. With a store /// configured, the journal is read now, without waiting on the store /// ([`PlatformWallet::restore_private_payments_or_defer`]): restored, the /// pairs are held through the wallet's journal mirror whether or not their /// senders are loaded yet; a busy store or a read that fails holds the /// wallet until a restoration succeeds. With none, a wallet whose persister /// keeps the private scan state is held until `configure_shielded` or a /// bind reads the journal: only such a persister lets a private payment be /// paid, so only its wallet can have journal records no marker shows. One /// that does not is never held for want of a store. #[cfg(feature = "shielded")] pub(crate) async fn hold_or_restore_private_payments(&self, wallet: &PlatformWallet) { match self.shielded_coordinator().await { Some(coordinator) => { wallet.restore_private_payments_or_defer(&coordinator).await; } None if wallet.persister().persists_private_contact_scan_state() => { wallet .persister() .hold_until_private_payments_restored() .await; } None => {} } } /// After `wallet` is published: a store configured since /// [`Self::hold_or_restore_private_payments`] found none restored the /// wallets published then, which this one was not yet, so it is restored /// here, without waiting on the store, while it is still held. #[cfg(feature = "shielded")] pub(crate) async fn restore_private_payments_configured_since(&self, wallet: &PlatformWallet) { if let Some(coordinator) = self.shielded_coordinator().await { if wallet.private_payments_held().await { wallet.restore_private_payments_or_defer(&coordinator).await; } } } /// Snapshot of the currently-installed shielded coordinator, /// or `None` if `configure_shielded` hasn't run yet on this /// manager. Cloned `Arc` so callers can hold the coordinator /// past the read-lock guard's drop. #[cfg(feature = "shielded")] pub async fn shielded_coordinator( &self, ) -> Option> { self.shielded_coordinator .read() .await .as_ref() .map(Arc::clone) } /// Tear down shielded sync state for a Clear / wipe flow. /// /// Single library entry point so the FFI stays a one-call bridge: /// first **quiesce** the sync manager (cancel the loop *and* drain /// any in-flight pass, including its persister-callback fan-out, so /// nothing can re-persist notes after this returns), then **clear** /// the network coordinator's per-subwallet registries AND reset the /// on-disk commitment-tree SQLite store. The per-network /// commitment-tree SQLite file stays on disk but its contents are /// reset to empty so the next bind cold-resyncs from index 0. /// /// # The missing-coordinator case is an ERROR, not a silent no-op /// /// Returning `Ok(())` when `shielded_coordinator()` is `None` — treating /// "no coordinator" as "nothing to clear" — masks a real on-device /// failure: the host taps Clear on a manager whose coordinator is **not /// installed on this instance** — e.g. an SDK rebuild handed the host a /// fresh `PlatformWalletManager` whose `configure_shielded` never ran (or /// ran on a different instance than the one currently syncing). The /// quiesce runs (sync loop stops), the call returns `Ok`, and the host /// then wipes its own Room/SwiftData rows — while the **on-disk /// commitment tree is never touched** (file mtime unchanged on device, no /// `reset_commitment_tree` call). The next bind reloads the still-full /// tree + its persisted watermark and re-freezes everything. /// /// The FFI only exposes this call behind a bound, shielded-enabled host /// surface (the "Clear" button), so reaching it with no coordinator is a /// genuine wiring fault, not a benign "shielded was never used" case. /// Returning an error makes the host fail closed (keep its rows) and /// surfaces the real problem instead of a phantom success. /// /// Returns an error if the coordinator is absent, or if the coordinator's /// store reset (which resets the on-disk tree to 0 leaves and verifies it) /// fails; the host must not commit its own persistence wipe in that case. #[cfg(feature = "shielded")] pub async fn clear_shielded(&self) -> Result<(), crate::error::PlatformWalletError> { // Hold the registry's per-key clearing latch across the WHOLE // quiesce -> wipe. While it is up, `ShieldedSyncManager::start` // (and any registry (re)start) is a no-op, so no fresh pass can // slip between the quiesce and the wipe and re-persist notes into // the store `coord.clear()` is about to reset. The guard's Drop // releases the latch on every exit path (including `?` and panic). let _clearing = self.registry.hold_clearing(WalletWorker::ShieldedSync); // Hold sync admission shut for the WHOLE quiesce -> wipe as well. // The clearing latch only bars registry (re)starts; a direct // `sync_now` / `sync_wallet` on a host thread does not consult it, // and a plain `quiesce()` reopens admission the instant it returns // — so such a pass could snapshot the old account set and refill // the commitment tree right after `coord.clear()` reset it. The // guard's Drop reopens admission on every exit path (`?`, panic). let Some(_quiesced) = self.shielded_sync_manager.quiesce_held().await else { // Fail closed: a pass is still holding `is_syncing` after the // drain budget, so wiping the store now would race its // persister fan-out. The host must NOT commit its own wipe. return Err(crate::error::PlatformWalletError::ShutdownIncomplete( "shielded sync pass did not drain within the quiesce budget; \ clear aborted — retry once sync is idle" .to_string(), )); }; match self.shielded_coordinator().await { Some(coord) => coord.clear().await, None => { tracing::error!( "clear_shielded: no shielded coordinator installed on this manager — the \ on-disk commitment tree cannot be reset. configure_shielded never ran on \ THIS manager instance (or ran on a different one)." ); Err(crate::error::PlatformWalletError::ShieldedStoreError( "shielded clear requested but no coordinator is configured on this manager — \ on-disk tree not reset" .to_string(), )) } } } /// Reset the platform-address (BLAST/DIP-17) incremental-sync /// watermark and drop every cached balance across **all** /// registered wallets, forcing a full rescan on the next sync. /// /// Backs the SwiftExampleApp "Clear" button. Manager-level (not /// per-wallet) to match [`clear_shielded`](Self::clear_shielded): /// the host's persistence delete is global, so a per-wallet reset /// would leave sibling wallets' in-memory watermarks to /// re-populate the deleted rows on the next sync. /// /// Quiesces the platform-address sync manager first so no in-flight /// pass can call `update_sync_state` and re-write the watermark (or /// re-seed balances) *after* the reset. Does NOT restart the loop — /// manual "Sync Now" works without it, and leaving it stopped is /// the desired UX: data stays cleared until the user explicitly /// resyncs. `quiesce` leaves the manager stopped-but-restartable. pub async fn reset_platform_address_sync_state( &self, ) -> Result<(), crate::error::PlatformWalletError> { // Same two-part exclusion as `clear_shielded`: the registry's // clearing latch bars a loop (re)start, and the held quiesce guard // bars a direct `sync_now` / `sync_wallet` for the whole // quiesce -> reset section. Both Drops run on every exit path. let _clearing = self .registry .hold_clearing(WalletWorker::PlatformAddressSync); let Some(_quiesced) = self.platform_address_sync_manager.quiesce_held().await else { // Fail closed, mirroring `clear_shielded`: resetting the // watermark while a wedged pass still holds `is_syncing` // would let its tail re-write the state this reset clears. return Err(crate::error::PlatformWalletError::ShutdownIncomplete( "platform-address sync pass did not drain within the quiesce budget; \ reset aborted — retry once sync is idle" .to_string(), )); }; // Snapshot Arc clones from the wait-free map; clone out rather // than holding the `ArcSwap` guard across the per-wallet // `.await`s below. let wallets: Vec> = self.wallets.load().values().cloned().collect(); for wallet in wallets { wallet.platform().reset_sync_state().await; } Ok(()) } /// Stop all background tasks, join their threads, and report how each /// one ended. /// /// Stops SPV and **quiesces** the periodic coordinators /// (`PlatformAddressSyncManager`, `IdentitySyncManager`, /// `DashPaySyncManager`, `ShieldedSyncManager`) — cancelling each loop /// *and draining any in-flight pass to completion*, including its /// persister / host-callback fan-out — then **joins** their loop OS /// threads through the shared [`ThreadRegistry`] and finally drains the /// wallet-event adapter task. Idempotent. /// /// Takes `&self`, so it cannot release the manager's own `Arc

` /// persister — reopening the same store additionally needs the manager /// dropped (see the [`Drop`] impl). /// /// Ordering matters and is fourfold: /// 1. SPV is stopped and joined FIRST so it cannot dispatch more wallet /// events, then payment-task admission is closed and all admitted /// DashPay payment-hook work is joined. TXO-reconcile engine guards a /// host still holds are force-released only after SPV stopped /// cleanly, never before, so no fork can land between a host's read /// and its in-flight store write; a failed stop leaves them held. /// 2. `quiesce()` each coordinator. Cancel-only `stop()` would /// let a pass already inside `sync_now` keep running and call /// `persister.store(...)` / fire a host completion callback after /// the FFI's `destroy` returned and the host freed the persister / /// event-handler context — a use-after-free. /// 3. `registry.shutdown()` then JOINS the coordinator OS threads. /// `quiesce`'s `is_syncing` barrier only proves no pass is *in /// flight*; the detached thread may still be unwinding out of /// `Handle::block_on`, touching `tokio::time` on a runtime the host /// is about to drop. Joining guarantees it has fully exited, and /// surfaces a panicked loop as a non-clean [`WorkerStatus`] rather /// than silently dropping it. /// 4. The event adapter — the sink those stores feed into — drains /// LAST. /// /// **Every phase but SPV stop's lock waits is bounded.** SPV stop /// bounds its wait for the teardown task, which it never aborts: a /// teardown still running at the deadline is reported non-clean and /// stays owned for a later stop to join. Before that deadline starts, /// SPV stop waits without bound for a concurrent start or stop and /// for client queries already in flight. The payment-hook drain is /// bounded by `PAYMENT_DRAIN_BUDGET`; the coordinator drains run /// concurrently under `COORDINATOR_DRAIN_BUDGET`; the registry join /// uses each worker's join budget; the adapter join is bounded too /// (its live handle is re-parked on timeout so a retry re-joins it). /// Past those SPV lock waits, a wedged await therefore surfaces as a /// non-clean report instead of hanging the FFI's `destroy` forever. /// A host still writing a TXO-reconcile page holds its engine guard /// through SPV stop, so SPV teardown (and anything queued on the engine /// behind it) waits for that write; a write that never ends turns into a /// timed-out SPV stop, not a hang. /// /// Returns a [`ShutdownReport`] keyed by [`WalletWorker`] — including /// the non-registry workers [`WalletWorker::Spv`], /// [`WalletWorker::DashPayPayments`], and /// [`WalletWorker::EventAdapter`], so no callback-capable background /// work is excluded from the verdict. Inspect /// [`ShutdownReport::all_clean`] before freeing the host callback /// context. A non-clean status flags a still-live worker or orphan. /// /// [`WorkerStatus`]: dash_async::WorkerStatus pub async fn shutdown(&self) -> ShutdownReport { // Stop serving SPV quorum keys before SPV stops, whether or not the // stop is clean: a stopping client must not answer proof lookups. #[cfg(feature = "spv-context")] self.withdraw_spv_quorums(); // SPV first: it is the event source feeding everything below. Its // `stop` bounds the wait for teardown but never aborts it, so a // timeout means SPV work is still live. Its outcome lands in the // report — a failed stop must not hide behind a clean coordinator join. // // A TXO reconcile's engine guard is held across one host store write // and released by the host, which may still be writing when this // runs. It is released here only AFTER SPV stopped cleanly — SPV is // what applies forks, and a fork landing under a revoked guard // before the host's write lands is exactly what the guard prevents. // Until then an SPV writer simply waits for the host's write, under // the stop's own deadline. A failed or timed-out stop releases // nothing (fail closed): the guard stays with the host's handle. let spv_status = match self.stop_spv_then_release_txo_reconcile_holds().await { Ok(()) => WorkerStatus::Ok, Err(error) => { tracing::warn!(?error, "SPV shutdown failed"); WorkerStatus::Error(error.to_string()) } }; // Close payment-hook admission and join the admitted tasks — // they clone the FFI persister, so a straggler is exactly the // callback-after-destroy hazard the report exists to catch. let payments_drained = self .dashpay_payment_handler .quiesce_within(PAYMENT_DRAIN_BUDGET) .await; // Drain the coordinators concurrently against one shared budget so // the drain phase as a whole is bounded (a wedged pass surfaces as // `Timeout` in the report instead of hanging destroy forever). // // `_sealed_` (not plain `quiesce_within`): shutdown is terminal, so // sync admission must NOT reopen when the drain returns. The FFI // resolves the manager under a shared read guard, so a `sync_now` // dispatched on a host thread can still be between its slot CAS and // its gate check while `destroy` runs; a reopened gate would let it // run a full pass — and fire persister / completion callbacks — // after `destroy` returned and the host freed those contexts. #[cfg(feature = "shielded")] let (pa_drained, id_drained, dp_drained, dpns_drained, sh_drained) = tokio::join!( self.platform_address_sync_manager .quiesce_sealed_within(COORDINATOR_DRAIN_BUDGET), self.identity_sync_manager .quiesce_sealed_within(COORDINATOR_DRAIN_BUDGET), self.dashpay_sync_manager .quiesce_sealed_within(COORDINATOR_DRAIN_BUDGET), self.dpns_sync_manager .quiesce_sealed_within(COORDINATOR_DRAIN_BUDGET), self.shielded_sync_manager .quiesce_sealed_within(COORDINATOR_DRAIN_BUDGET), ); #[cfg(not(feature = "shielded"))] let (pa_drained, id_drained, dp_drained, dpns_drained) = tokio::join!( self.platform_address_sync_manager .quiesce_sealed_within(COORDINATOR_DRAIN_BUDGET), self.identity_sync_manager .quiesce_sealed_within(COORDINATOR_DRAIN_BUDGET), self.dashpay_sync_manager .quiesce_sealed_within(COORDINATOR_DRAIN_BUDGET), self.dpns_sync_manager .quiesce_sealed_within(COORDINATOR_DRAIN_BUDGET), ); // Hard-join the coordinator loop threads now that every in-flight // pass has drained. This is the barrier `quiesce` cannot give: // it waits for the actual OS thread to terminate before the host // drops the runtime. let mut report = self.registry.shutdown().await; // Fold drain timeouts in. A timed-out drain means a pass — // possibly a *direct* `sync_now` running on a host FFI thread the // registry never sees — may still hold `is_syncing` and fire // persister callbacks, so a clean registry join must not mask it. let drains = [ (WalletWorker::PlatformAddressSync, pa_drained), (WalletWorker::IdentitySync, id_drained), (WalletWorker::DashPaySync, dp_drained), (WalletWorker::DpnsSync, dpns_drained), #[cfg(feature = "shielded")] (WalletWorker::ShieldedSync, sh_drained), ]; for (worker, drained) in drains { if !drained { let status = report .per_worker .entry(worker) .or_insert(WorkerStatus::Timeout); if status.is_clean() { *status = WorkerStatus::Timeout; } } } report.per_worker.insert(WalletWorker::Spv, spv_status); // The shielded balance emitter fires host callbacks, so it is // cancelled and joined here: once it has joined, no balance update // is delivered again. Cancelling first also stops a // `configure_shielded` racing this shutdown from spawning a new one. #[cfg(feature = "shielded")] { self.shielded_balance_emitter_cancel.cancel(); let emitter_status = { let mut slot = self.shielded_balance_emitter_join.lock().await; // Joined in place: the handle leaves the slot only once the // join completed. A timed-out join, or a caller that drops // this future mid-join while a host callback is still // running, leaves it there for the next shutdown to join. match slot.as_mut() { None => WorkerStatus::NotRunning, Some(handle) => { #[cfg(test)] self.shielded_balance_emitter_join_reached.notify_one(); match tokio::time::timeout(SHIELDED_BALANCE_EMITTER_JOIN_BUDGET, handle) .await { Ok(joined) => { *slot = None; match joined { Ok(()) => WorkerStatus::Ok, Err(e) if e.is_panic() => WorkerStatus::Panicked(e.to_string()), Err(e) => WorkerStatus::Stopped(Some(e.to_string())), } } Err(_) => { tracing::warn!( "shielded balance emitter did not join within {:?}; kept for a \ later shutdown", SHIELDED_BALANCE_EMITTER_JOIN_BUDGET ); WorkerStatus::Timeout } } } } }; report .per_worker .insert(WalletWorker::ShieldedBalanceEmitter, emitter_status); } report.per_worker.insert( WalletWorker::DashPayPayments, if payments_drained { WorkerStatus::Ok } else { WorkerStatus::Timeout }, ); // The wallet-event adapter is the sink the coordinators' stores // feed into, so it drains AFTER them. It is a plain tokio task, // not a registry worker; on a join timeout the live handle is // re-parked so a destroy retry can re-join it rather than // silently detaching the task. self.event_adapter_cancel.cancel(); let adapter_status = { let mut slot = self.event_adapter_join.lock().await; match slot.take() { None => WorkerStatus::NotRunning, Some(mut handle) => { match tokio::time::timeout(EVENT_ADAPTER_JOIN_BUDGET, &mut handle).await { Ok(Ok(())) => WorkerStatus::Ok, Ok(Err(e)) if e.is_panic() => WorkerStatus::Panicked(e.to_string()), Ok(Err(e)) => WorkerStatus::Stopped(Some(e.to_string())), Err(_) => { tracing::warn!( "wallet event adapter did not join within {:?}; re-parking", EVENT_ADAPTER_JOIN_BUDGET ); *slot = Some(handle); WorkerStatus::Timeout } } } } }; report .per_worker .insert(WalletWorker::EventAdapter, adapter_status); report } } /// Stops the wallet-event adapter task, which a dirty drop would otherwise /// leave running against a torn-down manager. /// /// Dropping the manager releases its own persister references. The idle adapter /// holds only a `Weak

`, but a drain, wallet handle, worker or in-flight read /// can retain a strong reference. Reopening the same storage path must wait /// until all such references are released; this drop does not guarantee it. /// /// **Buffered events are best-effort on this path.** Cancelling is all a `Drop` /// can do: if dropping the fields releases the last `Arc

` before the adapter /// claims it, the adapter exits with the backlog uncommitted. Nothing /// durable breaks — a wallet's sync watermark rides the same `store()` as the /// rows it implies, so the next SPV pass re-derives both. Use /// [`shutdown`](PlatformWalletManager::shutdown) for a lossless drain: it holds /// the manager, and with it the persister, alive while it joins the task, and /// reports a status back. /// /// Having a `Drop` at all changes teardown for every holder of this public /// type: a plain drop stops the adapter instead of detaching it, and the type's /// fields can no longer be moved out. impl Drop for PlatformWalletManager

{ fn drop(&mut self) { // As in `shutdown`: stop serving SPV quorum keys first. Until the lease // goes, the SDK's slot keeps this manager's SPV runtime alive. #[cfg(feature = "spv-context")] self.withdraw_spv_quorums(); // Cancel and detach, never `abort`: the task observes the token at its // next `recv` and exits after committing whatever its drain claimed the // persister for. Aborting stops it at whatever await it is parked on, // dropping a claimed batch mid-commit. self.event_adapter_cancel.cancel(); // The balance emitter exits at its next await once cancelled. #[cfg(feature = "shielded")] self.shielded_balance_emitter_cancel.cancel(); } } #[cfg(test)] mod tests { use super::*; use std::sync::OnceLock; use dash_async::WorkerStatus; use crate::changeset::flush_ledger::FlushLedgers; use crate::changeset::{ ClientStartState, FlushLedger, PersistenceError, PersistenceErrorKind, PlatformWalletChangeSet, PlatformWalletPersistence, }; use crate::events::{EventHandler, PlatformEventHandler}; 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()) } } /// Records the highest `synced_height` any `store()` carried, into state /// held OUTSIDE the persister — so a test can read the outcome after the /// persister itself has been released. struct WatermarkPersister { highest_synced_height: Arc, } impl PlatformWalletPersistence for WatermarkPersister { fn store( &self, _wallet_id: WalletId, changeset: PlatformWalletChangeSet, ) -> Result<(), PersistenceError> { if let Some(height) = changeset.core.as_ref().and_then(|core| core.synced_height) { self.highest_synced_height .fetch_max(height, std::sync::atomic::Ordering::SeqCst); } 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 {} /// A buffering backend whose flush fails for good, dropping its buffer. struct FatalFlushPersister; impl PlatformWalletPersistence for FatalFlushPersister { fn store( &self, _wallet_id: WalletId, _changeset: PlatformWalletChangeSet, ) -> Result<(), PersistenceError> { Ok(()) } fn flush(&self, _wallet_id: WalletId) -> Result<(), PersistenceError> { Err(PersistenceError::backend("the database is corrupt")) } fn load(&self) -> Result { Ok(ClientStartState::default()) } } /// The flush the manager makes itself, of the backfill record it replaces /// before a wallet is published, is counted where the handles of that /// wallet id count theirs. One that fails for good dropped what a handle /// of an earlier wallet under the id still had buffered, and that handle /// then vouches for nothing it stored: a flush of its own would succeed /// over an empty buffer. #[cfg(feature = "shielded")] #[tokio::test] async fn should_count_its_backfill_flush_in_the_wallet_ids_flush_ledger() { use crate::wallet::persister::{NotDurable, WalletPersister}; let persister = Arc::new(FatalFlushPersister); let mgr = PlatformWalletManager::new( Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk")), Arc::clone(&persister), Arc::new(NoopEventHandler) as Arc, ); let wallet_id: WalletId = [7; 32]; // As `PlatformWallet::new` makes the handle of a wallet under the id. let earlier = WalletPersister::new( wallet_id, Arc::clone(&persister) as Arc, ); assert!(!earlier.buffered_writes_lost()); // Coverage the wallet about to be published does not hold was // dropped, so the host's record is replaced and flushed. let mut cursors = mgr.durable_cursors.lock().await; let settled = mgr.settle_published_backfill( &mut cursors, wallet_id, DashPayBackfillRecord::default(), true, 5, 5, ); assert!(settled.is_err(), "the flush failed for good"); assert!( earlier.buffered_writes_lost(), "the earlier wallet's handle learns of the flush that dropped the buffer" ); assert!(matches!(earlier.flush_durably(), Err(NotDurable::Lost))); // A handle made after it starts from what is on disk. let later = WalletPersister::new( wallet_id, Arc::clone(&persister) as Arc, ); assert!(!later.buffered_writes_lost()); } /// A buffering backend whose every store is taken at once by a flush of /// another handle of the wallet id, as one from another thread would /// take it before the storer's own flush. That flush fails, for good or /// keeping what it took, and the storer's own then succeeds over a buffer /// that does not hold the record. struct OvertakenPersister { /// The ledger the other handle's flush is counted in, once known. ledger: OnceLock>, /// Whether the other flush fails for good. for_good: bool, } /// A buffering backend whose flush fails keeping what it took. struct TransientFlushPersister; impl PlatformWalletPersistence for TransientFlushPersister { fn store( &self, _wallet_id: WalletId, _changeset: PlatformWalletChangeSet, ) -> Result<(), PersistenceError> { Ok(()) } fn flush(&self, _wallet_id: WalletId) -> Result<(), PersistenceError> { Err(PersistenceError::backend_with_kind( PersistenceErrorKind::Transient, "the database is locked", )) } fn load(&self) -> Result { Ok(ClientStartState::default()) } } impl PlatformWalletPersistence for OvertakenPersister { fn store( &self, wallet_id: WalletId, _changeset: PlatformWalletChangeSet, ) -> Result<(), PersistenceError> { if let Some(ledger) = self.ledger.get() { let overtaking = if self.for_good { ledger.flush(&FatalFlushPersister, wallet_id) } else { ledger.flush(&TransientFlushPersister, wallet_id) }; assert!(overtaking.is_err(), "the other handle's flush fails"); } Ok(()) } fn flush(&self, _wallet_id: WalletId) -> Result<(), PersistenceError> { Ok(()) } fn load(&self) -> Result { Ok(ClientStartState::default()) } } /// The manager's own flush of the backfill record it replaces succeeding /// is not proof the record is on the host: a flush by a handle of an /// earlier wallet under the id may have taken it first and failed. The /// wallet is then not published, and the error says whether the record /// is gone (the other flush failed for good) or still buffered for a /// later flush (it kept what it took). #[tokio::test] async fn should_not_publish_over_a_backfill_record_another_flush_took() { for for_good in [true, false] { let persister = Arc::new(OvertakenPersister { ledger: OnceLock::new(), for_good, }); let mgr = PlatformWalletManager::new( Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk")), Arc::clone(&persister), Arc::new(NoopEventHandler) as Arc, ); let wallet_id: WalletId = [7; 32]; persister .ledger .set( FlushLedgers::of_backend( &(Arc::clone(&persister) as Arc), ) .of(wallet_id), ) .expect("set once"); // Coverage the wallet about to be published does not hold was // dropped, so the host's record is replaced and flushed. let mut cursors = mgr.durable_cursors.lock().await; let settled = mgr.settle_published_backfill( &mut cursors, wallet_id, DashPayBackfillRecord::default(), true, 5, 5, ); match settled { Err(PlatformWalletError::PersisterFlush(error)) => assert_eq!( error.is_transient(), !for_good, "to be tried again only when the record is still buffered" ), other => panic!("the wallet is not published, got {other:?}"), } } } fn make_manager() -> Arc> { let sdk = Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk")); Arc::new(PlatformWalletManager::new( sdk, Arc::new(NoopPersister), Arc::new(NoopEventHandler) as Arc, )) } /// The constructor must register [`SpendObservationHandler`] on the event /// fan-out, over the LIVE wallets map: a spend-bearing wallet event /// dispatched through the manager's /// own `event_manager` must release a registered wallet's in-broadcast /// fence. Dropping the handler from the constructor's handler list — the /// accidental-omission regression this pins — fails the final assertion, /// because nothing else on the fan-out calls `observe_spent`. #[tokio::test] async fn constructor_wires_spend_observation_into_the_event_fanout() { let mgr = make_manager(); // A funded wallet registered in the manager's live wallets map — the // same map the constructor handed to its handlers. let (wallet_manager, wallet_id, generation, _signer) = crate::test_support::funded_wallet_manager( key_wallet::account::account_type::StandardAccountType::BIP44Account, ) .await; let spv = Arc::new(SpvRuntime::new( Arc::clone(&wallet_manager), Arc::new(PlatformEventManager::new(Vec::new())), )); let wallet = Arc::new(PlatformWallet::new( Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk")), wallet_id, wallet_manager, Arc::clone(&generation), Arc::new(Notify::new()), Arc::new(NoopPersister) as Arc, Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), Arc::new(std::sync::atomic::AtomicBool::new(false)), crate::changeset::DurableCursors::default(), )); mgr.wallets.rcu(|wallets| { let mut next = std::collections::BTreeMap::clone(wallets); next.insert(wallet_id, Arc::clone(&wallet)); next }); // Fence an outpoint the way a dispatch does: pin, then settle into the // pending-spend phase that only an observed spend may end. let tx = dashcore::Transaction { version: 2, lock_time: 0, input: vec![dashcore::TxIn { previous_output: dashcore::OutPoint { txid: dashcore::Txid::from_slice(&[9u8; 32]).expect("txid"), vout: 0, }, script_sig: dashcore::ScriptBuf::new(), sequence: 0xffff_ffff, witness: dashcore::Witness::new(), }], output: Vec::new(), special_transaction_payload: None, }; generation.pin_in_broadcast(&tx).settle_pending_spend(); assert!( generation.in_broadcast_conflict(&tx).is_some(), "the settled pin must leave the pending-spend fence up" ); // The spend event, dispatched through the manager's OWN fan-out — not // a hand-built handler — so the assertion covers registration itself. mgr.event_manager .on_wallet_event(&crate::test_support::observed_spend_event(wallet_id, &tx)); assert!( generation.in_broadcast_conflict(&tx).is_none(), "a spend event through the manager's event fan-out must release \ the registered wallet's fence — is SpendObservationHandler still \ in the constructor's handler list?" ); } /// `shutdown()` joins every started coordinator through the shared /// [`ThreadRegistry`], reports each as cleanly joined, and is /// idempotent — a second call finds nothing running and still reports /// clean. This is the barrier the previous discard-the-handle `start` /// could not give: proof the loop OS threads have terminated before the /// host drops the runtime. #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn shutdown_joins_started_coordinators_and_is_idempotent() { let mgr = make_manager(); // Empty wallet/identity state, so each coordinator's first pass is a // no-op and no network I/O happens; the point is thread lifecycle. Arc::clone(&mgr.identity_sync_manager).start(); Arc::clone(&mgr.platform_address_sync_manager).start(); Arc::clone(&mgr.dashpay_sync_manager).start(); let report = mgr.shutdown().await; assert!(report.all_clean(), "clean shutdown: {report:?}"); for worker in [ WalletWorker::IdentitySync, WalletWorker::PlatformAddressSync, WalletWorker::DashPaySync, ] { assert_eq!( report.per_worker.get(&worker), Some(&WorkerStatus::Ok), "{worker:?} must join cleanly" ); } // The verdict must also cover the non-registry workers: SPV, the // DashPay payment-hook tracker, and the wallet-event adapter. A // report that omitted them could pass `all_clean()` while // callback-capable background work stayed live. for worker in [ WalletWorker::Spv, WalletWorker::DashPayPayments, WalletWorker::EventAdapter, ] { assert!( report .per_worker .get(&worker) .is_some_and(WorkerStatus::is_clean), "{worker:?} must be present and clean in the report: {report:?}" ); } // Second shutdown: the coordinators already joined, so the registry // reports them NotRunning and the report stays clean. let again = mgr.shutdown().await; assert!(again.all_clean(), "idempotent shutdown: {again:?}"); } /// A joined `shutdown()` is the lossless drain: it keeps the manager — and /// with it the persister — alive while the adapter finishes, so no /// watermark buffered on the lossless channel is lost. A dirty `Drop` /// promises nothing of the sort; see this type's `Drop` rustdoc. /// /// Drives the real manager and keeps NO strong `Arc

`: the outcome is /// read from state that outlives the persister, so no reference the test /// itself holds open can keep the drain's target alive for it. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_joined_shutdown_commits_the_watermarks_a_live_manager_buffered() { use key_wallet::mnemonic::Mnemonic; use key_wallet::wallet::initialization::WalletAccountCreationOptions; use key_wallet_manager::WalletInterface; // Canonical all-`abandon` BIP-39 test vector. const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon \ abandon abandon abandon abandon abandon about"; const TIP: u32 = 64; let highest_synced_height = Arc::new(std::sync::atomic::AtomicU32::new(0)); let persister = Arc::new(WatermarkPersister { highest_synced_height: Arc::clone(&highest_synced_height), }); let sdk = Arc::new(dash_sdk::SdkBuilder::new_mock().build().expect("mock sdk")); let manager = PlatformWalletManager::new( sdk, persister, Arc::new(NoopEventHandler) as Arc, ); // `Some(0)` skips the SPV-tip birth-height lookup, so nothing here // touches the network. let seed = Mnemonic::from_phrase(TEST_MNEMONIC) .expect("valid test mnemonic") .to_seed(""); let wallet_id = manager .create_wallet_from_seed_bytes( key_wallet::Network::Testnet, &seed, WalletAccountCreationOptions::Default, Some(0), ) .await .expect("register the test wallet") .wallet_id(); // The upstream manager is the only producer on the lossless channel; // a forward watermark advance is its cheapest event. { let mut wallet_manager = manager.wallet_manager.write().await; for height in 1..=TIP { wallet_manager.update_wallet_synced_height(&wallet_id, height); } } let report = manager.shutdown().await; assert_eq!( report.per_worker.get(&WalletWorker::EventAdapter), Some(&WorkerStatus::Ok), "the adapter must have been joined, not timed out: {report:?}" ); assert_eq!( highest_synced_height.load(std::sync::atomic::Ordering::SeqCst), TIP, "a joined shutdown must commit every watermark the manager emitted" ); } /// `reset_platform_address_sync_state` must fail closed when the /// in-flight pass does not drain: resetting watermarks and balances /// under a live pass would let that pass's tail re-persist the state /// the reset just cleared. /// /// It must also leave no lifecycle latch stuck on the failure path — /// the registry's clearing latch is released by its guard's `Drop`, so /// a later retry (or a normal `start`) is not permanently barred. #[tokio::test(start_paused = true)] async fn reset_platform_address_state_fails_closed_on_a_wedged_pass() { let mgr = make_manager(); // Wedge a pass: take the slot and never release it, as a pass stuck // in a network / persister await would. assert!(mgr.platform_address_sync().wedge_sync_slot_for_test()); let error = tokio::time::timeout( Duration::from_secs(30), mgr.reset_platform_address_sync_state(), ) .await .expect("the reset must be bounded by the drain budget, not hang") .expect_err("a wedged pass must abort the reset"); assert!( matches!( error, crate::error::PlatformWalletError::ShutdownIncomplete(_) ), "expected ShutdownIncomplete so the FFI surfaces the typed code, got {error:?}" ); assert!( !mgr.registry.is_clearing(WalletWorker::PlatformAddressSync), "the clearing latch must be released on the failure path" ); } /// A concurrent holder's drop must NOT reopen admission while another /// drain is still in flight. /// /// RED against the close-then-hold-at-the-end gate: drain B closed the /// gate but only became a *holder* after its final `is_syncing` /// observation, so holder A dropping in that window stored /// `closed = false` — a direct `sync_now` could then claim the slot, /// pass the gate check, and run a full pass that B's caller (a /// clear/reset about to wipe state) believed was impossible. With the /// hold taken at drain entry, the gate is closed continuously from /// B's first instruction to its guard's drop. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn concurrent_drain_keeps_gate_closed_across_another_holders_drop() { use std::sync::atomic::{AtomicBool, Ordering}; let gate = Arc::new(QuiesceGate::default()); let is_syncing = Arc::new(AtomicBool::new(false)); // Holder A: a completed drain (idle coordinator) holding its guard. let guard_a = drain_pass(&gate, &is_syncing, || {}, Duration::from_secs(1)) .await .expect("idle drain must succeed"); // Drain B: in flight against a wedged pass, parked in its poll // loop. The guard cannot cross the task boundary (it borrows the // task-local gate Arc), so B holds it in-task and is driven over // channels. is_syncing.store(true, Ordering::Release); let gate_b = Arc::clone(&gate); let is_syncing_b = Arc::clone(&is_syncing); let (b_drained_tx, b_drained_rx) = tokio::sync::oneshot::channel::(); let (b_release_tx, b_release_rx) = tokio::sync::oneshot::channel::<()>(); let b = tokio::spawn(async move { let guard = drain_pass(&gate_b, &is_syncing_b, || {}, Duration::from_secs(5)).await; let _ = b_drained_tx.send(guard.is_some()); // Keep the guard held (B's caller "is mutating") until driven. let _ = b_release_rx.await; drop(guard); }); // Let B take its entry hold and enter the poll loop. tokio::time::sleep(Duration::from_millis(50)).await; // A finishes its mutation and drops. The gate must STAY closed: // B's drain is still deciding whether the pass has drained. drop(guard_a); assert!( gate.is_closed(), "a holder's drop must not reopen admission while a drain is in flight" ); // Release the wedge; B's drain completes and its guard keeps the // gate closed until B's caller is done mutating. is_syncing.store(false, Ordering::Release); let b_drained = tokio::time::timeout(Duration::from_secs(2), b_drained_rx) .await .expect("drain B must complete once the pass drains") .expect("channel"); assert!(b_drained, "drain B must succeed"); assert!(gate.is_closed()); b_release_tx.send(()).expect("drive B's guard drop"); tokio::time::timeout(Duration::from_secs(2), b) .await .expect("B must finish") .expect("join"); assert!(!gate.is_closed(), "last hold gone — admission restored"); } /// The timeout latch composes with the entry-hold: a timed-out drain /// leaves the gate closed even though its own hold is gone, and only /// a later successful drain clears the latch. #[tokio::test(start_paused = true)] async fn timed_out_drain_latches_gate_closed_until_a_successful_drain() { use std::sync::atomic::{AtomicBool, Ordering}; let gate = QuiesceGate::default(); let is_syncing = AtomicBool::new(true); assert!( drain_pass(&gate, &is_syncing, || {}, Duration::from_millis(50)) .await .is_none(), "a wedged pass must time the drain out" ); assert!(gate.is_closed(), "timed-out drain leaves the gate latched"); // The wedge clears; the next drain succeeds, clears the latch, and // its guard's drop restores admission. is_syncing.store(false, Ordering::Release); let guard = drain_pass(&gate, &is_syncing, || {}, Duration::from_millis(50)) .await .expect("drain must succeed once the pass drained"); assert!(gate.is_closed()); drop(guard); assert!(!gate.is_closed(), "successful drain clears the latch"); } /// `reopen_if_drained` is what a loop (re)start uses to clear a /// timeout latch: it must keep the gate closed while the wedged pass /// still holds `is_syncing`, clear the latch once that pass is gone, /// and never override a live hold or the seal. #[tokio::test(start_paused = true)] async fn reopen_if_drained_keeps_latch_while_pass_in_flight_and_clears_it_after() { use std::sync::atomic::{AtomicBool, Ordering}; let gate = QuiesceGate::default(); let is_syncing = AtomicBool::new(true); assert!( drain_pass(&gate, &is_syncing, || {}, Duration::from_millis(50)) .await .is_none(), "a wedged pass must time the drain out" ); assert!(gate.is_closed(), "timed-out drain leaves the gate latched"); // The wedged pass is still running: the latch must hold. assert!( !gate.reopen_if_drained(&is_syncing), "latch must survive while the wedged pass holds is_syncing" ); assert!(gate.is_closed()); // The wedged pass finished: a restart may clear the latch itself. is_syncing.store(false, Ordering::Release); assert!(gate.reopen_if_drained(&is_syncing)); assert!(!gate.is_closed(), "cleared latch reopens admission"); // Idempotent on an open gate. assert!(gate.reopen_if_drained(&is_syncing)); assert!(!gate.is_closed()); // A live hold still closes the gate even though the latch is clear. is_syncing.store(true, Ordering::Release); assert!( drain_pass(&gate, &is_syncing, || {}, Duration::from_millis(50)) .await .is_none(), "a wedged pass must time the drain out" ); is_syncing.store(false, Ordering::Release); let hold = gate.hold(); assert!(gate.reopen_if_drained(&is_syncing), "latch is cleared"); assert!(gate.is_closed(), "but the live hold keeps the gate closed"); drop(hold); assert!(!gate.is_closed()); // The seal wins over everything. gate.seal(); assert!(gate.reopen_if_drained(&is_syncing)); assert!(gate.is_closed(), "a sealed gate never reopens"); } /// `SyncSlotGuard` must clear the `is_syncing` slot on panic unwind, /// not just on normal fall-through. Without this, a pass that panics /// leaves the flag latched and every subsequent `quiesce()` drain /// burns its full budget before reporting non-clean — turning one /// panicked pass into a permanently wedged (slow, never-clean) /// teardown. #[test] fn sync_slot_guard_clears_flag_on_panic_unwind() { let flag = std::sync::atomic::AtomicBool::new(true); let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let _slot = SyncSlotGuard(&flag); panic!("pass body panicked"); })); assert!(result.is_err(), "the pass body must have panicked"); assert!( !flag.load(std::sync::atomic::Ordering::Acquire), "guard must clear the slot during unwind" ); } /// A balance snapshot delivered while a lifecycle write to the /// `wallets` map is in flight must still land in the wallet's /// lock-free balance atomics. The event bus neither retries nor /// coalesces, so a snapshot dropped here is gone for good: the /// wallet keeps displaying the superseded totals until some later /// event happens to carry a fresh balance, and nothing guarantees /// one arrives. /// /// When the map was a `tokio::sync::RwLock` and the handler used /// `try_read()`, this exact delivery-under-contention scenario /// dropped the snapshot (the pre-fix form of this test held /// `wallets.write()` across the delivery and failed). With the map /// an `ArcSwap`, the closest reachable window is a lifecycle writer /// parked mid-`rcu`; the handler's `load()` must observe a committed /// map and apply the balance immediately, before that writer /// completes. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn balance_snapshot_survives_wallets_map_write_contention() { use std::collections::BTreeMap; use crate::test_support::test_platform_wallet_manager; use crate::wallet::core::BalanceUpdateHandler; use key_wallet::wallet::balance::WalletCoreBalance; let (manager, wallet_id) = test_platform_wallet_manager().await; let wallet = manager .get_wallet(&wallet_id) .await .expect("fixture wallet is registered"); // The production unit under test, holding the same map the // manager registers at construction. let handler = BalanceUpdateHandler::new(Arc::clone(&manager.wallets)); // Park a lifecycle writer mid-publication: its `rcu` closure has // read the current map but not yet committed the replacement. // This pins open the window in which the old lock-based map // made `try_read()` fail and lose the event. let (entered_tx, entered_rx) = std::sync::mpsc::channel::<()>(); let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); let wallets_for_writer = Arc::clone(&manager.wallets); let writer = std::thread::spawn(move || { // `rcu` re-runs its closure if the compare-and-swap loses, so the // release must be waited on ONCE: a second `recv()` would block // forever on a channel the test only sends to once, and // `writer.join()` below would hang the suite instead of failing // it. Nothing else writes this map today, so the retry is latent // — which is exactly why it must not be able to wedge the test. let mut parked = false; wallets_for_writer.rcu(|current| { if !parked { parked = true; let _ = entered_tx.send(()); let _ = release_rx.recv(); } Arc::clone(current) }); }); entered_rx .recv() .expect("the writer must reach its rcu closure"); // Deliver the balance-bearing event while the write is in flight. let corrected = WalletCoreBalance::new(1_234, 0, 0, 0); handler.on_wallet_event(&crate::events::WalletEvent::BlockProcessed { wallet_id, height: 1_000, chain_lock: None, inserted: vec![], updated: vec![], matured: vec![], balance: corrected, account_balances: BTreeMap::new(), addresses_derived: vec![], }); // Observable immediately — before the lifecycle writer commits. assert_eq!( wallet.balance().confirmed(), corrected.confirmed(), "the balance snapshot was dropped: a lifecycle write to the wallets map \ was in flight during delivery, and the bus will not re-deliver it" ); release_tx.send(()).expect("writer still parked"); writer.join().expect("writer thread completes"); } /// A dirty drop CANCELS the wallet-event adapter; it must never `abort` it. /// An aborted task dies at whatever await it is parked on, taking with it /// the events it had already pulled off the lossless channel — the loss the /// channel exists to rule out. The parked sentinel below stands in for an /// adapter mid-batch: it can only finish if the drop left it running. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn dropping_the_manager_does_not_abort_the_adapter_task() { let manager = make_manager(); let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>(); let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>(); let sentinel = tokio::spawn(async move { let _ = release_rx.await; let _ = done_tx.send(()); }); // Park the sentinel where the real adapter's handle lives, so the drop // path acts on it. The displaced adapter has its own cancel token and // exits on its own. manager.event_adapter_join.lock().await.replace(sentinel); drop(manager); release_tx .send(()) .expect("the adapter task was aborted on drop: its receiver is already gone"); tokio::time::timeout(std::time::Duration::from_secs(5), done_rx) .await .expect("the parked adapter task never resumed after the manager was dropped") .expect("the adapter task was aborted on drop: it never finished"); } }