Repository navigation
feat(swift-sdk): wallet presence flag readable while the device is locked - #4992
romchornyi wants to merge 4 commits into
Conversation
…vice 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.<hex-walletId>` under the sibling service `<keychainService>.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 <[email protected]>
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 49 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
|
🔍 Review in progress (commit 242e382) · live progress
|
|
@thepastaclaw review No review for |
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 1 + Phase 2
Verified the supplied findings against head 4c6051f, the changed tests, and surrounding callers. Interrupted writes and concurrent deletion/backfill can leave persistent false-positive wallet markers, and the public marker mutators bypass the documented lifecycle invariant. These are classified as suggestions under the supplied policy for non-consensus correctness issues; verification was source-based, without independently rerunning the reported harnesses.
🟡 3 suggestion(s)
Review provenance
Source: reviewer 1: gemini-3.8-flash-high (agent: phase1-reviewer, role: general); reviewer 2: gemini-3.8-flash-high (agent: phase1-reviewer, role: architecture-layering); reviewer 3: gemini-3.8-flash-high (agent: phase1-reviewer, role: security-auditor); reviewer 4: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 5: gpt-6-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 6: gpt-6-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6-astra (agent: astra-verifier, role: final-verifier)
- Triage:
criticalbygpt-6-astra(effort low) — The substantial and intricate change modifies WalletStorage keychain handling and mnemonic write/delete coupling, directly affecting wallet key-material persistence and accessibility semantics. - Phase 1 reviewers:
gemini-3.8-flash-high— general (completed, effort high); agentphase1-reviewer,gemini-3.8-flash-high— architecture-layering (completed, effort high); agentphase1-reviewer,gemini-3.8-flash-high— security-auditor (completed, effort high); agentphase1-reviewer - Phase 1 model:
gemini-3.8-flash-high— antigravity quota: weekly 75% left, 5h 58% left - Fresh verifier:
gpt-6-astra— final-verifier; agentastra-verifier - Phase 2 reviewers:
gpt-6-astra— general (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— security-auditor (completed, effort xhigh); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift:109: Persisting the marker first leaves a phantom wallet after interruption
On a first mnemonic write, this call persists the marker before the mnemonic exists. If the process terminates before the mnemonic's SecItemAdd succeeds, the error-handler cleanup never executes. Subsequent walletPresence() calls return .present from the marker without consulting the empty mnemonic inventory, even after unlocking or restarting. Rewriting an existing mnemonic has the same failure window between its deletion and replacement. An application following the documented rule that only .absent permits setup can therefore suppress Create/Recover indefinitely despite having no stored mnemonic. Make persistence interruption-safe: establish the mnemonic before publishing its marker, and ensure rewrites cannot retain a marker across a delete/add gap. A mnemonic without a marker already has a safe inventory fallback. Add regression coverage for interruption at these persistence boundaries.
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift:453-464: Backfill can recreate a marker during a successful mnemonic deletion
The inventory read and marker backfill are not coordinated with mnemonic mutations. With independently created WalletStorage instances, deleteMnemonic() can remove a wallet's marker and pause before removing its mnemonic; walletPresence() can then observe an empty marker list, inventory the still-existing mnemonic, and recreate its marker. Deletion subsequently removes the mnemonic and succeeds, leaving a marker that makes future presence calls return .present without checking the now-empty inventory. WalletStorage has no shared synchronization or actor isolation preventing this schedule, and PlatformWalletManager.deleteWallet creates its own storage instance. Coordinate the complete inventory-read/backfill sequence with mnemonic writes and deletes across storage instances sharing the service. Add an interleaving regression at the Keychain-operation boundary; the current scripted classification tests do not exercise this lifecycle.
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift:350-355: Keep raw marker mutation out of the public SDK contract
The new public storePresenceMarker(for:) can create a marker for a wallet ID with no stored mnemonic. walletPresence() then reports .present without consulting the empty mnemonic inventory, violating its documented marker-implies-wallet invariant. The comments explicitly discourage independent marker mutation, and no production caller outside WalletStorage needs these mutators. Keep storePresenceMarker and deletePresenceMarker internal or private lifecycle helpers rather than exposing unsupported independent writes as public SDK operations. Internal visibility preserves the override seam used by the @testable test target without publishing it to applications.
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 <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The complete diff at bccb27b addresses all three prior findings: marker mutation is internal, lifecycle operations share a process-wide lock, and mnemonic writes use interruption-safe ordering. One non-consensus correctness suggestion remains: interrupted deletion can leave a stale marker that produces a false presence result while the inventory is unreadable. Verification was based on source, caller, and test inspection; tests were not rerun.
🟡 1 suggestion(s)
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: architecture-layering); reviewer 3: muse-spark-1.3-contributor (agent: phase1-reviewer, role: security-auditor); reviewer 4: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 5: gpt-6-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 6: gpt-6-astra (agent: phase2-reviewer, role: security-auditor); reviewer 7: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 8: gpt-6-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 9: gpt-6-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6-astra (agent: astra-verifier, role: final-verifier)
- Triage:
criticalbygpt-6-astra(effort low) — The diff is large and intricate and changes WalletStorage.swift, which handles mnemonic key material and Keychain persistence, a critical key-handling and storage surface. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— architecture-layering (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— security-auditor (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity below 15% reserve: weekly 35% left, 5h 0% left),glm-5.3-flash(not used above high effort; tier asks max) - Fresh final gate: an independent Phase-2 review ran after iterative findings were reconciled
- Fresh verifier:
gpt-6-astra— final-verifier; agentastra-verifier - Phase 2 reviewers:
gpt-6-astra— general (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— security-auditor (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— general (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— security-auditor (completed, effort xhigh); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift:283-284: Deleting the mnemonic before its marker can leave a phantom wallet
These are independent keychain operations. If the process stops after mnemonic deletion, or the subsequent marker deletion throws, the durable marker survives without its mnemonic. When the mnemonic inventory is unreadable, `walletPresence()` trusts that marker and returns `.present` at line 485. There is a concrete affected caller: the example app's `deleteStoredMnemonics()` skips metadata cleanup when `deleteMnemonic()` throws, leaving protected metadata under the inventory service that can make a later locked inventory query fail even though the mnemonic is gone. Unlocked reconciliation repairs this state, but cannot prevent the false result during a locked launch.
Remove the marker first under the existing mutation lock, then delete the mnemonic. The lock already prevents same-process backfill between those steps; an interruption then leaves at most an unmarked mnemonic rather than a phantom marker. Update the lifecycle comments and `testDeleteRemovesTheMnemonicBeforeTheMarker`, and add coverage for failure or interruption between the two deletions.
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 <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The complete diff and relevant lifecycle callers contain no confirmed in-scope defects; all four prior findings are fixed. Marker ordering, internal mutators, and the shared lock address the interruption and backfill scenarios without weakening mnemonic protection. All 17 WalletPresenceTests passed using the existing XCTest bundle; the full SDK was not rebuilt, and physical-device locked-keychain behavior was not independently exercised.
🔴 0 blocking | 🟡 0 suggestion(s) | 💬 0 nitpick(s)
Review provenance
Source: reviewer 1: gemini-3.8-flash-high (agent: phase1-reviewer, role: general); reviewer 2: gemini-3.8-flash-high (agent: phase1-reviewer, role: architecture-layering); reviewer 3: gemini-3.8-flash-high (agent: phase1-reviewer, role: security-auditor); reviewer 4: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 5: gpt-6-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 6: gpt-6-astra (agent: phase2-reviewer, role: security-auditor); reviewer 7: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 8: gpt-6-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 9: gpt-6-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6-astra (agent: astra-verifier, role: final-verifier)
- Triage:
criticalbygpt-6-astra(effort low) — WalletStorage.swift intricately changes mnemonic storage and deletion in storeMnemonic/deleteMnemonic, coupling key-material lifecycle operations to durable marker reconciliation with shared locking, interruption ordering, and partial-failure handling. - Phase 1 reviewers:
gemini-3.8-flash-high— general (completed, effort high); agentphase1-reviewer,gemini-3.8-flash-high— architecture-layering (completed, effort high); agentphase1-reviewer,gemini-3.8-flash-high— security-auditor (completed, effort high); agentphase1-reviewer - Phase 1 model:
gemini-3.8-flash-high— antigravity quota: weekly 33% left, 5h 96% left - Fresh final gate: an independent Phase-2 review ran after iterative findings were reconciled
- Fresh verifier:
gpt-6-astra— final-verifier; agentastra-verifier - Phase 2 reviewers:
gpt-6-astra— general (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— security-auditor (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— general (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6-astra— security-auditor (completed, effort xhigh); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify the current code and confirm that no unresolved issues remain.
No unresolved findings remain from the prior review on this head.
Out-of-scope follow-up suggestions (1)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Example app metadata cleanup error handling — Routine pre-existing cleanup outside this PR's scope. ContentView.deleteStoredMnemonics() intentionally tolerates metadata deletion failure after successful mnemonic deletion. The current marker-first deletion has already removed the presence marker, so surviving metadata cannot recreate the reported phantom-marker condition.
- Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.
|
/self-reviewed |
|
@coderabbitai review No review for |
|
/self-reviewed |
|
Policy satisfied — this can merge. |
llbartekll
left a comment
There was a problem hiding this comment.
Question on the design: does the marker need to live in the keychain at all? Could it be a plain flag in UserDefaults instead (kept by the app, or written by WalletStorage itself)?
As I understand it, the reason for the keychain is lifecycle: a keychain item survives a reinstall like the mnemonic does, while UserDefaults is wiped. So after a reinstall we would have a mnemonic with no marker.
But I don't see how that state can ever reach the user. iOS does not launch an app in the background until the user has opened it once, and to open it the device has to be unlocked. So the first presence read after an install or reinstall always runs with a readable mnemonic inventory, which is the source of truth and backfills the marker right there. By the time a locked background launch can happen, the marker is already in place.
If that holds, UserDefaults gives the same behaviour with less machinery: no sibling keychain service, and the wallet id is not exposed in an AfterFirstUnlock keychain item.
Is there a concrete scenario where a UserDefaults flag gives the wrong answer and the keychain marker does not? If so, it would be worth stating it in the doc comment on presenceKeychainService.
The keychain marker was chosen to survive a reinstall, but that buys nothing: iOS does not launch an app in the background until the user has opened it, so the first presence read after any (re)install runs with the mnemonic inventory readable and backfills the flag before a locked launch can need it. Replace the per-wallet AfterFirstUnlock keychain items (and their sibling service) with one boolean in UserDefaults that carries no wallet id. The ordering (flag off first, on last), the shared lock and the reconciliation from a readable inventory stay as they were. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
You're right — switched in 242e382. The keychain came from the original sketch's "survives reinstall" note, and I can't back it with a scenario. After a reinstall the SwiftData store is gone too, so a locked launch has nothing to start from until the user opens the app, and that first open runs unlocked and backfills the flag. The cases I checked for a
What changed: one boolean under |
|
Waiting for bot review — thepastaclaw reviewed an earlier commit, not yet this one. Wait for the missing reviews, or a writer can post |
llbartekll
left a comment
There was a problem hiding this comment.
Thanks for the quick turnaround. Now that it is a single UserDefaults boolean, I think this can live entirely in dashwallet-ios, and this PR is not really needed.
The SDK already reports the locked case honestly: listWalletIdsWithMnemonic() throws instead of returning an empty list. The defect in dashpay/dashwallet-ios#1147 is the app folding that error into "no wallet". The app can fix that on its own:
- when the listing succeeds, store the result (wallet / no wallet) in its own
UserDefaults; - when the listing throws, fall back to the stored value, and with no stored value treat it as unknown and do not show Create/Recover;
- update the flag when it creates or deletes a wallet, since the app drives both.
Which screen to show is an app decision, and the storage layer does not need to know about it. Keeping it in the SDK would only pay off with several apps needing the same thing.
Unless you see something the app cannot do without an SDK change, I would close this one and do it in the dashwallet-ios PR.
|
Agreed — the app drives every create and delete (the SDK's only own mnemonic delete is |
Issue being fixed or feature implemented
WalletStoragestores mnemonics and metadata askSecAttrAccessibleWhenUnlockedThisDeviceOnly. A process launched while the device is locked (aBGAppRefreshlaunch) cannot enumerate them:listWalletIdsWithMnemonic()throws, and an app that folds that error intofalseconcludes "no wallet" and shows its Create/Recover screen — the defect behind dashpay/dashwallet-ios#1147. The review of dashpay/dashwallet-ios#1088 promised a "non-secret wallet marker" follow-up in the SDK; this is that follow-up, as aUserDefaultsflag.App-side adoption (calling the new API, SDK pin bump) is a separate dashwallet-ios PR.
What was done?
All in
packages/swift-sdk/Sources/SwiftDashSDK/Core/Wallet/WalletStorage.swift:UserDefaults.standardunderWalletStorage.presenceDefaultsKey(=<keychainService>.walletPresent, so theDASH_KEYCHAIN_SERVICEoverride still applies). No wallet id, no secret. Readable while the device is locked once it has been unlocked since boot.storeMnemonicruns in this order: clear the flag, remove the old mnemonic, add the new mnemonic, set the flag.deleteMnemonicclears the flag, removes the mnemonic, and sets the flag again if other mnemonics remain.storeMnemonic,deleteMnemonicandwalletPresence()share one static lock, so they are serialised across everyWalletStorageinstance in the process (includingPlatformWalletManager.deleteWallet's own instance). A presence read cannot set the flag in the middle of a deletion.cleanupLegacyItemsis unaffected.WalletStorage.WalletPresence { present, absent, unknown(OSStatus) }andwalletPresence(). The flag accessorsreadPresenceFlag()/writePresenceFlag(_:)areinternallifecycle steps, not SDK operations..present, empty means.absent, and the flag is rewritten to match (the lazy backfill for wallets stored before this change, and after a reinstall, where the keychain survives andUserDefaultsdoes not)..present, unset means.unknown(status). Nothing is written then.UserDefaultsand not a keychain item: the first presence read after any (re)install runs with the inventory readable — iOS does not launch an app in the background until the user has opened it, which takes an unlocked device — so the flag is always backfilled before a locked launch can need it. Surviving a reinstall buys nothing. Before the first unlock since bootUserDefaultsreads empty, which gives.unknown, never.absent. A backup restored to another device carries the flag but not theThisDeviceOnlymnemonic; that gives at most a stale.presenton a locked launch (a deferral, not a setup screen), and the next unlocked read clears it.Not covered on purpose: the legacy DashSync wallet.
How Has This Been Tested?
packages/swift-sdk/SwiftTests/SwiftDashSDKTests/WalletPresenceTests.swift(12 tests). They run the realstoreMnemonic/deleteMnemonic/walletPresence()bodies against an in-memory fake keychain and flag shared by twoWalletStorageinstances. Covered:UserDefaults.standard(cleared, not stored asfalse) and the key's derivation fromkeychainService.bash build_ios.sh --target tests --profile dev, thenswift test→ 732 unit tests, 0 failures (3 skipped; the integration target's 14 tests are env-gated). ThexcodebuildSwiftExampleApp simulator test run ofrun_tests.shwas not executed locally.Breaking Changes
None. Existing APIs keep their signatures and semantics;
storeMnemonic/deleteMnemonicadditionally set / clear oneUserDefaultsboolean. Wallets stored before this change get the flag on the firstwalletPresence()call made while the inventory is readable.Overlap note: #4615 (v4.2-dev) restructures the same
storeMnemonic/deleteMnemonicbodies into shared primitives; when it is forward-merged the flag calls need to be carried into the new shape (a small textual conflict, no semantic one).Checklist:
structure.rs, regeneratedgrovedb-structure.json, and checked the structure viewer link posted on this pull requestFor repository code-owners and collaborators only
🤖 Generated with Claude Code
PR Hygiene ·
242e382/skip-botsproceeds without the ones not yet reported/self-reviewedWhen every merge requirement is met, the
PR Hygienecheck passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.