Repository navigation
fix(platform): harden ShieldFromIdentity admission and recovery - #4715
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
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. Comment |
|
🕓 Queued for automated review — 10th in line, estimated start in ~4 h (commit aca80e5)
|
4f0e018 to
ea0d777
Compare
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## claude/identity-shielded-pool-transition-847713 #4715 +/- ##
===================================================================================
+ Coverage 86.25% 87.92% +1.67%
===================================================================================
Files 2782 2782
Lines 367866 362631 -5235
===================================================================================
+ Hits 317303 318853 +1550
+ Misses 50563 43778 -6785
🚀 New features to boost your workflow:
|
QuantumExplorer
left a comment
There was a problem hiding this comment.
Re-review at 22192e9. The blocker from the first pass is fixed and all three design points were acted on. One more change is needed before merge (a remaining liveness gap); two smaller notes inline. Posted as a comment review because GitHub does not allow requesting changes on one's own pull request.
Verification. The PR's own run skips the Rust and Swift jobs (base is not v4.2-dev), so I checked the head out locally: 34 drive-abci ShieldFromIdentity and check_tx tests, 65 wallet coordinator, redrive, store and bind tests, and 6 FFI mapping tests pass; clippy at CI settings is clean on drive-abci, wallet and FFI. A full tests.yml dispatch on the branch (run 34731708108) covers the rest, including the Swift build.
What the second commit fixed
- Re-key displacement (the blocker): registration now refuses to remove or re-key an account that holds an unresolved identity debit, keeps the old keys and notes untouched, and on restart rejects keys that cannot recover the guard's outputs. Tests cover rekey, omitted account and restart.
- Honest re-broadcast after eviction: successful verifications are cached by transaction hash and protocol version, so identical bytes re-admit without proof work or capacity, while different bytes at the same nonce stay blocked. The cache is bounded (4,096 identities, one replacement per minute, in-flight protection).
- Guard lifetime: a proven-consumed nonce parks the guard so re-broadcasts stop (with a schema migration for existing stores). Keeping the guard until the scan observes the outputs is a deliberate choice and is fine for the normal one-pass case.
- The floor test now asserts what it proves, the pending-row abort is documented, code 55
ShieldedIdentityDebitPendingis wired through FFI, Swift, Kotlin and the registry, and the dead classifier is gone.
Remaining gap (needs a change): no terminal state for a shield that can never succeed. Details on the inline comment in operations.rs.
The policy / reconcile check is red from the policy script itself exiting 1, unrelated to this change.
🤖 Review by Claude Code
| } | ||
| } | ||
| } | ||
| // Unused or unverified state permits only the original signed bytes. |
There was a problem hiding this comment.
Terminal state missing. Failure verdicts are now never trusted, so a transition the network rejects deterministically keeps its guard forever: this loop re-broadcasts it and fetches a nonce proof on every sync pass, and has_unresolved_identity_shield locks the identity out of shielding on this wallet until a Clear.
Concrete cases: the identity's balance was spent from another device, so every rebroadcast fails the fee gate with the nonce still unused; a client-side proof bug; or the identity's nonce advancing past the 24-slot window through other transitions, which identity_nonce_proves_unused treats as possibly used, so the guard parks without any outputs ever appearing.
Two safe exits exist and neither is wired:
- once the committed nonce is more than
MAX_MISSING_IDENTITY_REVISIONSpast the guard's nonce, the transition provably cannot execute anymore (NonceTooFarInPast), so the guard can be released even though the row's outcome stays unknown until the scan; - a parked guard whose outputs have not appeared after several scans can be marked Failed and cleared.
One of those, or an explicit host API to discard a parked guard, is needed before this ships; otherwise the README's "should not be used to retry" advice about Clear is the only way out.
| }) || stale.iter().any(|(stale_id, _)| *stale_id == id)) | ||
| { | ||
| return Err(PlatformWalletError::ShieldedStoreError(format!( | ||
| "account {} has an unresolved identity debit; keep its original viewing key registered until shielded sync confirms the payment", |
There was a problem hiding this comment.
A corrupt or undecodable guard row takes this same path at startup (identity_redrive_output_cmxs returns None), so the wallet cannot bind until the row is deleted, and the host sees a generic ShieldedStoreError indistinguishable from a database fault. Fail-closed is defensible, but this should be a typed, actionable error (and probably distinguish "wrong keys" from "unreadable guard").
| // Each replacement can reopen at most 48 nonce attempts (24 missing + 24 future), | ||
| // so cycling funded identities cannot turn bounded memory into unbounded proof work. | ||
| const MAX_TRACKED_IDENTITIES: usize = 4_096; | ||
| const IDENTITY_REPLACEMENT_INTERVAL: Duration = Duration::from_secs(60); |
There was a problem hiding this comment.
Mild griefing surface: an entry costs only a signature plus a balance above the admission floor (about 0.0012 DASH per identity), so 4,096 cheap identities touched periodically keep the cache full, after which honest first-time shields are throttled to one new identity per minute per node. It only degrades ShieldFromIdentity admission, so not a blocker, but consider a larger cap or letting eviction ignore the interval when the victim has no in-flight and no failed attempts.
Keep abandoned identity debits durable as outcome unknown, require scoped acknowledgement, and expose recovery through native and mobile SDK APIs. Preserve typed damaged-record and viewing-key errors during setup, fail closed on inconsistent persisted recovery metadata, and replace the full-cache newcomer throttle with a weighted proof-work budget. Cover restart, later confirmation, failed persistence, corrupt transaction routing, native error propagation, and cache churn with regression tests.
22192e9 to
ed7f5c7
Compare
QuantumExplorer
left a comment
There was a problem hiding this comment.
Re-review at ed7f5c7 (the first two commits are unchanged rebases; the third is new). The change requested in the previous round is addressed in substance and all three smaller notes were acted on. One new regression in the CheckTx limiter needs a change before merge; two further notes inline. Posted as a comment review because GitHub does not allow requesting changes on one's own pull request.
Verification. The PR's own run still skips the Rust and Swift jobs (base is not v4.2-dev), so I checked the head out locally: 36 drive-abci ShieldFromIdentity and check_tx tests, 70 wallet coordinator, redrive, store and bind tests, and 15 FFI recovery and mapping tests pass; clippy at CI settings is clean on drive-abci, wallet, FFI and the Kotlin JNI crate. A full tests.yml dispatch on the branch (run 34736544424, including Swift and Kotlin) is in progress.
What the third commit does
- Terminal state via explicit recovery: hosts can list durable records (
identity_debit_recovery_records) and abandon one with a mandatory acknowledgement. Abandonment archives the signed record, sets the activity to the newUnknownstatus (tag 3, wired through FFI, Swift persistence and both example apps), releases only that guard, stops re-broadcasts, and still lets a later scan confirm it. Declining auto-release on nonce expiry or empty scans is a defensible position and the audit trail is preserved. - Typed startup errors:
ShieldedRecoveryCorrupted(56) andShieldedRecoveryKeysRequired(57) replace the generic store error and distinguish a damaged record from a missing account, a re-keyed account and keys that cannot recover the outputs. Wired through FFI, JNI, Swift, Kotlin and the code registry. - Cache throttle replaced: the one-replacement-per-minute gate is gone; plain LRU eviction of inactive identities plus a global token-bucket budget for uncached proof work. Failed entries are not refreshed and cached successes cost nothing.
Needs a change: the global proof budget is cheaper to exhaust than the slots it protects. Details on the inline comment in check_tx_proof_verifier.rs.
🤖 Review by Claude Code
| } | ||
|
|
||
| impl IdentityProofBudget { | ||
| fn try_consume(&mut self, now: Instant, weight: usize, capacity: usize) -> bool { |
There was a problem hiding this comment.
Regression: this bucket is cheaper to exhaust than the proof slots it protects. It refills at capacity credits per second (1 to 4 on real nodes) with a burst of four waves, and every uncached identity proof draws from it.
Before this commit an attacker had to keep all proof slots continuously busy, on the order of a hundred requests per second at 10 to 50 ms per verification, and honest requests still interleaved between verifications. Now four signed requests per second with fresh nonces keep the bucket empty and every honest first-time identity shield on that node gets CheckTxProofVerificationBusy deterministically for as long as the attacker keeps sending. Failed nonces are remembered per identity, but about 4,100 cheap identities (each needs only a balance above the admission floor, about 0.0012 DASH) cycle through the LRU and reopen their nonce windows indefinitely.
Two ways out: account the budget per identity (bounded by the same LRU) so churn is capped without starving strangers, or set the refill to a multiple of real verification throughput (say 20x capacity per second) so it only catches pathological churn and never honest load.
| // Its exact transition bytes, rather than note reservations, | ||
| // preserve idempotency across restarts. | ||
| if nullifiers.len() % 32 != 0 { | ||
| return Err(corrupted("invalid nullifier width")); |
There was a problem hiding this comment.
Store open now fails closed on any malformed pending row, including plain note-spend reservations. A bad identifier width, a bad nullifier width or an invalid flag on a note-spend row used to be dropped with a warning; now it fails configure_shielded for the whole shielded subsystem, and since the abandon API needs an open store there is no in-app remediation short of deleting the SQLite file, which destroys the very identity guards being protected.
Suggest keeping fail-closed for rows that are (or could be) identity debits, and dropping or quarantining malformed note-spend rows as before; note-spend rows only carry reservations, the chain's nullifier set is the real double-spend guard.
| /// Park exact-byte retries once a proof makes the nonce unavailable. Both | ||
| /// outcomes retain the payment guard: unused may execute later, while finalized | ||
| /// may already have executed. Never resurrect a guard the scan already cleared. | ||
| fn reconcile_identity_shield_nonce<S: ShieldedStore>( |
There was a problem hiding this comment.
Once the committed nonce is more than MAX_MISSING_IDENTITY_REVISIONS past this guard's nonce, the transition provably cannot execute anymore (NonceTooFarInPast). Routing that case through abandonment makes the user acknowledge that the payment "may still execute" when it cannot. A distinct terminal state for provably-unexecutable guards (outcome still Unknown, retry impossible) would be more honest, and could release the guard without the acknowledgement.
beb8e28
into
claude/identity-shielded-pool-transition-847713
#4708 (ShieldFromIdentity) was squash-merged into v4.2-dev as 8c35ed1 together with #4715's hardening, so the original #4708 commits carried by this branch now conflict textually with the squash. The merge tree is the pure top-up delta (this branch relative to the last #4708 tip it merged, ead503c) re-applied onto the new v4.2-dev with a three-way apply, which landed without conflicts, and verified: fmt, targeted dpp/drive/drive-abci/ wallet/FFI tests, clippy at CI settings, wasm32, verify-only drive and the Kotlin compile all pass. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Issue being fixed or feature implemented
Follow-up to #4708. ShieldFromIdentity needs bounded mempool proof work and safe recovery when a relay or result fetch leaves an identity debit unresolved. A nonce snapshot does not distinguish that payment from another operation, and an unused nonce can still execute after the snapshot.
What was done?
Unknown. This does not cancel the original transaction, which may have executed or may execute later; a separately authorized payment can debit the identity again. Archived records survive restart and account rebind, stale host activities cannot undo the recovery choice, and later output observations can still confirm them.How Has This Been Tested?
cargo test -p platform-wallet --lib --features shielded --offline: 1,232 passed, including explicit recovery/acknowledgement, restart, stale-host-status overlay, later confirmation, persistence failures, and corrupt metadata/type routing.cargo clippy -p drive-abci -p platform-wallet -p platform-wallet-ffi -p rs-unified-sdk-jni --all-features --all-targets --offline -- -D warnings: passed. The initial GroveDBG build-script download failure was resolved using its cached, checksum-verified release archive.cargo check --workspace --all-targets --offline: passed. Formatting and staged diff checks passed.Breaking Changes
No consensus-breaking changes. Rust callers must handle coordinator registration's
Result, the newShieldedActivityStatus::Unknownvariant, and the typedFileShieldedStoreErrorenum.PendingRedrivegainsidentity_nonce_finalizedandidentity_user_abandoned; both SQLite columns migrate automatically with false defaults. Existing FFI error codes and activity status values 0/1/2 retain their meanings; activity status 3 represents Unknown. Recovery is opt-in and requires an explicit acknowledgement argument.Checklist:
For repository code-owners and collaborators only