diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift index 43349fb73e..8465cd7086 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift @@ -157,10 +157,23 @@ final class SwiftDashSDKWalletRuntime: NSObject { /// turn "Sync Now" into a real in-session recovery action after Stop or a /// recover-time binding race. func rearmPlatformSync() async { - let task = enqueueAwaitable { [weak self] in - await self?.refresh(trigger: .platformSyncRearm) - } - await task.value + await awaitRefresh(trigger: .platformSyncRearm) + } + + /// Rebuild the shared runtime after the SwiftData rows it loaded from were + /// edited underneath it, and return once that rebuild has settled (started, + /// or failed back to a stopped runtime). + /// + /// Runs the same serialized stop → load → start the lifecycle queue drives + /// for a network or wallet switch: on load the Rust wallet rehydrates its + /// tx set, UTXOs and `spent_outpoints` from the rows as they now are, and + /// dash-spv's mempool tracker restarts without the deleted transactions. + /// + /// `.walletRowsChanged` is never elided by `shouldSkipRefresh`: a runtime + /// that still looks ready is precisely the one holding the pre-edit state + /// this call exists to discard. + func reloadAfterWalletRowsChanged() async { + await awaitRefresh(trigger: .walletRowsChanged) } /// Restart Core SPV to dial a fresh peer set ("sync too slow? change @@ -393,6 +406,16 @@ final class SwiftDashSDKWalletRuntime: NSObject { } } + /// Awaiting sibling of `enqueueRefresh`: appends the same single + /// `refresh(trigger:)` op to the serial chain and returns only once it — + /// and every op queued ahead of it — has finished. Callers that must + /// observe the rebuilt runtime go through here. + private func awaitRefresh(trigger: RefreshTrigger) async { + await enqueueAwaitable { [weak self] in + await self?.refresh(trigger: trigger) + }.value + } + private func enqueueFullReset(lastError: String?, forWipe: Bool) { enqueue { [weak self] in await self?.fullReset(lastError: lastError, forWipe: forWipe) @@ -468,6 +491,17 @@ final class SwiftDashSDKWalletRuntime: NSObject { // bound so identity/banner consumers re-read destination // state instead of the cleared transition mirror. publishActiveWalletDidChange(reason: "network-changed") + } else if trigger == .walletRowsChanged { + // A rows-changed rebuild rebinds the wallet just like the + // two above, and it can resolve a network key that an + // interactive switch has ALREADY flipped while its own + // refresh is still queued behind this one. That switch's + // refresh then finds the destination runtime ready and + // elides, taking its "network-changed" publish with it — + // so publish here too, or consumers that listen only for + // this notification (SwiftDashSDKContactsService) keep a + // pre-switch snapshot. + publishActiveWalletDidChange(reason: "wallet-rows-changed") } } catch { Self.logger.error("🧭 RUNTIME :: start failed: \(String(describing: error), privacy: .public)") @@ -527,11 +561,14 @@ final class SwiftDashSDKWalletRuntime: NSObject { private func shouldSkipRefresh(for network: Network, trigger: RefreshTrigger) -> Bool { switch trigger { - case .walletMaterialChanged, .walletDidChange: + case .walletMaterialChanged, .walletDidChange, .walletRowsChanged: // A runtime wallet switch always rebuilds — the active-wallet // registry was repointed to a different wallet on the SAME // network, so `currentNetwork == network` would otherwise wrongly - // elide the rebind. + // elide the rebind. A rows-changed rebuild always runs for the + // mirror-image reason: the SwiftData rows were edited behind a + // runtime that never stopped, so a runtime that looks ready is + // exactly the one still holding the pre-edit in-memory wallet. return false case .startIfReady, .networkDidChange, .platformSyncRearm: return isRuntimeReady(for: network) @@ -639,6 +676,7 @@ final class SwiftDashSDKWalletRuntime: NSObject { case networkDidChange case walletMaterialChanged case walletDidChange + case walletRowsChanged case platformSyncRearm } diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UnconfirmedTransactionRemover.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UnconfirmedTransactionRemover.swift index cfd1781a7a..0a6dda44ab 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UnconfirmedTransactionRemover.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UnconfirmedTransactionRemover.swift @@ -56,6 +56,22 @@ struct UnconfirmedTransactionRemover { subsystem: "org.dashfoundation.dash", category: "swift-sdk-migration.unconfirmed-tx-remover") + /// What the removal achieved beyond deleting the rows. The rows are gone + /// in every case; the cases differ in how much of the recovery path behind + /// them ran, so a caller never has to claim more than actually happened. + enum RemovalOutcome { + /// Runtime reloaded and the recovery filter rescan is running. + case rescanArmed + /// Runtime reloaded, but the rescan did not arm (no chain tip to + /// anchor on, or the arm threw). Rescan Filters still works. + case rescanUnavailable + /// The reload took the runtime down and it did not come back: a BLAST + /// start failure makes `refresh` fall back to `fullReset`, which stops + /// the host and Core SPV too. Rescan Filters refuses while SPV is + /// stopped, so this case must NOT point the user at it. + case runtimeStopped + } + enum RemovalError: LocalizedError { case notReady case transactionNotFound @@ -89,13 +105,13 @@ struct UnconfirmedTransactionRemover { /// estimate (~1 day), covering clock skew and variable block times. private static let rescanMarginBlocks: UInt32 = 576 - /// - Returns: whether the recovery filter rescan was armed. `false` - /// means the removal itself succeeded but the rescan didn't start - /// (SPV not running / arm threw) — the caller should tell the user - /// to run Rescan Filters manually so the safety net isn't silently - /// skipped. + /// - Returns: how far past the row deletion the removal got. Anything + /// other than `.rescanArmed` means the safety net didn't start, and + /// `.runtimeStopped` additionally means the wallet runtime is down — + /// the caller must say so rather than pointing at Rescan Filters, + /// which refuses while SPV is stopped. @discardableResult - func remove(txidWire: Data) async throws -> Bool { + func remove(txidWire: Data) async throws -> RemovalOutcome { guard let container = SwiftDashSDKHost.shared.modelContainer, let network = WalletEnvironment.network, let walletId = WalletEnvironment.activeWalletId(for: WalletEnvironment.networkKind) else { @@ -161,19 +177,19 @@ struct UnconfirmedTransactionRemover { /// a dropped transaction that IS on the blockchain is re-matched and /// restored by it. Nothing is sent to the network. /// - /// - Returns: how many transactions were dropped (0 = nothing to - /// drop; no reload or rescan runs, so `rescanArmed` is `false`), - /// and whether the recovery rescan was armed — `false` after a - /// non-zero drop means the caller must tell the user to run - /// Rescan Filters manually. - func dropAllUnconfirmedAndRescan() async throws -> (dropped: Int, rescanArmed: Bool) { + /// - Returns: how many transactions were dropped (0 = nothing to drop; + /// no reload or rescan runs, so the outcome is `.rescanUnavailable`), + /// and how far the removal tail got. `.runtimeStopped` after a + /// non-zero drop means the wallet runtime is down, so the caller must + /// not offer Rescan Filters as the remedy. + func dropAllUnconfirmedAndRescan() async throws -> (dropped: Int, outcome: RemovalOutcome) { guard let container = SwiftDashSDKHost.shared.modelContainer, let walletId = WalletEnvironment.activeWalletId(for: WalletEnvironment.networkKind) else { throw RemovalError.notReady } let context = container.mainContext let rows = try Self.unconfirmedRows(in: context, walletId: walletId) - guard !rows.isEmpty else { return (dropped: 0, rescanArmed: false) } + guard !rows.isEmpty else { return (dropped: 0, outcome: .rescanUnavailable) } var oldestFirstSeen = UInt64.max var displayTxids: [String] = [] @@ -188,9 +204,9 @@ struct UnconfirmedTransactionRemover { try context.save() Self.logger.notice("🗑️ TX-REMOVE :: bulk-dropped \(rows.count, privacy: .public) unconfirmed tx(s): \(displayTxids.joined(separator: ","), privacy: .public)") - let rescanArmed = await Self.finishRemoval( + let outcome = await Self.finishRemoval( txidsWire: txidsWire, walletId: walletId, oldestFirstSeen: oldestFirstSeen) - return (dropped: rows.count, rescanArmed: rescanArmed) + return (dropped: rows.count, outcome: outcome) } /// The active wallet's unconfirmed (mempool-context, no block) rows — @@ -250,13 +266,12 @@ struct UnconfirmedTransactionRemover { /// Shared removal tail, after the rows are deleted and saved: /// app-side metadata cleanup, full runtime reload, filter rescan, - /// and cache refresh. Returns whether the rescan was armed — the - /// rescan is the recovery step that restores a wrongly-removed - /// on-chain transaction, so callers surface `false` to the user - /// instead of claiming a complete recovery. + /// and cache refresh. The rescan is the recovery step that restores a + /// wrongly-removed on-chain transaction, so anything short of + /// `.rescanArmed` is surfaced instead of claiming a complete recovery. private static func finishRemoval( txidsWire: [Data], walletId: Data, oldestFirstSeen: UInt64 - ) async -> Bool { + ) async -> RemovalOutcome { // App-side metadata (tax category override) keyed by the same // hash — a fresh install knows nothing about a removed tx, and // neither should this one. @@ -266,41 +281,73 @@ struct UnconfirmedTransactionRemover { } } + // How deep the recovery rescan reaches is decided HERE, before the + // reload, because the reload stops SPV and `resetPublishedState` + // zeroes the coordinator's `tipHeight`; the restarted client only + // re-seeds it on a later progress tick, so a post-reload read finds 0 + // and arms nothing. Anchoring on the pre-reload tip is the safe + // direction — the tip only advances, so the older value rewinds + // deeper, never shallower. + // + // The window reaches back past the OLDEST removed transaction's first + // appearance — uncapped in depth, because this is the step that + // restores a removed tx that actually IS mined (the bulk path never + // explorer-checked, and the single path's explorer can be wrong). The + // SDK floors the rescan at the wallet's birth height and the locally + // stored chain data; a row with no usable first-seen time rescans from + // the floor. + let tip = SwiftDashSDKSPVCoordinator.shared.tipHeight + let rescanFromHeight: UInt32? = { + guard tip > 0 else { return nil } + let ageSeconds = max(0, Date().timeIntervalSince1970 - TimeInterval(oldestFirstSeen)) + let ageBlocks = UInt32(clamping: Int(ageSeconds / 150)) + rescanMarginBlocks + let blocksBack = max(minRescanBlocks, ageBlocks) + return tip > blocksBack ? tip - blocksBack : 1 + }() + // Full runtime reload — the same serialized stop → load → start // lifecycle a network switch runs. The reloaded Rust wallet // rebuilds its tx set, UTXOs and spent_outpoints from the rows as // they now are, and dash-spv's mempool tracker (which kept // rebroadcasting) restarts without the removed transactions. - await SwiftDashSDKWalletRuntime.shared.rearmPlatformSync() + await SwiftDashSDKWalletRuntime.shared.reloadAfterWalletRowsChanged() - // Rescan compact filters, reaching back past the OLDEST removed - // transaction's first appearance — uncapped in depth, because - // this is the step that restores a removed tx that actually IS - // mined (the bulk path never explorer-checked, and the single - // path's explorer can be wrong). The SDK floors the rescan at - // the wallet's birth height and the locally stored chain data; - // a row with no usable first-seen time rescans from the floor. - var rescanArmed = false - let tip = SwiftDashSDKSPVCoordinator.shared.tipHeight - if tip > 0, let manager = SwiftDashSDKHost.shared.manager { - let ageSeconds = max(0, Date().timeIntervalSince1970 - TimeInterval(oldestFirstSeen)) - let ageBlocks = UInt32(clamping: Int(ageSeconds / 150)) + rescanMarginBlocks - let blocksBack = max(minRescanBlocks, ageBlocks) - let fromHeight = tip > blocksBack ? tip - blocksBack : 1 + // Did the reload actually bring the runtime back? `refresh` starts + // Core SPV and then BLAST, and falls back to `fullReset` if EITHER + // throws — so a Platform outage, which has nothing to do with the + // Core-side row the user just repaired, stops the host and Core SPV + // as well. The rows are already deleted and stay deleted; what this + // decides is which remedy the caller can honestly offer, because + // Rescan Filters refuses while SPV is stopped. + let runtimeReady = WalletEnvironment.network + .map { SwiftDashSDKWalletRuntime.shared.isRuntimeReady(for: $0) } ?? false + + let outcome: RemovalOutcome + if !runtimeReady { + outcome = .runtimeStopped + logger.error("🗑️ TX-REMOVE :: runtime did not come back after the reload — rows deleted, wallet stopped") + } else if let fromHeight = rescanFromHeight, let manager = SwiftDashSDKHost.shared.manager { + // Rewind the compact-filter checkpoint on the manager the reload + // just built — the previous instance died with the old runtime. do { try manager.spvRescanFilters(walletId: walletId, fromHeight: fromHeight) - rescanArmed = true + outcome = .rescanArmed logger.notice("🗑️ TX-REMOVE :: filter rescan armed from height \(fromHeight, privacy: .public) (tip \(tip, privacy: .public))") } catch { + outcome = .rescanUnavailable logger.error("🗑️ TX-REMOVE :: filter rescan arm failed: \(String(describing: error), privacy: .public)") } + } else if rescanFromHeight == nil { + outcome = .rescanUnavailable + logger.error("🗑️ TX-REMOVE :: filter rescan skipped — no chain tip when the removal started") } else { - logger.error("🗑️ TX-REMOVE :: filter rescan skipped — SPV not running after reload") + outcome = .rescanUnavailable + logger.error("🗑️ TX-REMOVE :: filter rescan skipped — no manager after the reload") } // App caches that mirror the deleted rows. await ShieldedTxLookup.shared.refresh(reason: "transaction-removal-completed") - return rescanArmed + return outcome } /// One GET against the network's Insight API. 200 = the explorer diff --git a/DashWallet/Sources/UI/Menu/SyncInfo/SwiftDashSDKSPVStatusScreen.swift b/DashWallet/Sources/UI/Menu/SyncInfo/SwiftDashSDKSPVStatusScreen.swift index 026dd604bc..c8c8322ef8 100644 --- a/DashWallet/Sources/UI/Menu/SyncInfo/SwiftDashSDKSPVStatusScreen.swift +++ b/DashWallet/Sources/UI/Menu/SyncInfo/SwiftDashSDKSPVStatusScreen.swift @@ -952,24 +952,40 @@ extension SwiftDashSDKSPVStatusScreen { dropResultMessage = NSLocalizedString( "No unconfirmed transactions to drop.", comment: "SPV diagnostics") - } else if outcome.rescanArmed { - dropResultIsError = false - dropResultMessage = String( - format: NSLocalizedString( - "Dropped %d unconfirmed transaction(s) — rescanning filters, watch the Filters row.", - comment: "SPV diagnostics"), - outcome.dropped) } else { - // The drop finished but the recovery rescan didn't - // arm — flag it instead of claiming the safety net ran. - dropResultIsError = true - dropResultMessage = String( - format: NSLocalizedString( - "Dropped %d unconfirmed transaction(s), but the filter rescan couldn't start — run Rescan Filters above.", - comment: "SPV diagnostics"), - outcome.dropped) + switch outcome.outcome { + case .rescanArmed: + dropResultIsError = false + dropResultMessage = String( + format: NSLocalizedString( + "Dropped %d unconfirmed transaction(s) — rescanning filters, watch the Filters row.", + comment: "SPV diagnostics"), + outcome.dropped) + case .rescanUnavailable: + // The drop finished but the recovery rescan didn't + // arm — flag it instead of claiming the safety net ran. + dropResultIsError = true + dropResultMessage = String( + format: NSLocalizedString( + "Dropped %d unconfirmed transaction(s), but the filter rescan couldn't start — run Rescan Filters above.", + comment: "SPV diagnostics"), + outcome.dropped) + case .runtimeStopped: + // Rescan Filters above is disabled while SPV is + // stopped, so restarting comes first — and it has to + // be followed by the rescan, which restarting does + // not replay. This path never explorer-checked, so + // that rescan is the only on-chain safety check the + // dropped transactions ever get. + dropResultIsError = true + dropResultMessage = String( + format: NSLocalizedString( + "Dropped %d unconfirmed transaction(s), but the wallet stopped and the filter rescan never ran. Restart the wallet (reopen the app, or Sync Now in Platform sync), then run Rescan Filters above.", + comment: "SPV diagnostics"), + outcome.dropped) + } } - Self.logger.info("🛰️ SPV-STATUS :: bulk unconfirmed drop finished — \(outcome.dropped, privacy: .public) tx(s), rescanArmed=\(outcome.rescanArmed, privacy: .public)") + Self.logger.info("🛰️ SPV-STATUS :: bulk unconfirmed drop finished — \(outcome.dropped, privacy: .public) tx(s), outcome=\(String(describing: outcome.outcome), privacy: .public)") } catch { dropResultIsError = true dropResultMessage = error.localizedDescription diff --git a/DashWallet/Sources/UI/Tx/Details/TxDetailViewController.swift b/DashWallet/Sources/UI/Tx/Details/TxDetailViewController.swift index 94922bd7c1..34be507e09 100644 --- a/DashWallet/Sources/UI/Tx/Details/TxDetailViewController.swift +++ b/DashWallet/Sources/UI/Tx/Details/TxDetailViewController.swift @@ -368,14 +368,25 @@ extension TXDetailViewController { self?.view.dw_hideProgressHUD() } do { - let rescanArmed = try await UnconfirmedTransactionRemover().remove(txidWire: txidWire) - // Never claim the rescan safety net ran when it didn't — - // point at the manual Rescan Filters action instead. - self?.view.dw_showInfoHUD(withText: rescanArmed - ? NSLocalizedString("Transaction removed", comment: "Remove never-accepted transaction: success") - : NSLocalizedString("Transaction removed — rescan couldn't start, run Rescan Filters in Core Sync Status", comment: "Remove never-accepted transaction: removed but the recovery rescan did not arm")) - // The row this sheet describes no longer exists. - self?.closeAction() + let outcome = try await UnconfirmedTransactionRemover().remove(txidWire: txidWire) + switch outcome { + case .rescanArmed: + self?.view.dw_showInfoHUD(withText: NSLocalizedString("Transaction removed", comment: "Remove never-accepted transaction: success")) + // The row this sheet describes no longer exists. + self?.closeAction() + case .rescanUnavailable: + // Never claim the rescan safety net ran when it didn't. + self?.view.dw_showInfoHUD(withText: NSLocalizedString("Transaction removed — rescan couldn't start, run Rescan Filters in Core Sync Status", comment: "Remove never-accepted transaction: removed but the recovery rescan did not arm")) + self?.closeAction() + case .runtimeStopped: + // A HUD would not survive this: it is added to this + // controller's own view, which `closeAction` tears down. + // The stopped wallet needs an acknowledged alert that + // dismisses the sheet only once the user has read it — + // and it must name BOTH steps, because restarting the + // runtime does not replay this removal's rescan. + self?.presentRemovalLeftWalletStopped() + } } catch UnconfirmedTransactionRemover.RemovalError.transactionOnChain { self?.presentRemovalRefused() } catch { @@ -389,6 +400,24 @@ extension TXDetailViewController { } } + /// The rows are deleted, but reloading the runtime left the wallet + /// stopped (Core SPV is torn down when the Platform side fails to come + /// back). Both recovery steps are spelled out: restarting the runtime + /// does NOT replay the rescan this removal skipped, so the transaction's + /// on-chain safety check still has to be run by hand afterwards. The + /// sheet is dismissed only after the user acknowledges. + private func presentRemovalLeftWalletStopped() { + let alert = UIAlertController( + title: NSLocalizedString("Transaction removed, but the wallet stopped", comment: "Remove never-accepted transaction: removed but the runtime reload left the wallet stopped"), + message: NSLocalizedString("The transaction was deleted from this device. Reloading the wallet didn't finish, so the wallet is stopped and the rescan that double-checks the blockchain never ran.\n\nRestart the wallet — reopen the app, or tap Sync Now in Sync Info — and then run Rescan Filters in Core Sync Status. Restarting alone does not repeat the rescan.", comment: "Remove never-accepted transaction: both recovery steps after a failed runtime reload"), + preferredStyle: .alert) + alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .cancel) { [weak self] _ in + // The row this sheet describes no longer exists. + self?.closeAction() + }) + present(alert, animated: true) + } + /// The explorer knows the transaction, either from the mempool or a /// block. Removal is refused until the local wallet catches up. private func presentRemovalRefused() {