From c667bcd173e75293a3da27b30c65a1920829dc23 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Fri, 9 Oct 2026 17:29:06 +0200 Subject: [PATCH 1/9] fix(wallet): classify a failed keychain replay as a keys failure on open SwiftDashSDKHost.start wraps every failure of the keychain replay as walletBootstrapFailed, and the runtime's prepareWallet closure mapped only modelContainerFailed: for anything else the overlay finished and enqueueRefresh dropped the returned record, leaving a home screen with no balance, no card and no way to export logs. A record built later from the HostError (Try Again, a reset restart) carried only OtherError:4, because HostError is not CustomNSError and its payload is lost when bridged. WalletPreparationFailure gains Kind.keychain with init(keys:status:), never resettable, whose only codes are the host's reason and the Security status of the failed read. SwiftDashSDKHost.preparationFailure(forStartError:) is the one place that draws the keys/store line, matching by type: WalletStorageError, the resolver's errors, invalidMnemonic and mnemonicRoundTripMismatch are keys failures; a store write that failed while replaying, a recovery marker that could not be written, and walletNotFound keep the database card, whose "keys are stored safely" copy is true there. The runtime passes that function as the closure. Harness: the host fakes gain WalletStorageError and the resolver error, the unreadable-keychain stub throws the SDK error, and four host tests plus one failure-record test cover the classification (108 tests). Co-Authored-By: Claude Fable 5.1 --- .../SwiftDashSDK/SwiftDashSDKHost.swift | 46 +++++++++++++ .../SwiftDashSDKWalletRuntime.swift | 7 +- .../WalletPreparationFailure.swift | 36 +++++++++- .../WalletPreparationFailureTests.swift | 18 +++++ scripts/test_wallet_preparation.py | 65 ++++++++++++++++++- 5 files changed, 161 insertions(+), 11 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift index f8a95b1db8..7365e40015 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift @@ -519,6 +519,52 @@ final class SwiftDashSDKHost { } } + /// The wallet-open card's record for a failed `start(network:)`, or nil + /// for errors that keep their existing recovery flow (devnet preflight, + /// SDK init, configure). A store that would not open keeps the database + /// card; a bootstrap failure is a keys failure only when `keysFailure(in:)` + /// recognizes its cause, otherwise it is a store failure too — a SwiftData + /// write that failed while replaying the keychain, or a recovery marker + /// that could not be written — and the database card's Reset recreates the + /// rows from the keychain that was just read. Keys readable but nothing + /// eligible for the network (`walletNotFound`) also stays on that card: + /// its "keys are stored safely" copy is true and the phrase backup works. + nonisolated static func preparationFailure(forStartError error: Error) -> WalletPreparationFailure? { + switch error { + case HostError.modelContainerFailed(let underlying): + return WalletPreparationFailure(error: underlying) + case HostError.walletBootstrapFailed(let underlying): + if let keys = keysFailure(in: underlying) { + return WalletPreparationFailure(keys: keys.reason, status: keys.status) + } + return WalletPreparationFailure(error: underlying) + default: + return nil + } + } + + /// Only a cause this host knows to be about the keys classifies as one; + /// every other error is treated as a store failure. Matched by type, not + /// by NSError domain: app enums bridge to domains carrying the module + /// name, and `WalletStorageError.keychainError` loses its status when + /// bridged. + nonisolated static func keysFailure(in error: Error) -> (reason: WalletPreparationFailure.KeysReason, status: OSStatus?)? { + switch error { + case WalletStorageError.keychainError(let status): + return (.unreadable, status) + case WalletStorageError.mnemonicNotFound: + return (.notFound, nil) + case SwiftDashSDKWalletDeletionError.invalidMnemonic, + SwiftDashSDKWalletDeletionError.unrecognizedWalletNetwork, + HostError.invalidMnemonic: + return (.unclassifiable, nil) + case HostError.mnemonicRoundTripMismatch: + return (.idMismatch, nil) + default: + return nil + } + } + private struct RuntimeHandles { let sdk: SDK let manager: PlatformWalletManager diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift index 660d407616..837096026c 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift @@ -913,12 +913,7 @@ final class SwiftDashSDKWalletRuntime: NSObject { WalletLifecycleOverlayPresenter.shared.ensureActive() let (manager, wallet) = try await WalletLifecycleTransitionState.shared.prepareWallet { try await SwiftDashSDKHost.shared.start(network: network) - } failure: { error in - if case let SwiftDashSDKHost.HostError.modelContainerFailed(underlying) = error { - return WalletPreparationFailure(error: underlying) - } - return nil - } + } failure: { SwiftDashSDKHost.preparationFailure(forStartError: $0) } PlatformAddressSyncCoordinator.shared.prepareLocalPlatformState( manager: manager, walletId: wallet.walletId, network: network) await PlatformAddressSyncCoordinator.shared.prepareLocalShieldedState( diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift index 173dbd1f11..e075f646c7 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift @@ -1,16 +1,24 @@ import Foundation import SQLite3 -/// Display and support evidence for a failed wallet open, or for a failed -/// import of the previous app generation's wallet. Never retains an Error or +/// Display and support evidence for a failed wallet open, for a failed +/// import of the previous app generation's wallet, or for wallet keys that +/// could not be read back from the keychain. Never retains an Error or /// its userInfo: Core Data errors can contain paths and stored values. struct WalletPreparationFailure: Equatable, Identifiable { - enum Kind: String { case database, storage, legacyMigration } + /// `keychain`: the store is not the problem — the wallet keys could not + /// be read or replayed from the keychain, and nothing was deleted. + enum Kind: String { case database, storage, legacyMigration, keychain } /// Why the DashSync → SwiftDashSDK key migration did not deliver a wallet. /// Only the migrator's terminal flag names leave this boundary. enum LegacyMigrationReason: String { case failed, unknownChain, timedOut, unreadableKeychain } + /// How the keychain replay of the wallet keys failed, as + /// `SwiftDashSDKHost.keysFailure(in:)` classifies it. Only these names and + /// the Security framework status of a failed read leave this boundary. + enum KeysReason: String { case unreadable, notFound, unclassifiable, idMismatch } + let id: UUID let kind: Kind let occurredAt: Date @@ -25,6 +33,17 @@ struct WalletPreparationFailure: Equatable, Identifiable { canResetLocalData = false } + /// The store opened, but the wallet keys could not be read or replayed. + /// Never resettable: deleting the store cannot help, and the card offers + /// no phrase backup either, since the phrase is what could not be read. + init(keys reason: KeysReason, status: OSStatus? = nil, now: Date = Date()) { + id = UUID() + occurredAt = now + kind = .keychain + codes = ["Keychain:\(reason.rawValue)"] + (status.map { ["OSStatus:\($0)"] } ?? []) + canResetLocalData = false + } + init(error: Error, now: Date = Date()) { id = UUID() occurredAt = now @@ -78,6 +97,10 @@ struct WalletPreparationFailure: Equatable, Identifiable { return NSLocalizedString("Couldn't move your wallet", comment: "Wallet preparation failure") } + if kind == .keychain { + return NSLocalizedString("Couldn't read your wallet keys", + comment: "Wallet preparation failure") + } return NSLocalizedString("Couldn't open your wallet data", comment: "Wallet preparation failure") } @@ -93,6 +116,13 @@ struct WalletPreparationFailure: Equatable, Identifiable { "There isn't enough free space to prepare your wallet. Free up storage in iPhone Settings, then try again. Your wallet keys are still stored safely on this device.", comment: "Wallet preparation failure") } + if kind == .keychain { + // Neither "your keys are safe" nor "your keys are lost": a read + // failed, and the keychain is untouched by the app. + return NSLocalizedString( + "Your wallet keys could not be read from this device's secure storage. Nothing was deleted. Do not delete this app. Try again or contact support for help.", + comment: "Wallet preparation failure") + } return NSLocalizedString( "Your wallet could not be opened. Your wallet keys are still stored safely on this device. Try again or contact support for help.", comment: "Wallet preparation failure") diff --git a/DashWalletTests/WalletPreparationFailureTests.swift b/DashWalletTests/WalletPreparationFailureTests.swift index 3c876c44fe..d6241eaf99 100644 --- a/DashWalletTests/WalletPreparationFailureTests.swift +++ b/DashWalletTests/WalletPreparationFailureTests.swift @@ -93,4 +93,22 @@ final class WalletPreparationFailureTests: XCTestCase { XCTAssertTrue(report.contains("KeyMigrator:timedOut")) XCTAssertEqual(WalletPreparationFailure(legacyMigration: .unreadableKeychain).codes, ["KeyMigrator:unreadableKeychain"]) } + + func testKeysFailureIsNeverResettableAndCarriesOnlyReasonAndStatus() { + let failure = WalletPreparationFailure(keys: .unreadable, status: -25308, now: Date(timeIntervalSince1970: 0)) + XCTAssertEqual(failure.kind, .keychain) + XCTAssertEqual(failure.codes, ["Keychain:unreadable", "OSStatus:-25308"]) + XCTAssertFalse(failure.canResetLocalData) + let database = WalletPreparationFailure(error: NSError(domain: "SwiftData.SwiftDataError", code: 1)) + XCTAssertNotEqual(failure.title, database.title) + XCTAssertNotEqual(failure.title, WalletPreparationFailure(legacyMigration: .failed).title) + // Neither claim: the keys were not read, and nothing was deleted. + XCTAssertFalse(failure.message.contains("stored safely")) + XCTAssertFalse(failure.message.lowercased().contains("lost")) + let report = failure.diagnosticReport(appVersion: "1", systemVersion: "2") + XCTAssertTrue(report.contains("Category: keychain")) + XCTAssertTrue(report.contains("Keychain:unreadable\nOSStatus:-25308")) + XCTAssertEqual(WalletPreparationFailure(keys: .notFound).codes, ["Keychain:notFound"]) + XCTAssertEqual(WalletPreparationFailure(keys: .idMismatch).codes, ["Keychain:idMismatch"]) + } } diff --git a/scripts/test_wallet_preparation.py b/scripts/test_wallet_preparation.py index 5402c8c974..f604b4cea5 100644 --- a/scripts/test_wallet_preparation.py +++ b/scripts/test_wallet_preparation.py @@ -76,6 +76,9 @@ def declaration(source, start): " private func registryNetworkKind(", " private func recoverPersistedWallet(", " func validateLocalStoreReset()", + # The wallet-open card's classification of a failed start: keys vs store. + " nonisolated static func preparationFailure(forStartError", + " nonisolated static func keysFailure(in", )) (sources / "HostRecoveryHarness.swift").write_text(r''' import Foundation @@ -121,9 +124,16 @@ def declaration(source, start): func deleteWallet(walletId: Data) throws { wallets[walletId] = nil; Self.rows[walletId] = nil } func shutdown() async { Self.shutdowns += 1 } } +/// The SDK's keychain error and the app's resolver error, as the host's keys +/// classification matches them by type. +enum WalletStorageError: Error { case keychainError(OSStatus), mnemonicNotFound } +enum SwiftDashSDKWalletDeletionError: Error { case invalidMnemonic, unrecognizedWalletNetwork } @MainActor final class HostRecoveryHarness { static let logger = Logger(subsystem: "wallet-preparation-tests", category: "recovery") - enum HostError: Error { case walletNotFound(Network), walletBootstrapFailed(Error), mnemonicRoundTripMismatch, invalidMnemonic } + enum HostError: Error { + case sdkInitFailed(Error), modelContainerFailed(Error), walletNotFound(Network), walletBootstrapFailed(Error) + case mnemonicRoundTripMismatch, invalidMnemonic + } struct RuntimeHandles { let manager: PlatformWalletManager; let network: Network } static var directory: URL! nonisolated(unsafe) static var unreadableKeychain = false @@ -143,7 +153,7 @@ def declaration(source, start): func provisionDevnetWallets(handles: RuntimeHandles) async -> ManagedPlatformWallet? { nil } func unlockDashPayContactCrypto(manager: PlatformWalletManager, wallet: ManagedPlatformWallet) {} nonisolated static func strictlyPersistedMnemonics() throws -> [(walletId: Data, mnemonic: String)] { - if unreadableKeychain { throw NSError(domain: "InjectedKeychain", code: 1) } + if unreadableKeychain { throw WalletStorageError.keychainError(-25308) } if nulMaterial { return [(Data("wallet-a".utf8), "wallet-a\u{0}trailing bytes")] } return ["wallet-a", "wallet-b"].map { (Data($0.utf8), $0) } } @@ -299,6 +309,57 @@ def declaration(source, start): return XCTFail("Expected invalidMnemonic, got \(String(describing: nul))") } } + /// The card record the runtime shows for a failed start, or nil when the + /// start succeeded or the error keeps its existing flow. + private func startFailure(_ host: HostRecoveryHarness) async -> WalletPreparationFailure? { + do { _ = try await host.start(network: .mainnet); return nil } catch { + return HostRecoveryHarness.preparationFailure(forStartError: error) + } + } + func testUnreadableKeychainShowsTheKeysCardWithItsStatus() async throws { + HostRecoveryHarness.unreadableKeychain = true + let failure = await startFailure(HostRecoveryHarness()) + XCTAssertEqual(failure?.kind, .keychain) + XCTAssertEqual(failure?.codes, ["Keychain:unreadable", "OSStatus:-25308"]) + XCTAssertEqual(failure?.canResetLocalData, false) + } + func testUnclassifiableMaterialShowsTheKeysCard() async throws { + HostRecoveryHarness.invalidMaterial = true + let failure = await startFailure(HostRecoveryHarness()) + XCTAssertEqual(failure?.kind, .keychain) + XCTAssertEqual(failure?.codes, ["Keychain:unclassifiable"]) + } + func testStoreWriteFailureWhileReplayingTheKeychainKeepsTheDatabaseCard() async throws { + PlatformWalletManager.failingMnemonic = "wallet-a" + let failure = await startFailure(HostRecoveryHarness()) + XCTAssertEqual(failure?.kind, .database) + XCTAssertEqual(failure?.codes, ["OtherError:1"]) + XCTAssertEqual(failure?.canResetLocalData, false) + } + func testOnlyKnownKeysCausesClassifyAsKeys() { + typealias HostError = HostRecoveryHarness.HostError + let swiftData = NSError(domain: "SwiftData.SwiftDataError", code: 1) + let store = HostRecoveryHarness.preparationFailure(forStartError: HostError.modelContainerFailed(swiftData)) + XCTAssertEqual(store?.kind, .database) + XCTAssertEqual(store?.canResetLocalData, true) + // Keys readable, nothing eligible for the network: the database card's + // "keys are stored safely" is true there, and never a reset. + let notFound = HostRecoveryHarness.preparationFailure( + forStartError: HostError.walletBootstrapFailed(HostError.walletNotFound(.mainnet))) + XCTAssertEqual(notFound?.kind, .database) + XCTAssertEqual(notFound?.canResetLocalData, false) + let mismatch = HostRecoveryHarness.preparationFailure( + forStartError: HostError.walletBootstrapFailed(HostError.mnemonicRoundTripMismatch)) + XCTAssertEqual(mismatch?.codes, ["Keychain:idMismatch"]) + let missing = HostRecoveryHarness.preparationFailure( + forStartError: HostError.walletBootstrapFailed(WalletStorageError.mnemonicNotFound)) + XCTAssertEqual(missing?.codes, ["Keychain:notFound"]) + let resolver = HostRecoveryHarness.preparationFailure( + forStartError: HostError.walletBootstrapFailed(SwiftDashSDKWalletDeletionError.unrecognizedWalletNetwork)) + XCTAssertEqual(resolver?.codes, ["Keychain:unclassifiable"]) + XCTAssertNil(HostRecoveryHarness.preparationFailure(forStartError: HostError.sdkInitFailed(swiftData))) + XCTAssertNil(HostRecoveryHarness.keysFailure(in: swiftData)) + } } ''') (sources / "ProcessNetworkValueCache.swift").write_text( From ab81b968d9801c68d5e1677d6fd697e235974a31 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Fri, 9 Oct 2026 17:29:15 +0200 Subject: [PATCH 2/9] fix(wallet): show the keys card without Backup or Reset, with a PIN-gated export The wallet-open card for Kind.keychain says the keys could not be read and nothing was deleted, offers Try Again, Export Logs and Help only, hides Backup (the phrase is what could not be read; the view model refuses it too) and authenticates the export first, as the migration card does. Reset stays behind canResetLocalData, which a keys failure never sets. The Help sheet gets matching guidance and a support draft. English catalog only; other locales come through Transifex. Co-Authored-By: Claude Fable 5.1 --- .../UI/Main/WalletLifecycleOverlay.swift | 30 ++++++++++++------- .../UI/Main/WalletPreparationSupport.swift | 10 +++++++ DashWallet/en.lproj/Localizable.strings | 4 +++ 3 files changed, 34 insertions(+), 10 deletions(-) diff --git a/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift b/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift index 1a45b85cba..af53e50e91 100644 --- a/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift +++ b/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift @@ -368,9 +368,12 @@ final class WalletLifecycleOverlayViewModel: ObservableObject { /// Backup recovery phrase on the wallet-open failure card: the Security /// menu's flow (PIN, then one phrase or a wallet picker), hosted modally - /// in the overlay window because the card has no navigation stack. + /// in the overlay window because the card has no navigation stack. Not + /// on a keys failure: the phrase is what could not be read, and the card + /// does not show the button. func backupRecoveryPhrase() { guard !isBusy, + preparationFailure?.kind != .keychain, requirePin( for: NSLocalizedString("Backup recovery phrase", comment: "Wallet preparation"), message: NSLocalizedString("Unlock with your wallet PIN to continue.", comment: "Wallet preparation")) @@ -515,14 +518,16 @@ struct WalletLifecycleOverlayView: View { title: NSLocalizedString("Preparing your wallet…", comment: "Wallet preparation"), subtitle: NSLocalizedString("Please keep the app open.", comment: "Wallet preparation")) case let .failedWalletOpen(failure): + // A keys failure shows neither Backup nor Reset, and its + // Export Logs authenticates first, as the migration card's does. card { failureHeader(title: failure.title, message: failure.message) actionButton(NSLocalizedString("Try Again", comment: ""), prominent: true) { viewModel.retryWalletOpen() } .disabled(viewModel.isBusy) - walletRecoveryActions - preparationHelp + walletRecoveryActions(for: failure) + preparationHelp(authenticatedExport: failure.kind == .keychain) } case let .failedLegacyMigration(failure): // No Create/Recover here: the wallet is still in the keychain. @@ -584,7 +589,7 @@ struct WalletLifecycleOverlayView: View { } .disabled(viewModel.isBusy) } - if viewModel.showsLocalStoreRecovery { walletRecoveryActions } + if viewModel.showsLocalStoreRecovery { walletRecoveryActions(for: viewModel.preparationFailure) } preparationHelp } case let .failedWalletSwitch(targetId, targetName, previousId, message): @@ -650,12 +655,16 @@ struct WalletLifecycleOverlayView: View { .recoveryPhraseFlowAlert(viewModel.recoveryPhraseFlow) } + /// Backup is offered unless the keys themselves failed to read; Reset + /// only when the failure record and the keychain inventory allow it. @ViewBuilder - private var walletRecoveryActions: some View { - actionButton(NSLocalizedString("Backup recovery phrase", comment: "Wallet preparation"), prominent: false) { - viewModel.backupRecoveryPhrase() + private func walletRecoveryActions(for failure: WalletPreparationFailure?) -> some View { + if failure?.kind != .keychain { + actionButton(NSLocalizedString("Backup recovery phrase", comment: "Wallet preparation"), prominent: false) { + viewModel.backupRecoveryPhrase() + } + .disabled(viewModel.isBusy) } - .disabled(viewModel.isBusy) if viewModel.canResetWalletData { actionButton( NSLocalizedString("Reset wallet data and rescan", comment: "Wallet preparation"), @@ -671,8 +680,9 @@ struct WalletLifecycleOverlayView: View { preparationHelp(authenticatedExport: false) } - /// `authenticatedExport`: the card shows before the lock screen, so - /// Export Logs authenticates first (see `exportDiagnosticLogs`). + /// `authenticatedExport`: the migration card shows before the lock screen + /// and the keys card cannot rely on it, so Export Logs authenticates + /// first (see `exportDiagnosticLogs`). @ViewBuilder private func preparationHelp(authenticatedExport: Bool) -> some View { if viewModel.preparationFailure != nil { diff --git a/DashWallet/Sources/UI/Main/WalletPreparationSupport.swift b/DashWallet/Sources/UI/Main/WalletPreparationSupport.swift index aa5b7226c1..437ed46a5a 100644 --- a/DashWallet/Sources/UI/Main/WalletPreparationSupport.swift +++ b/DashWallet/Sources/UI/Main/WalletPreparationSupport.swift @@ -41,6 +41,11 @@ final class WalletPreparationSupportViewModel: ObservableObject { "Do not delete the app. Try moving your wallet again, or contact support if the problem continues.", comment: "Wallet preparation help") } + if kind == .keychain { + return NSLocalizedString( + "Your wallet keys could not be read from this device. Do not delete the app. Try opening your wallet again, or contact support if the problem continues.", + comment: "Wallet preparation help") + } return NSLocalizedString( "Your wallet keys are still stored safely on this device. Try opening your wallet again, or contact support if the problem continues.", comment: "Wallet preparation help") @@ -58,6 +63,11 @@ final class WalletPreparationSupportViewModel: ObservableObject { body = String(format: NSLocalizedString( "To: %@\n\nI couldn't move my wallet from the previous version of the app.\n\nWhat happened before the error:\n", comment: "Editable wallet support message"), recipient) + } else if kind == .keychain { + subject = "Dash Wallet — unable to read wallet keys" + body = String(format: NSLocalizedString( + "To: %@\n\nI couldn't open my wallet. The app says my wallet keys could not be read.\n\nWhat happened before the error:\n", + comment: "Editable wallet support message"), recipient) } else { subject = "Dash Wallet — unable to open wallet" body = String(format: NSLocalizedString( diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index c9a20938b5..bb4b0cdb1e 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -6110,6 +6110,8 @@ "Couldn't open your wallet data" = "Couldn't open your wallet data"; "There isn't enough free space to prepare your wallet. Free up storage in iPhone Settings, then try again. Your wallet keys are still stored safely on this device." = "There isn't enough free space to prepare your wallet. Free up storage in iPhone Settings, then try again. Your wallet keys are still stored safely on this device."; "Your wallet could not be opened. Your wallet keys are still stored safely on this device. Try again or contact support for help." = "Your wallet could not be opened. Your wallet keys are still stored safely on this device. Try again or contact support for help."; +"Couldn't read your wallet keys" = "Couldn't read your wallet keys"; +"Your wallet keys could not be read from this device's secure storage. Nothing was deleted. Do not delete this app. Try again or contact support for help." = "Your wallet keys could not be read from this device's secure storage. Nothing was deleted. Do not delete this app. Try again or contact support for help."; "Couldn't move your wallet" = "Couldn't move your wallet"; "Do not delete the app. Try moving your wallet again, or contact support if the problem continues." = "Do not delete the app. Try moving your wallet again, or contact support if the problem continues."; "To: %@\n\nI couldn't move my wallet from the previous version of the app.\n\nWhat happened before the error:\n" = "To: %@\n\nI couldn't move my wallet from the previous version of the app.\n\nWhat happened before the error:\n"; @@ -6129,6 +6131,8 @@ "Try Again" = "Try Again"; "To: %@\n\nI couldn't open my wallet.\n\nWhat happened before the error:\n" = "To: %@\n\nI couldn't open my wallet.\n\nWhat happened before the error:\n"; "Your wallet keys are still stored safely on this device. Try opening your wallet again, or contact support if the problem continues." = "Your wallet keys are still stored safely on this device. Try opening your wallet again, or contact support if the problem continues."; +"Your wallet keys could not be read from this device. Do not delete the app. Try opening your wallet again, or contact support if the problem continues." = "Your wallet keys could not be read from this device. Do not delete the app. Try opening your wallet again, or contact support if the problem continues."; +"To: %@\n\nI couldn't open my wallet. The app says my wallet keys could not be read.\n\nWhat happened before the error:\n" = "To: %@\n\nI couldn't open my wallet. The app says my wallet keys could not be read.\n\nWhat happened before the error:\n"; "Never share your recovery phrase or private keys with anyone, including support." = "Never share your recovery phrase or private keys with anyone, including support."; "Include diagnostic report" = "Include diagnostic report"; "Preview diagnostic report" = "Preview diagnostic report"; From 43ded4af016ff928bc8ddbbef614eaabb4037e64 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Mon, 12 Oct 2026 13:56:11 +0200 Subject: [PATCH 3/9] fix(wallet): keep walletNotFound off the failure card walletBootstrapFailed(walletNotFound) is the "keys readable, nothing eligible for the selected network" outcome. WalletEnvironment.hasWallet deliberately routes that inventory (devnet-only material in a shipping build) to setup, and the runtime can still start underneath it on a connectivity kick, so a database card there would sit over Create/Recover. Map it to nil, the flow it had before this branch; the harness asserts it. Co-Authored-By: Claude Fable 5.1 --- .../Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift | 7 +++++-- scripts/test_wallet_preparation.py | 10 ++++------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift index 7365e40015..3e3ca6e755 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift @@ -527,12 +527,15 @@ final class SwiftDashSDKHost { /// write that failed while replaying the keychain, or a recovery marker /// that could not be written — and the database card's Reset recreates the /// rows from the keychain that was just read. Keys readable but nothing - /// eligible for the network (`walletNotFound`) also stays on that card: - /// its "keys are stored safely" copy is true and the phrase backup works. + /// eligible for the network (`walletNotFound`) keeps its existing flow + /// with no card: `WalletEnvironment.hasWallet` routes that inventory to + /// setup, and a blocking card would sit over it. nonisolated static func preparationFailure(forStartError error: Error) -> WalletPreparationFailure? { switch error { case HostError.modelContainerFailed(let underlying): return WalletPreparationFailure(error: underlying) + case HostError.walletBootstrapFailed(HostError.walletNotFound): + return nil case HostError.walletBootstrapFailed(let underlying): if let keys = keysFailure(in: underlying) { return WalletPreparationFailure(keys: keys.reason, status: keys.status) diff --git a/scripts/test_wallet_preparation.py b/scripts/test_wallet_preparation.py index f604b4cea5..95db44deac 100644 --- a/scripts/test_wallet_preparation.py +++ b/scripts/test_wallet_preparation.py @@ -342,12 +342,10 @@ def declaration(source, start): let store = HostRecoveryHarness.preparationFailure(forStartError: HostError.modelContainerFailed(swiftData)) XCTAssertEqual(store?.kind, .database) XCTAssertEqual(store?.canResetLocalData, true) - // Keys readable, nothing eligible for the network: the database card's - // "keys are stored safely" is true there, and never a reset. - let notFound = HostRecoveryHarness.preparationFailure( - forStartError: HostError.walletBootstrapFailed(HostError.walletNotFound(.mainnet))) - XCTAssertEqual(notFound?.kind, .database) - XCTAssertEqual(notFound?.canResetLocalData, false) + // Keys readable, nothing eligible for the network: no card, the + // existing flow (hasWallet routes that inventory to setup) stays. + XCTAssertNil(HostRecoveryHarness.preparationFailure( + forStartError: HostError.walletBootstrapFailed(HostError.walletNotFound(.mainnet)))) let mismatch = HostRecoveryHarness.preparationFailure( forStartError: HostError.walletBootstrapFailed(HostError.mnemonicRoundTripMismatch)) XCTAssertEqual(mismatch?.codes, ["Keychain:idMismatch"]) From 935e8f9109570b301a40bc8ffdd54c860b417f55 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Mon, 12 Oct 2026 14:45:44 +0200 Subject: [PATCH 4/9] fix(wallet): keep the keys card through Try Again and classify locked and refused material Try Again re-enters refresh, whose wallet-presence gate and unclassified-start fallback build a store record around the open; retryWalletPreparation pinned that record, replacing the keys card with "keys are stored safely" and Backup. It now keeps the keys card unless the open itself classified the new failure (the record prepareWallet left behind). errSecInteractionNotAllowed is the lock, not broken material: the replay keeps its no-card flow so the foreground kick heals it, instead of a pinned card that turns automatic preparation off. KeyWalletError from the resolver's wallet construction is a keys failure (unclassifiable). The card policy lives on the record: offersPhraseBackup and requiresAuthenticatedExport replace the kind checks in the overlay, and the switch cards now authenticate the export for a keys failure too. The keys message no longer claims nothing was deleted (the card can follow a reset). Core start failures log their category and codes to the file log, so an export from the card carries them. Harness: the resolver stub throws the real resolver error, locked and KeyWalletError cases, and the retry rule. Co-Authored-By: Claude Fable 5.1 --- .../SwiftDashSDK/SwiftDashSDKHost.swift | 24 ++++++-- .../SwiftDashSDKWalletRuntime.swift | 16 +++++- .../WalletPreparationFailure.swift | 14 ++++- .../UI/Main/WalletLifecycleOverlay.swift | 29 ++++------ DashWallet/en.lproj/Localizable.strings | 2 +- .../WalletPreparationFailureTests.swift | 5 ++ scripts/test_wallet_preparation.py | 57 ++++++++++++++++++- 7 files changed, 115 insertions(+), 32 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift index 3e3ca6e755..f12d486496 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift @@ -525,17 +525,25 @@ final class SwiftDashSDKHost { /// card; a bootstrap failure is a keys failure only when `keysFailure(in:)` /// recognizes its cause, otherwise it is a store failure too — a SwiftData /// write that failed while replaying the keychain, or a recovery marker - /// that could not be written — and the database card's Reset recreates the - /// rows from the keychain that was just read. Keys readable but nothing - /// eligible for the network (`walletNotFound`) keeps its existing flow - /// with no card: `WalletEnvironment.hasWallet` routes that inventory to - /// setup, and a blocking card would sit over it. + /// that could not be written — and `WalletPreparationFailure(error:)` + /// decides from its codes whether a reset is offered. + /// + /// Two bootstrap causes keep the no-card flow this path always had, so an + /// automatic kick (foreground, connectivity) retries instead of a pinned + /// card: keys readable but nothing eligible for the network + /// (`walletNotFound`) — `WalletEnvironment.hasWallet` routes that + /// inventory to setup, and a card would sit over it — and a keychain read + /// refused because protected data was unavailable + /// (`errSecInteractionNotAllowed`), which heals on unlock. nonisolated static func preparationFailure(forStartError error: Error) -> WalletPreparationFailure? { + let interactionNotAllowed: OSStatus = -25308 // errSecInteractionNotAllowed switch error { case HostError.modelContainerFailed(let underlying): return WalletPreparationFailure(error: underlying) case HostError.walletBootstrapFailed(HostError.walletNotFound): return nil + case HostError.walletBootstrapFailed(WalletStorageError.keychainError(interactionNotAllowed)): + return nil case HostError.walletBootstrapFailed(let underlying): if let keys = keysFailure(in: underlying) { return WalletPreparationFailure(keys: keys.reason, status: keys.status) @@ -559,7 +567,11 @@ final class SwiftDashSDKHost { return (.notFound, nil) case SwiftDashSDKWalletDeletionError.invalidMnemonic, SwiftDashSDKWalletDeletionError.unrecognizedWalletNetwork, - HostError.invalidMnemonic: + HostError.invalidMnemonic, + is KeyWalletError: + // The resolver derives ids by constructing a wallet from the + // stored phrase; `KeyWalletError` is that construction refusing + // material that passed word validation. return (.unclassifiable, nil) case HostError.mnemonicRoundTripMismatch: return (.idMismatch, nil) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift index 837096026c..1a67a39245 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift @@ -243,9 +243,19 @@ final class SwiftDashSDKWalletRuntime: NSObject { func retryWalletPreparation() async { await enqueueAwaitable { let state = WalletLifecycleTransitionState.shared - guard case .failedWalletOpen = state.phase else { return } + guard case let .failedWalletOpen(shown) = state.phase else { return } if let failure = await self.refresh(trigger: .startIfReady) { - state.fail(.failedWalletOpen(failure)) + // A record the open classified itself replaces the card. One + // built around the open — the wallet-presence gate, or the + // fallback for a start error the host left unclassified — + // carries the store copy's "keys are stored safely" and + // Backup, which must not replace a keys card. + let classifiedByOpen = state.preparationFailure == failure + if shown.kind == .keychain, !classifiedByOpen { + state.fail(.failedWalletOpen(shown)) + } else { + state.fail(.failedWalletOpen(failure)) + } } }.value } @@ -923,6 +933,8 @@ final class SwiftDashSDKWalletRuntime: NSObject { } catch { Self.logger.error("🧭 RUNTIME :: Core start failed: \(String(describing: error), privacy: .public)") let failure = WalletLifecycleTransitionState.shared.preparationFailure ?? WalletPreparationFailure(error: error) + // os_log does not reach the diagnostic export; the file log does. + DWLogger.log("RUNTIME Core start failed category=\(failure.kind.rawValue) codes=\(failure.codes.joined(separator: ","))") await fullReset(lastError: error.localizedDescription, forWipe: false) return failure } diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift index e075f646c7..f80212fe9a 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift @@ -7,9 +7,16 @@ import SQLite3 /// its userInfo: Core Data errors can contain paths and stored values. struct WalletPreparationFailure: Equatable, Identifiable { /// `keychain`: the store is not the problem — the wallet keys could not - /// be read or replayed from the keychain, and nothing was deleted. + /// be read or replayed from the keychain. enum Kind: String { case database, storage, legacyMigration, keychain } + /// The card's recovery policy, derived here so every card that renders a + /// failure reads one source: the phrase backup is offered unless the keys + /// themselves failed to read, and Export Logs authenticates first for the + /// cards that cannot rely on the lock screen having read the PIN. + var offersPhraseBackup: Bool { kind != .keychain } + var requiresAuthenticatedExport: Bool { kind == .keychain || kind == .legacyMigration } + /// Why the DashSync → SwiftDashSDK key migration did not deliver a wallet. /// Only the migrator's terminal flag names leave this boundary. enum LegacyMigrationReason: String { case failed, unknownChain, timedOut, unreadableKeychain } @@ -118,9 +125,10 @@ struct WalletPreparationFailure: Equatable, Identifiable { } if kind == .keychain { // Neither "your keys are safe" nor "your keys are lost": a read - // failed, and the keychain is untouched by the app. + // failed. No claim about the stores either — this card can + // follow a reset that removed them. return NSLocalizedString( - "Your wallet keys could not be read from this device's secure storage. Nothing was deleted. Do not delete this app. Try again or contact support for help.", + "Your wallet keys could not be read from this device's secure storage. Do not delete this app. Try again or contact support for help.", comment: "Wallet preparation failure") } return NSLocalizedString( diff --git a/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift b/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift index af53e50e91..b119e99e71 100644 --- a/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift +++ b/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift @@ -373,7 +373,7 @@ final class WalletLifecycleOverlayViewModel: ObservableObject { /// does not show the button. func backupRecoveryPhrase() { guard !isBusy, - preparationFailure?.kind != .keychain, + preparationFailure?.offersPhraseBackup != false, requirePin( for: NSLocalizedString("Backup recovery phrase", comment: "Wallet preparation"), message: NSLocalizedString("Unlock with your wallet PIN to continue.", comment: "Wallet preparation")) @@ -518,8 +518,6 @@ struct WalletLifecycleOverlayView: View { title: NSLocalizedString("Preparing your wallet…", comment: "Wallet preparation"), subtitle: NSLocalizedString("Please keep the app open.", comment: "Wallet preparation")) case let .failedWalletOpen(failure): - // A keys failure shows neither Backup nor Reset, and its - // Export Logs authenticates first, as the migration card's does. card { failureHeader(title: failure.title, message: failure.message) actionButton(NSLocalizedString("Try Again", comment: ""), prominent: true) { @@ -527,7 +525,7 @@ struct WalletLifecycleOverlayView: View { } .disabled(viewModel.isBusy) walletRecoveryActions(for: failure) - preparationHelp(authenticatedExport: failure.kind == .keychain) + preparationHelp(authenticatedExport: failure.requiresAuthenticatedExport) } case let .failedLegacyMigration(failure): // No Create/Recover here: the wallet is still in the keychain. @@ -537,7 +535,7 @@ struct WalletLifecycleOverlayView: View { viewModel.retryLegacyMigration() } .disabled(viewModel.isExportingLogs) - preparationHelp(authenticatedExport: true) + preparationHelp(authenticatedExport: failure.requiresAuthenticatedExport) } case let .switchingNetwork(_, to): progressCard( @@ -590,7 +588,7 @@ struct WalletLifecycleOverlayView: View { .disabled(viewModel.isBusy) } if viewModel.showsLocalStoreRecovery { walletRecoveryActions(for: viewModel.preparationFailure) } - preparationHelp + preparationHelp(authenticatedExport: viewModel.preparationFailure?.requiresAuthenticatedExport ?? false) } case let .failedWalletSwitch(targetId, targetName, previousId, message): card { @@ -607,7 +605,7 @@ struct WalletLifecycleOverlayView: View { } .disabled(viewModel.isExportingLogs) } - preparationHelp + preparationHelp(authenticatedExport: viewModel.preparationFailure?.requiresAuthenticatedExport ?? false) } case let .failedWalletRemoval(message): card { @@ -655,11 +653,11 @@ struct WalletLifecycleOverlayView: View { .recoveryPhraseFlowAlert(viewModel.recoveryPhraseFlow) } - /// Backup is offered unless the keys themselves failed to read; Reset - /// only when the failure record and the keychain inventory allow it. + /// Backup per the failure record's policy (never for a keys failure); + /// Reset only when the record and the keychain inventory allow it. @ViewBuilder private func walletRecoveryActions(for failure: WalletPreparationFailure?) -> some View { - if failure?.kind != .keychain { + if failure?.offersPhraseBackup != false { actionButton(NSLocalizedString("Backup recovery phrase", comment: "Wallet preparation"), prominent: false) { viewModel.backupRecoveryPhrase() } @@ -676,13 +674,10 @@ struct WalletLifecycleOverlayView: View { } } - private var preparationHelp: some View { - preparationHelp(authenticatedExport: false) - } - - /// `authenticatedExport`: the migration card shows before the lock screen - /// and the keys card cannot rely on it, so Export Logs authenticates - /// first (see `exportDiagnosticLogs`). + /// `authenticatedExport` comes from the failure record's + /// `requiresAuthenticatedExport`: the migration card shows before the + /// lock screen and the keys card cannot rely on it, so Export Logs + /// authenticates first (see `exportDiagnosticLogs`). @ViewBuilder private func preparationHelp(authenticatedExport: Bool) -> some View { if viewModel.preparationFailure != nil { diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index bb4b0cdb1e..e8e703e0bf 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -6111,7 +6111,7 @@ "There isn't enough free space to prepare your wallet. Free up storage in iPhone Settings, then try again. Your wallet keys are still stored safely on this device." = "There isn't enough free space to prepare your wallet. Free up storage in iPhone Settings, then try again. Your wallet keys are still stored safely on this device."; "Your wallet could not be opened. Your wallet keys are still stored safely on this device. Try again or contact support for help." = "Your wallet could not be opened. Your wallet keys are still stored safely on this device. Try again or contact support for help."; "Couldn't read your wallet keys" = "Couldn't read your wallet keys"; -"Your wallet keys could not be read from this device's secure storage. Nothing was deleted. Do not delete this app. Try again or contact support for help." = "Your wallet keys could not be read from this device's secure storage. Nothing was deleted. Do not delete this app. Try again or contact support for help."; +"Your wallet keys could not be read from this device's secure storage. Do not delete this app. Try again or contact support for help." = "Your wallet keys could not be read from this device's secure storage. Do not delete this app. Try again or contact support for help."; "Couldn't move your wallet" = "Couldn't move your wallet"; "Do not delete the app. Try moving your wallet again, or contact support if the problem continues." = "Do not delete the app. Try moving your wallet again, or contact support if the problem continues."; "To: %@\n\nI couldn't move my wallet from the previous version of the app.\n\nWhat happened before the error:\n" = "To: %@\n\nI couldn't move my wallet from the previous version of the app.\n\nWhat happened before the error:\n"; diff --git a/DashWalletTests/WalletPreparationFailureTests.swift b/DashWalletTests/WalletPreparationFailureTests.swift index d6241eaf99..120941afce 100644 --- a/DashWalletTests/WalletPreparationFailureTests.swift +++ b/DashWalletTests/WalletPreparationFailureTests.swift @@ -99,7 +99,12 @@ final class WalletPreparationFailureTests: XCTestCase { XCTAssertEqual(failure.kind, .keychain) XCTAssertEqual(failure.codes, ["Keychain:unreadable", "OSStatus:-25308"]) XCTAssertFalse(failure.canResetLocalData) + XCTAssertFalse(failure.offersPhraseBackup) + XCTAssertTrue(failure.requiresAuthenticatedExport) let database = WalletPreparationFailure(error: NSError(domain: "SwiftData.SwiftDataError", code: 1)) + XCTAssertTrue(database.offersPhraseBackup) + XCTAssertFalse(database.requiresAuthenticatedExport) + XCTAssertTrue(WalletPreparationFailure(legacyMigration: .failed).requiresAuthenticatedExport) XCTAssertNotEqual(failure.title, database.title) XCTAssertNotEqual(failure.title, WalletPreparationFailure(legacyMigration: .failed).title) // Neither claim: the keys were not read, and nothing was deleted. diff --git a/scripts/test_wallet_preparation.py b/scripts/test_wallet_preparation.py index 95db44deac..650d608091 100644 --- a/scripts/test_wallet_preparation.py +++ b/scripts/test_wallet_preparation.py @@ -128,6 +128,7 @@ def declaration(source, start): /// classification matches them by type. enum WalletStorageError: Error { case keychainError(OSStatus), mnemonicNotFound } enum SwiftDashSDKWalletDeletionError: Error { case invalidMnemonic, unrecognizedWalletNetwork } +enum KeyWalletError: Error { case invalidMnemonic } @MainActor final class HostRecoveryHarness { static let logger = Logger(subsystem: "wallet-preparation-tests", category: "recovery") enum HostError: Error { @@ -153,12 +154,14 @@ def declaration(source, start): func provisionDevnetWallets(handles: RuntimeHandles) async -> ManagedPlatformWallet? { nil } func unlockDashPayContactCrypto(manager: PlatformWalletManager, wallet: ManagedPlatformWallet) {} nonisolated static func strictlyPersistedMnemonics() throws -> [(walletId: Data, mnemonic: String)] { - if unreadableKeychain { throw WalletStorageError.keychainError(-25308) } + if unreadableKeychain { throw WalletStorageError.keychainError(-25291) } // errSecNotAvailable if nulMaterial { return [(Data("wallet-a".utf8), "wallet-a\u{0}trailing bytes")] } return ["wallet-a", "wallet-b"].map { (Data($0.utf8), $0) } } nonisolated static func persistedSDKWalletNetworks(in entries: [(walletId: Data, mnemonic: String)]) throws -> Set { - if invalidMaterial { throw HostError.invalidMnemonic } + // Production resolves ids through SwiftDashSDKStoredWalletNetworkResolver, + // whose refusal is this error. + if invalidMaterial { throw SwiftDashSDKWalletDeletionError.unrecognizedWalletNetwork } return [.mainnet] } static func recoverablePersistedMnemonics(_ entries: [(walletId: Data, mnemonic: String)], @@ -320,9 +323,19 @@ def declaration(source, start): HostRecoveryHarness.unreadableKeychain = true let failure = await startFailure(HostRecoveryHarness()) XCTAssertEqual(failure?.kind, .keychain) - XCTAssertEqual(failure?.codes, ["Keychain:unreadable", "OSStatus:-25308"]) + XCTAssertEqual(failure?.codes, ["Keychain:unreadable", "OSStatus:-25291"]) XCTAssertEqual(failure?.canResetLocalData, false) } + func testLockedKeychainDuringTheReplayKeepsTheNoCardFlow() { + // errSecInteractionNotAllowed heals on unlock; a pinned card would + // turn the foreground kick off (`allowsAutomaticWalletPreparation`). + typealias HostError = HostRecoveryHarness.HostError + XCTAssertNil(HostRecoveryHarness.preparationFailure( + forStartError: HostError.walletBootstrapFailed(WalletStorageError.keychainError(-25308)))) + XCTAssertEqual(HostRecoveryHarness.preparationFailure( + forStartError: HostError.walletBootstrapFailed(WalletStorageError.keychainError(-25291)))?.codes, + ["Keychain:unreadable", "OSStatus:-25291"]) + } func testUnclassifiableMaterialShowsTheKeysCard() async throws { HostRecoveryHarness.invalidMaterial = true let failure = await startFailure(HostRecoveryHarness()) @@ -355,6 +368,11 @@ def declaration(source, start): let resolver = HostRecoveryHarness.preparationFailure( forStartError: HostError.walletBootstrapFailed(SwiftDashSDKWalletDeletionError.unrecognizedWalletNetwork)) XCTAssertEqual(resolver?.codes, ["Keychain:unclassifiable"]) + // The resolver constructs a wallet from the stored phrase; its refusal + // of material that passed word validation is a keys failure too. + let construction = HostRecoveryHarness.preparationFailure( + forStartError: HostError.walletBootstrapFailed(KeyWalletError.invalidMnemonic)) + XCTAssertEqual(construction?.codes, ["Keychain:unclassifiable"]) XCTAssertNil(HostRecoveryHarness.preparationFailure(forStartError: HostError.sdkInitFailed(swiftData))) XCTAssertNil(HostRecoveryHarness.keysFailure(in: swiftData)) } @@ -461,13 +479,23 @@ def declaration(source, start): var events: [String] = [] func enqueue(_ op: @escaping @MainActor () async -> Void) { lifecycleQueue.enqueue(op) } func drain() async { await lifecycleQueue.enqueue {}.value } + /// Returned around the open, as the wallet-presence gate and the + /// unclassified-start fallback do in production. var refreshFailure: WalletPreparationFailure? + /// Classified by the open itself (the `prepareWallet` failure closure). + var openFailure: WalletPreparationFailure? @discardableResult func refresh(trigger: RefreshTrigger, runtimeAlreadyStopped: Bool = false) async -> WalletPreparationFailure? { refreshCalls += 1 events.append("refresh") if runtimeAlreadyStopped { assert(WalletLifecycleTransitionState.shared.phase == .resettingLocalStores) } if let refreshFailure { return refreshFailure } + if let openFailure { + try? await WalletLifecycleTransitionState.shared.prepareWallet { + throw NSError(domain: "Open", code: 1) + } failure: { _ in openFailure } + return WalletLifecycleTransitionState.shared.preparationFailure ?? openFailure + } try? await WalletLifecycleTransitionState.shared.prepareWallet {} failure: { _ in nil } return nil } @@ -520,6 +548,7 @@ def declaration(source, start): state.finish() runtime.refreshCalls = 0 runtime.refreshFailure = nil + runtime.openFailure = nil runtime.events = [] SwiftDashSDKHost.shared.validationError = nil SwiftDashSDKHost.shared.releaseError = nil @@ -765,6 +794,28 @@ def declaration(source, start): XCTAssertNil(state.preparationFailure) XCTAssertEqual(runtime.refreshCalls, 2) } + func testRetryFromTheKeysCardKeepsItUnlessTheOpenClassifiedTheFailure() async { + let keys = WalletPreparationFailure(keys: .unreadable, status: -25291) + state.fail(.failedWalletOpen(keys)) + // The presence gate or the unclassified-start fallback: a store + // record built around the open must not replace the keys card. + runtime.refreshFailure = WalletPreparationFailure(error: NSError(domain: "Presence", code: 2)) + await runtime.retryWalletPreparation() + XCTAssertEqual(state.phase, .failedWalletOpen(keys)) + XCTAssertEqual(state.preparationFailure, keys) + // A record the open itself classified replaces it. + runtime.refreshFailure = nil + let store = WalletPreparationFailure(error: NSError(domain: "SwiftData.SwiftDataError", code: 1)) + runtime.openFailure = store + await runtime.retryWalletPreparation() + XCTAssertEqual(state.phase, .failedWalletOpen(store)) + // A store card keeps today's rule: any returned record replaces it. + runtime.openFailure = nil + let other = WalletPreparationFailure(error: NSError(domain: "Presence", code: 2)) + runtime.refreshFailure = other + await runtime.retryWalletPreparation() + XCTAssertEqual(state.phase, .failedWalletOpen(other)) + } } ''') (package / "Package.swift").write_text('''// swift-tools-version: 5.9 From db3eca8315235845f6f14e405b1d8b55881432dc Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Mon, 12 Oct 2026 15:14:38 +0200 Subject: [PATCH 5/9] fix(wallet): keep Backup on the keys card, retry by whether the open ran, heal transient statuses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Backup returns to every failure card: the recovery-phrase flow reads each stored phrase on its own, and one entry failing the replay (an unclassifiable or mismatching entry, or one of several) does not mean the others cannot be read. Hiding it left a blocking "do not delete this app" card with no way to save a readable phrase. retryWalletPreparation now decides by whether prepareWallet ran: it moves the phase the moment it does, so a phase still showing the old record means the wallet-presence gate refused before the open — the same keychain failure, whose store record must not replace a keys card. Once the open ran, the keys were read, and whatever the attempt returns is the card. A keys card leaves automatic preparation on, so a transient keychain status (the lock, securityd) is cleared by the next foreground or connectivity kick instead of pinning the card until Try Again; the -25308 special case goes. KeyWalletError classifies as keys only for invalidMnemonic and invalidInput, the construction refusing material; the HostError.invalidMnemonic arm, which start's bootstrap no longer produces, goes. The file log names a category only for a record the open classified. Co-Authored-By: Claude Fable 5.1 --- .../SwiftDashSDK/SwiftDashSDKHost.swift | 32 +++---- .../SwiftDashSDKWalletRuntime.swift | 33 ++++--- .../WalletLifecycleTransitionState.swift | 7 +- .../WalletPreparationFailure.swift | 13 ++- .../UI/Main/WalletLifecycleOverlay.swift | 26 +++--- .../WalletPreparationFailureTests.swift | 2 - scripts/test_wallet_preparation.py | 89 +++++++++++++++---- 7 files changed, 131 insertions(+), 71 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift index f12d486496..14836e00e2 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift @@ -525,25 +525,23 @@ final class SwiftDashSDKHost { /// card; a bootstrap failure is a keys failure only when `keysFailure(in:)` /// recognizes its cause, otherwise it is a store failure too — a SwiftData /// write that failed while replaying the keychain, or a recovery marker - /// that could not be written — and `WalletPreparationFailure(error:)` - /// decides from its codes whether a reset is offered. + /// that could not be written. Those bridge to `OtherError` codes, so the + /// database card they get never offers a reset; only a store that would + /// not open can. /// - /// Two bootstrap causes keep the no-card flow this path always had, so an - /// automatic kick (foreground, connectivity) retries instead of a pinned - /// card: keys readable but nothing eligible for the network - /// (`walletNotFound`) — `WalletEnvironment.hasWallet` routes that - /// inventory to setup, and a card would sit over it — and a keychain read - /// refused because protected data was unavailable - /// (`errSecInteractionNotAllowed`), which heals on unlock. + /// Keys readable but nothing eligible for the network (`walletNotFound`) + /// keeps the no-card flow this path always had: `WalletEnvironment.hasWallet` + /// routes that inventory to setup, and a card would sit over it. A + /// transient keychain status (the lock, securityd unavailable) gets the + /// keys card, but that card leaves automatic preparation on + /// (`WalletLifecycleTransitionState.allowsAutomaticWalletPreparation`), + /// so the next foreground or connectivity kick clears it. nonisolated static func preparationFailure(forStartError error: Error) -> WalletPreparationFailure? { - let interactionNotAllowed: OSStatus = -25308 // errSecInteractionNotAllowed switch error { case HostError.modelContainerFailed(let underlying): return WalletPreparationFailure(error: underlying) case HostError.walletBootstrapFailed(HostError.walletNotFound): return nil - case HostError.walletBootstrapFailed(WalletStorageError.keychainError(interactionNotAllowed)): - return nil case HostError.walletBootstrapFailed(let underlying): if let keys = keysFailure(in: underlying) { return WalletPreparationFailure(keys: keys.reason, status: keys.status) @@ -567,11 +565,13 @@ final class SwiftDashSDKHost { return (.notFound, nil) case SwiftDashSDKWalletDeletionError.invalidMnemonic, SwiftDashSDKWalletDeletionError.unrecognizedWalletNetwork, - HostError.invalidMnemonic, - is KeyWalletError: + KeyWalletError.invalidMnemonic, + KeyWalletError.invalidInput: // The resolver derives ids by constructing a wallet from the - // stored phrase; `KeyWalletError` is that construction refusing - // material that passed word validation. + // stored phrase; these two `KeyWalletError` cases are that + // construction refusing material that passed word validation. + // Its other cases (allocation, network, state) say nothing about + // the keys and stay a store failure. return (.unclassifiable, nil) case HostError.mnemonicRoundTripMismatch: return (.idMismatch, nil) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift index 1a67a39245..0fb54a5d63 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift @@ -245,17 +245,17 @@ final class SwiftDashSDKWalletRuntime: NSObject { let state = WalletLifecycleTransitionState.shared guard case let .failedWalletOpen(shown) = state.phase else { return } if let failure = await self.refresh(trigger: .startIfReady) { - // A record the open classified itself replaces the card. One - // built around the open — the wallet-presence gate, or the - // fallback for a start error the host left unclassified — - // carries the store copy's "keys are stored safely" and - // Backup, which must not replace a keys card. - let classifiedByOpen = state.preparationFailure == failure - if shown.kind == .keychain, !classifiedByOpen { - state.fail(.failedWalletOpen(shown)) - } else { - state.fail(.failedWalletOpen(failure)) - } + // `prepareWallet` moves the phase the moment the open runs + // (to the record it classified, or to idle). A phase still + // showing the old record means the open was never reached: + // the wallet-presence gate refused, which for a keys card is + // the same keychain failure, and its store record ("keys are + // stored safely") must not replace the card. Once the open + // ran, the keys were read, and whatever the attempt returns + // is the card to show. + let openNotReached = state.phase == .failedWalletOpen(shown) && state.preparationFailure == shown + if shown.kind == .keychain, openNotReached { return } + state.fail(.failedWalletOpen(failure)) } }.value } @@ -933,8 +933,15 @@ final class SwiftDashSDKWalletRuntime: NSObject { } catch { Self.logger.error("🧭 RUNTIME :: Core start failed: \(String(describing: error), privacy: .public)") let failure = WalletLifecycleTransitionState.shared.preparationFailure ?? WalletPreparationFailure(error: error) - // os_log does not reach the diagnostic export; the file log does. - DWLogger.log("RUNTIME Core start failed category=\(failure.kind.rawValue) codes=\(failure.codes.joined(separator: ","))") + // os_log does not reach the diagnostic export; the file log + // does. Only a record the open classified names a category: + // the fallback for anything else (SPV start, devnet preflight) + // bridges to OtherError codes and would mislabel the cause. + if let classified = WalletLifecycleTransitionState.shared.preparationFailure { + DWLogger.log("RUNTIME Core start failed category=\(classified.kind.rawValue) codes=\(classified.codes.joined(separator: ","))") + } else { + DWLogger.log("RUNTIME Core start failed outside the wallet open codes=\(failure.codes.joined(separator: ","))") + } await fullReset(lastError: error.localizedDescription, forWipe: false) return failure } diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift index 0e8d7a302a..e0d9592c5c 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift @@ -128,9 +128,14 @@ final class WalletLifecycleTransitionState: ObservableObject { /// Automatic kicks must leave the failure card and any unsent support /// draft intact. Explicit Retry / Sync Now use their existing entry points. + /// A keys card leaves automatic preparation on: a keychain status that + /// failed the replay is often transient (the lock, securityd), and the + /// next foreground or connectivity kick is what heals it. A store card + /// keeps the kicks off until the user acts. var allowsAutomaticWalletPreparation: Bool { switch phase { - case .failedWalletOpen, .resettingLocalStores: return false + case let .failedWalletOpen(failure): return failure.kind == .keychain + case .resettingLocalStores: return false default: return true } } diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift index f80212fe9a..18849c8392 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift @@ -10,11 +10,9 @@ struct WalletPreparationFailure: Equatable, Identifiable { /// be read or replayed from the keychain. enum Kind: String { case database, storage, legacyMigration, keychain } - /// The card's recovery policy, derived here so every card that renders a - /// failure reads one source: the phrase backup is offered unless the keys - /// themselves failed to read, and Export Logs authenticates first for the - /// cards that cannot rely on the lock screen having read the PIN. - var offersPhraseBackup: Bool { kind != .keychain } + /// Export Logs authenticates first on the cards that cannot rely on the + /// lock screen having read the PIN. Derived here so every card that + /// renders a failure reads one source. var requiresAuthenticatedExport: Bool { kind == .keychain || kind == .legacyMigration } /// Why the DashSync → SwiftDashSDK key migration did not deliver a wallet. @@ -41,8 +39,9 @@ struct WalletPreparationFailure: Equatable, Identifiable { } /// The store opened, but the wallet keys could not be read or replayed. - /// Never resettable: deleting the store cannot help, and the card offers - /// no phrase backup either, since the phrase is what could not be read. + /// Never resettable: deleting the store cannot help. The phrase backup + /// stays on the card as a best-effort read — one bad entry fails the + /// replay for every wallet, while the others may read fine. init(keys reason: KeysReason, status: OSStatus? = nil, now: Date = Date()) { id = UUID() occurredAt = now diff --git a/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift b/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift index b119e99e71..f47e87001a 100644 --- a/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift +++ b/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift @@ -368,12 +368,11 @@ final class WalletLifecycleOverlayViewModel: ObservableObject { /// Backup recovery phrase on the wallet-open failure card: the Security /// menu's flow (PIN, then one phrase or a wallet picker), hosted modally - /// in the overlay window because the card has no navigation stack. Not - /// on a keys failure: the phrase is what could not be read, and the card - /// does not show the button. + /// in the overlay window because the card has no navigation stack. Also + /// on a keys failure: the flow reads each stored phrase on its own, and + /// one entry failing the replay does not mean the others cannot be read. func backupRecoveryPhrase() { guard !isBusy, - preparationFailure?.offersPhraseBackup != false, requirePin( for: NSLocalizedString("Backup recovery phrase", comment: "Wallet preparation"), message: NSLocalizedString("Unlock with your wallet PIN to continue.", comment: "Wallet preparation")) @@ -524,7 +523,7 @@ struct WalletLifecycleOverlayView: View { viewModel.retryWalletOpen() } .disabled(viewModel.isBusy) - walletRecoveryActions(for: failure) + walletRecoveryActions preparationHelp(authenticatedExport: failure.requiresAuthenticatedExport) } case let .failedLegacyMigration(failure): @@ -587,7 +586,7 @@ struct WalletLifecycleOverlayView: View { } .disabled(viewModel.isBusy) } - if viewModel.showsLocalStoreRecovery { walletRecoveryActions(for: viewModel.preparationFailure) } + if viewModel.showsLocalStoreRecovery { walletRecoveryActions } preparationHelp(authenticatedExport: viewModel.preparationFailure?.requiresAuthenticatedExport ?? false) } case let .failedWalletSwitch(targetId, targetName, previousId, message): @@ -653,16 +652,15 @@ struct WalletLifecycleOverlayView: View { .recoveryPhraseFlowAlert(viewModel.recoveryPhraseFlow) } - /// Backup per the failure record's policy (never for a keys failure); - /// Reset only when the record and the keychain inventory allow it. + /// Backup on every failure card — a best-effort read of each stored + /// phrase, which a keys failure of one entry does not rule out; Reset + /// only when the record and the keychain inventory allow it. @ViewBuilder - private func walletRecoveryActions(for failure: WalletPreparationFailure?) -> some View { - if failure?.offersPhraseBackup != false { - actionButton(NSLocalizedString("Backup recovery phrase", comment: "Wallet preparation"), prominent: false) { - viewModel.backupRecoveryPhrase() - } - .disabled(viewModel.isBusy) + private var walletRecoveryActions: some View { + actionButton(NSLocalizedString("Backup recovery phrase", comment: "Wallet preparation"), prominent: false) { + viewModel.backupRecoveryPhrase() } + .disabled(viewModel.isBusy) if viewModel.canResetWalletData { actionButton( NSLocalizedString("Reset wallet data and rescan", comment: "Wallet preparation"), diff --git a/DashWalletTests/WalletPreparationFailureTests.swift b/DashWalletTests/WalletPreparationFailureTests.swift index 120941afce..342775d1eb 100644 --- a/DashWalletTests/WalletPreparationFailureTests.swift +++ b/DashWalletTests/WalletPreparationFailureTests.swift @@ -99,10 +99,8 @@ final class WalletPreparationFailureTests: XCTestCase { XCTAssertEqual(failure.kind, .keychain) XCTAssertEqual(failure.codes, ["Keychain:unreadable", "OSStatus:-25308"]) XCTAssertFalse(failure.canResetLocalData) - XCTAssertFalse(failure.offersPhraseBackup) XCTAssertTrue(failure.requiresAuthenticatedExport) let database = WalletPreparationFailure(error: NSError(domain: "SwiftData.SwiftDataError", code: 1)) - XCTAssertTrue(database.offersPhraseBackup) XCTAssertFalse(database.requiresAuthenticatedExport) XCTAssertTrue(WalletPreparationFailure(legacyMigration: .failed).requiresAuthenticatedExport) XCTAssertNotEqual(failure.title, database.title) diff --git a/scripts/test_wallet_preparation.py b/scripts/test_wallet_preparation.py index 650d608091..7ada8d7bd8 100644 --- a/scripts/test_wallet_preparation.py +++ b/scripts/test_wallet_preparation.py @@ -128,7 +128,7 @@ def declaration(source, start): /// classification matches them by type. enum WalletStorageError: Error { case keychainError(OSStatus), mnemonicNotFound } enum SwiftDashSDKWalletDeletionError: Error { case invalidMnemonic, unrecognizedWalletNetwork } -enum KeyWalletError: Error { case invalidMnemonic } +enum KeyWalletError: Error { case invalidInput(String), invalidMnemonic(String), invalidState(String) } @MainActor final class HostRecoveryHarness { static let logger = Logger(subsystem: "wallet-preparation-tests", category: "recovery") enum HostError: Error { @@ -326,15 +326,21 @@ def declaration(source, start): XCTAssertEqual(failure?.codes, ["Keychain:unreadable", "OSStatus:-25291"]) XCTAssertEqual(failure?.canResetLocalData, false) } - func testLockedKeychainDuringTheReplayKeepsTheNoCardFlow() { - // errSecInteractionNotAllowed heals on unlock; a pinned card would - // turn the foreground kick off (`allowsAutomaticWalletPreparation`). + func testEveryKeychainStatusShowsTheKeysCardAndLeavesAutomaticPreparationOn() { + // Transient statuses (the lock, securityd) are not told apart here; + // the keys card leaves the automatic kicks on instead. typealias HostError = HostRecoveryHarness.HostError - XCTAssertNil(HostRecoveryHarness.preparationFailure( - forStartError: HostError.walletBootstrapFailed(WalletStorageError.keychainError(-25308)))) - XCTAssertEqual(HostRecoveryHarness.preparationFailure( - forStartError: HostError.walletBootstrapFailed(WalletStorageError.keychainError(-25291)))?.codes, - ["Keychain:unreadable", "OSStatus:-25291"]) + for status: OSStatus in [-25308, -25291, -34018] { + let failure = HostRecoveryHarness.preparationFailure( + forStartError: HostError.walletBootstrapFailed(WalletStorageError.keychainError(status))) + XCTAssertEqual(failure?.codes, ["Keychain:unreadable", "OSStatus:\(status)"]) + let state = WalletLifecycleTransitionState() + state.fail(.failedWalletOpen(failure!)) + XCTAssertTrue(state.allowsAutomaticWalletPreparation) + } + let store = WalletLifecycleTransitionState() + store.fail(.failedWalletOpen(WalletPreparationFailure(error: NSError(domain: "SwiftData.SwiftDataError", code: 1)))) + XCTAssertFalse(store.allowsAutomaticWalletPreparation) } func testUnclassifiableMaterialShowsTheKeysCard() async throws { HostRecoveryHarness.invalidMaterial = true @@ -370,9 +376,14 @@ def declaration(source, start): XCTAssertEqual(resolver?.codes, ["Keychain:unclassifiable"]) // The resolver constructs a wallet from the stored phrase; its refusal // of material that passed word validation is a keys failure too. - let construction = HostRecoveryHarness.preparationFailure( - forStartError: HostError.walletBootstrapFailed(KeyWalletError.invalidMnemonic)) - XCTAssertEqual(construction?.codes, ["Keychain:unclassifiable"]) + for material in [KeyWalletError.invalidMnemonic("bad"), .invalidInput("bad")] { + let construction = HostRecoveryHarness.preparationFailure( + forStartError: HostError.walletBootstrapFailed(material)) + XCTAssertEqual(construction?.codes, ["Keychain:unclassifiable"]) + } + // Its other cases say nothing about the stored material. + XCTAssertEqual(HostRecoveryHarness.preparationFailure( + forStartError: HostError.walletBootstrapFailed(KeyWalletError.invalidState("ffi")))?.kind, .database) XCTAssertNil(HostRecoveryHarness.preparationFailure(forStartError: HostError.sdkInitFailed(swiftData))) XCTAssertNil(HostRecoveryHarness.keysFailure(in: swiftData)) } @@ -484,6 +495,11 @@ def declaration(source, start): var refreshFailure: WalletPreparationFailure? /// Classified by the open itself (the `prepareWallet` failure closure). var openFailure: WalletPreparationFailure? + /// The open failed with a cause the host left unclassified (closure nil): + /// the production fallback record is returned after `finish()`. + var unclassifiedOpenFailure: WalletPreparationFailure? + /// The open succeeded and a later start step (SPV) failed. + var postOpenFailure: WalletPreparationFailure? @discardableResult func refresh(trigger: RefreshTrigger, runtimeAlreadyStopped: Bool = false) async -> WalletPreparationFailure? { refreshCalls += 1 @@ -496,8 +512,14 @@ def declaration(source, start): } failure: { _ in openFailure } return WalletLifecycleTransitionState.shared.preparationFailure ?? openFailure } + if let unclassifiedOpenFailure { + try? await WalletLifecycleTransitionState.shared.prepareWallet { + throw NSError(domain: "Open", code: 2) + } failure: { _ in nil } + return unclassifiedOpenFailure + } try? await WalletLifecycleTransitionState.shared.prepareWallet {} failure: { _ in nil } - return nil + return postOpenFailure } func resolveCurrentNetwork() -> Result { .success(.testnet) } func isCoreRuntimeReady(for network: WalletEnvironment.NetworkKind) -> Bool { @@ -549,6 +571,8 @@ def declaration(source, start): runtime.refreshCalls = 0 runtime.refreshFailure = nil runtime.openFailure = nil + runtime.unclassifiedOpenFailure = nil + runtime.postOpenFailure = nil runtime.events = [] SwiftDashSDKHost.shared.validationError = nil SwiftDashSDKHost.shared.releaseError = nil @@ -794,28 +818,57 @@ def declaration(source, start): XCTAssertNil(state.preparationFailure) XCTAssertEqual(runtime.refreshCalls, 2) } - func testRetryFromTheKeysCardKeepsItUnlessTheOpenClassifiedTheFailure() async { + func testRetryFromTheKeysCardKeepsItOnlyWhenTheOpenWasNotReached() async { let keys = WalletPreparationFailure(keys: .unreadable, status: -25291) state.fail(.failedWalletOpen(keys)) - // The presence gate or the unclassified-start fallback: a store - // record built around the open must not replace the keys card. + // The wallet-presence gate refused before the open: the same keychain + // failure, and its store record must not replace the keys card. runtime.refreshFailure = WalletPreparationFailure(error: NSError(domain: "Presence", code: 2)) await runtime.retryWalletPreparation() XCTAssertEqual(state.phase, .failedWalletOpen(keys)) XCTAssertEqual(state.preparationFailure, keys) - // A record the open itself classified replaces it. + // The open ran and classified a store failure: it replaces the card. runtime.refreshFailure = nil let store = WalletPreparationFailure(error: NSError(domain: "SwiftData.SwiftDataError", code: 1)) runtime.openFailure = store await runtime.retryWalletPreparation() XCTAssertEqual(state.phase, .failedWalletOpen(store)) - // A store card keeps today's rule: any returned record replaces it. + // The open ran and failed unclassified (walletNotFound): the keys + // were read, so the fallback record is the card, not the stale one. + state.fail(.failedWalletOpen(keys)) runtime.openFailure = nil + let fallback = WalletPreparationFailure(error: NSError(domain: "Fallback", code: 3)) + runtime.unclassifiedOpenFailure = fallback + await runtime.retryWalletPreparation() + XCTAssertEqual(state.phase, .failedWalletOpen(fallback)) + // The open succeeded and SPV failed afterwards: same, the keys were read. + state.fail(.failedWalletOpen(keys)) + runtime.unclassifiedOpenFailure = nil + let spv = WalletPreparationFailure(error: NSError(domain: "SPV", code: 4)) + runtime.postOpenFailure = spv + await runtime.retryWalletPreparation() + XCTAssertEqual(state.phase, .failedWalletOpen(spv)) + // A store card keeps today's rule: any returned record replaces it. + runtime.postOpenFailure = nil let other = WalletPreparationFailure(error: NSError(domain: "Presence", code: 2)) runtime.refreshFailure = other await runtime.retryWalletPreparation() XCTAssertEqual(state.phase, .failedWalletOpen(other)) } + func testKeysCardIsClearedByTheNextAutomaticKick() async { + state.fail(.failedWalletOpen(WalletPreparationFailure(keys: .unreadable, status: -25308))) + runtime.enqueueRefresh(trigger: .startIfReady) + await runtime.drain() + XCTAssertEqual(runtime.refreshCalls, 1) + XCTAssertEqual(state.phase, .idle) + XCTAssertNil(state.preparationFailure) + // A store card still refuses the automatic kick. + await failOpen() + runtime.enqueueRefresh(trigger: .startIfReady) + await runtime.drain() + XCTAssertEqual(runtime.refreshCalls, 1) + guard case .failedWalletOpen = state.phase else { return XCTFail("Store card dismissed by an automatic kick") } + } } ''') (package / "Package.swift").write_text('''// swift-tools-version: 5.9 From 7f8f31b189766a93b76339e03c0d0a54f8a920ae Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Mon, 12 Oct 2026 15:23:30 +0200 Subject: [PATCH 6/9] fix(wallet): admit the connectivity-return kick from a keys card startIfReadyWhenLifecycleIdle admitted only .idle, so connectivity returning under a keys card never reached refresh although that card leaves automatic preparation on. Admit .failedWalletOpen of kind .keychain there too; every interactive transition still owns the runtime. Co-Authored-By: Claude Fable 5.1 --- .../SwiftDashSDK/SwiftDashSDKWalletRuntime.swift | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift index 0fb54a5d63..679d88ad56 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift @@ -373,7 +373,16 @@ final class SwiftDashSDKWalletRuntime: NSObject { nonisolated static func startIfReadyWhenLifecycleIdle() { dispatchOnPipeline { shared.enqueue { - guard WalletLifecycleTransitionState.shared.phase == .idle else { + // Idle, or a keys card: that card leaves automatic preparation + // on, and connectivity returning is one of the kicks meant to + // clear it. Every interactive transition still owns the runtime. + let admitted: Bool + switch WalletLifecycleTransitionState.shared.phase { + case .idle: admitted = true + case let .failedWalletOpen(failure): admitted = failure.kind == .keychain + default: admitted = false + } + guard admitted else { Self.logger.info( "🧭 RUNTIME :: connectivity-return kick skipped — a lifecycle transition owns the runtime") return From 494e3aaf5b19b42b3743882034d93ac9d0568dc7 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Mon, 12 Oct 2026 15:47:13 +0200 Subject: [PATCH 7/9] fix(wallet): retry from a keys card follows the automatic kick's no-card rule MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the retry reached the open and the start ended unclassified (walletNotFound, SDK init, configure) or failed after a successful open (SPV), retryWalletPreparation pinned the fallback record — a database card with "keys are stored safely" and automatic preparation off — where an automatic kick would have left no card. From a keys card the retry now agrees with the kick: a phase at idle after the attempt means nothing was classified, so nothing is pinned; a phase still showing the old record means the open was not reached, so the card stays; only a record the open classified replaces it. Store cards keep today's rule. Co-Authored-By: Claude Fable 5.1 --- .../SwiftDashSDKWalletRuntime.swift | 24 ++++++++++++------- scripts/test_wallet_preparation.py | 18 +++++++------- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift index 679d88ad56..263800ec6e 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift @@ -246,15 +246,21 @@ final class SwiftDashSDKWalletRuntime: NSObject { guard case let .failedWalletOpen(shown) = state.phase else { return } if let failure = await self.refresh(trigger: .startIfReady) { // `prepareWallet` moves the phase the moment the open runs - // (to the record it classified, or to idle). A phase still - // showing the old record means the open was never reached: - // the wallet-presence gate refused, which for a keys card is - // the same keychain failure, and its store record ("keys are - // stored safely") must not replace the card. Once the open - // ran, the keys were read, and whatever the attempt returns - // is the card to show. - let openNotReached = state.phase == .failedWalletOpen(shown) && state.preparationFailure == shown - if shown.kind == .keychain, openNotReached { return } + // (to the record it classified, or to idle). From a keys card + // the retry follows the automatic kick's rule: a phase still + // showing the old record means the open was never reached + // (the wallet-presence gate refused, or a step before the + // open failed — the same keychain failure, or no keychain + // read at all), so the card stays; a phase at idle means the + // open ran and classified nothing, and the fallback record + // (`OtherError`, "keys are stored safely") is no card at all, + // exactly as the kick would leave it. Only a record the open + // classified replaces the card. A store card keeps today's + // rule: any returned record replaces it. + if shown.kind == .keychain { + let openNotReached = state.phase == .failedWalletOpen(shown) && state.preparationFailure == shown + if openNotReached || state.phase == .idle { return } + } state.fail(.failedWalletOpen(failure)) } }.value diff --git a/scripts/test_wallet_preparation.py b/scripts/test_wallet_preparation.py index 7ada8d7bd8..ef002b8846 100644 --- a/scripts/test_wallet_preparation.py +++ b/scripts/test_wallet_preparation.py @@ -833,23 +833,23 @@ def declaration(source, start): runtime.openFailure = store await runtime.retryWalletPreparation() XCTAssertEqual(state.phase, .failedWalletOpen(store)) - // The open ran and failed unclassified (walletNotFound): the keys - // were read, so the fallback record is the card, not the stale one. + // The open ran and classified nothing (walletNotFound, SDK init): the + // automatic kick's rule — the fallback record is no card at all. state.fail(.failedWalletOpen(keys)) runtime.openFailure = nil - let fallback = WalletPreparationFailure(error: NSError(domain: "Fallback", code: 3)) - runtime.unclassifiedOpenFailure = fallback + runtime.unclassifiedOpenFailure = WalletPreparationFailure(error: NSError(domain: "Fallback", code: 3)) await runtime.retryWalletPreparation() - XCTAssertEqual(state.phase, .failedWalletOpen(fallback)) - // The open succeeded and SPV failed afterwards: same, the keys were read. + XCTAssertEqual(state.phase, .idle) + XCTAssertNil(state.preparationFailure) + // The open succeeded and SPV failed afterwards: same, no card. state.fail(.failedWalletOpen(keys)) runtime.unclassifiedOpenFailure = nil - let spv = WalletPreparationFailure(error: NSError(domain: "SPV", code: 4)) - runtime.postOpenFailure = spv + runtime.postOpenFailure = WalletPreparationFailure(error: NSError(domain: "SPV", code: 4)) await runtime.retryWalletPreparation() - XCTAssertEqual(state.phase, .failedWalletOpen(spv)) + XCTAssertEqual(state.phase, .idle) // A store card keeps today's rule: any returned record replaces it. runtime.postOpenFailure = nil + await failOpen() let other = WalletPreparationFailure(error: NSError(domain: "Presence", code: 2)) runtime.refreshFailure = other await runtime.retryWalletPreparation() From f0f485dba2a0c87d291df81388fbf3ba8b66bf94 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Mon, 12 Oct 2026 19:27:35 +0200 Subject: [PATCH 8/9] fix(wallet): hold automatic preparation while a card flow owns the window A keys card leaves automatic preparation on, so a foreground or connectivity kick could reach prepareWallet while the card's PIN prompt, phrase modal, Help sheet with its composer, or share sheet was up; the phase change would take the phrase screen down and, on a successful open, release the window with an unsent support message. The overlay view model now holds the presentation on the transition state while any of those flows is up (the phrase modal reports its presentation through the presenter), both automatic entry points refuse a kick under the hold and record it, and the release replays the recorded kick through startIfReady. Store cards are unaffected. Covered in the state tests and the harness through the real enqueueRefresh and network-change path. Co-Authored-By: Claude Fable 5.1 --- .../SwiftDashSDKWalletRuntime.swift | 18 +++++++--- .../WalletLifecycleTransitionState.swift | 35 +++++++++++++++++-- .../UI/Main/WalletLifecycleOverlay.swift | 32 ++++++++++++++--- .../UI/Menu/Security/RecoveryPhraseFlow.swift | 6 ++++ .../WalletLifecycleTransitionStateTests.swift | 19 ++++++++++ scripts/test_wallet_preparation.py | 18 ++++++++++ 6 files changed, 116 insertions(+), 12 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift index 263800ec6e..ca214dcb1b 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift @@ -380,15 +380,18 @@ final class SwiftDashSDKWalletRuntime: NSObject { dispatchOnPipeline { shared.enqueue { // Idle, or a keys card: that card leaves automatic preparation - // on, and connectivity returning is one of the kicks meant to - // clear it. Every interactive transition still owns the runtime. + // on (unless one of its flows holds the window), and + // connectivity returning is one of the kicks meant to clear + // it. Every interactive transition still owns the runtime. + let state = WalletLifecycleTransitionState.shared let admitted: Bool - switch WalletLifecycleTransitionState.shared.phase { + switch state.phase { case .idle: admitted = true - case let .failedWalletOpen(failure): admitted = failure.kind == .keychain + case .failedWalletOpen: admitted = state.allowsAutomaticWalletPreparation default: admitted = false } guard admitted else { + state.recordDeferredAutomaticPreparation() Self.logger.info( "🧭 RUNTIME :: connectivity-return kick skipped — a lifecycle transition owns the runtime") return @@ -818,7 +821,12 @@ final class SwiftDashSDKWalletRuntime: NSObject { // Automatic kicks (including material-change notifications) must // leave Help and its unsent draft intact. Re-read on the serial // queue: opening may have failed since this kick was enqueued. - guard WalletLifecycleTransitionState.shared.allowsAutomaticWalletPreparation else { return } + let state = WalletLifecycleTransitionState.shared + guard state.allowsAutomaticWalletPreparation else { + // A keys card under one of its own flows: replayed on release. + state.recordDeferredAutomaticPreparation() + return + } await self?.refresh(trigger: trigger) } } diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift index e0d9592c5c..738ad5fc73 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift @@ -130,16 +130,45 @@ final class WalletLifecycleTransitionState: ObservableObject { /// draft intact. Explicit Retry / Sync Now use their existing entry points. /// A keys card leaves automatic preparation on: a keychain status that /// failed the replay is often transient (the lock, securityd), and the - /// next foreground or connectivity kick is what heals it. A store card - /// keeps the kicks off until the user acts. + /// next foreground or connectivity kick is what heals it — unless one of + /// the card's own flows holds the window (`holdRecoveryPresentation`), + /// since a start would take the phase from under the phrase modal or the + /// Help composer. A store card keeps the kicks off until the user acts. var allowsAutomaticWalletPreparation: Bool { switch phase { - case let .failedWalletOpen(failure): return failure.kind == .keychain + case let .failedWalletOpen(failure): return failure.kind == .keychain && !recoveryPresentationHeld case .resettingLocalStores: return false default: return true } } + /// Set by the failure card while its PIN prompt, phrase modal, Help sheet + /// or share sheet owns the window; cleared when that flow ends. + private(set) var recoveryPresentationHeld = false + /// An automatic kick the hold refused, to be replayed on release. + private(set) var automaticPreparationDeferred = false + + func holdRecoveryPresentation() { + recoveryPresentationHeld = true + } + + /// Ends the hold. Returns whether a kick was refused meanwhile, so the + /// caller can replay it; the deferral is consumed either way. + @discardableResult + func releaseRecoveryPresentation() -> Bool { + recoveryPresentationHeld = false + defer { automaticPreparationDeferred = false } + return automaticPreparationDeferred + } + + /// Called by an automatic entry point that was refused: remembers the + /// kick when only the hold stood in its way (a keys card under a flow). + func recordDeferredAutomaticPreparation() { + guard recoveryPresentationHeld, + case let .failedWalletOpen(failure) = phase, failure.kind == .keychain else { return } + automaticPreparationDeferred = true + } + /// Atomically admit `next` as the active operation. Admission rules: any /// operation may begin from `.idle`; a network switch may also begin from /// `.failedNetworkSwitch` (the failure card's Retry / Switch Back); a diff --git a/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift b/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift index f47e87001a..c97d204846 100644 --- a/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift +++ b/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift @@ -207,10 +207,10 @@ final class WalletLifecycleOverlayViewModel: ObservableObject { @Published private(set) var phase: WalletLifecycleTransitionState.Phase @Published private(set) var preparationFailure: WalletPreparationFailure? - @Published var supportFailure: WalletPreparationFailure? + @Published var supportFailure: WalletPreparationFailure? { didSet { updateRecoveryPresentationHold() } } @Published private(set) var retryPending = false - @Published private(set) var isExportingLogs = false - @Published var exportedLogsURL: URL? + @Published private(set) var isExportingLogs = false { didSet { updateRecoveryPresentationHold() } } + @Published var exportedLogsURL: URL? { didSet { updateRecoveryPresentationHold() } } /// One alert for every gated action's refusal: no PIN on record, /// authentication failed, export or reset error. @Published var actionFailure: ActionFailure? @@ -221,7 +221,28 @@ final class WalletLifecycleOverlayViewModel: ObservableObject { @Published var isConfirmingReset = false @Published private(set) var resetPending = false /// True while the overlay window is hidden behind the PIN prompt. - @Published private(set) var isAuthenticating = false + @Published private(set) var isAuthenticating = false { didSet { updateRecoveryPresentationHold() } } + /// True while the phrase picker or phrase screen is up in the overlay window. + private var isPresentingRecoveryPhrase = false { didSet { updateRecoveryPresentationHold() } } + + /// Any flow that owns the window — the PIN prompt, log export and its + /// share sheet, the Help sheet and its composer, the phrase modal — holds + /// automatic wallet preparation: a keys card's self-healing start would + /// otherwise move the phase from under it and drop a phrase screen or an + /// unsent support message. A kick refused meanwhile is replayed on release. + private var ownsRecoveryPresentation: Bool { + isAuthenticating || isExportingLogs || exportedLogsURL != nil || supportFailure != nil + || isPresentingRecoveryPhrase + } + + private func updateRecoveryPresentationHold() { + let state = WalletLifecycleTransitionState.shared + if ownsRecoveryPresentation { + if !state.recoveryPresentationHeld { state.holdRecoveryPresentation() } + } else if state.recoveryPresentationHeld, state.releaseRecoveryPresentation() { + SwiftDashSDKWalletRuntime.startIfReady() + } + } /// One operation at a time on a failure card: the share sheet, the PIN /// prompt, Try Again and Reset each own the window's presentation stack. @@ -240,6 +261,9 @@ final class WalletLifecycleOverlayViewModel: ObservableObject { phase = transitionState.phase preparationFailure = transitionState.preparationFailure apply(transitionState.phase) + recoveryPhraseModal.onPresentationChanged = { [weak self] presented in + self?.isPresentingRecoveryPhrase = presented + } transitionState.$phase .sink { [weak self] phase in self?.apply(phase) } .store(in: &cancellables) diff --git a/DashWallet/Sources/UI/Menu/Security/RecoveryPhraseFlow.swift b/DashWallet/Sources/UI/Menu/Security/RecoveryPhraseFlow.swift index 22c0a23225..55e7cccadc 100644 --- a/DashWallet/Sources/UI/Menu/Security/RecoveryPhraseFlow.swift +++ b/DashWallet/Sources/UI/Menu/Security/RecoveryPhraseFlow.swift @@ -752,6 +752,10 @@ enum RecoveryPhraseNavigation { final class RecoveryPhraseModalPresenter: NSObject, DWSecureWalletDelegate { private weak var navigationController: UINavigationController? + /// `true` when the modal goes up, `false` when this presenter takes it + /// down (Done, Back, resign, the host's own dismiss). The host uses it to + /// hold automatic wallet preparation while the phrase is on screen. + var onPresentationChanged: ((Bool) -> Void)? /// Presents `destination` from `anchor`. A `.phrase` arriving while the /// picker modal is up replaces the picker in place (the picker's select). @@ -785,6 +789,7 @@ final class RecoveryPhraseModalPresenter: NSObject, DWSecureWalletDelegate { navigation.view.accessibilityViewIsModal = true navigationController = navigation anchor.present(navigation, animated: true) + onPresentationChanged?(true) } func dismiss(animated: Bool) { @@ -794,6 +799,7 @@ final class RecoveryPhraseModalPresenter: NSObject, DWSecureWalletDelegate { // Addressed to the presenter: `dismiss` on the navigation controller // itself would only drop whatever it presented (the screenshot alert). presenter.dismiss(animated: animated) + onPresentationChanged?(false) } // The Objective-C protocol's requirements are nonisolated; UIKit calls diff --git a/DashWalletTests/WalletLifecycleTransitionStateTests.swift b/DashWalletTests/WalletLifecycleTransitionStateTests.swift index b6c834326b..f0c0ca2fb8 100644 --- a/DashWalletTests/WalletLifecycleTransitionStateTests.swift +++ b/DashWalletTests/WalletLifecycleTransitionStateTests.swift @@ -240,6 +240,25 @@ final class WalletLifecycleTransitionStateTests: XCTestCase { XCTAssertEqual(state.phase, phase) } + func testRecoveryPresentationHoldDefersKeysCardKicksAndReplaysOnRelease() { + let state = WalletLifecycleTransitionState() + state.fail(.failedWalletOpen(WalletPreparationFailure(keys: .unreadable, status: -25291))) + XCTAssertTrue(state.allowsAutomaticWalletPreparation) + state.holdRecoveryPresentation() + XCTAssertFalse(state.allowsAutomaticWalletPreparation) + XCTAssertFalse(state.releaseRecoveryPresentation(), "Nothing was refused") + state.holdRecoveryPresentation() + state.recordDeferredAutomaticPreparation() + XCTAssertTrue(state.releaseRecoveryPresentation()) + XCTAssertFalse(state.releaseRecoveryPresentation(), "Consumed") + XCTAssertTrue(state.allowsAutomaticWalletPreparation) + // A store card refuses kicks on its own; the hold records nothing. + state.fail(.failedWalletOpen(WalletPreparationFailure(error: NSError(domain: "SwiftData.SwiftDataError", code: 1)))) + state.holdRecoveryPresentation() + state.recordDeferredAutomaticPreparation() + XCTAssertFalse(state.releaseRecoveryPresentation()) + } + func testUnrelatedStartupFailureKeepsExistingRecoveryFlow() async { let state = WalletLifecycleTransitionState() do { diff --git a/scripts/test_wallet_preparation.py b/scripts/test_wallet_preparation.py index ef002b8846..17612dfa4d 100644 --- a/scripts/test_wallet_preparation.py +++ b/scripts/test_wallet_preparation.py @@ -869,6 +869,24 @@ def declaration(source, start): XCTAssertEqual(runtime.refreshCalls, 1) guard case .failedWalletOpen = state.phase else { return XCTFail("Store card dismissed by an automatic kick") } } + func testKicksAreDeferredWhileACardFlowHoldsTheWindowAndReplayedOnRelease() async { + let keys = WalletPreparationFailure(keys: .unreadable, status: -25291) + state.fail(.failedWalletOpen(keys)) + // The phrase modal, Help or the share sheet is up: a connectivity or + // foreground kick must not move the phase from under it. + state.holdRecoveryPresentation() + runtime.enqueueRefresh(trigger: .startIfReady) + runtime.handleObservedNetworkChange() + await runtime.drain() + XCTAssertEqual(runtime.refreshCalls, 0) + XCTAssertEqual(state.phase, .failedWalletOpen(keys)) + // Release reports the refused kick; its replay clears the card. + XCTAssertTrue(state.releaseRecoveryPresentation()) + runtime.enqueueRefresh(trigger: .startIfReady) + await runtime.drain() + XCTAssertEqual(runtime.refreshCalls, 1) + XCTAssertEqual(state.phase, .idle) + } } ''') (package / "Package.swift").write_text('''// swift-tools-version: 5.9 From 5e3d8c13474a6351a6775d0123cebad460676af5 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Mon, 12 Oct 2026 19:37:22 +0200 Subject: [PATCH 9/9] fix(wallet): never let a recovery presentation hold outlive its owner The phrase modal reported its dismissal only when it was still presented through the presenter, so a modal released or taken down by another route left the overlay's hold set. dismiss(animated:) now reports the dismissal whenever it had reported a presentation, also when the modal is already gone. The overlay window, and with it the view model that owns the hold, is released when the phase reaches idle; a hold set at that moment (a Help sheet open when a lock-screen wipe finishes) would have blocked the automatic kicks of the next keys card in the same process. finish() now drops the hold and any deferred kick with the window. Co-Authored-By: Claude Opus 5.5 --- .../WalletLifecycleTransitionState.swift | 5 ++++ .../UI/Menu/Security/RecoveryPhraseFlow.swift | 23 +++++++++++++++---- .../WalletLifecycleTransitionStateTests.swift | 14 +++++++++++ 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift index 738ad5fc73..d9cec04412 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift @@ -247,6 +247,11 @@ final class WalletLifecycleTransitionState: ObservableObject { } phase = .idle preparationFailure = nil + // The overlay window, and with it any card flow that held it, is + // released at idle; a hold its owner never released must not block + // the automatic kicks of the next keys card. + recoveryPresentationHeld = false + automaticPreparationDeferred = false } func fail(_ failure: Phase) { diff --git a/DashWallet/Sources/UI/Menu/Security/RecoveryPhraseFlow.swift b/DashWallet/Sources/UI/Menu/Security/RecoveryPhraseFlow.swift index 55e7cccadc..7fce1586fd 100644 --- a/DashWallet/Sources/UI/Menu/Security/RecoveryPhraseFlow.swift +++ b/DashWallet/Sources/UI/Menu/Security/RecoveryPhraseFlow.swift @@ -752,10 +752,18 @@ enum RecoveryPhraseNavigation { final class RecoveryPhraseModalPresenter: NSObject, DWSecureWalletDelegate { private weak var navigationController: UINavigationController? - /// `true` when the modal goes up, `false` when this presenter takes it - /// down (Done, Back, resign, the host's own dismiss). The host uses it to + /// `true` when the modal goes up, `false` on the next `dismiss(animated:)` + /// after that (Done, Back, resign, the host's own dismiss) — also when + /// the modal already went away by another route. The host uses it to /// hold automatic wallet preparation while the phrase is on screen. var onPresentationChanged: ((Bool) -> Void)? + private var reportedPresented = false + + private func reportPresentation(_ presented: Bool) { + guard presented != reportedPresented else { return } + reportedPresented = presented + onPresentationChanged?(presented) + } /// Presents `destination` from `anchor`. A `.phrase` arriving while the /// picker modal is up replaces the picker in place (the picker's select). @@ -789,17 +797,22 @@ final class RecoveryPhraseModalPresenter: NSObject, DWSecureWalletDelegate { navigation.view.accessibilityViewIsModal = true navigationController = navigation anchor.present(navigation, animated: true) - onPresentationChanged?(true) + reportPresentation(true) } func dismiss(animated: Bool) { + // Reported even when the modal is already gone (released, or taken + // down by another route): a host hold must never outlive it. + defer { reportPresentation(false) } guard let navigationController, - let presenter = navigationController.presentingViewController else { return } + let presenter = navigationController.presentingViewController else { + self.navigationController = nil + return + } self.navigationController = nil // Addressed to the presenter: `dismiss` on the navigation controller // itself would only drop whatever it presented (the screenshot alert). presenter.dismiss(animated: animated) - onPresentationChanged?(false) } // The Objective-C protocol's requirements are nonisolated; UIKit calls diff --git a/DashWalletTests/WalletLifecycleTransitionStateTests.swift b/DashWalletTests/WalletLifecycleTransitionStateTests.swift index f0c0ca2fb8..17615a7e51 100644 --- a/DashWalletTests/WalletLifecycleTransitionStateTests.swift +++ b/DashWalletTests/WalletLifecycleTransitionStateTests.swift @@ -259,6 +259,20 @@ final class WalletLifecycleTransitionStateTests: XCTestCase { XCTAssertFalse(state.releaseRecoveryPresentation()) } + /// The overlay window and its view model are released at idle; a hold + /// they never released must not block the next keys card's kicks. + func testFinishDropsARecoveryPresentationHoldItsOwnerNeverReleased() { + let state = WalletLifecycleTransitionState() + let keys = WalletPreparationFailure(keys: .unreadable, status: -25291) + state.fail(.failedWalletOpen(keys)) + state.holdRecoveryPresentation() + state.recordDeferredAutomaticPreparation() + state.finish() + state.fail(.failedWalletOpen(keys)) + XCTAssertTrue(state.allowsAutomaticWalletPreparation) + XCTAssertFalse(state.releaseRecoveryPresentation(), "No kick carried over from the released card") + } + func testUnrelatedStartupFailureKeepsExistingRecoveryFlow() async { let state = WalletLifecycleTransitionState() do {