Skip to content

perf(hashes): SIMD-batched SipHash-2-4 for BIP158 filter matching#845

Merged
xdustinface merged 1 commit into
devfrom
perf/siphash
Jul 8, 2026
Merged

perf(hashes): SIMD-batched SipHash-2-4 for BIP158 filter matching#845
xdustinface merged 1 commit into
devfrom
perf/siphash

Conversation

@ZocoLini

@ZocoLini ZocoLini commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator

Adds siphash() (scalar one-shot) and siphash_batch::() (SIMD: AVX2 12-lane on x86_64, NEON 12-message on aarch64, with a scalar fallback), bit-identical to the reference and verified against the official test vectors on both architectures.

Wires it into BIP158 through FilterQuery (elements bucketed by length once and reused): both filter matching (match_any/match_all) and filter building (GcsFilterWriter) now batch-hash the whole element set instead of one element at a time. The hot path when a wallet scans block filters against its watched scripts.

Note on the siphash HashEngine:

The engine form of siphash (siphash24::HashEngine, its hash_with_keys / hash_to_u64_with_keys helpers, and the io::Write impl) is unused anywhere in this repo — every call site goes through the free siphash() / siphash_batch()
functions. It's dead internally, but it's public API and matches the uniform "one HashEngine per hash" pattern, so this PR leaves it in place (removing it would be a breaking change). Flagging it in case we later want to slim the crate's public surface.

Longer term, batching would be cleaner as a trait — a "hash N equal-length inputs" method that any hash engine can implement — instead of a standalone siphash_batch function. Callers could be generic over it, and future SIMD work (other hashes, or an AVX-512 path) would reuse shared machinery instead of being duplicated per algorithm. Out of scope here, just worth noting

Summary by CodeRabbit

  • New Features
    • Added a SipHash benchmark to compare single-item vs batch hashing.
  • Performance
    • Improved compact-filter matching by pre-bucketing match queries and reusing prepared query data during wallet/block attribution.
    • Refactored SipHash to add explicit scalar and const-generic batch APIs with architecture-optimized paths.
  • Bug Fixes
    • Preserved existing compact-filter matching rules and “match-any” error handling while improving efficiency.
  • Tests
    • Updated and extended SipHash and compact-filter matching tests for the new query and batch hashing behavior.

@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@ZocoLini, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 35 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 17b402e2-8ea9-4a88-8ccb-0690638148dd

📥 Commits

Reviewing files that changed from the base of the PR and between fb9f3e4 and c8bafdc.

📒 Files selected for processing (8)
  • dash-spv/src/sync/filters/manager.rs
  • dash/src/bip152.rs
  • dash/src/bip158.rs
  • hashes/Cargo.toml
  • hashes/benches/hashes.rs
  • hashes/benches/siphash.rs
  • hashes/src/siphash24.rs
  • key-wallet-manager/src/matching.rs
📝 Walkthrough

Walkthrough

This PR adds a batched SipHash24 implementation and switches compact-filter matching to a pre-bucketed FilterQuery input. It also updates SipHash consumers, benchmarks, and tests to use the new APIs.

Changes

SipHash Core and Batching

Layer / File(s) Summary
Scalar SipRound refactor and bip152 usage
hashes/src/siphash24.rs, dash/src/bip152.rs
Adds sip_round_scalar and uses it in HashEngine; ShortId::with_siphash_keys switches to siphash24::siphash.
Public siphash/siphash_batch API and SIMD kernels
hashes/src/siphash24.rs
Adds siphash and siphash_batch, with AVX2/NEON paths, scalar fallback, and batch-vs-scalar tests.
Benchmark harness for siphash
hashes/benches/hashes.rs, hashes/benches/siphash.rs, hashes/Cargo.toml
Removes the old bench_siphash24, adds a dedicated siphash benchmark, and registers the new bench target.

FilterQuery-Based Compact Filter Matching

Layer / File(s) Summary
FilterQuery type and hash_query
dash/src/bip158.rs
Adds FilterQuery with bucketed storage and GcsFilter::hash_query for batched matching.
BlockFilter/GcsFilter matcher and writer updates
dash/src/bip158.rs
Changes matcher signatures to &FilterQuery, updates GcsFilterWriter to accumulate and hash FilterQuery, and adjusts tests.
dash-spv and key-wallet-manager consumers
dash-spv/src/sync/filters/manager.rs, key-wallet-manager/src/matching.rs
Builds reusable FilterQuery values before repeated filter checks.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • dashpay/rust-dashcore#781: Both PRs modify compact-filter matching to reuse prebuilt scriptPubKey inputs in dash-spv/src/sync/filters/manager.rs and related filter-matching code.

Suggested labels: ready-for-review

Suggested reviewers: xdustinface

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: SIMD-batched SipHash-2-4 used for BIP158 filter matching and related performance work.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/siphash

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.

