From 4c6051f0c97cd1ac507068359cb05ed47461a788 Mon Sep 17 00:00:00 2001 From: Roman Date: Thu, 24 Sep 2026 22:42:58 +0300 Subject: [PATCH 1/3] feat(swift-sdk): durable wallet presence marker readable while the device is locked The mnemonic and metadata items are WhenUnlockedThisDeviceOnly, so a process launched while the device is locked (background app refresh) cannot enumerate them; `listWalletIdsWithMnemonic()` throws and an app that folds that into `false` concludes "no wallet" and shows its setup screen. Add a non-secret per-wallet presence marker: a generic-password item at `wallet.present.` under the sibling service `.presence`, AfterFirstUnlockThisDeviceOnly, payload = the wallet id. It is written inside `storeMnemonic` and removed inside `deleteMnemonic`, so every write and delete path (including the manager's delete-wallet path) keeps the two in step. `walletPresence()` answers present / absent / unknown(OSStatus): a non-empty marker set is `present`; an empty one falls back to the mnemonic inventory, marking every wallet it finds (lazy backfill for wallets stored before the marker existed) and answering `absent` only on a readable empty inventory; any read failure is `unknown`. `markedWalletIds()` exposes the raw marker set. The marker lives in its own service because a service-wide query over a mix of AfterFirstUnlock and WhenUnlocked items on a locked device either fails as a whole (marker unreadable when needed) or drops the locked rows (the existing inventory would read empty instead of throwing). Co-Authored-By: Claude Fable 5.1 --- .../Core/Wallet/WalletStorage.swift | 213 +++++++++++++++++- .../WalletPresenceTests.swift | 120 ++++++++++ 2 files changed, 329 insertions(+), 4 deletions(-) create mode 100644 packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift index e468cc44406..139eec05f7b 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift @@ -26,6 +26,11 @@ import Security /// with the original name/description after a reinstall. /// * Enumeration of stored wallet ids (used by the orphan-mnemonic /// recovery flow in `ContentView`). +/// * A non-secret per-wallet presence marker at +/// `wallet.present.<64-char-hex-walletId>` under the sibling +/// service `.presence`, readable after the first +/// unlock so a locked device can still answer "does a wallet +/// exist?" — see [`walletPresence()`](x-source-tag://walletPresence). /// * Biometric-protected seed stash at `wallet.biometric` — not yet /// wired to a caller but kept because it's a different category /// (hardware-protected rather than a legacy PIN construct). @@ -57,6 +62,24 @@ public class WalletStorage { public static let metadataAccountPrefix = "wallet.metadata" private let biometricKeychainAccount = "wallet.biometric" + /// Keychain service for the per-wallet presence markers: + /// `.presence`. + /// + /// A sibling service rather than `keychainService` itself on purpose. + /// The markers are `AfterFirstUnlock` while every other per-wallet item + /// is `WhenUnlocked`, and a service-wide `SecItemCopyMatching` over a + /// mix of the two behaves badly on a locked device whichever way + /// securityd resolves it: fail the whole query and the marker is + /// unreadable exactly when it is needed; drop the locked rows and + /// `listWalletIdsWithMnemonic()` would return an empty inventory + /// instead of an error. Keeping each service homogeneous keeps both + /// answers honest. Derived from `keychainService` so the + /// `DASH_KEYCHAIN_SERVICE` override applies to both. + public static let presenceKeychainService = "\(keychainService).presence" + /// Base account string used to build per-wallet presence-marker + /// accounts via `perWalletPresenceMarkerAccount(for:)`. + public static let presenceMarkerAccountPrefix = "wallet.present" + public init() {} // MARK: - Per-Wallet Mnemonic Storage @@ -71,10 +94,20 @@ public class WalletStorage { } /// Store a mnemonic keyed by wallet id. + /// + /// Also writes the wallet's presence marker (see `walletPresence()`), + /// marker first so a stored mnemonic is never left without one. If + /// the mnemonic write then fails, the marker is removed again (best + /// effort) so it never asserts a wallet that was not stored. On a + /// rewrite whose delete step fails, that removal unmarks a wallet + /// whose old mnemonic still exists; `walletPresence()` tolerates + /// that direction of drift and re-marks it from the inventory. public func storeMnemonic(_ mnemonic: String, for walletId: Data) throws { let data = Data(mnemonic.utf8) let account = perWalletMnemonicAccount(for: walletId) + try storePresenceMarker(for: walletId) + let deleteQuery: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: keychainService, @@ -82,6 +115,7 @@ public class WalletStorage { ] let deleteStatus = SecItemDelete(deleteQuery as CFDictionary) guard deleteStatus == errSecSuccess || deleteStatus == errSecItemNotFound else { + try? deletePresenceMarker(for: walletId) throw WalletStorageError.keychainError(deleteStatus) } @@ -94,6 +128,7 @@ public class WalletStorage { ] let status = SecItemAdd(addQuery as CFDictionary, nil) guard status == errSecSuccess else { + try? deletePresenceMarker(for: walletId) throw WalletStorageError.keychainError(status) } } @@ -221,7 +256,14 @@ public class WalletStorage { } /// Delete a mnemonic keyed by wallet id. Idempotent. + /// + /// Removes the presence marker first: if the mnemonic delete then + /// fails, the wallet is merely unmarked (and `walletPresence()` falls + /// back to the mnemonic inventory, which re-marks it), never marked + /// without a mnemonic behind it. public func deleteMnemonic(for walletId: Data) throws { + try deletePresenceMarker(for: walletId) + let account = perWalletMnemonicAccount(for: walletId) let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, @@ -237,14 +279,25 @@ public class WalletStorage { /// Enumerate all wallet ids with a stored mnemonic. /// /// Reads every `kSecClassGenericPassword` entry under - /// `org.dash.wallet`, keeps those whose account starts with + /// `keychainService`, keeps those whose account starts with /// `wallet.mnemonic.` followed by a 64-character lowercase hex /// string, and decodes the suffix back into 32-byte wallet ids. - /// Returns an empty array if the keychain has none. + /// Returns an empty array if the keychain has none. Throws while the + /// device is locked (the items are `WhenUnlocked`); see + /// `walletPresence()` for the question that has to be answered then. public func listWalletIdsWithMnemonic() throws -> [Data] { + try listWalletIds(service: keychainService, accountPrefix: mnemonicKeychainAccount) + } + + /// Wallet ids encoded in the accounts of every generic-password item + /// under `service` whose account is `.<64-hex>`. + /// `errSecItemNotFound` is an empty list; any other failure is thrown + /// as `keychainError` so "nothing there" and "could not look" stay + /// distinguishable. + private func listWalletIds(service: String, accountPrefix: String) throws -> [Data] { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, - kSecAttrService as String: keychainService, + kSecAttrService as String: service, kSecMatchLimit as String: kSecMatchLimitAll, kSecReturnAttributes as String: true ] @@ -258,7 +311,7 @@ public class WalletStorage { } guard let items = result as? [[String: Any]] else { return [] } - let prefix = "\(mnemonicKeychainAccount)." + let prefix = "\(accountPrefix)." var walletIds: [Data] = [] for item in items { guard let account = item[kSecAttrAccount as String] as? String, @@ -270,6 +323,158 @@ public class WalletStorage { return walletIds } + // MARK: - Wallet Presence Marker + // + // The mnemonic and metadata items are `WhenUnlockedThisDeviceOnly`, so + // a process launched while the device is locked (a background app + // refresh, a silent push) cannot even enumerate them: the inventory + // read fails and a naive caller concludes "no wallet" and shows the + // setup screen. The marker is the durable, non-secret answer to that + // one question. It is written and removed inside `storeMnemonic` / + // `deleteMnemonic` so it cannot drift from the mnemonic on any + // write or delete path, including the manager's delete-wallet path. + // + // Security trade-off: `AfterFirstUnlockThisDeviceOnly` means anyone + // who can query this app's keychain after the first unlock since + // boot learns that a wallet exists here, and its 32-byte wallet id. + // The id is a hash, not key material; it identifies nothing outside + // this app and unlocks nothing. Like the mnemonic it stays in the + // keychain across a reinstall (which is why this is not a + // `UserDefaults` flag) and never syncs to iCloud. + + private func perWalletPresenceMarkerAccount(for walletId: Data) -> String { + let hex = walletId.map { String(format: "%02x", $0) }.joined() + return "\(Self.presenceMarkerAccountPrefix).\(hex)" + } + + /// Write (or rewrite) the presence marker for `walletId`. Called by + /// `storeMnemonic` and by the lazy backfill in `walletPresence()`; + /// there is no reason for an app to call it directly. Delete-then-add + /// like the other writers so the accessibility class is re-applied on + /// every write. The payload is the wallet id itself — no secret. + public func storePresenceMarker(for walletId: Data) throws { + let account = perWalletPresenceMarkerAccount(for: walletId) + + let deleteQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: Self.presenceKeychainService, + kSecAttrAccount as String: account + ] + let deleteStatus = SecItemDelete(deleteQuery as CFDictionary) + guard deleteStatus == errSecSuccess || deleteStatus == errSecItemNotFound else { + throw WalletStorageError.keychainError(deleteStatus) + } + + let addQuery: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: Self.presenceKeychainService, + kSecAttrAccount as String: account, + kSecValueData as String: walletId, + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly + ] + let status = SecItemAdd(addQuery as CFDictionary, nil) + guard status == errSecSuccess else { + throw WalletStorageError.keychainError(status) + } + } + + /// Delete the presence marker for `walletId`. Idempotent. Called by + /// `deleteMnemonic`; not meant to be called on its own. + public func deletePresenceMarker(for walletId: Data) throws { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: Self.presenceKeychainService, + kSecAttrAccount as String: perWalletPresenceMarkerAccount(for: walletId) + ] + let status = SecItemDelete(query as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { + throw WalletStorageError.keychainError(status) + } + } + + /// Wallet ids that carry a presence marker. Readable once the device + /// has been unlocked since boot, locked or not. Empty means "no + /// marker", which is *not* "no wallet" — see `walletPresence()`. + /// Throws `keychainError` before the first unlock or on any other + /// lookup failure. + public func markedWalletIds() throws -> [Data] { + try listWalletIds( + service: Self.presenceKeychainService, + accountPrefix: Self.presenceMarkerAccountPrefix + ) + } + + /// Three-way answer to "does this app hold at least one wallet?". + public enum WalletPresence: Sendable, Equatable { + /// At least one wallet id is marked, or the mnemonic inventory is + /// readable and non-empty. + case present + /// No marker *and* the mnemonic inventory was readable and empty. + /// The only verdict on which a setup screen may be shown. + case absent + /// Could not tell: the marker was unreadable (before the first + /// unlock, `errSecInteractionNotAllowed`, …) or it was empty and + /// the inventory was unreadable (a locked device with wallets + /// stored before the marker existed). Says nothing about whether + /// a wallet exists; decide later, not now. + case unknown(OSStatus) + } + + /// Whether at least one wallet exists, answerable on a locked device. + /// + /// Resolution order: + /// + /// 1. `markedWalletIds()` non-empty → `.present`. A marker is only + /// ever written next to a mnemonic. + /// 2. Marker readable but empty → consult `listWalletIdsWithMnemonic()`. + /// Non-empty → `.present`, and each id is marked so the next + /// locked launch is answered by step 1 (wallets stored before the + /// marker existed backfill themselves on the first unlocked read). + /// Empty → `.absent`. + /// 3. Either read failing → `.unknown(status)`. + /// + /// Invariant for callers: marker present ⇒ a wallet exists; a missing + /// marker on its own never means "no wallet" — only a readable, empty + /// inventory does. The backfill is best-effort; a failed marker write + /// does not change the verdict, it just defers the shortcut. + /// + /// - Tag: walletPresence + public func walletPresence() -> WalletPresence { + let marked: [Data] + do { + marked = try markedWalletIds() + } catch { + return .unknown(Self.status(of: error)) + } + if !marked.isEmpty { + return .present + } + + let inventory: [Data] + do { + inventory = try listWalletIdsWithMnemonic() + } catch { + return .unknown(Self.status(of: error)) + } + guard !inventory.isEmpty else { + return .absent + } + for walletId in inventory { + try? storePresenceMarker(for: walletId) + } + return .present + } + + /// The `OSStatus` behind a `WalletStorageError.keychainError`; anything + /// else (an override that throws its own error) maps to + /// `errSecInternalError` so `unknown` still carries *a* status. + private static func status(of error: Error) -> OSStatus { + if case WalletStorageError.keychainError(let status) = error { + return status + } + return errSecInternalError + } + // MARK: - Per-Wallet Metadata Storage // // User-facing display strings (name + description) carried in diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift new file mode 100644 index 00000000000..1935debddc5 --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift @@ -0,0 +1,120 @@ +import Security +import XCTest + +@testable import SwiftDashSDK + +/// Classification logic of `WalletStorage.walletPresence()` with the two +/// Keychain reads and the backfill write injected, so the suite never +/// touches the real Keychain (the same reason +/// `IdentityResolverSignIntegrationTests` uses an in-memory storage: a +/// CI runner's keychain session is an environment, not what is under +/// test). What the fake models is the *outcome* of each read on a +/// device in a given state — unreadable, readable-empty, readable-with-ids. +final class WalletPresenceTests: XCTestCase { + /// `WalletStorage` whose marker read, mnemonic inventory and marker + /// write are scripted. A `nil` result throws `keychainError(status)` + /// with the given status, the way the real reads fail on a locked + /// device. + private final class ScriptedStorage: WalletStorage { + var marked: [Data]? + var inventory: [Data]? + var failureStatus: OSStatus = errSecInteractionNotAllowed + var markerWriteStatus: OSStatus = errSecSuccess + private(set) var markerWrites: [Data] = [] + private(set) var inventoryReads = 0 + + override func markedWalletIds() throws -> [Data] { + guard let marked else { throw WalletStorageError.keychainError(failureStatus) } + return marked + } + + override func listWalletIdsWithMnemonic() throws -> [Data] { + inventoryReads += 1 + guard let inventory else { throw WalletStorageError.keychainError(failureStatus) } + return inventory + } + + override func storePresenceMarker(for walletId: Data) throws { + guard markerWriteStatus == errSecSuccess else { + throw WalletStorageError.keychainError(markerWriteStatus) + } + markerWrites.append(walletId) + } + } + + private let walletA = Data(repeating: 0xA1, count: 32) + private let walletB = Data(repeating: 0xB2, count: 32) + + func testMarkedWalletIsPresentWithoutConsultingTheInventory() { + let storage = ScriptedStorage() + storage.marked = [walletA] + storage.inventory = nil // would throw: the device is locked + + XCTAssertEqual(storage.walletPresence(), .present) + XCTAssertEqual(storage.inventoryReads, 0, "a marker answers on its own") + XCTAssertTrue(storage.markerWrites.isEmpty, "nothing to backfill") + } + + func testReadableEmptyMarkerAndEmptyInventoryIsAbsent() { + let storage = ScriptedStorage() + storage.marked = [] + storage.inventory = [] + + XCTAssertEqual(storage.walletPresence(), .absent) + XCTAssertEqual(storage.inventoryReads, 1) + XCTAssertTrue(storage.markerWrites.isEmpty) + } + + func testEmptyMarkerFallsBackToInventoryAndBackfillsEveryWallet() { + let storage = ScriptedStorage() + storage.marked = [] + storage.inventory = [walletA, walletB] + + XCTAssertEqual(storage.walletPresence(), .present) + XCTAssertEqual(storage.markerWrites, [walletA, walletB]) + } + + func testUnreadableMarkerIsUnknownWithTheKeychainStatus() { + let storage = ScriptedStorage() + storage.marked = nil // before the first unlock since boot + storage.inventory = [walletA] // must not be reached + + XCTAssertEqual(storage.walletPresence(), .unknown(errSecInteractionNotAllowed)) + XCTAssertEqual(storage.inventoryReads, 0, "an unreadable marker ends the lookup") + XCTAssertTrue(storage.markerWrites.isEmpty) + } + + func testEmptyMarkerWithUnreadableInventoryIsUnknownNotAbsent() { + // A locked device holding wallets stored before the marker + // existed: the marker reads empty, the inventory cannot be read. + let storage = ScriptedStorage() + storage.marked = [] + storage.inventory = nil + storage.failureStatus = errSecInteractionNotAllowed + + XCTAssertEqual(storage.walletPresence(), .unknown(errSecInteractionNotAllowed)) + XCTAssertTrue(storage.markerWrites.isEmpty) + } + + func testFailedBackfillDoesNotChangeThePresentVerdict() { + let storage = ScriptedStorage() + storage.marked = [] + storage.inventory = [walletA] + storage.markerWriteStatus = errSecWrPerm + + XCTAssertEqual(storage.walletPresence(), .present) + XCTAssertTrue(storage.markerWrites.isEmpty) + } + + func testMarkerServiceIsASiblingOfTheMnemonicService() { + // The marker items are `AfterFirstUnlock`, the mnemonic items + // `WhenUnlocked`; a shared service would make one service-wide + // query cover both accessibility classes. See the doc comment on + // `presenceKeychainService` for why that must not happen. + XCTAssertEqual( + WalletStorage.presenceKeychainService, + "\(WalletStorage.keychainService).presence" + ) + XCTAssertNotEqual(WalletStorage.presenceKeychainService, WalletStorage.keychainService) + } +} From bccb27b6b15c9642cb03ca816ae3d9a85ffbd32e Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:31:41 +0300 Subject: [PATCH 2/3] fix(swift-sdk): keep the presence marker from outliving its mnemonic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up on the wallet presence marker. Three ways a marker could assert a wallet that has no mnemonic: - storeMnemonic wrote the marker before the mnemonic, so a process killed in between left a phantom; a rewrite kept the marker across its delete/add gap. The steps now run marker-off, mnemonic-off, mnemonic-on, marker-on: an interruption at any point leaves at most a mnemonic without a marker. A failed trailing marker write no longer fails the store — the mnemonic is stored and the next unlocked presence read backfills the marker. - The backfill in walletPresence() was an uncoordinated read-then- write, so it could re-mark a wallet while deleteMnemonic (on its own WalletStorage instance) was between its two steps. storeMnemonic, deleteMnemonic and walletPresence() now share one static lock, and deleteMnemonic removes the mnemonic before the marker. - A non-empty marker set was never re-validated. When the inventory is readable it is now the source of truth: the verdict comes from it and the marker set is rewritten to match, so any phantom heals on the first unlocked read. The marker only stands in while the inventory is unreadable. storePresenceMarker / deletePresenceMarker are internal now; they are lifecycle steps, not SDK operations. The two raw mnemonic keychain steps are internal primitives too, so the ordering, the interruption points and the interleaving are covered by tests against an in-memory keychain shared between two storage instances. Co-Authored-By: Claude Fable 5.1 --- .../Core/Wallet/WalletStorage.swift | 173 +++++---- .../WalletPresenceTests.swift | 356 ++++++++++++++---- 2 files changed, 387 insertions(+), 142 deletions(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift index 139eec05f7b..74a7c2b30d3 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift @@ -95,40 +95,53 @@ public class WalletStorage { /// Store a mnemonic keyed by wallet id. /// - /// Also writes the wallet's presence marker (see `walletPresence()`), - /// marker first so a stored mnemonic is never left without one. If - /// the mnemonic write then fails, the marker is removed again (best - /// effort) so it never asserts a wallet that was not stored. On a - /// rewrite whose delete step fails, that removal unmarks a wallet - /// whose old mnemonic still exists; `walletPresence()` tolerates - /// that direction of drift and re-marks it from the inventory. + /// Also maintains the wallet's presence marker (see `walletPresence()`) + /// under the invariant *marker ⇒ a mnemonic was stored*. The steps run + /// in the one order that keeps it across an interruption at any + /// point: the marker comes off before the old mnemonic is deleted, + /// and goes back on only after the new mnemonic is in place. A + /// process killed in between leaves at most a mnemonic without a + /// marker — the one direction of drift the presence read repairs — + /// never a marker without a mnemonic. For the same reason a failed + /// trailing marker write is not an error here: the mnemonic *is* + /// stored, and the next `walletPresence()` call on an unlocked + /// device backfills the marker. public func storeMnemonic(_ mnemonic: String, for walletId: Data) throws { - let data = Data(mnemonic.utf8) - let account = perWalletMnemonicAccount(for: walletId) + Self.mutationLock.lock() + defer { Self.mutationLock.unlock() } - try storePresenceMarker(for: walletId) + try deletePresenceMarker(for: walletId) + try deleteMnemonicItem(for: walletId) + try addMnemonicItem(Data(mnemonic.utf8), for: walletId) + try? storePresenceMarker(for: walletId) + } - let deleteQuery: [String: Any] = [ + /// Raw delete of the mnemonic item. Idempotent. Overridable so tests + /// can observe the order of the keychain steps without a keychain. + func deleteMnemonicItem(for walletId: Data) throws { + let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: keychainService, - kSecAttrAccount as String: account + kSecAttrAccount as String: perWalletMnemonicAccount(for: walletId) ] - let deleteStatus = SecItemDelete(deleteQuery as CFDictionary) - guard deleteStatus == errSecSuccess || deleteStatus == errSecItemNotFound else { - try? deletePresenceMarker(for: walletId) - throw WalletStorageError.keychainError(deleteStatus) + let status = SecItemDelete(query as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { + throw WalletStorageError.keychainError(status) } + } + /// Raw add of the mnemonic item; the caller has deleted any previous + /// one so the `kSecAttrAccessible` value is rewritten on every save. + func addMnemonicItem(_ data: Data, for walletId: Data) throws { let addQuery: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: keychainService, - kSecAttrAccount as String: account, + kSecAttrAccount as String: perWalletMnemonicAccount(for: walletId), kSecValueData as String: data, kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly ] let status = SecItemAdd(addQuery as CFDictionary, nil) guard status == errSecSuccess else { - try? deletePresenceMarker(for: walletId) throw WalletStorageError.keychainError(status) } } @@ -257,23 +270,18 @@ public class WalletStorage { /// Delete a mnemonic keyed by wallet id. Idempotent. /// - /// Removes the presence marker first: if the mnemonic delete then - /// fails, the wallet is merely unmarked (and `walletPresence()` falls - /// back to the mnemonic inventory, which re-marks it), never marked - /// without a mnemonic behind it. + /// The mnemonic goes first and the presence marker second, under the + /// same lock `walletPresence()` takes: a presence read cannot slip + /// between the two steps and backfill a marker for a mnemonic that is + /// about to disappear, and an interruption between them leaves a + /// marker whose mnemonic is gone only until the next unlocked + /// presence read reconciles it away. public func deleteMnemonic(for walletId: Data) throws { - try deletePresenceMarker(for: walletId) + Self.mutationLock.lock() + defer { Self.mutationLock.unlock() } - let account = perWalletMnemonicAccount(for: walletId) - let query: [String: Any] = [ - kSecClass as String: kSecClassGenericPassword, - kSecAttrService as String: keychainService, - kSecAttrAccount as String: account - ] - let status = SecItemDelete(query as CFDictionary) - guard status == errSecSuccess || status == errSecItemNotFound else { - throw WalletStorageError.keychainError(status) - } + try deleteMnemonicItem(for: walletId) + try deletePresenceMarker(for: walletId) } /// Enumerate all wallet ids with a stored mnemonic. @@ -330,9 +338,20 @@ public class WalletStorage { // refresh, a silent push) cannot even enumerate them: the inventory // read fails and a naive caller concludes "no wallet" and shows the // setup screen. The marker is the durable, non-secret answer to that - // one question. It is written and removed inside `storeMnemonic` / - // `deleteMnemonic` so it cannot drift from the mnemonic on any - // write or delete path, including the manager's delete-wallet path. + // one question. + // + // Invariant: marker ⇒ a mnemonic was stored for that id. The marker + // is maintained only inside `storeMnemonic` / `deleteMnemonic`, in an + // order that keeps the invariant across an interruption at any step + // (mnemonic on before marker on; mnemonic off before marker off), and + // the three entry points that touch both items share one process-wide + // lock so a presence read cannot interleave with a write or delete + // (`PlatformWalletManager.deleteWallet` uses its own `WalletStorage` + // instance; the lock is static for that reason). Drift is therefore + // only ever a mnemonic *without* a marker — a wallet stored before the + // marker existed, a trailing marker write that failed — and every + // presence read made while the inventory is readable repairs it, in + // both directions: it rewrites the marker set to match the inventory. // // Security trade-off: `AfterFirstUnlockThisDeviceOnly` means anyone // who can query this app's keychain after the first unlock since @@ -342,17 +361,23 @@ public class WalletStorage { // keychain across a reinstall (which is why this is not a // `UserDefaults` flag) and never syncs to iCloud. + /// Serialises `storeMnemonic`, `deleteMnemonic` and `walletPresence()` + /// across every `WalletStorage` instance in the process. Held only + /// around keychain calls; never taken by the item-level helpers. + private static let mutationLock = NSLock() + private func perWalletPresenceMarkerAccount(for walletId: Data) -> String { let hex = walletId.map { String(format: "%02x", $0) }.joined() return "\(Self.presenceMarkerAccountPrefix).\(hex)" } - /// Write (or rewrite) the presence marker for `walletId`. Called by - /// `storeMnemonic` and by the lazy backfill in `walletPresence()`; - /// there is no reason for an app to call it directly. Delete-then-add - /// like the other writers so the accessibility class is re-applied on + /// Write (or rewrite) the presence marker for `walletId`. A lifecycle + /// step of `storeMnemonic` and of the reconciliation in + /// `walletPresence()`, not an SDK operation: a marker written on its + /// own would assert a wallet that may not exist. Delete-then-add like + /// the other writers so the accessibility class is re-applied on /// every write. The payload is the wallet id itself — no secret. - public func storePresenceMarker(for walletId: Data) throws { + func storePresenceMarker(for walletId: Data) throws { let account = perWalletPresenceMarkerAccount(for: walletId) let deleteQuery: [String: Any] = [ @@ -378,9 +403,10 @@ public class WalletStorage { } } - /// Delete the presence marker for `walletId`. Idempotent. Called by - /// `deleteMnemonic`; not meant to be called on its own. - public func deletePresenceMarker(for walletId: Data) throws { + /// Delete the presence marker for `walletId`. Idempotent. A lifecycle + /// step of `storeMnemonic`, `deleteMnemonic` and the reconciliation in + /// `walletPresence()`; not an SDK operation. + func deletePresenceMarker(for walletId: Data) throws { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: Self.presenceKeychainService, @@ -406,13 +432,13 @@ public class WalletStorage { /// Three-way answer to "does this app hold at least one wallet?". public enum WalletPresence: Sendable, Equatable { - /// At least one wallet id is marked, or the mnemonic inventory is - /// readable and non-empty. + /// The mnemonic inventory was readable and non-empty, or it was + /// unreadable and at least one wallet id is marked. case present - /// No marker *and* the mnemonic inventory was readable and empty. - /// The only verdict on which a setup screen may be shown. + /// The mnemonic inventory was readable and empty. The only verdict + /// on which a setup screen may be shown. case absent - /// Could not tell: the marker was unreadable (before the first + /// Could not tell: the marker set was unreadable (before the first /// unlock, `errSecInteractionNotAllowed`, …) or it was empty and /// the inventory was unreadable (a locked device with wallets /// stored before the marker existed). Says nothing about whether @@ -422,47 +448,52 @@ public class WalletStorage { /// Whether at least one wallet exists, answerable on a locked device. /// - /// Resolution order: + /// The mnemonic inventory is the source of truth whenever it can be + /// read; the marker set stands in for it only while it cannot: /// - /// 1. `markedWalletIds()` non-empty → `.present`. A marker is only - /// ever written next to a mnemonic. - /// 2. Marker readable but empty → consult `listWalletIdsWithMnemonic()`. - /// Non-empty → `.present`, and each id is marked so the next - /// locked launch is answered by step 1 (wallets stored before the - /// marker existed backfill themselves on the first unlocked read). - /// Empty → `.absent`. - /// 3. Either read failing → `.unknown(status)`. + /// 1. `markedWalletIds()` unreadable → `.unknown(status)`. + /// 2. `listWalletIdsWithMnemonic()` readable → verdict from it + /// (`.present` / `.absent`), and the marker set is reconciled to + /// it: a marker is written for every inventoried id without one + /// (wallets stored before the marker existed backfill themselves + /// on the first unlocked read) and any marker without a mnemonic + /// is removed. Best effort; a failed write or delete changes + /// nothing about the verdict. + /// 3. Inventory unreadable → marker set non-empty is `.present`, + /// empty is `.unknown(status)`. /// - /// Invariant for callers: marker present ⇒ a wallet exists; a missing - /// marker on its own never means "no wallet" — only a readable, empty - /// inventory does. The backfill is best-effort; a failed marker write - /// does not change the verdict, it just defers the shortcut. + /// Invariant for callers: marker present ⇒ a mnemonic was stored for + /// that id; a missing marker on its own never means "no wallet" — only + /// a readable, empty inventory does. /// /// - Tag: walletPresence public func walletPresence() -> WalletPresence { + Self.mutationLock.lock() + defer { Self.mutationLock.unlock() } + let marked: [Data] do { marked = try markedWalletIds() } catch { return .unknown(Self.status(of: error)) } - if !marked.isEmpty { - return .present - } let inventory: [Data] do { inventory = try listWalletIdsWithMnemonic() } catch { - return .unknown(Self.status(of: error)) + return marked.isEmpty ? .unknown(Self.status(of: error)) : .present } - guard !inventory.isEmpty else { - return .absent - } - for walletId in inventory { + + let markedSet = Set(marked) + let inventorySet = Set(inventory) + for walletId in inventory where !markedSet.contains(walletId) { try? storePresenceMarker(for: walletId) } - return .present + for walletId in marked where !inventorySet.contains(walletId) { + try? deletePresenceMarker(for: walletId) + } + return inventory.isEmpty ? .absent : .present } /// The `OSStatus` behind a `WalletStorageError.keychainError`; anything diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift index 1935debddc5..894b9fd28cc 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift @@ -3,109 +3,323 @@ import XCTest @testable import SwiftDashSDK -/// Classification logic of `WalletStorage.walletPresence()` with the two -/// Keychain reads and the backfill write injected, so the suite never -/// touches the real Keychain (the same reason +/// The presence-marker lifecycle of `WalletStorage` — `storeMnemonic`, +/// `deleteMnemonic` and `walletPresence()` — run against an in-memory +/// keychain instead of the real one (the same reason /// `IdentityResolverSignIntegrationTests` uses an in-memory storage: a /// CI runner's keychain session is an environment, not what is under -/// test). What the fake models is the *outcome* of each read on a -/// device in a given state — unreadable, readable-empty, readable-with-ids. +/// test). The fake models the *outcome* of each keychain step on a +/// device in a given state — unreadable, readable-empty, readable-with- +/// ids — and records the order of the steps, so the invariant *marker ⇒ +/// a mnemonic was stored* can be checked at every interruption point +/// and across an interleaving between two storage instances. final class WalletPresenceTests: XCTestCase { - /// `WalletStorage` whose marker read, mnemonic inventory and marker - /// write are scripted. A `nil` result throws `keychainError(status)` - /// with the given status, the way the real reads fail on a locked - /// device. - private final class ScriptedStorage: WalletStorage { - var marked: [Data]? - var inventory: [Data]? - var failureStatus: OSStatus = errSecInteractionNotAllowed - var markerWriteStatus: OSStatus = errSecSuccess - private(set) var markerWrites: [Data] = [] - private(set) var inventoryReads = 0 - - override func markedWalletIds() throws -> [Data] { - guard let marked else { throw WalletStorageError.keychainError(failureStatus) } - return marked + /// One keychain shared by every `FakeStorage` in a test, the way the + /// real one is shared by every `WalletStorage()` in the process. + private final class FakeKeychain: @unchecked Sendable { + private let lock = NSLock() + private var mnemonics: Set = [] + private var markers: Set = [] + private var log: [String] = [] + + /// `nil` means readable; a status means every read of that set + /// throws `keychainError(status)`, as on a locked device. + var inventoryFailure: OSStatus? + var markerReadFailure: OSStatus? + var markerWriteFailure: OSStatus? + var mnemonicAddFailure: OSStatus? + + func seed(mnemonics: [Data] = [], markers: [Data] = []) { + lock.withLock { + self.mnemonics = Set(mnemonics) + self.markers = Set(markers) + } + } + + var mnemonicIds: Set { lock.withLock { mnemonics } } + var markerIds: Set { lock.withLock { markers } } + var steps: [String] { lock.withLock { log } } + + private static func tag(_ id: Data) -> String { + String(format: "%02x", id.first ?? 0) } - override func listWalletIdsWithMnemonic() throws -> [Data] { - inventoryReads += 1 - guard let inventory else { throw WalletStorageError.keychainError(failureStatus) } - return inventory + func listMnemonics() throws -> [Data] { + try lock.withLock { + log.append("inventory") + if let status = inventoryFailure { throw WalletStorageError.keychainError(status) } + return Array(mnemonics) + } + } + + func listMarkers() throws -> [Data] { + try lock.withLock { + log.append("markers") + if let status = markerReadFailure { throw WalletStorageError.keychainError(status) } + return Array(markers) + } + } + + func addMnemonic(_ id: Data) throws { + try lock.withLock { + log.append("addMnemonic:\(Self.tag(id))") + if let status = mnemonicAddFailure { throw WalletStorageError.keychainError(status) } + mnemonics.insert(id) + } + } + + func deleteMnemonic(_ id: Data) { + lock.withLock { + log.append("deleteMnemonic:\(Self.tag(id))") + mnemonics.remove(id) + } + } + + func addMarker(_ id: Data) throws { + try lock.withLock { + log.append("addMarker:\(Self.tag(id))") + if let status = markerWriteFailure { throw WalletStorageError.keychainError(status) } + markers.insert(id) + } } - override func storePresenceMarker(for walletId: Data) throws { - guard markerWriteStatus == errSecSuccess else { - throw WalletStorageError.keychainError(markerWriteStatus) + func deleteMarker(_ id: Data) { + lock.withLock { + log.append("deleteMarker:\(Self.tag(id))") + markers.remove(id) } - markerWrites.append(walletId) } } + /// `WalletStorage` whose keychain steps go to a `FakeKeychain`. Only + /// the item-level primitives are overridden; the lifecycle logic under + /// test is the real one. + private class FakeStorage: WalletStorage, @unchecked Sendable { + let keychain: FakeKeychain + + init(_ keychain: FakeKeychain) { + self.keychain = keychain + super.init() + } + + override func listWalletIdsWithMnemonic() throws -> [Data] { try keychain.listMnemonics() } + override func markedWalletIds() throws -> [Data] { try keychain.listMarkers() } + override func addMnemonicItem(_ data: Data, for walletId: Data) throws { + try keychain.addMnemonic(walletId) + } + override func deleteMnemonicItem(for walletId: Data) throws { keychain.deleteMnemonic(walletId) } + override func storePresenceMarker(for walletId: Data) throws { try keychain.addMarker(walletId) } + override func deletePresenceMarker(for walletId: Data) throws { keychain.deleteMarker(walletId) } + } + private let walletA = Data(repeating: 0xA1, count: 32) private let walletB = Data(repeating: 0xB2, count: 32) + private let locked: OSStatus = errSecInteractionNotAllowed + + // MARK: - Classification - func testMarkedWalletIsPresentWithoutConsultingTheInventory() { - let storage = ScriptedStorage() - storage.marked = [walletA] - storage.inventory = nil // would throw: the device is locked + func testUnreadableMarkerIsUnknownWithoutConsultingTheInventory() { + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA]) + keychain.markerReadFailure = locked // before the first unlock since boot - XCTAssertEqual(storage.walletPresence(), .present) - XCTAssertEqual(storage.inventoryReads, 0, "a marker answers on its own") - XCTAssertTrue(storage.markerWrites.isEmpty, "nothing to backfill") + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .unknown(locked)) + XCTAssertEqual(keychain.steps, ["markers"], "an unreadable marker set ends the lookup") } - func testReadableEmptyMarkerAndEmptyInventoryIsAbsent() { - let storage = ScriptedStorage() - storage.marked = [] - storage.inventory = [] + func testMarkedWalletIsPresentWhileTheInventoryIsUnreadable() { + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA], markers: [walletA]) + keychain.inventoryFailure = locked - XCTAssertEqual(storage.walletPresence(), .absent) - XCTAssertEqual(storage.inventoryReads, 1) - XCTAssertTrue(storage.markerWrites.isEmpty) + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .present) + XCTAssertEqual(keychain.steps, ["markers", "inventory"], "no writes while locked") } - func testEmptyMarkerFallsBackToInventoryAndBackfillsEveryWallet() { - let storage = ScriptedStorage() - storage.marked = [] - storage.inventory = [walletA, walletB] + func testEmptyMarkerSetWithUnreadableInventoryIsUnknownNotAbsent() { + // A locked device holding wallets stored before the marker + // existed: the marker set reads empty, the inventory cannot be read. + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA]) + keychain.inventoryFailure = locked - XCTAssertEqual(storage.walletPresence(), .present) - XCTAssertEqual(storage.markerWrites, [walletA, walletB]) + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .unknown(locked)) + XCTAssertTrue(keychain.markerIds.isEmpty) } - func testUnreadableMarkerIsUnknownWithTheKeychainStatus() { - let storage = ScriptedStorage() - storage.marked = nil // before the first unlock since boot - storage.inventory = [walletA] // must not be reached + func testReadableEmptyInventoryIsAbsent() { + let keychain = FakeKeychain() - XCTAssertEqual(storage.walletPresence(), .unknown(errSecInteractionNotAllowed)) - XCTAssertEqual(storage.inventoryReads, 0, "an unreadable marker ends the lookup") - XCTAssertTrue(storage.markerWrites.isEmpty) + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .absent) + XCTAssertEqual(keychain.steps, ["markers", "inventory"]) } - func testEmptyMarkerWithUnreadableInventoryIsUnknownNotAbsent() { - // A locked device holding wallets stored before the marker - // existed: the marker reads empty, the inventory cannot be read. - let storage = ScriptedStorage() - storage.marked = [] - storage.inventory = nil - storage.failureStatus = errSecInteractionNotAllowed + // MARK: - Reconciliation while the inventory is readable - XCTAssertEqual(storage.walletPresence(), .unknown(errSecInteractionNotAllowed)) - XCTAssertTrue(storage.markerWrites.isEmpty) + func testUnmarkedWalletsAreBackfilledFromTheInventory() { + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA, walletB]) + + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .present) + XCTAssertEqual(keychain.markerIds, [walletA, walletB]) } - func testFailedBackfillDoesNotChangeThePresentVerdict() { - let storage = ScriptedStorage() - storage.marked = [] - storage.inventory = [walletA] - storage.markerWriteStatus = errSecWrPerm + func testMarkerWithoutMnemonicIsRemovedAndTheVerdictIsAbsent() { + // A phantom left by an older build or an interrupted write: the + // inventory is authoritative once readable. + let keychain = FakeKeychain() + keychain.seed(markers: [walletA]) - XCTAssertEqual(storage.walletPresence(), .present) - XCTAssertTrue(storage.markerWrites.isEmpty) + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .absent) + XCTAssertTrue(keychain.markerIds.isEmpty) } + func testMarkerSetIsRewrittenToMatchTheInventory() { + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletB], markers: [walletA]) + + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .present) + XCTAssertEqual(keychain.markerIds, [walletB]) + } + + func testFailedBackfillDoesNotChangeTheVerdict() { + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA]) + keychain.markerWriteFailure = errSecWrPerm + + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .present) + XCTAssertTrue(keychain.markerIds.isEmpty) + } + + // MARK: - Ordering inside storeMnemonic / deleteMnemonic + + func testStoreWritesTheMnemonicBeforeTheMarker() throws { + let keychain = FakeKeychain() + + try FakeStorage(keychain).storeMnemonic("abandon", for: walletA) + + XCTAssertEqual( + keychain.steps, + ["deleteMarker:a1", "deleteMnemonic:a1", "addMnemonic:a1", "addMarker:a1"] + ) + XCTAssertEqual(keychain.mnemonicIds, [walletA]) + XCTAssertEqual(keychain.markerIds, [walletA]) + } + + func testFailedMnemonicWriteLeavesNoMarker() { + // The interruption the order exists for: a process killed after + // the marker step but before the mnemonic step must not leave a + // marker behind — so the marker step is last. + let keychain = FakeKeychain() + keychain.mnemonicAddFailure = errSecWrPerm + + XCTAssertThrowsError(try FakeStorage(keychain).storeMnemonic("abandon", for: walletA)) + XCTAssertTrue(keychain.markerIds.isEmpty) + XCTAssertFalse(keychain.steps.contains("addMarker:a1")) + } + + func testRewriteTakesTheMarkerOffBeforeTheDeleteAddGap() throws { + // A kill between the old mnemonic's delete and the new one's add + // must not retain the marker across the gap. + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA], markers: [walletA]) + + try FakeStorage(keychain).storeMnemonic("abandon", for: walletA) + + let steps = keychain.steps + let markerOff = try XCTUnwrap(steps.firstIndex(of: "deleteMarker:a1")) + let mnemonicOff = try XCTUnwrap(steps.firstIndex(of: "deleteMnemonic:a1")) + XCTAssertLessThan(markerOff, mnemonicOff) + XCTAssertEqual(keychain.markerIds, [walletA]) + } + + func testFailedTrailingMarkerWriteDoesNotFailTheStore() throws { + let keychain = FakeKeychain() + keychain.markerWriteFailure = errSecWrPerm + + try FakeStorage(keychain).storeMnemonic("abandon", for: walletA) + + XCTAssertEqual(keychain.mnemonicIds, [walletA], "the mnemonic is stored") + XCTAssertTrue(keychain.markerIds.isEmpty, "the safe direction of drift") + keychain.markerWriteFailure = nil + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .present) + XCTAssertEqual(keychain.markerIds, [walletA], "and the next unlocked read repairs it") + } + + func testDeleteRemovesTheMnemonicBeforeTheMarker() throws { + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA], markers: [walletA]) + + try FakeStorage(keychain).deleteMnemonic(for: walletA) + + XCTAssertEqual(keychain.steps, ["deleteMnemonic:a1", "deleteMarker:a1"]) + XCTAssertTrue(keychain.mnemonicIds.isEmpty) + XCTAssertTrue(keychain.markerIds.isEmpty) + } + + // MARK: - Interleaving across storage instances + + func testPresenceReadCannotBackfillAMarkerDuringADeletion() throws { + // `deleteMnemonic` on one instance is paused at its first keychain + // step; `walletPresence()` on a second instance (the inventory + // still lists the wallet, no marker yet) must wait for the + // deletion instead of backfilling a marker the deletion would + // then leave behind. + final class PausingStorage: FakeStorage, @unchecked Sendable { + let entered = DispatchSemaphore(value: 0) + let release = DispatchSemaphore(value: 0) + override func deleteMnemonicItem(for walletId: Data) throws { + entered.signal() + release.wait() + try super.deleteMnemonicItem(for: walletId) + } + } + + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA]) + let deleting = PausingStorage(keychain) + let reading = FakeStorage(keychain) + + let walletA = walletA + let deleteDone = expectation(description: "delete finished") + Thread.detachNewThread { + try? deleting.deleteMnemonic(for: walletA) + deleteDone.fulfill() + } + XCTAssertEqual(deleting.entered.wait(timeout: .now() + 5), .success) + + let presenceDone = expectation(description: "presence finished") + let verdict = LockedBox(nil) + Thread.detachNewThread { + verdict.value = reading.walletPresence() + presenceDone.fulfill() + } + // The read is blocked behind the paused deletion: it has not + // touched the keychain yet. + Thread.sleep(forTimeInterval: 0.2) + XCTAssertNil(verdict.value) + XCTAssertFalse(keychain.steps.contains("markers")) + + deleting.release.signal() + wait(for: [deleteDone, presenceDone], timeout: 5) + + XCTAssertEqual(verdict.value, .absent) + XCTAssertTrue(keychain.mnemonicIds.isEmpty) + XCTAssertTrue(keychain.markerIds.isEmpty, "no marker survives the deletion") + } + + private final class LockedBox: @unchecked Sendable { + private let lock = NSLock() + private var stored: T + init(_ value: T) { stored = value } + var value: T { + get { lock.withLock { stored } } + set { lock.withLock { stored = newValue } } + } + } + + // MARK: - Layout + func testMarkerServiceIsASiblingOfTheMnemonicService() { // The marker items are `AfterFirstUnlock`, the mnemonic items // `WhenUnlocked`; a shared service would make one service-wide From 3428934e2e4b33958976c52ec215045ff6f0f279 Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Fri, 25 Sep 2026 14:54:16 +0300 Subject: [PATCH 3/3] fix(swift-sdk): remove the presence marker before the mnemonic on delete MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up. deleteMnemonic removed the mnemonic first and the marker second, so a process killed between the two steps, or a marker delete that threw, left a marker with no mnemonic behind it — and a locked presence read trusts the marker. The ordering was chosen to keep a concurrent backfill from re-marking the wallet, which the shared mutation lock now prevents on its own. The marker now comes off first: an interruption leaves at most an unmarked mnemonic, which a locked read reports as unknown and an unlocked read re-marks. The section and lifecycle comments say so, the delete-order test is renamed, and two tests cover a throw at either step between the deletions. Co-Authored-By: Claude Fable 5.1 --- .../Core/Wallet/WalletStorage.swift | 17 ++--- .../WalletPresenceTests.swift | 66 +++++++++++++++---- 2 files changed, 61 insertions(+), 22 deletions(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift index 74a7c2b30d3..e4917d293c1 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift @@ -270,18 +270,19 @@ public class WalletStorage { /// Delete a mnemonic keyed by wallet id. Idempotent. /// - /// The mnemonic goes first and the presence marker second, under the - /// same lock `walletPresence()` takes: a presence read cannot slip - /// between the two steps and backfill a marker for a mnemonic that is - /// about to disappear, and an interruption between them leaves a - /// marker whose mnemonic is gone only until the next unlocked - /// presence read reconciles it away. + /// The presence marker comes off first and the mnemonic second, so a + /// process killed between the two steps — or a mnemonic delete that + /// throws — leaves at most a mnemonic without a marker, which the next + /// unlocked presence read re-marks; never a marker without a mnemonic, + /// which a locked read would trust. The lock `walletPresence()` shares + /// keeps a presence read from backfilling the marker between the two + /// steps. public func deleteMnemonic(for walletId: Data) throws { Self.mutationLock.lock() defer { Self.mutationLock.unlock() } - try deleteMnemonicItem(for: walletId) try deletePresenceMarker(for: walletId) + try deleteMnemonicItem(for: walletId) } /// Enumerate all wallet ids with a stored mnemonic. @@ -343,7 +344,7 @@ public class WalletStorage { // Invariant: marker ⇒ a mnemonic was stored for that id. The marker // is maintained only inside `storeMnemonic` / `deleteMnemonic`, in an // order that keeps the invariant across an interruption at any step - // (mnemonic on before marker on; mnemonic off before marker off), and + // (the marker goes on last and comes off first), and // the three entry points that touch both items share one process-wide // lock so a presence read cannot interleave with a write or delete // (`PlatformWalletManager.deleteWallet` uses its own `WalletStorage` diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift index 894b9fd28cc..60461d183b3 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift @@ -27,7 +27,9 @@ final class WalletPresenceTests: XCTestCase { var inventoryFailure: OSStatus? var markerReadFailure: OSStatus? var markerWriteFailure: OSStatus? + var markerDeleteFailure: OSStatus? var mnemonicAddFailure: OSStatus? + var mnemonicDeleteFailure: OSStatus? func seed(mnemonics: [Data] = [], markers: [Data] = []) { lock.withLock { @@ -68,9 +70,10 @@ final class WalletPresenceTests: XCTestCase { } } - func deleteMnemonic(_ id: Data) { - lock.withLock { + func deleteMnemonic(_ id: Data) throws { + try lock.withLock { log.append("deleteMnemonic:\(Self.tag(id))") + if let status = mnemonicDeleteFailure { throw WalletStorageError.keychainError(status) } mnemonics.remove(id) } } @@ -83,9 +86,10 @@ final class WalletPresenceTests: XCTestCase { } } - func deleteMarker(_ id: Data) { - lock.withLock { + func deleteMarker(_ id: Data) throws { + try lock.withLock { log.append("deleteMarker:\(Self.tag(id))") + if let status = markerDeleteFailure { throw WalletStorageError.keychainError(status) } markers.remove(id) } } @@ -107,9 +111,9 @@ final class WalletPresenceTests: XCTestCase { override func addMnemonicItem(_ data: Data, for walletId: Data) throws { try keychain.addMnemonic(walletId) } - override func deleteMnemonicItem(for walletId: Data) throws { keychain.deleteMnemonic(walletId) } + override func deleteMnemonicItem(for walletId: Data) throws { try keychain.deleteMnemonic(walletId) } override func storePresenceMarker(for walletId: Data) throws { try keychain.addMarker(walletId) } - override func deletePresenceMarker(for walletId: Data) throws { keychain.deleteMarker(walletId) } + override func deletePresenceMarker(for walletId: Data) throws { try keychain.deleteMarker(walletId) } } private let walletA = Data(repeating: 0xA1, count: 32) @@ -246,32 +250,66 @@ final class WalletPresenceTests: XCTestCase { XCTAssertEqual(keychain.markerIds, [walletA], "and the next unlocked read repairs it") } - func testDeleteRemovesTheMnemonicBeforeTheMarker() throws { + func testDeleteRemovesTheMarkerBeforeTheMnemonic() throws { let keychain = FakeKeychain() keychain.seed(mnemonics: [walletA], markers: [walletA]) try FakeStorage(keychain).deleteMnemonic(for: walletA) - XCTAssertEqual(keychain.steps, ["deleteMnemonic:a1", "deleteMarker:a1"]) + XCTAssertEqual(keychain.steps, ["deleteMarker:a1", "deleteMnemonic:a1"]) XCTAssertTrue(keychain.mnemonicIds.isEmpty) XCTAssertTrue(keychain.markerIds.isEmpty) } + func testFailedMnemonicDeleteLeavesAnUnmarkedMnemonicNotAPhantom() { + // The interruption between the two deletions: the marker is + // already gone, the mnemonic is still there. A locked read then + // says unknown rather than present-for-a-wallet-that-is-gone, and + // an unlocked read re-marks the surviving mnemonic. + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA], markers: [walletA]) + keychain.mnemonicDeleteFailure = errSecWrPerm + + XCTAssertThrowsError(try FakeStorage(keychain).deleteMnemonic(for: walletA)) + XCTAssertEqual(keychain.mnemonicIds, [walletA]) + XCTAssertTrue(keychain.markerIds.isEmpty, "the safe direction of drift") + + keychain.inventoryFailure = locked + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .unknown(locked)) + + keychain.inventoryFailure = nil + XCTAssertEqual(FakeStorage(keychain).walletPresence(), .present) + XCTAssertEqual(keychain.markerIds, [walletA], "and the next unlocked read repairs it") + } + + func testFailedMarkerDeleteLeavesTheMnemonicInPlace() { + // The first step failing must not remove the mnemonic behind a + // marker that still exists. + let keychain = FakeKeychain() + keychain.seed(mnemonics: [walletA], markers: [walletA]) + keychain.markerDeleteFailure = errSecWrPerm + + XCTAssertThrowsError(try FakeStorage(keychain).deleteMnemonic(for: walletA)) + XCTAssertEqual(keychain.steps, ["deleteMarker:a1"]) + XCTAssertEqual(keychain.mnemonicIds, [walletA]) + XCTAssertEqual(keychain.markerIds, [walletA]) + } + // MARK: - Interleaving across storage instances func testPresenceReadCannotBackfillAMarkerDuringADeletion() throws { // `deleteMnemonic` on one instance is paused at its first keychain - // step; `walletPresence()` on a second instance (the inventory - // still lists the wallet, no marker yet) must wait for the - // deletion instead of backfilling a marker the deletion would - // then leave behind. + // step (the marker delete); `walletPresence()` on a second + // instance (the inventory still lists the wallet, no marker yet) + // must wait for the deletion instead of backfilling a marker the + // deletion would then leave behind. final class PausingStorage: FakeStorage, @unchecked Sendable { let entered = DispatchSemaphore(value: 0) let release = DispatchSemaphore(value: 0) - override func deleteMnemonicItem(for walletId: Data) throws { + override func deletePresenceMarker(for walletId: Data) throws { entered.signal() release.wait() - try super.deleteMnemonicItem(for: walletId) + try super.deletePresenceMarker(for: walletId) } }