diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift index f8a95b1db8..14836e00e2 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift @@ -519,6 +519,67 @@ 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. Those bridge to `OtherError` codes, so the + /// database card they get never offers a reset; only a store that would + /// not open can. + /// + /// 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? { + 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) + } + 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, + KeyWalletError.invalidMnemonic, + KeyWalletError.invalidInput: + // The resolver derives ids by constructing a wallet from the + // 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) + 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..ca214dcb1b 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift @@ -243,8 +243,24 @@ 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) { + // `prepareWallet` moves the phase the moment the open runs + // (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 @@ -363,7 +379,19 @@ 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 (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 state.phase { + case .idle: admitted = true + 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 @@ -793,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) } } @@ -913,12 +946,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( @@ -928,6 +956,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. 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..d9cec04412 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletLifecycleTransitionState.swift @@ -128,13 +128,47 @@ 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 — 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 .failedWalletOpen, .resettingLocalStores: return false + 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 @@ -213,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/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift index 173dbd1f11..18849c8392 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/WalletPreparationFailure.swift @@ -1,16 +1,29 @@ 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. + enum Kind: String { case database, storage, legacyMigration, 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. /// 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 +38,18 @@ 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. 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 + kind = .keychain + codes = ["Keychain:\(reason.rawValue)"] + (status.map { ["OSStatus:\($0)"] } ?? []) + canResetLocalData = false + } + init(error: Error, now: Date = Date()) { id = UUID() occurredAt = now @@ -78,6 +103,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 +122,14 @@ 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. 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. 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/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift b/DashWallet/Sources/UI/Main/WalletLifecycleOverlay.swift index 1a45b85cba..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) @@ -368,7 +392,9 @@ 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. 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, requirePin( @@ -522,7 +548,7 @@ struct WalletLifecycleOverlayView: View { } .disabled(viewModel.isBusy) walletRecoveryActions - preparationHelp + preparationHelp(authenticatedExport: failure.requiresAuthenticatedExport) } case let .failedLegacyMigration(failure): // No Create/Recover here: the wallet is still in the keychain. @@ -532,7 +558,7 @@ struct WalletLifecycleOverlayView: View { viewModel.retryLegacyMigration() } .disabled(viewModel.isExportingLogs) - preparationHelp(authenticatedExport: true) + preparationHelp(authenticatedExport: failure.requiresAuthenticatedExport) } case let .switchingNetwork(_, to): progressCard( @@ -585,7 +611,7 @@ struct WalletLifecycleOverlayView: View { .disabled(viewModel.isBusy) } if viewModel.showsLocalStoreRecovery { walletRecoveryActions } - preparationHelp + preparationHelp(authenticatedExport: viewModel.preparationFailure?.requiresAuthenticatedExport ?? false) } case let .failedWalletSwitch(targetId, targetName, previousId, message): card { @@ -602,7 +628,7 @@ struct WalletLifecycleOverlayView: View { } .disabled(viewModel.isExportingLogs) } - preparationHelp + preparationHelp(authenticatedExport: viewModel.preparationFailure?.requiresAuthenticatedExport ?? false) } case let .failedWalletRemoval(message): card { @@ -650,6 +676,9 @@ struct WalletLifecycleOverlayView: View { .recoveryPhraseFlowAlert(viewModel.recoveryPhraseFlow) } + /// 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 var walletRecoveryActions: some View { actionButton(NSLocalizedString("Backup recovery phrase", comment: "Wallet preparation"), prominent: false) { @@ -667,12 +696,10 @@ struct WalletLifecycleOverlayView: View { } } - private var preparationHelp: some View { - preparationHelp(authenticatedExport: false) - } - - /// `authenticatedExport`: the card shows before the lock screen, 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/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/Sources/UI/Menu/Security/RecoveryPhraseFlow.swift b/DashWallet/Sources/UI/Menu/Security/RecoveryPhraseFlow.swift index 22c0a23225..7fce1586fd 100644 --- a/DashWallet/Sources/UI/Menu/Security/RecoveryPhraseFlow.swift +++ b/DashWallet/Sources/UI/Menu/Security/RecoveryPhraseFlow.swift @@ -752,6 +752,18 @@ enum RecoveryPhraseNavigation { final class RecoveryPhraseModalPresenter: NSObject, DWSecureWalletDelegate { private weak var navigationController: UINavigationController? + /// `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). @@ -785,11 +797,18 @@ final class RecoveryPhraseModalPresenter: NSObject, DWSecureWalletDelegate { navigation.view.accessibilityViewIsModal = true navigationController = navigation anchor.present(navigation, animated: 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). diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index c9a20938b5..e8e703e0bf 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. 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"; @@ -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"; diff --git a/DashWalletTests/WalletLifecycleTransitionStateTests.swift b/DashWalletTests/WalletLifecycleTransitionStateTests.swift index b6c834326b..17615a7e51 100644 --- a/DashWalletTests/WalletLifecycleTransitionStateTests.swift +++ b/DashWalletTests/WalletLifecycleTransitionStateTests.swift @@ -240,6 +240,39 @@ 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()) + } + + /// 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 { diff --git a/DashWalletTests/WalletPreparationFailureTests.swift b/DashWalletTests/WalletPreparationFailureTests.swift index 3c876c44fe..342775d1eb 100644 --- a/DashWalletTests/WalletPreparationFailureTests.swift +++ b/DashWalletTests/WalletPreparationFailureTests.swift @@ -93,4 +93,25 @@ 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) + XCTAssertTrue(failure.requiresAuthenticatedExport) + let database = WalletPreparationFailure(error: NSError(domain: "SwiftData.SwiftDataError", code: 1)) + 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. + 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..17612dfa4d 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,17 @@ 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 } +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 { 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,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 NSError(domain: "InjectedKeychain", code: 1) } + 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)], @@ -299,6 +312,81 @@ 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:-25291"]) + XCTAssertEqual(failure?.canResetLocalData, false) + } + 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 + 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 + 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: 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"]) + 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"]) + // The resolver constructs a wallet from the stored phrase; its refusal + // of material that passed word validation is a keys failure too. + 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)) + } } ''') (sources / "ProcessNetworkValueCache.swift").write_text( @@ -402,15 +490,36 @@ 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? + /// 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 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 + } + 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 { @@ -461,6 +570,9 @@ def declaration(source, start): state.finish() 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 @@ -706,6 +818,75 @@ def declaration(source, start): XCTAssertNil(state.preparationFailure) XCTAssertEqual(runtime.refreshCalls, 2) } + func testRetryFromTheKeysCardKeepsItOnlyWhenTheOpenWasNotReached() async { + let keys = WalletPreparationFailure(keys: .unreadable, status: -25291) + state.fail(.failedWalletOpen(keys)) + // 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) + // 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)) + // 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 + runtime.unclassifiedOpenFailure = WalletPreparationFailure(error: NSError(domain: "Fallback", code: 3)) + await runtime.retryWalletPreparation() + XCTAssertEqual(state.phase, .idle) + XCTAssertNil(state.preparationFailure) + // The open succeeded and SPV failed afterwards: same, no card. + state.fail(.failedWalletOpen(keys)) + runtime.unclassifiedOpenFailure = nil + runtime.postOpenFailure = WalletPreparationFailure(error: NSError(domain: "SPV", code: 4)) + await runtime.retryWalletPreparation() + 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() + 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") } + } + 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