Skip to content

fix(wallet): arm the initial-restore-sync gate when wallets are recovered from the keychain - #1238

Merged
llbartekll merged 4 commits into
developfrom
fix/1227-keychain-recovery-arms-sync-gate
Oct 23, 2026
Merged

llbartekll merged 4 commits into
developfrom
fix/1227-keychain-recovery-arms-sync-gate

Conversation

@llbartekll

@llbartekll llbartekll commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Core spends were allowed while a wallet automatically recovered from the keychain was still scanning its history from the import floor, so an asset lock could select an input an older block had already spent (Core spends allowed during Keychain recovery sync can select already-spent inputs #1227, reproduced on TestFlight 9.1.4 (11), testnet).
  • The existing gate (WalletSendService.isBlockedByInitialRestoreSync = isResyncingWallet && !syncDone) had a single writer: the phrase restore in DWRecoverWalletCommand. Keychain recovery (reinstall + Keep, local-store reset, first entry to a network, WAL loss) started the same full scan without arming it.
  • Minimal fix: arm the same flag where the host recreates rows from the keychain. Clearing is unchanged (SyncingActivityMonitor at the first .syncDone) and every send surface already reads the flag live. No Platform / SDK changes.

Changes

  • SwiftDashSDKHost.swift: new InitialRestoreSyncGating collaborator (production: DWGlobalOptions.sharedInstance()), new Collaborators.restoreSyncGate. restoreWallet arms it once recoverPersistedWallet has recreated rows from the keychain; first-entry devnet provisioning keeps its own policy.
  • HostRecoveryTests.swift: RecordingRestoreSyncGate stub and three cases: recovery arms the gate; a healthy store does not; a failed recovery arms it only once a wallet opens.
  • Review follow-ups (164b94c, 1f85098, 4e3aac8): the gate is per network. InitialRestoreSyncGate (pure value type in WalletSendService.swift) holds the flag plus the set of armed persistenceScopes (nil = every network, the phrase restore). Keychain recovery adds its scope; SyncingActivityMonitor clears one scope at a time at .syncDone, crediting it to the SPV client that produced it (SwiftDashSDKSPVCoordinator.runningScope, not the network key a switch has already flipped); every send surface reads DWGlobalOptions.isResyncingCurrentNetworkWallet, so only the armed network is blocked. DWGlobalOptions.resyncingWalletScopes is the new persisted key (restoreToDefaults and the phrase restore reset it). The arm runs after localStoreRecovery.finish().

Out of scope (follow-ups, same class — tracked under #1227)

Rows created at the import floor, or a historical scan started, without arming the gate:

  • WalletsScreen.addWallet(isImported: true).
  • Legacy key migration: SwiftDashSDKKeyMigrator → createOrImportWallet(isImported: true); the next start finds healthy rows.
  • Cross-network mirrors: createOrImportWallet(provisionAcrossSupportedNetworks: true) / addWallet create rows at the other networks' import floor; the phrase restore arms the gate for every network, but the first switch after its .syncDone loads those rows as a healthy store (Core spends allowed during Keychain recovery sync can select already-spent inputs #1227 scenario 3).
  • Chain-store rebuild / birth-height resync (rebuildChainStoreIfPending, applyPendingChainResyncIfNeeded).
  • Core-funded identity flows (identity top-up, Core-funded registration) do not read the gate; ShieldedTransferCoordinator.performAssetLock rechecks sync only for .coinJoinDrain.
  • Gate semantics kept as-is: armed on every launch that passes through recovery even when all rows survived (pending reset intent); may lift early if SPVChainStoreRebuild.arm failed and the chain store survived; a kill between row creation and the arm, or between finish() and the UserDefaults flush, leaves the next launch ungated; a devnet renamed while armed keeps that scope armed until a wipe.
  • Per-wallet / per-network readiness owned by the SDK and enforced where Core spends are built, as proposed in Core spends allowed during Keychain recovery sync can select already-spent inputs #1227.

Test Plan

  • DashWalletTests/HostRecoveryTests + PassiveWalletStateUITailTests: 29 passed at 4e3aac8 (scheme dashwallet-dashpay, Debug, iPhone simulator).
  • Simulator smoke (iPhone 17, testnet): deleted Documents/SwiftDashSDK/Platform/testnet/DashModel.sqlite*, relaunched. Log: loadFromPersistor … restored=0 → HOST wallet recovery required for 1 → HOST recovered 1 wallet(s) from keychain for testnet skipped=1 birthHeight=0; DW_GLOB_resyncingWallet flipped from false to true.
  • Not verified here: the flag clearing at .syncDone after the from-genesis rescan (unchanged path) and the Send-screen block in the UI (predicate covered by PassiveWalletStateUITailTests).

Refs #1227

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Wallet restoration now coordinates initial syncing after recovering wallet data from the keychain. The sync gate clears when syncing completes on the network associated with the recovery; phrase-based restoration clears it after syncing on any network.
    • Healthy wallet stores do not trigger the recovery behavior. Failed recovery leaves the gate inactive until a later successful start.

…ed from the keychain

Core spends were allowed while a wallet automatically recovered from the
keychain was still scanning its history from the import floor. The gate
that blocks new Core spends until the first historical sync completes
(`WalletSendService.isBlockedByInitialRestoreSync`) keys off
`DWGlobalOptions.isResyncingWallet`, whose only writer was the phrase
restore in `DWRecoverWalletCommand`. Keychain recovery (reinstall + Keep,
local-store reset, first entry to a network, WAL loss) recreated the rows
at the import floor and started the same full scan without arming it, so
an asset lock could select an input an older block had already spent
(ios#1227, reproduced on TestFlight 9.1.4 (11), testnet).

`SwiftDashSDKHost.restoreWallet` now arms the gate through a new
`InitialRestoreSyncGating` collaborator (production:
`DWGlobalOptions.sharedInstance()`) once `recoverPersistedWallet` has
recreated rows from the keychain. First-entry devnet provisioning keeps
its own policy. `SyncingActivityMonitor` clears the flag at the first
`.syncDone` as before, and every send surface already reads it live.

Tests: three new `HostRecoveryTests` cases over the recording stub
(recovery arms; a healthy store does not; a failed recovery arms only
once a wallet opens). Smoke on the iPhone 17 simulator: deleting the
testnet SwiftData store and relaunching logged `HOST recovered 1
wallet(s) from keychain for testnet … birthHeight=0` and flipped
`DW_GLOB_resyncingWallet` from false to true.

Refs #1227

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Warning

Review limit reached

You'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 13 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3a50edeb-1c82-447b-a275-46f24c1ac2c8
📥 Commits

Reviewing files that changed from the base of the PR and between 164b94c and 4e3aac8.

📒 Files selected for processing: 13
  • DashWallet/Sources/Application/Syncyng Activity Monitor/SyncingActivityMonitor.swift
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKSPVCoordinator.swift
  • DashWallet/Sources/Models/DWGlobalOptions.h
  • DashWallet/Sources/Models/DWGlobalOptions.m
  • DashWallet/Sources/Models/Transactions/WalletSendService.swift
  • DashWallet/Sources/UI/Explore Dash/Views/DashSpend/DashSpendPayViewModel.swift
  • DashWallet/Sources/UI/Payments/Amount/Model/Send/SendAmountModel.swift
  • DashWallet/Sources/UI/Payments/InternalTransfer/InternalTransferViewModel.swift
  • DashWallet/Sources/UI/Payments/Pay/SendViewModel.swift
  • DashWallet/Sources/UI/Setup/RecoverWallet/DWRecoverWalletCommand.m
  • DashWalletTests/HostRecoveryTests.swift
  • DashWalletTests/PassiveWalletStateUITailTests.swift

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 336f4886-5954-4444-b15c-35a8684c7829
📥 Commits

Reviewing files that changed from the base of the PR and between 3fbd800 and 164b94c.

📒 Files selected for processing: 6
  • DashWallet/Sources/Application/Syncyng Activity Monitor/SyncingActivityMonitor.swift
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift
  • DashWallet/Sources/Models/DWGlobalOptions.h
  • DashWallet/Sources/Models/DWGlobalOptions.m
  • DashWalletTests/HostRecoveryTests.swift
  • DashWalletTests/PassiveWalletStateUITailTests.swift

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

📝 Walkthrough

The host now arms an initial restore sync gate after successful keychain wallet recovery. The gate records the network scope. Sync completion clears it only when the running network matches that scope, unless the gate has no recorded scope.

Changes: Initial Restore Sync

Layer / File(s) Summary
Scoped gate state and clearing
DashWallet/Sources/Models/DWGlobalOptions.h, DashWallet/Sources/Models/DWGlobalOptions.m, DashWallet/Sources/Application/Syncyng Activity Monitor/SyncingActivityMonitor.swift, DashWalletTests/PassiveWalletStateUITailTests.swift
DWGlobalOptions stores and resets the optional scope. SyncingActivityMonitor clears the gate when sync completes on the matching scope, or when the gate is unscoped. Tests cover both cases.
Restore gate contract and wiring
DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift
InitialRestoreSyncGating defines the arming operation. Production collaborators use DWGlobalOptions as the gate.
Recovery gating and tests
DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift, DashWalletTests/HostRecoveryTests.swift
After local-store recovery, the host arms the gate for the network scope only when keychain recovery returned a wallet. Tests cover successful recovery, healthy stores, and failure outcomes.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant SwiftDashSDKHost
  participant KeychainRecovery
  participant DWGlobalOptions
  participant SyncingActivityMonitor
  SwiftDashSDKHost->>KeychainRecovery: Recover wallet rows
  KeychainRecovery-->>SwiftDashSDKHost: Return recovered wallet
  SwiftDashSDKHost->>DWGlobalOptions: Arm gate with persistence scope
  DWGlobalOptions-->>SwiftDashSDKHost: Store scope and set isResyncingWallet
  SyncingActivityMonitor->>DWGlobalOptions: Read gate state when sync completes
  SyncingActivityMonitor->>SyncingActivityMonitor: Compare armed and running scopes
  SyncingActivityMonitor->>DWGlobalOptions: Clear gate when scopes match or gate is unscoped
Loading

Suggested reviewers: romchornyi, jeanpierreroma

Merge Risk: ⚪ Minimal · up to 164b9

Wallets recovered from the keychain now keep the send gate armed until the arming network completes its historical scan, and a sync on another network does not clear it. No concrete merge-blocking risk remains.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 17.65% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 5 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: arming the initial restore sync gate after keychain wallet recovery.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 17.65% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 5 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@thepastaclaw

thepastaclaw commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🕓 Review not started yet because the new head is waiting for the 30-minute push debounce.

  • Request normal review — click when the PR is ready for review.
  • Request priority review — click to move this review to the front of the queue.

Commit 4e3aac8. Normal review starts when eligible; priority review starts as soon as a slot is available.

@llbartekll llbartekll changed the title fix(host): arm the initial-restore-sync gate when wallets are recovered from the keychain fix(wallet): arm the initial-restore-sync gate when wallets are recovered from the keychain Oct 23, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final validation — Phase 1 + Phase 2

The change correctly arms the existing initial-restore-sync gate after successful keychain recovery and before the recovered wallet is returned, while preserving healthy-store and devnet behavior. One non-blocking gap remains: legacy key migration also creates imported wallets at the import floor but bypasses this new writer, leaving that recovery path ungated. Code-bearing CI checks and target-membership validation pass.

🟡 1 suggestion(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

🟡 Suggestion: Legacy key migration still creates import-floor wallets without arming the sync gate
DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift:800-818

The new gate is armed only in restoreWallet after recoverPersistedWallet returns a wallet. However, SwiftDashSDKKeyMigrator.createWalletOnHost calls createOrImportWallet(..., isImported: true), and createAndPersist consequently creates rows at importedWalletBirthHeight. Those rows can begin a historical scan without setting isResyncingWallet; on the subsequent runtime start, the persisted-store path resolves the healthy rows and returns before this new branch, so no gate is armed. This is the same stale-input window addressed here, just through the DashSync-to-SwiftDashSDK migration path. Arm the gate at the shared imported-wallet creation boundary, or otherwise make the migrator's imported-wallet creation use the same collaborator, while preserving the existing explicit phrase-restore behavior.

source: muse-spark-1.3-contributor (phase1-reviewer: general)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.1-sol (effort low) — This is a small, well-contained lifecycle-gating logic change in wallet recovery with focused tests, but it affects send availability during synchronization and merits ordinary review.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort high); agent phase2-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 `DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift`:
- [SUGGESTION] DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift:800-818: Legacy key migration still creates import-floor wallets without arming the sync gate
  The new gate is armed only in `restoreWallet` after `recoverPersistedWallet` returns a wallet. However, `SwiftDashSDKKeyMigrator.createWalletOnHost` calls `createOrImportWallet(..., isImported: true)`, and `createAndPersist` consequently creates rows at `importedWalletBirthHeight`. Those rows can begin a historical scan without setting `isResyncingWallet`; on the subsequent runtime start, the persisted-store path resolves the healthy rows and returns before this new branch, so no gate is armed. This is the same stale-input window addressed here, just through the DashSync-to-SwiftDashSDK migration path. Arm the gate at the shared imported-wallet creation boundary, or otherwise make the migrator's imported-wallet creation use the same collaborator, while preserving the existing explicit phrase-restore behavior.

@romchornyi romchornyi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 3fbd800007 as a layered review: idea → architecture → completeness → code (general pass plus funds, concurrency and edge-case lanes, since this guards Core spends). One inline comment (major). Everything else below is a non-blocking recommendation.

Level 1 — Idea: valid as an interim fix (treats a symptom)

The problem is real and well evidenced (#1227, TestFlight 9.1.4 (11) logs). Arming the existing gate where keychain recovery recreates rows closes the reproduced entry point. The root cause, though, is that spend permission depends on an app-global UI flag rather than on whether the spending wallet's history has actually been scanned — this PR closes one writer of that flag, not the dependency.

Level 2 — Architecture: works, but not in the owning layer

As #1227 itself says, the durable fix is an SDK-owned readiness signal per wallet and per network, enforced where Core spends are built/reserved, with the app showing the state. Keeping the decision in the app on a global flag is fine as a stop-gap; please keep #1227 open for the SDK-side readiness (it is referenced, not closed, which is right).

Level 3 — Completeness: gaps not listed in "Out of scope"

Same class (wallet rows created at the import floor, or a historical scan started, without arming the gate), all reachable at this head:

  • Legacy key migration — SwiftDashSDKKeyMigrator.swift:283-286 → createOrImportWallet(isImported: true); the next start finds healthy rows and never reaches the new arm (also raised by thepastaclaw).
  • Cross-network mirrors — createOrImportWallet(provisionAcrossSupportedNetworks: true) (SwiftDashSDKHost.swift:880-905, from SwiftDashSDKWalletCreator) and addWallet create rows at each other network's import floor; after the current network's .syncDone clears the flag, the first switch loads those rows as a healthy store, ungated (#1227 scenario 3).
  • Wallets-screen import — listed as out of scope, ✓.
  • Chain-store rebuild / birth-height resync (rebuildChainStoreIfPending, applyPendingChainResyncIfNeeded) also start historical scans without the gate.
  • Core-funded identity flows — identity top-up from transparent funds (SDKIdentityProfileSheet → topUpIdentityWithFunding) and Core-funded registration in DWIdentityRegistrationCoordinator don't read the gate at all; the asset lock they build has the same exposure.
  • Execution boundary — ShieldedTransferCoordinator.performAssetLock rechecks sync only for .coinJoinDrain; .bip44 relies on the screens' gate (no caller found that skips it today).

These are mostly inside #1227's acceptance criteria, but since the PR's out-of-scope list names only the Wallets-screen import, please either add them there or file issues so they stay tracked.

Level 4 — Code

Major: see the inline comment — another network's .syncDone clears the gate mid-scan.

Non-blocking recommendations

  1. Armed before a step that can throw. The gate is armed before localStoreRecovery(for:).finish(); if finish() throws, the start fails with walletBootstrapFailed but the persisted flag is already set — contrary to what testFailedRecoveryDoesNotArmTheGateUntilAWalletOpens describes. Arming right before return recovered avoids it.
  2. Over-blocking. recoverPersistedWallet returns a wallet even when every row survived (a pending reset intent with nothing to recreate), so the gate is armed on each such launch and an ordinary catch-up delays payments; and one global gate also blocks a fully synced active wallet when only an inactive one was recreated. (not verified)
  3. Gate can lift before the scan. If SPVChainStoreRebuild.arm fails inside recovery (logged and tolerated) and the chain store survived, waitForEvents at progress ≥ 0.999 maps to .syncDone on the first tick and the flag clears before any rescan from the floor. (not verified)
  4. Comment drift. "first-entry devnet provisioning keeps its policy" describes a gate policy that doesn't exist — devnet's height-0 genesis scan is simply ungated. Repo CLAUDE.md rule 2: comments state what the code does.
  5. Tests. The three new tests all run on mainnet and check only "recreated from an empty store → armed once". Nothing covers a network switch clearing the gate, devnet provisioning (changing the keychainRecovered != nil condition passes the suite), finish() throwing after the arm, the reset-intent-with-all-rows case, or the migrator / mirror / Wallets-screen paths. Of #1227's regression list only scenario 1 is covered, and only at host level.
  6. Exotic: a kill after finish() removed the marker but before NSUserDefaults flushed the flag leaves neither, so the next launch is ungated. (not verified)

🤖 Reviewed with Claude Code

…armed it

Review of #1238 (romchornyi): `isResyncingWallet` is one app-global flag
and `SyncingActivityMonitor` cleared it at any `.syncDone`, whatever
network reached it. On the first-entry path this PR covers, the user
could switch to an already caught-up network mid-scan, its `.syncDone`
cleared the gate, and the scan resumed ungated on the way back because
the rows now exist and the recovery marker is gone.

`DWGlobalOptions.resyncingWalletScope` records the `persistenceScope`
whose historical scan armed the gate; the monitor clears the gate only
when `.syncDone` arrives on that scope. No scope means the phrase
restore armed it for every network (unchanged behaviour), and the wallet
wipe's `restoreToDefaults` clears both.

Also from the review: the arm now runs after `localStoreRecovery.finish()`,
so a start that fails on the marker leaves no gate behind, and the
devnet comment states what the code does (devnet rows are not armed).

Tests: `initialRestoreSyncGateClears` predicate in
`PassiveWalletStateUITailTests`; `HostRecoveryTests` record the armed
scope and cover a recovery that fails before a wallet opens.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@llbartekll

Copy link
Copy Markdown
Collaborator Author

Thanks @romchornyi. Taken in 164b94c, kept the rest deliberately out of this PR.

Taken

  • Major (inline): the gate is now scoped to the network that armed it; another network's .syncDone no longer clears it.
  • Rec 1: the arm moved after localStoreRecovery.finish(), so a start that fails on the marker leaves no gate behind (testRecoveryThatFailsBeforeAWalletOpensArmsNoGate).
  • Rec 4: comment rewritten to state what the code does (devnet rows provisioned on first entry are not armed, unchanged).
  • Rec 5, partly: predicate test for the scope rule and the marker-failure case above.

Not in this PR, on purpose — this is the minimal stop-gap for the reproduced path; #1227 stays open for the SDK-owned readiness. The Level 3 gaps (legacy key migration, cross-network mirrors from createOrImportWallet(provisionAcrossSupportedNetworks:), chain-store rebuild / birth-height resync, Core-funded identity flows, the .bip44 execution boundary) and recs 2, 3 and 6 are the same class and are now listed in the PR description under "Out of scope", pointing at #1227 so they stay tracked. Each of them needs either its own arm site or the per-wallet readiness signal, which is exactly the scope this PR avoids.

🤖 Generated with Claude Code

@romchornyi romchornyi left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 2 major (inline) · 7 non-blocking recommendations · no blockers — reviewed at 164b94c367

Level Verdict
1 · Idea 🟡 interim fix closes the reproduced entry point of #1227, not the global-flag dependency
2 · Architecture 🟡 not the owning layer SDK-owned per-wallet / per-network readiness → #1227 stays open
3 · Completeness ✅ gaps tracked same-class paths listed under "Out of scope" → #1227
4 · Code 🟡 2 major both introduced by the scoping commit, see inline

Closed since the last review — thanks

  • the cross-network clear is scoped to the arming network
  • the arm moved after finish()
  • the devnet comment states what the code does
  • remaining gaps listed under "Out of scope" with #1227

Major (inline)

7 non-blocking recommendations
  1. Stale scope under a phrase restore — DWRecoverWalletCommand.m:53 sets only resyncingWallet = YES and never resets resyncingWalletScope; a scope left by an earlier keychain arm turns the "every network" gate into a single-network one. Set the scope to nil there.
  2. The ordering test doesn't pin the ordering — testRecoveryThatFailsBeforeAWalletOpensArmsNoGate fails at begin(), before any wallet exists; moving the arm back above finish() still passes.
  3. Re-arm with nothing recreated — the recovery branch arms on every start with a pending reset intent even when every row survived, so ordinary catch-ups are blocked. (not verified)
  4. UserDefaults churn — SyncingActivityMonitor.swift:161 writes two keys on every tick while .syncDone, even when nothing is armed; check isResyncingWallet first. (not verified)
  5. Exotic · attribution — SyncingActivityMonitor.swift:163 reads the scope from WalletEnvironment.network, not from the client that produced .syncDone. The switch detaches the old client first, so no reachable sequence found; SwiftDashSDKSPVCoordinator.shared.runningScope would remove the dependence on that ordering.
  6. Exotic · devnet — the scope is devnet-<name>; reconfiguring the devnet leaves a scope no .syncDone matches, armed until a wipe. (not verified)
  7. Exotic · kill window — a kill between rows.createWallet and the arm at SwiftDashSDKHost.swift:823 leaves rows without the gate; the next launch resumes ungated. (not verified)
Review details

Layered review: idea → architecture → completeness → code. This round re-ran the general code pass and a concurrency/lifecycle lane on the new commit; majors were verified against the code before posting.

🤖 Reviewed with Claude Code

…etwork

Re-review of #1238 (romchornyi), both introduced by the scoping commit:

- A second keychain recovery (every network with missing rows runs one)
  overwrote the first network's scope, so that network's `.syncDone`
  cleared a gate still owed to another scan. `InitialRestoreSyncGate`
  now keeps the armed scopes as a set, never narrows an every-network
  arm, and clears one scope at a time.
- The clear was scoped but the block was not: an arm left by another
  network's unfinished scan blocked Core sends, DashSpend and internal
  transfers on the current network through an ordinary catch-up. Every
  reader now goes through `isResyncingCurrentNetworkWallet`, which
  blocks only when the gate is armed for the selected network (or for
  every network).

Also from the review: the phrase restore resets the scopes so a stale
keychain-recovery scope cannot narrow it; the monitor writes nothing
while the gate is disarmed; the marker-failure test that did not pin
the ordering it described is removed.

`InitialRestoreSyncGate` is a pure value type next to the send
predicate, with the arm / clear / block rules covered in
`PassiveWalletStateUITailTests`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@llbartekll

Copy link
Copy Markdown
Collaborator Author

Thanks @romchornyi, re-review taken in 1f85098.

Taken

  • Both Majors (inline): armed scopes are a set, cleared one scope at a time; the block is scoped to the selected network through isResyncingCurrentNetworkWallet in every reader.
  • Rec 1: the phrase restore resets resyncingWalletScopes before arming, so a stale keychain scope cannot narrow it.
  • Rec 2: the marker-failure test is removed; it did not pin the ordering it described.
  • Rec 4: no UserDefaults write while the gate is disarmed.

Left out, on purpose (same stop-gap boundary as before; tracked in the PR description under "Out of scope" → #1227): rec 3 (re-arm with nothing recreated), rec 5 (reading the scope from the SPV client that produced the .syncDone), rec 6 (devnet renamed while armed), rec 7 (kill between row creation and the arm). Each needs either per-wallet readiness or a persisted arm-before-create with rollback, which is the SDK-owned design #1227 asks for.

🤖 Generated with Claude Code

@romchornyi romchornyi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Approve · 1 major (inline) · 4 non-blocking recommendations · no blockers — reviewed at 1f85098ccb

Level Verdict
1 · Idea 🟡 interim fix closes the reproduced entry points of #1227
2 · Architecture 🟡 not the owning layer SDK-owned per-wallet / per-network readiness → #1227
3 · Completeness ✅ gaps tracked listed under "Out of scope" → #1227
4 · Code 🟡 1 major verified; not a regression vs develop (that path had no gate at all)

Closed since the last review — thanks

  • armed scopes are a set; a second arm no longer replaces the first, and an every-network arm is never narrowed
  • the block is scoped to the current network in every reader
  • the phrase restore resets a stale scope
  • no UserDefaults writes while the gate is disarmed; the non-pinning test removed

Major (inline)

  • SyncingActivityMonitor.swift:155 — a .syncDone left over from the outgoing network clears the arm of the network being switched back to (the resetPublishedState() ordering or a reachability replay during the stop).
4 non-blocking recommendations
  1. Header comment vs. writers — DWGlobalOptions.h:105 says resyncingWalletScopes is read and written through DWGlobalOptions.initialRestoreSyncGate, but DWRecoverWalletCommand.m:55 and restoreToDefaults write it directly (repo CLAUDE.md rule 2: comments state what the code does).
  2. Stale comment — InternalTransferViewModel.swift:1331 still says the preview stands in for isResyncingWallet; the production reader is now isResyncingCurrentNetworkWallet.
  3. One predicate, several copies — SendAmountModel.swift:60, SendAmountModel.swift:150 and DashSpendPayViewModel.swift:440 re-implement isResyncingCurrentNetworkWallet == false || state == .syncDone inline instead of calling WalletSendService.isBlockedByInitialRestoreSync; with the raw global isResyncingWallet still public next to it, a new send surface can easily pick the old semantics. A single accessor would remove the copies.
  4. Tests stop at the value type — InitialRestoreSyncGate is well covered, but nothing exercises the real DWGlobalOptions two-key mapping, isResyncingCurrentNetworkWallet, or the monitor's clear attribution (the case in the inline comment).
Review details

Layered review: idea → architecture → completeness → code. This round re-ran the general code pass on the full PR and a verifier on every rare-path candidate; only candidates proven step by step in the code are published. Checked and ruled out: a stale .syncDone briefly allowing a spend during a switch (the host still holds the outgoing wallet, and the switch overlay is up), re-arming with nothing recreated (a pending reset intent rewinds the checkpoints, so that scan is historical), a renamed devnet scope (harmless now that the block is scoped), and the two-key write order (every interleaving fails safe).

🤖 Reviewed with Claude Code

…ot the network key

Review of #1238 (romchornyi): a network switch flips `WalletEnvironment.network`
in `switchToNetwork` while the outgoing client's resting snapshot can still be
delivered to `SyncingActivityMonitor`: `resetPublishedState()` emits
`(.synced, 0.0)` during `performStop`, and any reachability update in the stop
window replays the stale coordinator tuple. Both map to `.syncDone` under the
incoming network's key, so the gate armed for the network being switched back
to was cleared before its historical scan resumed.

The monitor now clears the gate with `SwiftDashSDKSPVCoordinator.runningScope`,
set with the client start and cleared at the end of the stop, so a stale
snapshot is credited to the network it came from, and with no client a scoped
arm stays (an every-network arm clears as before). `runningScope` becomes
`private(set)`; the monitor reads it on main and attributes nothing off main.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@llbartekll
llbartekll requested a review from romchornyi October 23, 2026 11:32
@llbartekll
llbartekll merged commit fe19bd3 into develop Oct 23, 2026
7 checks passed

@romchornyi romchornyi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Approval stands · no new major · 5 non-blocking recommendations — reviewed at 4e3aac83e6

Level Verdict
1 · Idea 🟡 interim fix closes the reproduced entry points of #1227
2 · Architecture 🟡 not the owning layer SDK-owned per-wallet / per-network readiness → #1227
3 · Completeness ✅ gaps tracked listed under "Out of scope" → #1227
4 · Code ✅ no new major last round's major verified closed

Closed since the last review — thanks

  • a .syncDone is credited to the client that produced it (runningScope), and performStop clears it before resetPublishedState(), so a leftover snapshot from the outgoing network no longer lifts the arm of the network being switched back to
5 non-blocking recommendations
  1. The phrase-restore arm is still lifted by any network's .syncDone — and is now cheap to scope. DWRecoverWalletCommand.m:55 arms every network (scopes = nil), and clearing disarms a nil-scope gate for any scope (WalletSendService.swift:928). A restore on mainnet, a switch to testnet mid-scan, testnet's .syncDone → back on mainnet the scan from the import floor resumes ungated; likewise the testnet mirror rows (at genesis) scan ungated once mainnet finishes. This was the case before the PR and is listed under "Out of scope", but with InitialRestoreSyncGate in place the fix is small: arm the concrete scopes the restore provisions ([mainnet, testnet], or the devnet scope) instead of nil. It would also make the comment at SyncingActivityMonitor.swift:151 ("would resume ungated on the way back") true for the phrase restore too, which it currently isn't (#1227 regression item 3).
  2. Defaults churn while another network is armed — SwiftDashSDKHost.swift:296 rewrites both keys on every .syncDone tick even when clearing returns the gate unchanged (e.g. testnet armed, user on a synced mainnet, or no client). guard cleared != gate else { return } keeps the "no write" intent of the doc comment.
  3. UX change worth naming — the first entry to a network for a wallet that was created (not imported) now recreates its rows at the import floor and arms that network (SwiftDashSDKHost.swift:846), so Core sends there are blocked for the whole from-genesis scan. If intended, worth a line in the PR description.
  4. Header comment vs. writers (from the last round) — DWGlobalOptions.h:105 still says resyncingWalletScopes is read and written through initialRestoreSyncGate, while DWRecoverWalletCommand.m:55 and restoreToDefaults write it directly.
  5. Design, optional — InitialRestoreSyncGate encodes three states as isArmed + an optional scopes that is ignored while disarmed; an enum { disarmed, everyNetwork, scopes(Set) } under one key would remove the two-key pairing and the stale-scope case. CoinJoinRecovery already keeps a per-scope "wide scan pending" flag reset on the same branch and cleared on a checkpoint-verified completion — deriving the gate from it (or from the SPVChainStoreRebuild markers) would avoid a second, weaker completion signal. Related, rare: if the rebuild is deferred in the recovery start (rebuildChainStoreIfPending returns [] after an I/O failure or a refused store clear), the gate lifts on the old store's .syncDone before the from-floor scan that a later start applies.
Review details

Layered review: idea → architecture → completeness → code. This round: the general code pass on the full PR plus a verifier on each rare-path candidate; only sequences proven in the code are published. Ruled out again: re-arming with nothing recreated (that scan is historical) and a stale .syncDone briefly allowing a spend during a switch (the host still holds the outgoing wallet).

🤖 Reviewed with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants