Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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):
Comment thread
llbartekll marked this conversation as resolved.
Resolved
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}
Expand Down Expand Up @@ -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) }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
llbartekll marked this conversation as resolved.
Resolved
PlatformAddressSyncCoordinator.shared.prepareLocalPlatformState(
manager: manager, walletId: wallet.walletId, network: network)
await PlatformAddressSyncCoordinator.shared.prepareLocalShieldedState(
Expand All @@ -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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
llbartekll marked this conversation as resolved.
Resolved
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
Expand Down Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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")
}
Expand All @@ -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")
Expand Down
Loading
Loading