From 4eb1491128e67d02285896180b09732160c57303 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Thu, 16 Jul 2026 05:38:22 +0700 Subject: [PATCH 1/2] fix(wallet): lowering the birth height now clears chain data at next launch so the rescan can actually reach it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The birth-height editor shipped in #804 claimed "Rescan now" honored the edit immediately. It never could, for two engine-level reasons: - The live Rust wallet's birth height is fed once from PersistentWallet at load and has no update FFI; the rescan FFI only rewinds synced_height, and dash-spv's filter scan clamps its start to max(birth height, header store start). Same-session rescans below the live birth height are silent no-ops. - dash-spv never re-anchors an existing header store (initialize_genesis_block returns early when any headers exist), so a store anchored at the newest checkpoint by the original mis-stamped import permanently caps how far back ANY rescan can reach — even after a relaunch with the corrected birth height. The repair that works is: rebuild the chain store on a launch that restores the lowered birth height. Lowering the height in the editor now also rewinds the row's syncedHeight (so the restored wallet's filter scan starts at the new height) and arms SPVChainResyncMarker, a UserDefaults marker the SPV coordinator applies on the next launch — deleting the network's SPV store before startSpv so the client re-anchors at the restored birth height, and re-arming the filter rescan in case the arming session re-raised the persisted checkpoint. A session guard keeps the marker from firing in the process that armed it (the store would just re-anchor at the stale in-memory floor). Raising the height keeps the plain persist-only path and disarms any pending marker it supersedes. UI copy now states the real contract: lowering requires a relaunch and triggers a full chain resync; rescans are floored at the wallet's creation height and locally stored chain data. The false "Rescan now" prompt is gone; wallet wipes drop pending markers. Co-Authored-By: Claude Fable 5 --- .../SwiftDashSDKSPVCoordinator.swift | 163 ++++++++++++++++++ .../SwiftDashSDKWalletWiper.swift | 4 + .../Tools/SwiftDashSDKSPVStatusScreen.swift | 84 +++++---- DashWallet/en.lproj/Localizable.strings | 27 +++ 4 files changed, 249 insertions(+), 29 deletions(-) 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..cfb297113b 100644 --- a/DashWallet/Sources/UI/Menu/Tools/SwiftDashSDKSPVStatusScreen.swift +++ b/DashWallet/Sources/UI/Menu/Tools/SwiftDashSDKSPVStatusScreen.swift @@ -56,9 +56,10 @@ 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 post-save "restart required" notice carrying + /// the height that was just written (only for lowered heights, which + /// arm a next-launch chain resync). + @State private var savedBirthHeightPendingResync: UInt32? init(vc: UINavigationController) { self.vc = vc @@ -137,7 +138,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 +172,26 @@ 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. Lowering it clears this network's chain data at the next launch and rescans from the new height.", comment: "SPV diagnostics")) } .alert( - NSLocalizedString("Birth height updated", comment: "SPV diagnostics"), + NSLocalizedString("Restart required", comment: "SPV diagnostics"), isPresented: Binding( - get: { savedBirthHeightPendingRescan != nil }, - set: { if !$0 { savedBirthHeightPendingRescan = nil } } + get: { savedBirthHeightPendingResync != nil }, + set: { if !$0 { savedBirthHeightPendingResync = nil } } ), - presenting: savedBirthHeightPendingRescan - ) { height in - Button(NSLocalizedString("Rescan now", comment: "SPV diagnostics")) { - savedBirthHeightPendingRescan = nil - performRescan(fromHeight: height) + presenting: savedBirthHeightPendingResync + ) { _ in + Button(NSLocalizedString("OK", comment: ""), role: .cancel) { + savedBirthHeightPendingResync = nil } - Button(NSLocalizedString("Later", comment: ""), role: .cancel) { - savedBirthHeightPendingRescan = 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( + "Birth height saved. Quit and reopen the app to apply it: the next launch clears this network's chain data and rescans filters from height %u. The running session keeps its old scan floor until then.", + comment: "SPV diagnostics"), + height)) } } @@ -665,14 +664,19 @@ 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 write it onto the bound + /// wallet's `PersistentWallet` row — the durable source the SDK's + /// `loadWallets` restore feeds back to Rust at every launch. The LIVE + /// session can never honor the 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. Lowering the height + /// therefore also rewinds the row's `syncedHeight` (so the next restore + /// starts the filter scan at the new height) and arms + /// `SPVChainResyncMarker`, which the SPV coordinator applies on the + /// next launch by deleting the chain store before `startSpv`. Raising + /// the height just persists — and disarms any pending marker it + /// supersedes. func saveEnteredBirthHeight() { let trimmed = birthHeightEntryText.trimmingCharacters(in: .whitespaces) guard let height = UInt32(trimmed) else { @@ -700,19 +704,41 @@ extension SwiftDashSDKSPVStatusScreen { comment: "SPV diagnostics") return } + 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 + } let previous = row.birthHeight guard height != previous else { return } + let previousSynced = row.syncedHeight row.birthHeight = height + let lowering = height < previous + if lowering, row.syncedHeight > height { + row.syncedHeight = height + } do { try container.mainContext.save() } catch { row.birthHeight = previous + row.syncedHeight = previousSynced rescanResultIsError = true rescanResultMessage = error.localizedDescription Self.logger.error("🛰️ SPV-STATUS :: birth-height save failed: \(String(describing: error), privacy: .public)") return } Self.logger.info("🛰️ SPV-STATUS :: birth height \(previous, privacy: .public) → \(height, privacy: .public)") - savedBirthHeightPendingRescan = height + if lowering { + SPVChainResyncMarker.arm(walletId: walletId, fromHeight: height, network: network) + savedBirthHeightPendingResync = height + } else { + 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") + } } } diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index 317f9a7f06..18fde1ea1d 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -418,6 +418,12 @@ /* 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."; + +/* SPV diagnostics */ +"Birth height saved. Quit and reopen the app to apply it: the next launch clears this network's chain data and rescans filters from height %u. The running session keeps its old scan floor until then." = "Birth height saved. Quit and reopen the app to apply it: the next launch clears this network's chain data and rescans filters from height %u. The running session keeps its old scan floor until then."; + /* Voting */ "Block" = "Block"; @@ -975,6 +981,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 +2002,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 +2368,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."; @@ -2497,6 +2512,9 @@ /* No comment provided by engineer. */ "Reset to Default" = "Reset to Default"; +/* SPV diagnostics */ +"Restart required" = "Restart required"; + /* Wallets */ "Restore an existing wallet" = "Restore an existing wallet"; @@ -3039,6 +3057,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 +3078,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. Lowering it clears this network's chain data at the next launch and rescans from the new height." = "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. Lowering it clears this network's chain data at the next launch and rescans from the new height."; + /* No comment provided by engineer. */ "There are no transactions to display" = "There are no transactions to display"; @@ -3479,6 +3503,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"; From fa184eee453c77c74669b1048bb82a5b3f16f298 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Thu, 16 Jul 2026 06:07:53 +0700 Subject: [PATCH 2/2] fix(wallet): birth-height resync is confirm-gated and re-arms at an equal height The QA mainnet wallet exposed a state the first commit couldn't repair from the UI: the row's birth height is already correct (200,000, stamped by the post-#804 recovery registration) but the chain store predates the fix and is anchored at the newest checkpoint (2,500,000), so every rescan still clamps to the anchor. The editor's equal-height guard made "rebuild the store from my existing floor" inexpressible. Saving a height at or below the current one now presents an explicit "Clear chain data and resync?" confirmation; nothing is written until the user confirms, and confirming saves the row, rewinds its synced checkpoint, and arms the next-launch resync marker. Raising stays persist-only. This replaces the previous save-then-inform alert, which armed the wipe before the user saw the consequence. Co-Authored-By: Claude Fable 5 --- .../Tools/SwiftDashSDKSPVStatusScreen.swift | 147 ++++++++++++------ DashWallet/en.lproj/Localizable.strings | 20 ++- 2 files changed, 115 insertions(+), 52 deletions(-) diff --git a/DashWallet/Sources/UI/Menu/Tools/SwiftDashSDKSPVStatusScreen.swift b/DashWallet/Sources/UI/Menu/Tools/SwiftDashSDKSPVStatusScreen.swift index cfb297113b..f4c4a82e00 100644 --- a/DashWallet/Sources/UI/Menu/Tools/SwiftDashSDKSPVStatusScreen.swift +++ b/DashWallet/Sources/UI/Menu/Tools/SwiftDashSDKSPVStatusScreen.swift @@ -56,10 +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 "restart required" notice carrying - /// the height that was just written (only for lowered heights, which - /// arm a next-launch chain resync). - @State private var savedBirthHeightPendingResync: 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 @@ -172,24 +176,31 @@ 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. Lowering it clears this network's chain data at the next launch and rescans from the new height.", + "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("Restart required", comment: "SPV diagnostics"), + NSLocalizedString("Clear chain data and resync?", comment: "SPV diagnostics"), isPresented: Binding( - get: { savedBirthHeightPendingResync != nil }, - set: { if !$0 { savedBirthHeightPendingResync = nil } } + get: { pendingResyncConfirmHeight != nil }, + set: { if !$0 { pendingResyncConfirmHeight = nil } } ), - presenting: savedBirthHeightPendingResync - ) { _ in - Button(NSLocalizedString("OK", comment: ""), role: .cancel) { - savedBirthHeightPendingResync = nil + presenting: pendingResyncConfirmHeight + ) { height in + Button( + NSLocalizedString("Clear & resync", comment: "SPV diagnostics"), + role: .destructive + ) { + pendingResyncConfirmHeight = nil + armBirthHeightResync(height: height) + } + Button(NSLocalizedString("Cancel", comment: ""), role: .cancel) { + pendingResyncConfirmHeight = nil } } message: { height in Text(String( format: NSLocalizedString( - "Birth height saved. Quit and reopen the app to apply it: the next launch clears this network's chain data and rescans filters from height %u. The running session keeps its old scan floor until then.", + "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)) } @@ -664,19 +675,22 @@ extension SwiftDashSDKSPVStatusScreen { } } - /// Validate the birth-height text field and write it onto the bound - /// wallet's `PersistentWallet` row — the durable source the SDK's - /// `loadWallets` restore feeds back to Rust at every launch. The LIVE - /// session can never honor the 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. Lowering the height - /// therefore also rewinds the row's `syncedHeight` (so the next restore - /// starts the filter scan at the new height) and arms - /// `SPVChainResyncMarker`, which the SPV coordinator applies on the - /// next launch by deleting the chain store before `startSpv`. Raising - /// the height just persists — and disarms any pending marker it - /// supersedes. + /// 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 { @@ -685,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( @@ -702,43 +729,73 @@ 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 + 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 } - let previousSynced = row.syncedHeight row.birthHeight = height - let lowering = height < previous - if lowering, row.syncedHeight > height { - row.syncedHeight = height - } do { try container.mainContext.save() } catch { row.birthHeight = previous - row.syncedHeight = previousSynced rescanResultIsError = true rescanResultMessage = error.localizedDescription Self.logger.error("🛰️ SPV-STATUS :: birth-height save failed: \(String(describing: error), privacy: .public)") return } Self.logger.info("🛰️ SPV-STATUS :: birth height \(previous, privacy: .public) → \(height, privacy: .public)") - if lowering { - SPVChainResyncMarker.arm(walletId: walletId, fromHeight: height, network: network) - savedBirthHeightPendingResync = height - } else { - 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") + 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 18fde1ea1d..841bc9164e 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -421,9 +421,6 @@ /* 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."; -/* SPV diagnostics */ -"Birth height saved. Quit and reopen the app to apply it: the next launch clears this network's chain data and rescans filters from height %u. The running session keeps its old scan floor until then." = "Birth height saved. Quit and reopen the app to apply it: the next launch clears this network's chain data and rescans filters from height %u. The running session keeps its old scan floor until then."; - /* Voting */ "Block" = "Block"; @@ -551,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"; @@ -593,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."; @@ -2512,9 +2518,6 @@ /* No comment provided by engineer. */ "Reset to Default" = "Reset to Default"; -/* SPV diagnostics */ -"Restart required" = "Restart required"; - /* Wallets */ "Restore an existing wallet" = "Restore an existing wallet"; @@ -2524,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"; @@ -3079,7 +3085,7 @@ "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. Lowering it clears this network's chain data at the next launch and rescans from the new height." = "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. Lowering it clears this network's chain data at the next launch and rescans from the new height."; +"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";