Skip to content

Wallet: Lock Spark address state - #1879

Merged
reubenyap merged 2 commits into
masterfrom
codex/fix-spark-address-locking
Jul 30, 2026
Merged

Wallet: Lock Spark address state#1879
reubenyap merged 2 commits into
masterfrom
codex/fix-spark-address-locking

Conversation

@reubenyap

@reubenyap reubenyap commented Jul 25, 2026

Copy link
Copy Markdown
Member

PR intention

Fixes #1878.

CSparkWallet accessed its Spark address map and lastDiversifier from concurrent RPC and GUI paths without cs_spark_wallet. An address insertion can rehash the std::unordered_map while another thread copies or iterates it, causing undefined behavior and potentially crashing the wallet process.

Review also found one existing unlocked coinMeta access in UpdateSpendState(), reachable from wallet transaction handling while Spark worker threads use the same map.

Code changes brief

  • Take cs_spark_wallet in every address-state accessor, the two diversifier database helpers, and the shared UpdateSpendState() implementation.
  • Mark lastDiversifier, addresses, and coinMeta with GUARDED_BY(cs_spark_wallet) so Clang thread-safety analysis can detect future unlocked access.

Testing

  • git diff --check
  • Audited every affected caller and confirmed the existing lock order remains cs_main, then cs_wallet, then cs_spark_wallet.
  • Verified the branch merges cleanly with current master and the merged result retains every lock and annotation.
  • A native build was not run because this Windows environment has no C++ toolchain or existing build artifacts.

@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

CSparkWallet now synchronizes diversifier, address, and spend-state access with cs_spark_wallet. Member annotations document the protected fields, while wallet persistence, address operations, and spend updates acquire the mutex.

Changes

Spark wallet thread safety

Layer / File(s) Summary
Locking contract and diversifier persistence
src/spark/sparkwallet.h, src/spark/sparkwallet.cpp
cs_spark_wallet is documented as guarding wallet state, the shared members receive GUARDED_BY annotations, and diversifier database access acquires the mutex.
Address state synchronization
src/spark/sparkwallet.cpp
Address generation, default retrieval, enumeration, lookup, and ownership checks now acquire cs_spark_wallet while accessing shared state.
Spend-state synchronization
src/spark/sparkwallet.cpp
UpdateSpendState acquires cs_spark_wallet before checking coinMeta and updating spend-entry state.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: levonpetrosyan93, navidr, levoncrypto

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes protect the six address-related methods and preserve lock order as required by issue #1878.
Out of Scope Changes check ✅ Passed The patch stays focused on Spark wallet locking and thread-safety annotations with no unrelated code changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly and concisely summarizes the main change: locking Spark wallet address state.
Description check ✅ Passed The description follows the template and includes the PR intention, code changes brief, and testing details.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/fix-spark-address-locking

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.

@reubenyap
reubenyap marked this pull request as ready for review July 25, 2026 19:55
@reubenyap
reubenyap force-pushed the codex/fix-spark-address-locking branch from 8cd6fa6 to 87348ae Compare July 25, 2026 19:55
@codeant-ai

codeant-ai Bot commented Jul 25, 2026

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Reviewed your PR 87348ae Jul 25, 2026 · 19:55 19:57

@coderabbitai
coderabbitai Bot requested a review from navidR July 25, 2026 19:55
@codeant-ai codeant-ai Bot added the size:S This PR changes 10-29 lines, ignoring generated files label Jul 25, 2026
@codeant-ai

codeant-ai Bot commented Jul 25, 2026

Copy link
Copy Markdown

User description

PR intention

Fixes #1878.

CSparkWallet accessed its Spark address map and lastDiversifier from concurrent RPC and GUI paths without cs_spark_wallet. An address insertion can rehash the std::unordered_map while another thread copies or iterates it, causing undefined behavior and potentially crashing the wallet process.

Code changes brief

  • Take cs_spark_wallet in every address-state accessor and the two diversifier database helpers.
  • Mark lastDiversifier and addresses with GUARDED_BY(cs_spark_wallet) so Clang thread-safety analysis can detect future unlocked access.

Testing

  • git diff --check
  • Audited every affected caller and confirmed the existing lock order remains cs_main, then cs_wallet, then cs_spark_wallet.
  • A native build was not run because this Windows environment has no C++ toolchain or existing build artifacts.

CodeAnt-AI Description

Prevent wallet crashes while Spark addresses are accessed concurrently

What Changed

  • Spark address data and diversifier values are now protected whenever they are generated, read, copied, or checked
  • Database updates and restores use the same protection as address operations
  • Concurrent wallet and interface activity can no longer modify address state while another operation is reading it