@codecov

codecov Bot commented Jul 6, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.68874% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 73.43%. Comparing base (647fa98) to head (c8bafdc).
⚠️ Report is 2 commits behind head on dev.

Files with missing lines Patch % Lines
hashes/src/siphash24.rs 96.37% 7 Missing ⚠️
dash/src/bip158.rs 96.90% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #845      +/-   ##
==========================================
+ Coverage   73.34%   73.43%   +0.08%     
==========================================
  Files         324      324              
  Lines       72923    73150     +227     
==========================================
+ Hits        53486    53715     +229     
+ Misses      19437    19435       -2     
Flag Coverage Δ
core 77.08% <96.57%> (+0.13%) ⬆️
ffi 45.65% <ø> (+0.16%) ⬆️
rpc 20.00% <ø> (ø)
spv 90.61% <100.00%> (+0.02%) ⬆️
wallet 72.97% <100.00%> (+<0.01%) ⬆️
Files with missing lines Coverage Δ
dash-spv/src/sync/filters/manager.rs 97.57% <100.00%> (+<0.01%) ⬆️
dash/src/bip152.rs 80.93% <100.00%> (ø)
key-wallet-manager/src/matching.rs 95.86% <100.00%> (+0.03%) ⬆️
dash/src/bip158.rs 94.42% <96.90%> (-0.39%) ⬇️
hashes/src/siphash24.rs 93.76% <96.37%> (-0.15%) ⬇️

... and 21 files with indirect coverage changes

@ZocoLini ZocoLini force-pushed the perf/siphash branch 4 times, most recently from f1c14f5 to 9747d1f Compare July 6, 2026 15:00
@ZocoLini ZocoLini requested a review from xdustinface July 6, 2026 15:08
@ZocoLini ZocoLini marked this pull request as ready for review July 6, 2026 15:08
@xdustinface

Copy link
Copy Markdown
Collaborator

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
dash/src/bip158.rs (1)

392-399: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

push uses expect in library code.

The try_into().expect(...) calls are provably infallible here (guarded by the len() match), but per coding guidelines library code should avoid expect(). Since the invariant is local to this match, the risk is only that a future edit to the arm/length constants silently reintroduces a panic. Optional to harden.

As per coding guidelines: "Avoid unwrap() and expect() in library code; use proper error types".

🤖 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 `@dash/src/bip158.rs` around lines 392 - 399, The Bip158::push method uses
expect in library code for the 25-byte and 23-byte arms, which should be avoided
even if the match currently makes the conversion infallible. Replace the
try_into().expect(...) calls with a non-panicking conversion path in push, or
otherwise make the length-to-type routing explicit so the invariant is enforced
without expect. Keep the fix localized to push and the p2pkh/p2sh handling so
future changes to the length buckets do not reintroduce a panic.

Source: Coding guidelines

🤖 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.

Inline comments:
In `@hashes/src/siphash24.rs`:
- Around line 334-366: The `siphash_batch` public API only validates `out.len()
>= inputs.len()` with `debug_assert!`, so release builds can reach the unsafe
AVX2/NEON paths and write past the end of `out`. Replace that check in
`siphash_batch` with a runtime `assert!` (or equivalent always-on validation)
before calling `hash_many_wide_avx2`, `hash_many_neon_wide`, or `siphash_each`,
so undersized output buffers fail deterministically in all build modes.

---

Nitpick comments:
In `@dash/src/bip158.rs`:
- Around line 392-399: The Bip158::push method uses expect in library code for
the 25-byte and 23-byte arms, which should be avoided even if the match
currently makes the conversion infallible. Replace the try_into().expect(...)
calls with a non-panicking conversion path in push, or otherwise make the
length-to-type routing explicit so the invariant is enforced without expect.
Keep the fix localized to push and the p2pkh/p2sh handling so future changes to
the length buckets do not reintroduce a panic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6f1ebe5f-249f-4797-ae34-e8e52917a35a

📥 Commits

Reviewing files that changed from the base of the PR and between 647fa98 and 9747d1f.

📒 Files selected for processing (8)
  • dash-spv/src/sync/filters/manager.rs
  • dash/src/bip152.rs
  • dash/src/bip158.rs
  • hashes/Cargo.toml
  • hashes/benches/hashes.rs
  • hashes/benches/siphash.rs
  • hashes/src/siphash24.rs
  • key-wallet-manager/src/matching.rs

Comment thread hashes/src/siphash24.rs Outdated

@xdustinface xdustinface left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice! Have a look at the one comment i posted.

Comment thread dash/src/bip158.rs Outdated
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 7, 2026
@xdustinface xdustinface merged commit 832bab2 into dev Jul 8, 2026
36 of 37 checks passed
@xdustinface xdustinface deleted the perf/siphash branch July 8, 2026 13:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants