diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKSPVCoordinator.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKSPVCoordinator.swift index 7162c07489..e96996ae41 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKSPVCoordinator.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKSPVCoordinator.swift @@ -191,6 +191,15 @@ public final class SwiftDashSDKSPVCoordinator: NSObject, ObservableObject { // (a near-empty one-time scan for wallets that never used CoinJoin). applyCoinJoinRecoveryGapIfNeeded(for: network) + // Pending birth-height chain resync: with the store deleted BEFORE + // startSpv, the client re-anchors at the restored (lowered) birth + // height and the armed rescan walks the recovered range. Must also + // run before startSpv so the delete never races the sync loop's + // segment writes. See `SPVChainResyncMarker` for why this only + // happens on the launch after the marker was armed. + let appliedChainResync = applyPendingChainResyncIfNeeded( + for: network, dataDir: dataDir, manager: manager) + do { try manager.startSpv(config: config) } catch { @@ -198,6 +207,14 @@ public final class SwiftDashSDKSPVCoordinator: NSObject, ObservableObject { return .failure(StartError.spvClient(error)) } + // The resync marker survives a failed startSpv (the store is empty + // either way; the next launch simply re-applies), and is consumed + // only once the resynced client is actually running. + if appliedChainResync { + SPVChainResyncMarker.clear(for: network) + Self.logger.info("🛰️ SPVCOORD :: chain resync applied on \(network.rawValue, privacy: .public)") + } + runningNetwork = network lastError = nil subscribeToManagerProgress(manager: manager) @@ -273,6 +290,56 @@ public final class SwiftDashSDKSPVCoordinator: NSObject, ObservableObject { } } + // MARK: - Pending chain resync application + + /// Apply a pending birth-height chain resync (see `SPVChainResyncMarker`): + /// delete the network's SPV store so the upcoming `startSpv` re-anchors at + /// the restored birth height, and rewind the wallet's live filter + /// checkpoint to the marker height. The rewind is belt-and-suspenders for + /// the arming session having re-raised the persisted `syncedHeight` after + /// the arm (the arming save already rewound the row, which normally feeds + /// the restore); a rewind failure is logged but doesn't retain the marker. + /// + /// Returns true when applied — the caller clears the marker once + /// `startSpv` succeeds. Returns false (marker retained) when there is + /// nothing pending, the marker was armed by this process (it must wait + /// for a launch that restores the lowered birth height into Rust), or + /// the store delete failed (retried next launch). + @MainActor + private func applyPendingChainResyncIfNeeded( + for network: Network, + dataDir: String, + manager: PlatformWalletManager + ) -> Bool { + guard let pending = SPVChainResyncMarker.pending(for: network) else { return false } + guard !pending.armedByThisSession else { + Self.logger.info("🛰️ SPVCOORD :: chain resync armed this session — deferred to next launch") + return false + } + + let dir = URL(fileURLWithPath: dataDir, isDirectory: true) + do { + if FileManager.default.fileExists(atPath: dir.path) { + try FileManager.default.removeItem(at: dir) + } + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + } catch { + Self.logger.error("🛰️ SPVCOORD :: chain resync store delete failed: \(String(describing: error), privacy: .public)") + return false + } + + do { + try manager.spvRescanFilters(walletId: pending.walletId, fromHeight: pending.fromHeight) + } catch { + // The wallet may have been wiped since arming (nothing left to + // rescan; the store delete was the safe direction regardless). + Self.logger.error("🛰️ SPVCOORD :: chain resync rescan arm failed: \(String(describing: error), privacy: .public)") + } + + Self.logger.info("🛰️ SPVCOORD :: chain store cleared for resync from height \(pending.fromHeight, privacy: .public)") + return true + } + /// After a widened recovery scan reaches `.synced`, mark recovery complete /// so future launches revert to the fast default gap. One completed wide /// scan is sufficient: the deep CoinJoin (4') UTXOs it discovered — and @@ -457,3 +524,99 @@ public final class SwiftDashSDKSPVCoordinator: NSObject, ObservableObject { var errorDescription: String? { "Platform SDK does not support \(network.rawValue)" } } } + +// MARK: - Pending chain resync (birth-height repair) + +/// One-shot "clear the SPV chain store and rescan at the next launch" +/// marker, armed by the SPV Status screen when a wallet's birth height is +/// lowered and applied by `SwiftDashSDKSPVCoordinator.performStart`. +/// +/// Why a next-launch marker instead of acting immediately: the running Rust +/// wallet's birth height is fed once from `PersistentWallet` when wallets +/// load and has no update FFI, and dash-spv never re-anchors an existing +/// header store (`initialize_genesis_block` returns early when any headers +/// exist). A lowered birth height can therefore only take effect on a launch +/// whose SPV start finds an EMPTY store: the client then anchors at the +/// freshly restored birth height and the filter scan can reach the recovered +/// range. Applying the marker in the session that armed it would delete the +/// store and immediately re-anchor at the stale in-memory birth height, +/// consuming the marker without repairing anything — hence the session guard. +/// +/// UserDefaults-backed, per network, one wallet at a time (the repair is a +/// single-wallet diagnostic; arming again overwrites). Follows the +/// `CoinJoinRecovery` pre-start maintenance-flag pattern; lives in this file +/// because `performStart` is its consumer and the SPV Status screen its only +/// producer. +enum SPVChainResyncMarker { + + private static let logger = Logger( + subsystem: "org.dashfoundation.dash", + category: "swift-sdk-migration.spv-chain-resync") + + /// Stable for the lifetime of this process. A marker armed by this + /// process is only applied by a later one (see type doc). + private static let sessionId = UUID().uuidString + + struct Pending { + let walletId: Data + let fromHeight: UInt32 + let armedBySessionId: String + + var armedByThisSession: Bool { armedBySessionId == SPVChainResyncMarker.sessionId } + } + + private static func key(for network: Network) -> String { + "spvChainResync.v1.pending.\(network == .mainnet ? "mainnet" : "testnet")" + } + + /// Arm the marker: `network`'s chain store is deleted before the first + /// `startSpv` of a later app session, and `walletId`'s filter checkpoint + /// is rewound to `fromHeight`. Overwrites any pending marker for the + /// network. + static func arm(walletId: Data, fromHeight: UInt32, network: Network) { + UserDefaults.standard.set( + [ + "walletId": walletId.hexEncodedString(), + "fromHeight": NSNumber(value: fromHeight), + "sessionId": sessionId, + ] as [String: Any], + forKey: key(for: network)) + logger.info("🛰️ SPV-RESYNC :: armed for \(network.rawValue, privacy: .public) from height \(fromHeight, privacy: .public)") + } + + /// Drop a pending marker for `walletId` (e.g. the birth height was + /// raised again before the resync ran, superseding it). No-op when the + /// pending marker belongs to a different wallet. + static func disarm(walletId: Data, network: Network) { + guard let p = pending(for: network), p.walletId == walletId else { return } + clear(for: network) + logger.info("🛰️ SPV-RESYNC :: disarmed for \(network.rawValue, privacy: .public)") + } + + static func pending(for network: Network) -> Pending? { + guard let dict = UserDefaults.standard.dictionary(forKey: key(for: network)), + let walletIdHex = dict["walletId"] as? String, + let walletId = Data(hexString: walletIdHex), + let fromHeight = (dict["fromHeight"] as? NSNumber)?.uint32Value, + let armedBySessionId = dict["sessionId"] as? String else { + return nil + } + return Pending( + walletId: walletId, + fromHeight: fromHeight, + armedBySessionId: armedBySessionId) + } + + static func clear(for network: Network) { + UserDefaults.standard.removeObject(forKey: key(for: network)) + } + + /// Clear pending markers on a wallet wipe: the rows and chain data they + /// reference are gone, so a stale marker would only wipe the next + /// wallet's fresh sync. Clears both networks, mirroring + /// `CoinJoinRecovery.resetForWipe`. + static func resetForWipe() { + clear(for: .mainnet) + clear(for: .testnet) + } +} diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift index daf63010fa..2ce14146ce 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift @@ -91,6 +91,10 @@ final class SwiftDashSDKWalletWiper: NSObject { CoinJoinRecovery.shared.resetForWipe() CoinJoinWithdrawalStore.shared.resetForWipe() ShieldedWithdrawalStore.shared.resetForWipe() + // Pending birth-height chain resyncs reference wallet rows and chain + // data this wipe destroys; a stale marker would only wipe the next + // wallet's fresh sync. UserDefaults-only, safe from this queue. + SPVChainResyncMarker.resetForWipe() // CrowdNode state is per-wallet-keyed; the wipe destroys every wallet, so // clear every wallet's keys (the CrowdNode singleton's own // `DWWillWipeWallet` observer only resets the ACTIVE wallet's keys). Also diff --git a/DashWallet/Sources/UI/Menu/Tools/SwiftDashSDKSPVStatusScreen.swift b/DashWallet/Sources/UI/Menu/Tools/SwiftDashSDKSPVStatusScreen.swift index 47bc229a79..f4c4a82e00 100644 --- a/DashWallet/Sources/UI/Menu/Tools/SwiftDashSDKSPVStatusScreen.swift +++ b/DashWallet/Sources/UI/Menu/Tools/SwiftDashSDKSPVStatusScreen.swift @@ -56,9 +56,14 @@ struct SwiftDashSDKSPVStatusScreen: View { /// Bound to the birth-height text field; validated to a `UInt32` /// before use, never defaulted. @State private var birthHeightEntryText = "" - /// Non-nil presents the post-save "rescan now?" prompt carrying the - /// height that was just written. - @State private var savedBirthHeightPendingRescan: UInt32? + /// Non-nil presents the clear-and-resync confirmation carrying the + /// entered height. Nothing is written until the user confirms; on + /// confirm the row is updated and the next-launch chain resync armed. + /// Entered heights at or below the current one land here — "equal" + /// included, because a store anchored above the (already-correct) + /// birth height can only be repaired by the resync, and re-saving + /// the current height is the only way to express that in this UI. + @State private var pendingResyncConfirmHeight: UInt32? init(vc: UINavigationController) { self.vc = vc @@ -137,7 +142,7 @@ struct SwiftDashSDKSPVStatusScreen: View { Button(NSLocalizedString("Cancel", comment: ""), role: .cancel) {} } message: { Text(NSLocalizedString( - "Re-checks the compact block filters from the chosen height for this wallet's transactions, re-downloading and re-matching them. This rediscovers any missed transactions but can take a while. Full rescan re-checks every filter since genesis and can take a long time on mainnet.", + "Re-checks the compact block filters from the chosen height for this wallet's transactions, re-downloading and re-matching them. Rescans are floored at the wallet's creation height and at the locally stored chain data — to recover history below that, lower the wallet birth height instead.", comment: "SPV diagnostics")) } .alert( @@ -171,28 +176,33 @@ struct SwiftDashSDKSPVStatusScreen: View { Button(NSLocalizedString("Cancel", comment: ""), role: .cancel) {} } message: { Text(NSLocalizedString( - "The wallet's creation height — the floor for filter scans and \"From wallet creation\" rescans. Set it at or below the wallet's first funding; imports default to 200000 on mainnet and 0 on testnet.", + "The wallet's creation height — the floor for filter scans and \"From wallet creation\" rescans. Set it at or below the wallet's first funding; imports default to 200000 on mainnet and 0 on testnet. Saving a height at or below the current one clears this network's chain data at the next launch and rescans from it.", comment: "SPV diagnostics")) } .alert( - NSLocalizedString("Birth height updated", comment: "SPV diagnostics"), + NSLocalizedString("Clear chain data and resync?", comment: "SPV diagnostics"), isPresented: Binding( - get: { savedBirthHeightPendingRescan != nil }, - set: { if !$0 { savedBirthHeightPendingRescan = nil } } + get: { pendingResyncConfirmHeight != nil }, + set: { if !$0 { pendingResyncConfirmHeight = nil } } ), - presenting: savedBirthHeightPendingRescan + presenting: pendingResyncConfirmHeight ) { height in - Button(NSLocalizedString("Rescan now", comment: "SPV diagnostics")) { - savedBirthHeightPendingRescan = nil - performRescan(fromHeight: height) + Button( + NSLocalizedString("Clear & resync", comment: "SPV diagnostics"), + role: .destructive + ) { + pendingResyncConfirmHeight = nil + armBirthHeightResync(height: height) } - Button(NSLocalizedString("Later", comment: ""), role: .cancel) { - savedBirthHeightPendingRescan = nil + Button(NSLocalizedString("Cancel", comment: ""), role: .cancel) { + pendingResyncConfirmHeight = nil } - } message: { _ in - Text(NSLocalizedString( - "The saved height becomes the scan floor from the next launch. Rescan filters from it now to pick up any missed history immediately.", - comment: "SPV diagnostics")) + } message: { height in + Text(String( + format: NSLocalizedString( + "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start.", + comment: "SPV diagnostics"), + height)) } } @@ -665,14 +675,22 @@ extension SwiftDashSDKSPVStatusScreen { } } - /// Validate the birth-height text field and write it onto the - /// bound wallet's `PersistentWallet` row. The row is the durable - /// source: the SDK's `loadWallets` restore sends `birthHeight` - /// back to Rust at every launch, so the edit becomes the wallet's - /// scan floor from the next start. The LIVE session's floor is - /// unchanged (Rust read it at configure) — the post-save prompt - /// offers an immediate filter rescan from the new height, which - /// reads the row and therefore honors the edit right away. + /// Validate the birth-height text field and route it. The row is the + /// durable source the SDK's `loadWallets` restore feeds back to Rust at + /// every launch; the LIVE session can never honor an edit (the Rust + /// wallet's birth height has no update FFI, and dash-spv never + /// re-anchors an existing header store, so heights below the store's + /// first stored block stay unreachable until the store is rebuilt). + /// + /// - Raising the height persists immediately — it needs no chain + /// rebuild — and disarms any pending resync marker it supersedes. + /// - A height at or below the current one means "make this floor + /// real", which requires the next-launch chain resync; nothing is + /// written until the user confirms via `armBirthHeightResync`. + /// Equal heights are included: a store anchored above an + /// already-correct birth height (e.g. created before the birth + /// height was fixed) is repaired the same way, and re-saving the + /// current height is how this UI expresses that. func saveEnteredBirthHeight() { let trimmed = birthHeightEntryText.trimmingCharacters(in: .whitespaces) guard let height = UInt32(trimmed) else { @@ -681,13 +699,26 @@ extension SwiftDashSDKSPVStatusScreen { "Enter a valid block height.", comment: "SPV diagnostics") return } + guard let (row, walletId, network) = boundWalletRow() else { return } + if height <= row.birthHeight { + pendingResyncConfirmHeight = height + return + } + saveRaisedBirthHeight(height, row: row, walletId: walletId, network: network) + } + + /// Fetch the bound wallet's `PersistentWallet` row plus the identifiers + /// the birth-height flows need. Emits the error banner and returns nil + /// when no wallet is bound, the row is missing, or it carries no + /// network. + private func boundWalletRow() -> (PersistentWallet, walletId: Data, network: Network)? { guard let wallet = SwiftDashSDKHost.shared.wallet, let container = SwiftDashSDKHost.shared.modelContainer else { rescanResultIsError = true rescanResultMessage = NSLocalizedString( "Available only while SPV is running with a wallet bound.", comment: "SPV diagnostics") - return + return nil } let walletId = wallet.walletId var descriptor = FetchDescriptor( @@ -698,10 +729,25 @@ extension SwiftDashSDKSPVStatusScreen { rescanResultMessage = NSLocalizedString( "No persisted wallet row found for the bound wallet.", comment: "SPV diagnostics") - return + return nil } + guard let network = row.network else { + rescanResultIsError = true + rescanResultMessage = NSLocalizedString( + "The persisted wallet row has no network — cannot arm a resync.", + comment: "SPV diagnostics") + return nil + } + return (row, walletId, network) + } + + /// Persist a raised birth height (no chain rebuild needed) and disarm + /// any pending resync marker the raise supersedes. + private func saveRaisedBirthHeight( + _ height: UInt32, row: PersistentWallet, walletId: Data, network: Network + ) { + guard let container = SwiftDashSDKHost.shared.modelContainer else { return } let previous = row.birthHeight - guard height != previous else { return } row.birthHeight = height do { try container.mainContext.save() @@ -713,6 +759,43 @@ extension SwiftDashSDKSPVStatusScreen { return } Self.logger.info("🛰️ SPV-STATUS :: birth height \(previous, privacy: .public) → \(height, privacy: .public)") - savedBirthHeightPendingRescan = height + SPVChainResyncMarker.disarm(walletId: walletId, network: network) + rescanResultIsError = false + rescanResultMessage = NSLocalizedString( + "Birth height saved — the raised scan floor applies from the next launch.", + comment: "SPV diagnostics") + } + + /// Confirmed clear-and-resync: write the birth height, rewind the row's + /// `syncedHeight` so the restored wallet's filter scan starts at the new + /// floor, and arm `SPVChainResyncMarker` — the SPV coordinator applies + /// it on the next launch by deleting the chain store before `startSpv`. + func armBirthHeightResync(height: UInt32) { + guard let (row, walletId, network) = boundWalletRow(), + let container = SwiftDashSDKHost.shared.modelContainer else { return } + let previousBirth = row.birthHeight + let previousSynced = row.syncedHeight + row.birthHeight = height + if row.syncedHeight > height { + row.syncedHeight = height + } + do { + try container.mainContext.save() + } catch { + row.birthHeight = previousBirth + row.syncedHeight = previousSynced + rescanResultIsError = true + rescanResultMessage = error.localizedDescription + Self.logger.error("🛰️ SPV-STATUS :: birth-height resync save failed: \(String(describing: error), privacy: .public)") + return + } + SPVChainResyncMarker.arm(walletId: walletId, fromHeight: height, network: network) + Self.logger.info("🛰️ SPV-STATUS :: birth height \(previousBirth, privacy: .public) → \(height, privacy: .public), chain resync armed") + rescanResultIsError = false + rescanResultMessage = String( + format: NSLocalizedString( + "Resync armed from height %u — quit and reopen the app to start.", + comment: "SPV diagnostics"), + height) } } diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index 317f9a7f06..841bc9164e 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -418,6 +418,9 @@ /* No comment provided by engineer. */ "Biometrics Access Required" = "Biometrics Access Required"; +/* SPV diagnostics */ +"Birth height saved — the raised scan floor applies from the next launch." = "Birth height saved — the raised scan floor applies from the next launch."; + /* Voting */ "Block" = "Block"; @@ -545,6 +548,12 @@ /* No comment provided by engineer. */ "Claimed" = "Claimed"; +/* SPV diagnostics */ +"Clear & resync" = "Clear & resync"; + +/* SPV diagnostics */ +"Clear chain data and resync?" = "Clear chain data and resync?"; + /* Maya */ "Clipboard" = "Clipboard"; @@ -587,6 +596,9 @@ /* No comment provided by engineer. */ "Confirm Platform Send" = "Confirm Platform Send"; +/* SPV diagnostics */ +"Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start."; + /* ZenLedger */ "Connect your crypto wallets to the ZenLedger platform. Learn more and get started with your Dash Wallet transactions." = "Connect your crypto wallets to the ZenLedger platform. Learn more and get started with your Dash Wallet transactions."; @@ -975,6 +987,9 @@ /* No comment provided by engineer. */ "Easily stake Dash and earn passive income with a few simple clicks." = "Easily stake Dash and earn passive income with a few simple clicks."; +/* SPV diagnostics */ +"Edit birth height" = "Edit birth height"; + /* No comment provided by engineer. */ "Edit Profile" = "Edit Profile"; @@ -1993,6 +2008,9 @@ /* DashPay Contacts */ "No payments with this contact yet" = "No payments with this contact yet"; +/* SPV diagnostics */ +"No persisted wallet row found for the bound wallet." = "No persisted wallet row found for the bound wallet."; + /* Explore Dash/Merchants/Filters */ "No Results Found" = "No Results Found"; @@ -2356,6 +2374,9 @@ /* ex., Rate 1 US $ = 0.000009 Dash */ "Rate: %@ = %@" = "Rate: %1$@ = %2$@"; +/* SPV diagnostics */ +"Re-checks the compact block filters from the chosen height for this wallet's transactions, re-downloading and re-matching them. Rescans are floored at the wallet's creation height and at the locally stored chain data — to recover history below that, lower the wallet birth height instead." = "Re-checks the compact block filters from the chosen height for this wallet's transactions, re-downloading and re-matching them. Rescans are floored at the wallet's creation height and at the locally stored chain data — to recover history below that, lower the wallet birth height instead."; + /* SPV diagnostics */ "Re-checks the compact block filters from the chosen height for this wallet's transactions, re-downloading and re-matching them. This rediscovers any missed transactions but can take a while. Full rescan re-checks every filter since genesis and can take a long time on mainnet." = "Re-checks the compact block filters from the chosen height for this wallet's transactions, re-downloading and re-matching them. This rediscovers any missed transactions but can take a while. Full rescan re-checks every filter since genesis and can take a long time on mainnet."; @@ -2506,6 +2527,9 @@ /* Usernames */ "Results" = "Results"; +/* SPV diagnostics */ +"Resync armed from height %u — quit and reopen the app to start." = "Resync armed from height %u — quit and reopen the app to start."; + /* No comment provided by engineer. */ "Retry" = "Retry"; @@ -3039,6 +3063,9 @@ /* Coinbase */ "The minimum amount you can send is %@" = "The minimum amount you can send is %@"; +/* SPV diagnostics */ +"The persisted wallet row has no network — cannot arm a resync." = "The persisted wallet row has no network — cannot arm a resync."; + /* Dash DEX / dex_error_price_moved */ "The price moved too much. Please go back and try again." = "The price moved too much. Please go back and try again."; @@ -3057,6 +3084,9 @@ /* Usernames */ "The username '%@' was blocked by the Dash Network. Please try again by requesting another username." = "The username '%@' was blocked by the Dash Network. Please try again by requesting another username."; +/* SPV diagnostics */ +"The wallet's creation height — the floor for filter scans and \"From wallet creation\" rescans. Set it at or below the wallet's first funding; imports default to 200000 on mainnet and 0 on testnet. Saving a height at or below the current one clears this network's chain data at the next launch and rescans from it." = "The wallet's creation height — the floor for filter scans and \"From wallet creation\" rescans. Set it at or below the wallet's first funding; imports default to 200000 on mainnet and 0 on testnet. Saving a height at or below the current one clears this network's chain data at the next launch and rescans from it."; + /* No comment provided by engineer. */ "There are no transactions to display" = "There are no transactions to display"; @@ -3479,6 +3509,9 @@ /* Enter Address Screen */ "Wallet Address" = "Wallet Address"; +/* SPV diagnostics */ +"Wallet birth height" = "Wallet birth height"; + /* No comment provided by engineer. */ "Wallet disabled" = "Wallet disabled";