Repository navigation
fix(platform-wallet): own the shielded coordinator and wipe host rows inside Clear - #5934
PastaPastaPasta wants to merge 4 commits into
Conversation
… inside Clear Shielded Clear spanned three owners with nothing tying them together. Wallet calls took a caller-supplied coordinator, so a wallet could stay bound to one Clear never reset. The host deleted its own shielded rows after Clear returned, so a bind or account add with a delayed host write, or a snapshot read before the Clear, could survive it. Each race had its own guard (clear_generation, snapshot_predates_clear). - The manager owns the coordinator; wallet shielded operations resolve it themselves and the coordinator parameter leaves the public API. - Clear calls the new persister method wipe_shielded_state(network), declared by PersistenceCapabilities::SHIELDED_STATE_WIPE, after the native reset and before returning. A persister without it makes Clear refuse before anything is reset. A failed wipe refuses binds, account adds and restores until a later Clear succeeds. - The FFI vtable extension gains on_wipe_shielded_state_fn, the JNI bridge onWipeShieldedState, and the Swift, Kotlin and SQLite persisters implement the network-scoped wipe; the app-side deletion after Clear is gone. - One admission lock (shared for every durable shielded mutation, exclusive for Clear across reset, host wipe and epoch bump) replaces clear_generation and snapshot_predates_clear. Lock order is wallet shield_guard, admission, lifecycle, store, so an operation queued behind a long shield never holds admission against a Clear. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
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. |
|
⛔ Final review complete — 3 blocking finding(s) (commit 36e5549) · triage: critical · Phase 2 only (queue backlog) |
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 1 + Phase 2
The manager-owned coordinator and exclusive Clear admission close the primary bind, sync, spend, and host-wipe races, and the FFI capability negotiation is fail-closed. However, shielded balance reads still convert an unconfigured manager into an empty balance, and private-payment restoration can mutate the journal and wallet reservations outside the Clear admission; both violate the PR's stated lifecycle boundary. The CI snapshot has no failed code checks; Kotlin passed while Rust wallet and Swift checks are skipped.
🔴 2 blocking | 🟡 3 suggestion(s)
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: architecture-layering); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 6: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — This is a large, intricate change to shielded wallet key handling, durable state deletion, and concurrent wallet mutation paths, including functions such asPlatformWalletManager::clear_shieldedandPlatformWalletPersistence::wipe_shielded_stateinpackages/rs-platform-wallet, which directly affect funds-related wallet state and viewing-key storage. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
- Fresh verifier:
gpt-6.1-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/rs-platform-wallet/src/wallet/platform_wallet.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:1531-1532: Do not report an unconfigured shielded wallet as having zero balance
`shielded_balances` catches every error from `shielded_coordinator()` and returns an empty map. A manager that has never run `configure_shielded` is therefore indistinguishable from a configured and bound wallet whose accounts genuinely have no unspent notes. Callers such as balance UIs can display zero for an unknown/unconfigured state, contrary to the PR's fail-loudly behavior for other shielded operations and the wallet invariant that unknown funds must not become zero.
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:1984-1987: Serialize private-payment restoration with the Clear admission
`restore_private_contact_payments` resolves the manager-owned coordinator and calls `restore_and_release` without acquiring `coordinator.admit()`. The same unadmitted restoration is used by the public/configuration paths, the persister retry closure, and the deferred task created by `restore_private_payments_or_defer`; only the immediate bind call happens incidentally while its caller still holds an admission. Restoration reads the journal, updates wallet reservation state and persister buffers, discharges entries, and can reopen the journal after the read. Clear can therefore reset the native store and complete the host wipe while a restoration continues, allowing pre-Clear journal or reservation state to be recreated afterward; it also bypasses `host_wipe_pending` after a failed host wipe. Add an admission-aware restoration helper, with an already-admitted variant for bind paths, and acquire shared admission in every deferred and retry execution through the final store/persister write.
In `packages/rs-platform-wallet-storage/src/sqlite/persister.rs`:
- [SUGGESTION] packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1353-1362: Do not flush unclassified or unrelated wallet buffers during shielded Clear
`dirty_wallets()` includes every pending per-wallet changeset, but the network filter only consults the durable `wallets` row. When that row is absent, the condition at line 1360 flushes the buffer as though it belonged to the network being cleared. A newly registered wallet can have its network metadata and viewing-key changeset buffered before its durable row exists, so a buffer from another network can be committed during this Clear. For wallets that are correctly classified, `flush_locked` still writes the entire changeset, so an unrelated core write failure can make the host wipe fail after the native reset. Determine ownership from buffered metadata when no durable row exists, and avoid coupling shielded deletion to unrelated buffered domains.
In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/persistence.rs:2146-2150: Avoid discovering an open FFI changeset round after native Clear reset
`FFIPersister::wipe_shielded_state` rejects an open changeset round, but the coordinator invokes it only after resetting the native store, clearing registries, and advancing the Clear state. An unrelated core, identity, or DPNS persistence round can therefore leave Clear with native state already wiped, host rows intact, and `host_wipe_pending` set; subsequent binds are refused until a retry succeeds. Check for an open round or coordinate its drain before performing the native reset, rather than discovering this precondition only in the host-wipe half.
In `packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs:1339-1425: Release the lifecycle mutex before the synchronous host wipe
`clear` keeps the coordinator lifecycle mutex held from before the native reset through the synchronous `host.wipe_shielded_state` callback. By the time the host callback is reached, `hydrated`, `accounts`, and `persisters` have already been cleared, while the exclusive admission still blocks new installs and sync mutations. The only lifecycle user that bypasses admission, `unregister_wallet`, can safely observe the cleared maps and purge an already-reset store. Holding the Tokio mutex across potentially slow Swift/Kotlin or SQLite I/O unnecessarily blocks wallet removal and can widen executor stalls. Drop the lifecycle guard before the host callback while retaining exclusive admission for the complete native-reset/host-wipe boundary.
| let Ok(coordinator) = self.shielded_coordinator().await else { | ||
| return Ok(std::collections::BTreeMap::new()); |
There was a problem hiding this comment.
✅ Resolved at
1754d1aa; see the replies below.
🔴 Blocking: Do not report an unconfigured shielded wallet as having zero balance
shielded_balances catches every error from shielded_coordinator() and returns an empty map. A manager that has never run configure_shielded is therefore indistinguishable from a configured and bound wallet whose accounts genuinely have no unspent notes. Callers such as balance UIs can display zero for an unknown/unconfigured state, contrary to the PR's fail-loudly behavior for other shielded operations and the wallet invariant that unknown funds must not become zero.
| let Ok(coordinator) = self.shielded_coordinator().await else { | |
| return Ok(std::collections::BTreeMap::new()); | |
| let coordinator = self.shielded_coordinator().await?; |
source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)
There was a problem hiding this comment.
Fixed in 1754d1a. shielded_balances now returns the error when the manager is unconfigured, and an unbound wallet still gets an empty map. Test: should_refuse_a_balance_read_before_the_manager_is_configured.
🤖 Posted autonomously by Claude on behalf of pasta.
There was a problem hiding this comment.
Resolved (re-reviewed at 1754d1aa): shielded_balances now propagates the coordinator-resolution error before reading keys, while a configured but unbound wallet still returns an empty map. The added behavior distinguishes an unconfigured manager from a genuinely unbound wallet.
| let coordinator = self.shielded_coordinator().await?; | ||
| self.private_payment_restore(&coordinator) | ||
| .restore_and_release(true) | ||
| .await |
There was a problem hiding this comment.
✅ Resolved at
1754d1aa; see the replies below.
🔴 Blocking: Serialize private-payment restoration with the Clear admission
restore_private_contact_payments resolves the manager-owned coordinator and calls restore_and_release without acquiring coordinator.admit(). The same unadmitted restoration is used by the public/configuration paths, the persister retry closure, and the deferred task created by restore_private_payments_or_defer; only the immediate bind call happens incidentally while its caller still holds an admission. Restoration reads the journal, updates wallet reservation state and persister buffers, discharges entries, and can reopen the journal after the read. Clear can therefore reset the native store and complete the host wipe while a restoration continues, allowing pre-Clear journal or reservation state to be recreated afterward; it also bypasses host_wipe_pending after a failed host wipe. Add an admission-aware restoration helper, with an already-admitted variant for bind paths, and acquire shared admission in every deferred and retry execution through the final store/persister write.
source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)
There was a problem hiding this comment.
Fixed in 1754d1a. Every restoration now runs under a shared admission held until its last store or persister write, and it is refused while a failed host wipe is pending.
- Bind reuses its own admission instead of taking a second one.
- The explicit and deferred paths wait on
admit(). - The non-blocking paths (retry before a send, load, register) use
try_admit()and stay held when a Clear holds or waits for the lock.
Tests inlifecycle_boundary_tests.rscover Clear against a running restoration, restoration during the host wipe, the failed-wipe refusal, and a bind with a Clear queued.
🤖 Posted autonomously by Claude on behalf of pasta.
There was a problem hiding this comment.
Resolved (re-reviewed at 1754d1aa): The new restoration helper acquires or reuses shared admission through its final store and persister writes, checks the failed-host-wipe state, and uses the same admission for deferred and retry paths. The separate legacy redrive restoration is not covered by that helper and is reported as a new finding.
| for wallet_id in self | ||
| .buffer | ||
| .dirty_wallets() | ||
| .map_err(PersistenceError::from)? | ||
| { | ||
| let stored = | ||
| schema::wallets::fetch(&conn, &wallet_id).map_err(PersistenceError::from)?; | ||
| if !matches!(&stored, Some((stored_network, _)) if stored_network != label) { | ||
| self.flush_locked(&mut conn, &wallet_id)?; | ||
| } |
There was a problem hiding this comment.
⚖️ Disputed (left to the maintainers; not blocking) at
36e55493; see the replies below.
🟡 Suggestion: Do not flush unclassified or unrelated wallet buffers during shielded Clear
dirty_wallets() includes every pending per-wallet changeset, but the network filter only consults the durable wallets row. When that row is absent, the condition at line 1360 flushes the buffer as though it belonged to the network being cleared. A newly registered wallet can have its network metadata and viewing-key changeset buffered before its durable row exists, so a buffer from another network can be committed during this Clear. For wallets that are correctly classified, flush_locked still writes the entire changeset, so an unrelated core write failure can make the host wipe fail after the native reset. Determine ownership from buffered metadata when no durable row exists, and avoid coupling shielded deletion to unrelated buffered domains.
source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)
There was a problem hiding this comment.
Fixed the classification in 1754d1a: a wallet with no wallets row is classified by the network in its buffered metadata, and another network's wallet is skipped. Test: shielded_wipe_classifies_a_wallet_with_no_row_by_its_buffered_network. Flushing stays per wallet, so a wallet's whole buffer is written together; splitting it by domain is out of scope here.
🤖 Posted autonomously by Claude on behalf of pasta.
There was a problem hiding this comment.
Still applies (re-reviewed at 1754d1aa): The new buffered-network lookup fixes the missing durable-row case when metadata is present, but a buffer with no durable row and no metadata is still flushed by the !other_network fallback. The whole per-wallet changeset also still couples shielded deletion to unrelated pending domains, so the original finding remains partially unresolved.
There was a problem hiding this comment.
Keeping the remaining case as it is. A buffer with no row and no metadata can't be attributed, and flushing it is the safe direction: if it holds this network's viewing keys, they must land before the delete. If it belongs to another network, the flush only makes it durable early. Flushing per wallet keeps each wallet's buffer atomic; splitting it by domain is out of scope here.
🤖 Posted autonomously by Claude on behalf of pasta.
There was a problem hiding this comment.
Still applies (re-reviewed at 2352c3c6): The no-row/no-metadata case still flushes an unclassifiable buffer, and that can create an orphan FVK which delete_for_network cannot match. The current code therefore still allows Clear to report success while shielded host state remains.
There was a problem hiding this comment.
Fixed in 36e5549. The wipe now drops the buffered shielded writes of a wallet that has no row and no metadata, and keeps the rest of its buffer. delete_for_network also deletes stored viewing keys whose wallet has no row, matching the Kotlin and Swift wipes.
One correction to the scenario: SQLite enforces the foreign key from shielded_viewing_keys to wallets, so that flush failed rather than leaving an orphan, and every later Clear failed the same way. This fixes that too. Test: shielded_wipe_drops_viewing_keys_of_wallets_with_no_row_or_metadata.
🤖 Posted autonomously by Claude on behalf of pasta.
There was a problem hiding this comment.
Disputed (re-reviewed at 36e55493): We still disagree on this one, and my answer is above, so I'm leaving the call to the maintainers. It no longer blocks this pull request, and I won't raise it again unless a later change brings the problem back.
| let round = self.round_lock.lock(); | ||
| if round.in_round { | ||
| return Err(PersistenceError::backend( | ||
| "FFIPersister: cannot wipe shielded state inside an unclosed changeset round", | ||
| )); |
There was a problem hiding this comment.
✅ Withdrawn at
2352c3c6; see the replies below.
🟡 Suggestion: Avoid discovering an open FFI changeset round after native Clear reset
FFIPersister::wipe_shielded_state rejects an open changeset round, but the coordinator invokes it only after resetting the native store, clearing registries, and advancing the Clear state. An unrelated core, identity, or DPNS persistence round can therefore leave Clear with native state already wiped, host rows intact, and host_wipe_pending set; subsequent binds are refused until a retry succeeds. Check for an open round or coordinate its drain before performing the native reset, rather than discovering this precondition only in the host-wipe half.
source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)
There was a problem hiding this comment.
Declining. A check before the native reset can't close this, because a round can still open between that check and the wipe. The case is already fail-closed: host_wipe_pending refuses binds and the error says to retry Clear, which then completes the host half.
🤖 Posted autonomously by Claude on behalf of pasta.
There was a problem hiding this comment.
Still applies (re-reviewed at 1754d1aa): The retry is not sufficient for the explicitly modeled unwound-round state: in_round remains true after begin_round, so every later wipe returns before calling the host callback. Clear therefore can remain permanently partial for the life of the persister unless that round state is recovered.
There was a problem hiding this comment.
Still declining. A healthy round can't make the wipe fail. store holds round_lock for the whole round, so the wipe waits for the lock and then finds in_round false. in_round stays set only after a round unwinds, and that leaves the persister unusable for everything: store and load refuse the same state (persistence.rs:2358, :3870). Recovering an unwound round is a general persister fix, not part of this PR.
🤖 Posted autonomously by Claude on behalf of pasta.
There was a problem hiding this comment.
Withdrawn (re-reviewed at 2352c3c6): The healthy-round case is serialized by round_lock, while an unwound round leaves store and load unusable as well as wipe; this is general persister recovery rather than a defect introduced by this PR, so I withdraw this prior identity.
| @@ -1297,32 +1400,41 @@ impl NetworkShieldedCoordinator { | |||
| } | |||
| } | |||
| } | |||
| // Hydration and snapshot validity go regardless of the outcome. | |||
| // Either reset may fail after changing part of its persistent state, | |||
| // so the next identical bind must not fast-path over a potentially | |||
| // half-reset store. The generation bump also prevents an in-flight | |||
| // bind from restoring a pre-Clear snapshot afterward. | |||
| // Hydration goes regardless of the outcome: either reset may fail | |||
| // after changing part of its persistent state, so the next identical | |||
| // bind must not fast-path over a potentially half-reset store. | |||
| self.hydrated.write().await.clear(); | |||
| self.clear_generation | |||
| .fetch_add(1, std::sync::atomic::Ordering::AcqRel); | |||
| clear_state.epoch = clear_state.epoch.wrapping_add(1); | |||
|
|
|||
| if let Some(e) = first_err { | |||
| return Err(e); | |||
| } | |||
|
|
|||
| // Store reset succeeded — now it is safe to drop the in-memory | |||
| // registries and reset the cooldown so the first post-clear | |||
| // background pass runs immediately rather than honoring a stale | |||
| // "caught up" stamp. The registries deliberately survive a failed | |||
| // clear: dropping them would make the coordinator forget every | |||
| // bound wallet (no syncs until the host rebinds) while the host, | |||
| // Store reset succeeded — drop the in-memory registries and reset the | |||
| // cooldown so the first post-clear background pass runs immediately. | |||
| // The registries survive a failed store reset: dropping them would | |||
| // make the coordinator forget every bound wallet while the host, | |||
| // told the clear failed, keeps its own state. | |||
| self.accounts.write().await.clear(); | |||
| self.persisters.write().await.clear(); | |||
| if let Ok(mut g) = self.last_caught_up_at.lock() { | |||
| *g = None; | |||
| } | |||
| Ok(()) | |||
|
|
|||
| // The host half, still under the exclusive admission. | |||
| match host.wipe_shielded_state(self.network) { | |||
There was a problem hiding this comment.
✅ Withdrawn at
1754d1aa; see the replies below.
🟡 Suggestion: Release the lifecycle mutex before the synchronous host wipe
clear keeps the coordinator lifecycle mutex held from before the native reset through the synchronous host.wipe_shielded_state callback. By the time the host callback is reached, hydrated, accounts, and persisters have already been cleared, while the exclusive admission still blocks new installs and sync mutations. The only lifecycle user that bypasses admission, unregister_wallet, can safely observe the cleared maps and purge an already-reset store. Holding the Tokio mutex across potentially slow Swift/Kotlin or SQLite I/O unnecessarily blocks wallet removal and can widen executor stalls. Drop the lifecycle guard before the host callback while retaining exclusive admission for the complete native-reset/host-wipe boundary.
source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)
There was a problem hiding this comment.
Declining. The executor stall comes from the synchronous host callback itself; releasing the mutex wouldn't remove it. Keeping the lifecycle lock means unregister_wallet can't interleave with any part of Clear, and it only waits while a Clear runs.
🤖 Posted autonomously by Claude on behalf of pasta.
There was a problem hiding this comment.
Withdrawn (re-reviewed at 1754d1aa): The lifecycle mutex intentionally covers the complete Clear transaction, including the host callback, so unregister_wallet cannot interleave with registry reset, host deletion, or native purge. Releasing it would weaken that lifecycle guarantee without removing the synchronous callback's executor stall, so I withdraw this performance suggestion.
…n unconfigured balance - shielded_balances returns an error when the manager has no shielded coordinator, instead of an empty map that reads as a zero balance. - Private contact payment restoration runs under the coordinator's shielded admission from its journal read to its last store and persister write, so a Clear lands entirely before or after it, and a Clear whose host wipe failed refuses it as it refuses binds. A bind restores under its own admission; restorations that must not wait (retry before a send, load, register, repeat configure) take one without blocking and treat a Clear as a busy store. - SqlitePersister::wipe_shielded_state classifies a dirty wallet with no wallets row by the network of its buffered metadata, so another network's new wallet is not flushed by this network's wipe. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@thepastaclaw review 🤖 Posted autonomously by Claude on behalf of pasta. |
|
@PastaPastaPasta on it — I've queued this as job |
|
Thanks — reviewsys handles PR reviews here; it answers on the finding’s thread and re-reviews on push. |
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The follow-up fixes the unconfigured balance result and admitted journal restoration, but the Clear boundary still has several state-integrity gaps. In particular, failed host wipes are not durable across restart, shielded mutations and balance reads bypass the failed-wipe latch, and two host-side wipe paths can acknowledge success while shielded state remains. No code check is reported failed; Kotlin passed, while Rust and Swift checks were skipped and review/hygiene checks remain pending.
🔴 5 blocking | 🟡 3 suggestion(s)
1 finding(s) not shown inline (the lines are not part of this PR's diff)
🔴 Blocking: Do not report zero balances while the host wipe is pending
packages/rs-platform-wallet/src/wallet/platform_wallet.rs:1539-1549
shielded_balances resolves the coordinator and snapshots the wallet keys without acquiring shared admission or checking host_wipe_pending. After a native reset followed by a failed host wipe, the host can still contain the old viewing keys and notes while the native store is empty, so this method returns an empty/zero balance. It can also interleave with a successful Clear and observe a partially changed state. Acquire shared admission before the key snapshot, reject a pending host wipe, and retain the admission through balances_across.
let coordinator = self.shielded_coordinator().await?;
let admission = coordinator.admit().await;
admission.ensure_host_cleared()?;
let guard = self.shielded_keys.read().await;
source: gpt-6.1-sol (phase2-reviewer: architecture-layering)
Still open from earlier rounds (3)
- 🔴 Blocking: Serialize legacy private-contact restoration with Clear admission —
packages/rs-platform-wallet/src/wallet/platform_wallet.rs:1942-1946(thread) - 🟡 Suggestion: Avoid discovering an open FFI changeset round after native Clear reset —
packages/rs-platform-wallet-ffi/src/persistence.rs:2146-2150(thread) - 🟡 Suggestion: Do not flush unclassified or unrelated wallet buffers during shielded Clear —
packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1359-1369(thread)
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: rust-quality); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — This is a large, intricate change to shielded wallet lifecycle and persistence that directly changes viewing-key handling and coordinated state wiping across Rust, SQLite, Swift, Kotlin, and FFI boundaries. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
- Code unchanged since the last final review (
20f2680a): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 confirmed - Fresh verifier:
gpt-6.1-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs:1445-1455: Persist an incomplete host wipe across manager restart
`host_wipe_pending` is stored only in the in-memory `ClearState`. If the process exits after the native store has been reset but before the host callback completes, or after the callback fails, a newly constructed coordinator starts with the default `host_wipe_pending = false`. The next startup can load the host's surviving viewing keys and shielded rows, and a later bind can restore them into the empty native store, silently undoing Clear. Persist an incomplete-wipe marker or perform an equivalent startup recovery before any host shielded rows are restored.
In `packages/rs-platform-wallet/src/wallet/platform_wallet.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:2759-2762: Block shielded mutations while a host wipe is pending
The mutation acquires shared admission but never calls `ensure_host_cleared()`. After native Clear succeeds and the host wipe fails, this path—and the analogous transfer, unshield, withdrawal, top-up, identity-create, funding, and abandonment paths—can still read the old viewing keys, sign or broadcast a payment, and write new native or host state while the pre-Clear host rows remain. A subsequent retry can delete those new rows, and a process restart loses the in-memory latch entirely. Every durable shielded mutation must check the admission state before reading keys, selecting notes, signing, broadcasting, or queueing persistence.
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:1539-1549: Do not report zero balances while the host wipe is pending
`shielded_balances` resolves the coordinator and snapshots the wallet keys without acquiring shared admission or checking `host_wipe_pending`. After a native reset followed by a failed host wipe, the host can still contain the old viewing keys and notes while the native store is empty, so this method returns an empty/zero balance. It can also interleave with a successful Clear and observe a partially changed state. Acquire shared admission before the key snapshot, reject a pending host wipe, and retain the admission through `balances_across`.
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:1294-1301: Serialize shielded account additions with bind registration
`shielded_add_account` takes shared admission but not `shield_guard`, while both bind paths take `shield_guard` before admission. Because shared admissions are concurrent, an account add can snapshot and update `shielded_keys` while a bind replaces the wallet registration. The bind can overwrite the newly added key, or the add can finish after the bind and leave a key in the wallet slot that is absent from the coordinator's account registry; the persisted viewing key then will not be included in sync. Take the wallet guard before acquiring admission, matching the bind lock order.
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:1942-1946: Serialize legacy private-contact restoration with Clear admission
(carried; thread: https://github.com/dashpay/platform/pull/5934#discussion_r4577885048)
In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt`:
- [BLOCKING] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt:2693-2703: Do not report a successful wipe while unclassified shielded rows remain
The host callback enumerates only wallet metadata rows whose `networkRaw` matches the requested network. `networkRaw` is nullable while metadata is being completed, and the shielded tables have no wallet foreign key, so viewing keys, notes, sync state, or activity can exist for a wallet that is absent from this query or still has a null network. The callback then returns success while those rows remain and Clear reports success. A later metadata write can make the surviving rows eligible for restoration, defeating Clear. Classify unresolved or buffered wallet metadata before wiping, or fail closed when any shielded rows cannot be assigned to the requested network. The Swift handler has the same selection defect.
_Raised on code unchanged since the last review, and confirmed by an independent pass: If a shielded row exists for wallet W while W has no wallet metadata row or its networkRaw is null, clearShielded(N) makes both handlers enumerate no W, yet they return success. The native reset therefore completes while W's viewing key, notes, sync state, or activity remain; if W's metadata is later completed with network N, those rows become restorable on a later load and defeat Clear._
In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/persistence.rs:2146-2150: Avoid discovering an open FFI changeset round after native Clear reset
(carried; thread: https://github.com/dashpay/platform/pull/5934#discussion_r4577885060)
In `packages/rs-platform-wallet-storage/src/sqlite/persister.rs`:
- [SUGGESTION] packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1359-1369: Do not flush unclassified or unrelated wallet buffers during shielded Clear
(carried; thread: https://github.com/dashpay/platform/pull/5934#discussion_r4577885055)
| match host.wipe_shielded_state(self.network) { | ||
| Ok(()) => { | ||
| clear_state.host_wipe_pending = false; | ||
| Ok(()) | ||
| } | ||
| Err(e) => { | ||
| tracing::error!(error = %e, "host shielded wipe failed after the native reset"); | ||
| clear_state.host_wipe_pending = true; | ||
| Err(PlatformWalletError::Persistence(format!( | ||
| "native shielded state was reset but the host wipe failed: {e}; retry Clear" | ||
| ))) |
There was a problem hiding this comment.
✅ Resolved at
2352c3c6; see the replies below.
🔴 Blocking: Persist an incomplete host wipe across manager restart
host_wipe_pending is stored only in the in-memory ClearState. If the process exits after the native store has been reset but before the host callback completes, or after the callback fails, a newly constructed coordinator starts with the default host_wipe_pending = false. The next startup can load the host's surviving viewing keys and shielded rows, and a later bind can restore them into the empty native store, silently undoing Clear. Persist an incomplete-wipe marker or perform an equivalent startup recovery before any host shielded rows are restored.
source: gpt-6.1-sol (phase2-reviewer: general)
There was a problem hiding this comment.
Fixed in 2352c3c. The native store now keeps host_wipe_pending durably in shielded_store_meta. Clear sets it before the native reset and clears it only after the host wipe succeeds, and a new coordinator reads it when it opens. Test: should_keep_a_failed_host_wipe_pending_across_a_reopen.
🤖 Posted autonomously by Claude on behalf of pasta.
There was a problem hiding this comment.
Resolved (re-reviewed at 2352c3c6): The pending marker is now stored in shielded_store_meta before reset, reloaded when the coordinator opens, and cleared only after host deletion succeeds.
| let _shield_guard = self.shield_guard.lock().await; | ||
| let coordinator = self.shielded_coordinator().await?; | ||
| let _admission = coordinator.admit().await; | ||
|
|
There was a problem hiding this comment.
✅ Resolved at
2352c3c6; see the replies below.
🔴 Blocking: Block shielded mutations while a host wipe is pending
The mutation acquires shared admission but never calls ensure_host_cleared(). After native Clear succeeds and the host wipe fails, this path—and the analogous transfer, unshield, withdrawal, top-up, identity-create, funding, and abandonment paths—can still read the old viewing keys, sign or broadcast a payment, and write new native or host state while the pre-Clear host rows remain. A subsequent retry can delete those new rows, and a process restart loses the in-memory latch entirely. Every durable shielded mutation must check the admission state before reading keys, selecting notes, signing, broadcasting, or queueing persistence.
| let _shield_guard = self.shield_guard.lock().await; | |
| let coordinator = self.shielded_coordinator().await?; | |
| let _admission = coordinator.admit().await; | |
| let admission = coordinator.admit().await; | |
| admission.ensure_host_cleared()?; |
source: gpt-6.1-sol (phase2-reviewer: security-auditor)
There was a problem hiding this comment.
Fixed in 2352c3c. admit() and try_admit() now refuse while a host wipe is pending, so every shielded mutation is refused, and shielded_balances reads under an admission. That also covers the balance finding that wasn't posted inline. Test: should_refuse_mutations_and_balance_reads_while_the_host_wipe_is_pending.
🤖 Posted autonomously by Claude on behalf of pasta.
There was a problem hiding this comment.
Resolved (re-reviewed at 2352c3c6): The admission helpers now reject while host_wipe_pending is set, covering the shielded mutation paths before they can read or persist state.
| override fun onWipeShieldedState(network: Int): Int = guarded { | ||
| runBlockingCatching { | ||
| database.withTransaction { | ||
| val dao = database.shieldedDao() | ||
| for (wallet in database.walletDao().getByNetwork(network)) { | ||
| dao.deleteActivityByWallet(wallet.walletId) | ||
| dao.deleteOutgoingNotesByWallet(wallet.walletId) | ||
| dao.deleteNotesByWallet(wallet.walletId) | ||
| dao.deleteSyncStatesByWallet(wallet.walletId) | ||
| dao.deleteViewingKeysByWallet(wallet.walletId) | ||
| } |
There was a problem hiding this comment.
✅ Resolved at
2352c3c6; see the replies below.
🔴 Blocking: Do not report a successful wipe while unclassified shielded rows remain
The host callback enumerates only wallet metadata rows whose networkRaw matches the requested network. networkRaw is nullable while metadata is being completed, and the shielded tables have no wallet foreign key, so viewing keys, notes, sync state, or activity can exist for a wallet that is absent from this query or still has a null network. The callback then returns success while those rows remain and Clear reports success. A later metadata write can make the surviving rows eligible for restoration, defeating Clear. Classify unresolved or buffered wallet metadata before wiping, or fail closed when any shielded rows cannot be assigned to the requested network. The Swift handler has the same selection defect.
Raised on code unchanged since the last review, and confirmed by an independent pass: If a shielded row exists for wallet W while W has no wallet metadata row or its networkRaw is null, clearShielded(N) makes both handlers enumerate no W, yet they return success. The native reset therefore completes while W's viewing key, notes, sync state, or activity remain; if W's metadata is later completed with network N, those rows become restorable on a later load and defeat Clear.
source: gpt-6.1-sol (phase2-reviewer: security-auditor)
There was a problem hiding this comment.
Fixed in 2352c3c, in both the Kotlin and Swift handlers. They now enumerate wallet ids from the shielded tables themselves:
- rows of a wallet whose network is null fail the wipe and nothing is deleted;
- rows of a wallet on this network are deleted;
- rows with no wallet row at all are deleted, the same way wallet deletion removes them.
Failing closed on that last case would block shielded use permanently, because no network-locked manager can ever load such a wallet.
🤖 Posted autonomously by Claude on behalf of pasta.
There was a problem hiding this comment.
Resolved (re-reviewed at 2352c3c6): Both managed-language handlers now enumerate shielded rows directly, delete orphan rows, and refuse the wipe when a wallet's network is still unknown.
| self.ensure_shielded_attached()?; | ||
| // Admitted for the whole read-check-write-install span, as a bind | ||
| // is: no Clear lands between the snapshot read and the key's | ||
| // installation, and none completes with this key's row still to be | ||
| // written. | ||
| let coordinator = self.shielded_coordinator().await?; | ||
| let admission = coordinator.admit().await; | ||
| admission.ensure_host_cleared()?; |
There was a problem hiding this comment.
✅ Resolved at
2352c3c6; see the replies below.
🟡 Suggestion: Serialize shielded account additions with bind registration
shielded_add_account takes shared admission but not shield_guard, while both bind paths take shield_guard before admission. Because shared admissions are concurrent, an account add can snapshot and update shielded_keys while a bind replaces the wallet registration. The bind can overwrite the newly added key, or the add can finish after the bind and leave a key in the wallet slot that is absent from the coordinator's account registry; the persisted viewing key then will not be included in sync. Take the wallet guard before acquiring admission, matching the bind lock order.
| self.ensure_shielded_attached()?; | |
| // Admitted for the whole read-check-write-install span, as a bind | |
| // is: no Clear lands between the snapshot read and the key's | |
| // installation, and none completes with this key's row still to be | |
| // written. | |
| let coordinator = self.shielded_coordinator().await?; | |
| let admission = coordinator.admit().await; | |
| admission.ensure_host_cleared()?; | |
| let _shield_guard = self.shield_guard.lock().await; | |
| let coordinator = self.shielded_coordinator().await?; | |
| let admission = coordinator.admit().await; | |
| admission.ensure_host_cleared()?; |
source: gpt-6.1-sol (phase2-reviewer: rust-quality)
There was a problem hiding this comment.
Fixed in 2352c3c: shielded_add_account takes shield_guard before the admission, the same order as bind.
🤖 Posted autonomously by Claude on behalf of pasta.
There was a problem hiding this comment.
Resolved (re-reviewed at 2352c3c6): The new shielded_add_account ordering takes shield_guard before coordinator admission, so account registration can no longer interleave with bind replacement.
… work until it completes A Clear that reset native shielded state but could not wipe the host kept that fact in memory only, and only binds and restorations checked it. - The shielded store keeps a durable host-wipe-pending mark, set before the native reset and cleared only once the host wipe succeeds. A coordinator opened over the store starts from it, so a process that dies in between still refuses shielded work after a restart. - admit()/try_admit() refuse while the mark is set, so every spend, transfer, unshield, withdrawal, top-up, funding, abandonment, account add, sync pass and restoration is refused rather than run against the reset store next to the host's surviving rows. - shielded_balances and restore_pending_private_contact_requests take a shared admission from their store read through their last use of it. - shielded_add_account takes shield_guard before admission, as a bind does. - The Kotlin and Swift host wipes enumerate the shielded tables. Rows of a wallet whose network is unknown fail the wipe with nothing deleted; rows of a wallet with no wallet row are deleted with the network's own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
Static verification at the exact head finds three blocking issues: shielded asset-lock funding can proceed without a configured manager coordinator, wallet deletion does not fence delayed shielded host-key writes, and SQLite Clear can materialize an unclassified viewing-key buffer into an orphan that survives deletion. Kotlin checks pass; Rust, Swift, and broader suites are skipped in the supplied CI snapshot, and no local builds or tests were run.
🔴 3 blocking
1 finding(s) not shown inline (the lines are not part of this PR's diff)
🔴 Blocking: Fence shielded host-key writes against wallet deletion
packages/rs-platform-wallet/src/wallet/platform_wallet.rs:938-976
The detached check runs before the host snapshot and the later persister.store(), but wallet removal does not acquire the same shield guard or admission before marking the handle detached, unregistering it, and returning to the host-side wallet-row deletion. A retained handle can therefore pause after the initial check, let removal delete the host rows, then resume and persist its viewing key. The subsequent detached check only prevents installation into native memory; it cannot roll back the host write, leaving an orphaned FVK that can become restorable if the deterministic wallet ID is recreated. shielded_add_account has the same ordering at lines 1292 and 1348. Serialize teardown with these host writes, or make the persistence callback reject writes for detached wallet IDs under the same exclusion used by deletion.
source: gpt-6.1-sol (phase2-reviewer: security-auditor)
Still open from earlier rounds (1)
- 🔴 Blocking: Do not flush unclassified or unrelated wallet buffers during shielded Clear —
packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1359-1376(thread)
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: rust-quality); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — This is a large, intricate change that modifies shielded wallet key/state handling, lifecycle concurrency, persistence wiping, and cross-language FFI boundaries, directly affecting a critical key-handling surface. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
- Fresh verifier:
gpt-6.1-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/rs-platform-wallet/src/wallet/shielded/fund_from_asset_lock.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/shielded/fund_from_asset_lock.rs:276-277: Fail closed when shielded funding has no configured coordinator
This `if let Ok` silently ignores failure to resolve the manager-owned coordinator. Before `configure_shielded`, the method therefore continues through funding resolution, transaction construction, broadcast, and settlement; the later activity recorder also treats the missing coordinator as a best-effort recording miss. A direct Rust caller can consequently consume transparent asset-lock funds without any coordinator-backed shielded store or durable activity, violating the manager-owned coordinator contract and the PR's fail-before-configuration guarantee. Propagate the coordinator error before any funding or broadcast work, while still dropping the admission immediately so the long broadcast and ChainLock wait do not block Clear.
In `packages/rs-platform-wallet/src/wallet/platform_wallet.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:938-976: Fence shielded host-key writes against wallet deletion
The detached check runs before the host snapshot and the later `persister.store()`, but wallet removal does not acquire the same shield guard or admission before marking the handle detached, unregistering it, and returning to the host-side wallet-row deletion. A retained handle can therefore pause after the initial check, let removal delete the host rows, then resume and persist its viewing key. The subsequent detached check only prevents installation into native memory; it cannot roll back the host write, leaving an orphaned FVK that can become restorable if the deterministic wallet ID is recreated. `shielded_add_account` has the same ordering at lines 1292 and 1348. Serialize teardown with these host writes, or make the persistence callback reject writes for detached wallet IDs under the same exclusion used by deletion.
In `packages/rs-platform-wallet-storage/src/sqlite/persister.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1359-1376: Do not flush unclassified or unrelated wallet buffers during shielded Clear
(carried; thread: https://github.com/dashpay/platform/pull/5934#discussion_r4577885055)
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.
- Update the stale host-wipe limitation in the PR description — The Known limitations section still says
host_wipe_pendingis memory-only and that a restart can restore surviving host rows. The reviewed code now persists the marker inshielded_store_metaand reloads it on coordinator startup, so the description gives obsolete recovery guidance.- Follow-up: Update PR #5934's Known limitations section before merge to describe the durable marker and retry behavior.
| if let Ok(coordinator) = self.shielded_coordinator().await { | ||
| drop(coordinator.admit().await?); |
There was a problem hiding this comment.
✅ Resolved at
36e55493; see the replies below.
🔴 Blocking: Fail closed when shielded funding has no configured coordinator
This if let Ok silently ignores failure to resolve the manager-owned coordinator. Before configure_shielded, the method therefore continues through funding resolution, transaction construction, broadcast, and settlement; the later activity recorder also treats the missing coordinator as a best-effort recording miss. A direct Rust caller can consequently consume transparent asset-lock funds without any coordinator-backed shielded store or durable activity, violating the manager-owned coordinator contract and the PR's fail-before-configuration guarantee. Propagate the coordinator error before any funding or broadcast work, while still dropping the admission immediately so the long broadcast and ChainLock wait do not block Clear.
| if let Ok(coordinator) = self.shielded_coordinator().await { | |
| drop(coordinator.admit().await?); | |
| self.ensure_shielded_attached()?; | |
| let coordinator = self.shielded_coordinator().await?; | |
| drop(coordinator.admit().await?); |
source: gpt-6.1-sol (phase2-reviewer: general)
There was a problem hiding this comment.
Fixed in 36e5549. Funding now resolves the coordinator and takes an admission with ? before any funding resolution or broadcast, then releases it at once. Test: should_refuse_funding_before_any_lock_without_a_shielded_coordinator.
🤖 Posted autonomously by Claude on behalf of pasta.
There was a problem hiding this comment.
Resolved (re-reviewed at 36e55493): Funding now resolves the manager-owned coordinator and acquires admission with ? before resolving funding or broadcasting, so an unconfigured manager fails before consuming an asset lock.
|
@thepastaclaw please file a tracking issue for "Fence shielded host-key writes against wallet deletion" ( The race is between wallet removal and a retained handle's viewing-key persist. It predates this PR: the bind persist and the 🤖 Posted autonomously by Claude on behalf of pasta. |
|
@PastaPastaPasta on it — I've queued this as job |
|
Filed tracking issue #5936, platform-wallet: fence shielded host-key writes against wallet deletion. It covers the retained-handle race across wallet removal, bind/ |
…owless viewing keys Shielded funding now fails with the coordinator error before resolving any funding, so a manager without configure_shielded never builds or broadcasts an asset lock that has no shielded store behind it. The SQLite shielded wipe no longer flushes a wallet that has neither a wallets row nor buffered metadata: its viewing key could only fail the foreign key and block every Clear. Its buffered shielded writes are dropped instead, and the wipe also deletes stored viewing keys whose wallet has no row, matching the Kotlin and Swift wipes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 2 only (queue backlog)
Three in-scope blocking defects remain at this head: retained wallet handles can write shielded viewing keys after wallet removal, asset-lock funding can record stale activity after Clear completes, and SQLite recovery mode falsely advertises wipe capability. The previously reported unrelated-buffer coupling remains a valid suggestion; the other prior findings are fixed or settled.
A pattern across this PR's review rounds
This is review round 4, and the PR has drawn 10 blocking findings so far. 10 of them share 4 underlying causes. They are listed with the other findings as usual; fixing the cause is likely to be cheaper than fixing each case.
1. Shielded fail-closed behavior is not centralized (3 earlier finding(s))
The manager-owned coordinator requirement is enforced inconsistently across shielded entry points. Some paths turn an unavailable or pending coordinator into an empty balance or a best-effort no-op, while funding can proceed without a coordinator, so each newly added operation needs its own refusal patch.
2. Host wipe capability is only an attestation (1 new in this round, 3 earlier finding(s))
Clear resets native state before invoking a host callback whose capability bit does not prove that the backend can currently complete a network-scoped wipe. Open persistence rounds, recovery mode, unclassified wallet metadata, and rows without wallet ownership are outside one atomic preflight, so Clear can cross the reset boundary before discovering that host state cannot be completely wiped.
In this round: Do not attest shielded Clear support in SQLite recovery mode
3. Clear has no operation-generation boundary (1 new in this round, 3 earlier finding(s))
The admission lock protects selected intervals, but the design does not carry a durable Clear generation through restorations, long asset-lock operations, or deferred activity writes. Work can therefore bypass admission, lose its pending-wipe fence across a restart, or reacquire a fresh post-Clear admission and write state derived from before Clear.
In this round: Prevent asset-lock activity from being written after Clear
4. Wallet lifecycle is outside the admission protocol (2 earlier finding(s))
Registration, account addition, and wallet removal do not all use the same shield guard and lifecycle boundary. A retained wallet handle can consequently overlap registration replacement or host-row deletion, allowing stale viewing-key state to be written after teardown.
Suggested decision (redesign the component): Redesign the rs-platform-wallet shielded coordinator and host-persistence boundary before adding more caller-specific guards. The design must provide a preflightable network-scoped wipe whose capability means the backend can complete it in its current mode and classify every relevant row and buffer, plus an operation-generation fence that covers work crossing broadcasts, callbacks, and restarts. Make every shielded entry point and wallet teardown use that single protocol so Clear cannot report completion while pre-Clear-derived state can still be written.
If a later review again finds new blockers from these causes, it will ask for that decision and pause automatic re-review until it is made.
🔴 3 blocking
1 finding(s) not shown inline (the lines are not part of this PR's diff)
🔴 Blocking: Fence shielded host-key writes against wallet deletion
packages/rs-platform-wallet/src/wallet/platform_wallet.rs:938-976
bind_shielded and shielded_add_account hold the coordinator admission, but remove_wallet does not acquire that admission before marking the handle detached and calling unregister_wallet. Removal can therefore delete the host rows while a retained handle is already past its initial detached check and is waiting in persister.store(...). The bind path has no post-write detached check, and the account-add path checks only after the write, so the later lifecycle check cannot retract a viewing-key row written after wallet teardown. Fence removal and host viewing-key persistence with the same lifecycle/admission boundary, or delete the row if removal wins the race.
source: gpt-6.1-sol (phase2-reviewer: architecture-layering, ffi-engineer, security-auditor)
Disputed — left to maintainers (1)
- 🟡 Suggestion: Do not flush unclassified or unrelated wallet buffers during shielded Clear —
packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1353-1362(thread)
Review provenance
Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — This large, intricate diff changes shielded wallet key handling, durable wallet state, and funding-related concurrency across Rust, Swift, Kotlin, JNI, FFI, and SQLite surfaces. - Phase 1 reviewers: not run (skipped for throughput: 12 PRs queued, above the 10 limit)
- Fresh verifier:
gpt-6.1-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
Several findings on this PR share an underlying cause (the review's "pattern" section): Shielded fail-closed behavior is not centralized; Host wipe capability is only an attestation; Clear has no operation-generation boundary; Wallet lifecycle is outside the admission protocol. When you fix the findings below, fix the cause, not only the reported case. The review suggests (redesign the component): Redesign the rs-platform-wallet shielded coordinator and host-persistence boundary before adding more caller-specific guards. The design must provide a preflightable network-scoped wipe whose capability means the backend can complete it in its current mode and classify every relevant row and buffer, plus an operation-generation fence that covers work crossing broadcasts, callbacks, and restarts. Make every shielded entry point and wallet teardown use that single protocol so Clear cannot report completion while pre-Clear-derived state can still be written. If that decision is not yours to make, say so to the PR's author or maintainer.
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/rs-platform-wallet/src/wallet/platform_wallet.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:938-976: Fence shielded host-key writes against wallet deletion
`bind_shielded` and `shielded_add_account` hold the coordinator admission, but `remove_wallet` does not acquire that admission before marking the handle detached and calling `unregister_wallet`. Removal can therefore delete the host rows while a retained handle is already past its initial detached check and is waiting in `persister.store(...)`. The bind path has no post-write detached check, and the account-add path checks only after the write, so the later lifecycle check cannot retract a viewing-key row written after wallet teardown. Fence removal and host viewing-key persistence with the same lifecycle/admission boundary, or delete the row if removal wins the race.
In `packages/rs-platform-wallet/src/wallet/shielded/fund_from_asset_lock.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/shielded/fund_from_asset_lock.rs:800-814: Prevent asset-lock activity from being written after Clear
The funding operation releases its initial admission before the asset-lock broadcast and ChainLock wait, then reacquires admission only when recording activity. Clear can therefore reset the native store, wipe host rows, and complete between settlement and `record_shield_from_asset_lock_activity`. The stale recorder then obtains a fresh post-Clear admission and queues the pre-Clear activity bundle, recreating shielded state after Clear reported success. Carry a Clear epoch or equivalent operation generation through funding and reject the activity record when Clear occurred during the long operation.
In `packages/rs-platform-wallet-storage/src/sqlite/persister.rs`:
- [BLOCKING] packages/rs-platform-wallet-storage/src/sqlite/persister.rs:1306-1334: Do not attest shielded Clear support in SQLite recovery mode
`persistence_capabilities()` unconditionally advertises `SHIELDED_STATE_WIPE` whenever the shielded feature is enabled, including for `LoadPolicy::Recovery`. That mode is explicitly read-only, and `wipe_shielded_state()` immediately rejects it through `ensure_writable()`. `PlatformWalletManager::clear_shielded()` relies on the capability bit as its fail-before-reset check, so a recovery-mode persister passes preflight, resets native state, and only then fails the host wipe, leaving host rows and the durable pending marker behind. Omit the wipe capability for recovery-mode instances or make the capability reflect whether this backend can actually perform the wipe.
| // The only shielded write of a funding, admitted on its own: the | ||
| // asset lock's broadcast and ChainLock wait before it, which can take | ||
| // indefinitely long, write no shielded state and hold no Clear back. | ||
| // `shield_guard` is held here, which the lock order allows: it comes | ||
| // before admission everywhere. | ||
| let Ok(coordinator) = self.shielded_coordinator().await else { | ||
| return; | ||
| }; | ||
| let _admission = match coordinator.admit().await { | ||
| Ok(admission) => admission, | ||
| Err(error) => { | ||
| tracing::warn!(%error, "shield-from-asset-lock activity not recorded"); | ||
| return; | ||
| } | ||
| }; |
There was a problem hiding this comment.
🔴 Blocking: Prevent asset-lock activity from being written after Clear
The funding operation releases its initial admission before the asset-lock broadcast and ChainLock wait, then reacquires admission only when recording activity. Clear can therefore reset the native store, wipe host rows, and complete between settlement and record_shield_from_asset_lock_activity. The stale recorder then obtains a fresh post-Clear admission and queues the pre-Clear activity bundle, recreating shielded state after Clear reported success. Carry a Clear epoch or equivalent operation generation through funding and reject the activity record when Clear occurred during the long operation.
source: gpt-6.1-sol (phase2-reviewer: rust-quality)
| .union(PersistenceCapabilities::DASHPAY_PAYMENTS); | ||
| #[cfg(feature = "shielded")] | ||
| { | ||
| capabilities.union(PersistenceCapabilities::SHIELDED_VIEWING_KEYS) | ||
| capabilities | ||
| .union(PersistenceCapabilities::SHIELDED_VIEWING_KEYS) | ||
| .union(PersistenceCapabilities::SHIELDED_STATE_WIPE) | ||
| } |
There was a problem hiding this comment.
🔴 Blocking: Do not attest shielded Clear support in SQLite recovery mode
persistence_capabilities() unconditionally advertises SHIELDED_STATE_WIPE whenever the shielded feature is enabled, including for LoadPolicy::Recovery. That mode is explicitly read-only, and wipe_shielded_state() immediately rejects it through ensure_writable(). PlatformWalletManager::clear_shielded() relies on the capability bit as its fail-before-reset check, so a recovery-mode persister passes preflight, resets native state, and only then fails the host wipe, leaving host rows and the durable pending marker behind. Omit the wipe capability for recovery-mode instances or make the capability reflect whether this backend can actually perform the wipe.
source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, rust-quality, security-auditor)
Issue being fixed or feature implemented
Shielded Clear crossed three owners, and nothing tied them together:
clear_generationcounter,ShieldedInstall::snapshot_predates_clearand per-call ownership checks. None of them covered the host deletion, because it ran outside Rust.The DashPay shielded tips (#5288) and per-identity shielded accounts (#5905) work both add shielded mutations and were adding more of these guards. This PR moves the boundary into one place first, so those branches can drop their guards when they rebase.
What was done?
1. The manager owns the coordinator. Wallet shielded operations resolve the manager's coordinator internally (
PlatformWallet::shielded_coordinator()), and the coordinator parameter is gone from the public wallet API. Beforeconfigure_shielded, a shielded call fails with "not configured" and writes nothing to the host.2. Clear runs the host wipe itself.
PlatformWalletPersistence::wipe_shielded_state(network), declared by the new capabilityPersistenceCapabilities::SHIELDED_STATE_WIPE(1 << 16). Its default implementation returns an error.PlatformWalletManager::clear_shieldedrefuses before anything is reset (the error message ends in "nothing was reset") when the persister does not attest the capability. Other capabilities are declared and checked the same way.wipe_shielded_state(network). It returns only after the wipe.Persistenceerror. Every bind, account add and coordinator restore is then refused until a later Clear wipes the host.on_wipe_shielded_state_fn: Option<unsafe extern "C" fn(context: *mut c_void, network: FFINetwork) -> i32>(WipeShieldedStateFn) and C constantPLATFORM_WALLET_PERSISTENCE_CAPABILITY_SHIELDED_STATE_WIPE.NativePersistenceBridge.onWipeShieldedState(network: Int): Int(descriptor(I)I). The slot is wired only when the bridge overrides the method; the inherited body returns -1.PlatformWalletPersistenceHandlerand KotlinPlatformWalletPersistenceHandlereach delete, in one transaction, the viewing keys, notes, outgoing notes, sync states and activity of every wallet on that network.ShieldedService.clearLocalState()in the Kotlin SDK and in SwiftExampleApp no longer deletes rows itself.3. One admission protocol. The coordinator has an
admission: tokio::sync::RwLock<ClearState { epoch, host_wipe_pending }>.shield_guard→ admission → coordinatorlifecycle→store.shield_guardcomes first, so an operation queued behind a long shield-class operation (an asset-lock funding waiting on its ChainLock) holds no admission and cannot stall a Clear.NetworkShieldedCoordinator::clear_generation(field and method);ShieldedInstall::snapshot_predates_clear;NetworkShieldedCoordinator::begin_install, which now lives on the admission (ShieldedAdmission::begin_install).NetworkShieldedCoordinator::clear_epoch()reports how many Clears reached the native reset.How Has This Been Tested?
New deterministic race tests in
rs-platform-wallet(wallet::shielded::lifecycle_boundary_tests). A host persister parks one side at a host callback, and the test waits until Clear is queued on the admission before releasing it:shielded_add_accountagainst Clear, both ways round;ShutdownIncomplete, nothing reset, no host call;shield_guarddoes not stall Clear. This test fails with the previous lock order;configure_shielded, and none before it.Other tests:
manager.configure_shielded(..).onWipeShieldedState.Commands run:
Not tested locally: the Swift SDK and SwiftExampleApp changes, including the new
ShieldedStateWipeTests, were not built here; they rely on CI. The Kotlin androidTest was compiled but not run on a device. Locally, the existing Kotlin testaSweepReleasingMoreOutpointsThanSqliteCanBindStillCommits(40,000 outpoints) hit its 1-minuterunTestlimit under heavy host load; it does not exercise the code changed here.Breaking Changes
No consensus or protocol change. API and persister contract changes:
PlatformWalletshielded methods:bind_shielded,bind_shielded_from_persisted,shielded_balances,shielded_transfer_to,shielded_unshield_to,shielded_withdraw_to,shielded_shield_from_account[_to_recipient],shielded_shield_from_identity[_to_recipient],shielded_identity_top_up_from_pool,shielded_identity_create_from_pool,shielded_fund_from_asset_lock,shielded_seed_pool_notes,abandon_shielded_identity_debit, and the private contact request methods (send_private_contact_request,accept_private_contact_request,restore_private_contact_payments,restore_pending_private_contact_requests). Configure the manager withconfigure_shieldedfirst.PrivateReplyPaymentno longer has acoordinatorfield.NetworkShieldedCoordinator::clearis crate-internal and takes the host persister; usePlatformWalletManager::clear_shielded.clear_generation,ShieldedInstall::snapshot_predates_clearand the coordinator-levelbegin_installwere removed.register_walletandrestore_for_walletnow fail after a Clear whose host wipe failed.SHIELDED_STATE_WIPEand a workingwipe_shielded_state. Without them, Clear returns an error and resets nothing.on_wipe_shielded_state_fn(appended toPersistenceCallbacksExtension; olderstruct_sizevalues stay valid but cannot Clear) and declare the bit.onWipeShieldedState.ShieldedService.clearLocalState()no longer takes a database.ShieldedService.clearLocalState()no longer takes a model context.PlatformWalletPersistenceCapabilities.SHIELDED_STATE_WIPE(Kotlin) and.shieldedStateWipe(Swift) were added.host_wipe_pendingis in memory only. If the app is killed between a successful native reset and a failed host wipe, the next launch can restore the host's surviving rows. Run Clear again.ShutdownIncompleteafter the 10 s budget and resets nothing.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