Impact

✅ Fewer wallet crashes during concurrent activity
✅ Safer Spark address generation
✅ Reliable address lookups and database updates

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Comment thread src/spark/sparkwallet.h

public:
// to protect coinMeta
// Protects lastDiversifier, addresses, and coinMeta.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: The synchronization comment claims that cs_spark_wallet protects coinMeta, but coinMeta is not annotated with GUARDED_BY(cs_spark_wallet). Clang thread-safety analysis therefore cannot enforce the stated protection for this member, allowing future unlocked accesses to go undetected. Annotate coinMeta as guarded or remove it from the comment. [comment mismatch]

Severity Level: Major ⚠️
- ❌ Unlocked coin metadata access can race wallet updates.
- ⚠️ Clang analysis misses violations on transaction handling paths.
- ⚠️ Future coinMeta accesses may bypass synchronization undetected.
Steps of Reproduction ✅
1. Build with Clang thread-safety analysis enabled; `GUARDED_BY` expands to Clang's
`guarded_by` attribute in `src/threadsafety.h:9-19`.

2. Follow the production wallet transaction path from `CWallet::HandleSparkTransaction()`
at `src/wallet/wallet.cpp:5580-5598`, which calls `CSparkWallet::UpdateSpendState()` at
line 5592.

3. `CSparkWallet::UpdateSpendState()` accesses `coinMeta` at
`src/spark/sparkwallet.cpp:497-499` without taking `cs_spark_wallet`.

4. Because `coinMeta` at `src/spark/sparkwallet.h:177` lacks
`GUARDED_BY(cs_spark_wallet)`, Clang cannot diagnose this unlocked access even though the
class comment at line 160 claims the map is protected. Annotating the member would expose
this current access and protect against future unlocked accesses.

Fix in Cursor Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/spark/sparkwallet.h
**Line:** 160:160
**Comment:**
	*Comment Mismatch: The synchronization comment claims that `cs_spark_wallet` protects `coinMeta`, but `coinMeta` is not annotated with `GUARDED_BY(cs_spark_wallet)`. Clang thread-safety analysis therefore cannot enforce the stated protection for this member, allowing future unlocked accesses to go undetected. Annotate `coinMeta` as guarded or remove it from the comment.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (1)
src/spark/sparkwallet.h (1)

160-174: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Align the coinMeta guarding annotation and access contract.

coinMeta is protected by cs_spark_wallet in the comment, but the declaration lacks GUARDED_BY(cs_spark_wallet). Add the annotation and wrap UpdateSpendState(..., uint256, bool) (which reads/writes coinMeta) with LOCK(cs_spark_wallet) so the annotation reflects the actual contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/spark/sparkwallet.h` around lines 160 - 174, Annotate the coinMeta
declaration with GUARDED_BY(cs_spark_wallet), then update UpdateSpendState(...,
uint256, bool) to acquire LOCK(cs_spark_wallet) before accessing coinMeta,
preserving its existing read/write behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/spark/sparkwallet.h`:
- Around line 160-174: Annotate the coinMeta declaration with
GUARDED_BY(cs_spark_wallet), then update UpdateSpendState(..., uint256, bool) to
acquire LOCK(cs_spark_wallet) before accessing coinMeta, preserving its existing
read/write behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3a987c0d-114b-4e71-b179-218f776bb92c

📥 Commits

Reviewing files that changed from the base of the PR and between e6328be and 87348ae.

📒 Files selected for processing (2)
  • src/spark/sparkwallet.cpp
  • src/spark/sparkwallet.h

@reubenyap
reubenyap merged commit 2eb8480 into master Jul 30, 2026
71 of 99 checks passed
@reubenyap
reubenyap deleted the codex/fix-spark-address-locking branch July 30, 2026 17:06
reubenyap pushed a commit that referenced this pull request Jul 31, 2026
Bring in the six commits master gained since the previous merge:
Mac nap inhibitor (#1867), Spark address state locking (#1879),
prevector destruction backport (#1882), GUI freeze fixes (#1883),
Spark wallet scan/lookup speedups (#1885, #1886).

No conflicts, and no semantic interaction with this branch's changes:
isAddressMine() now takes cs_spark_wallet internally (#1879), which
both SignMessage() call paths acquire after cs_wallet -- the same
order the existing RPC path already established.

Refreshing the merge base also makes the PR diff show this branch's
own 14 files again instead of master's already-merged work.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0131ZL8NntcsaPuYepdwsx2C
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:S This PR changes 10-29 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CSparkWallet address map is read and mutated without cs_spark_wallet (data race)

2 participants