← Back to Pull requests

fix(bloom): guard contains and add against a zero-capacity filter #1635

Merged
valentynkit merged 3 files (102 lines) on Jul 21, 2026 13:46 UTC
View on GitHub
valentynkit valentynkit commented on Jun 28, 2026 10:19 UTC
Author

Intent

Closes #1633. A gossip PullRequest can carry a bloom filter whose keys list is non-empty while its bit array has zero capacity. Building the pull response calls Bloom.contains on that filter, which reaches pos:

return hashAtIndex(bytes, hash_index) % @as(u64, self.bits.capacity());

When capacity() is zero this divides by zero, so one unauthenticated UDP packet aborts the node.

The zero-capacity state is reachable from the wire. BitVec(T) stores bits as an optional slice with a separate len, and keys deserializes independently, so keys = [k] with bits = null and len = 0 is a valid encoding. Agave avoids this because its Bloom checks bits.is_empty() in contains and add and uses checked_rem in pos; Sig's Bloom omits that guard.

Implementation

Return early from contains (false) and add (no-op) when the filter has no bits, before any key is hashed. A zero-capacity filter has no set bits, so it matches nothing, which is what false already means on the response path. The guard goes in contains and add rather than pos because a guarded pos would still hand an index to bits.isSet, which asserts index < bit_length on the empty bitset. Putting it in the primitive also covers every caller, not just the gossip path.

Ramifications

The behavior change is limited to zero-capacity filters: contains returns false and add is a no-op instead of panicking. Filters that have capacity are untouched. The bug itself is a remote, unauthenticated, single-packet crash, with no amplification (the pull response is already bounded by the filter mask and max_number_values) and no memory unsafety.

A defense-in-depth option is to also reject such a filter in GossipMessage.sanitize (the empty .PullRequest arm), as #1565 does for EpochSlots, which would drop the packet and count it as invalid. I kept this PR at the bloom layer to match Agave; I can add the sanitize check as well if you'd prefer.

Tests

test "zero-capacity filter does not divide by zero" in src/bloom/bloom.zig builds a filter with n_bits = 0 and one key, then exercises contains and add. It aborts in pos without the guard and passes with it.

Diff: 102 lines (+102 / -0) across 3 files Reviewer: ajw221 Review duration: 33326m
All Vouch review confidence checks passed
Residual risk 0.09 = Change Risk (0.34) × (1 − Review Confidence (0.74)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.34 · 102 lines diff across 3 files
0.34
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.50 · 5 substantive comment(s)
0.50
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
73%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.277
Real PR Conversation Timeline
13 items
ajw221 ajw221 commented on code on Jun 30, 2026 15:47 UTC
Code Review
src/bloom/bloom.zig:1
@@ -183,6 +185,15 @@ test "serialized bytes equal rust (one key)" {
     try testing.expectEqualSlices(u8, &rust_bytes, bytes[0..bytes.len]);
 }
 
+test "zero-capacity filter does not divide by zero" {
+    var bloom = try Bloom.init(testing.allocator, 0, null);
+    defer bloom.deinit();
+
+    try bloom.addKey(1);
+    try testing.expect(!bloom.contains(&[_]u8{ 1, 2, 3 }));
+    bloom.add(&[_]u8{ 1, 2, 3 });
+}
+

while this test _does_ cover the target codepath, I think it's worth adding another specifically around the bincode deserialization that would most likely be hit on a live validator run

ajw221 ajw221 requested changes on Jun 30, 2026 15:47 UTC
Changes Requested Reviewer

Requested changes.

valentynkit valentynkit commented on code on Jun 30, 2026 16:02 UTC
Code Review
src/bloom/bloom.zig:1
@@ -183,6 +185,15 @@ test "serialized bytes equal rust (one key)" {
     try testing.expectEqualSlices(u8, &rust_bytes, bytes[0..bytes.len]);
 }
 
+test "zero-capacity filter does not divide by zero" {
+    var bloom = try Bloom.init(testing.allocator, 0, null);
+    defer bloom.deinit();
+
+    try bloom.addKey(1);
+    try testing.expect(!bloom.contains(&[_]u8{ 1, 2, 3 }));
+    bloom.add(&[_]u8{ 1, 2, 3 });
+}
+

Thanks for feedback!
Will create follow up commit to handle this.

valentynkit valentynkit commented on code on Jun 30, 2026 20:53 UTC
Code Review
src/bloom/bloom.zig:1
@@ -183,6 +185,15 @@ test "serialized bytes equal rust (one key)" {
     try testing.expectEqualSlices(u8, &rust_bytes, bytes[0..bytes.len]);
 }
 
+test "zero-capacity filter does not divide by zero" {
+    var bloom = try Bloom.init(testing.allocator, 0, null);
+    defer bloom.deinit();
+
+    try bloom.addKey(1);
+    try testing.expect(!bloom.contains(&[_]u8{ 1, 2, 3 }));
+    bloom.add(&[_]u8{ 1, 2, 3 });
+}
+

Added deserialization tests at three layers (defense in depth):

  • the filter itself

  • a full PullRequest GossipMessage

  • filterSignedGossipDatas.
  • Each panics in pos without the guard.

    Still getting familiar with Sig's conventions, so if this is more coverage than you'd want here, let me know and I'll trim.

    ajw221 ajw221 commented on code on Jul 14, 2026 17:12 UTC
    Code Review
    src/bloom/bloom.zig:1
    @@ -60,6 +61,7 @@ pub const Bloom = struct {
         }
     
         pub fn contains(self: *const Bloom, key: []const u8) bool {
    +        if (self.bits.capacity() == 0) return false;

    I'm just now realizing if self.keys is empty _and_ capacity is 0, this will return true, which seems like a pre-existing bug we may want to account for here now that we're checking the capacity

    ajw221 ajw221 commented on code on Jul 14, 2026 17:36 UTC
    Code Review
    src/gossip/pull_response.zig:1
    @@ -147,3 +147,39 @@ test "gossip.pull_response: test filtering values works" {
             return err;
         };
     }
    +
    +test "gossip.pull_response: zero-capacity filter does not divide by zero" {
    +    // a filter with keys but a zero-length bit array makes the response call
    +    // contains on a zero-capacity filter
    +    var prng = std.Random.DefaultPrng.init(std.testing.random_seed);
    +    const random = prng.random();
    +
    +    var gossip_table = try GossipTable.init(std.testing.allocator, std.testing.allocator);
    +    defer gossip_table.deinit();
    +
    +    const kp = try KeyPair.generateDeterministic([_]u8{1} ** 32);
    +    for (0..8) |_| {
    +        const id = Pubkey.initRandom(random);
    +        var legacy_contact_info = LegacyContactInfo.default(id);
    +        legacy_contact_info.wallclock = 0;
    +        const value = SignedGossipData.initSigned(&kp, .{
    +            .LegacyContactInfo = legacy_contact_info,
    +        });
    +        _ = try gossip_table.insert(value, 0);
    +    }
    +
    +    // mask_bits 0 matches every entry, so the filter is queried against them
    +    var filter = try GossipPullFilter.init(std.testing.allocator);
    +    defer filter.deinit();
    +    try filter.filter.addKey(1);
    +
    +    var result = try filterSignedGossipDatas(
    +        random,
    +        std.testing.allocator,
    +        &gossip_table,
    +        &filter,
    +        0,
    +        100,
    +    );
    +    defer result.deinit();

    Currently the test ensures a panic didn't occur, but isn't ensuring this is functioning as intended. I think adding the assertion here would close the loop in terms of ensuring this test is full testing what it needs.

        defer result.deinit();
        
        try std.testing.expectEqual(@as(usize, 8), result.items.len);
    

    ajw221 ajw221 requested changes on Jul 14, 2026 17:37 UTC
    Changes Requested Reviewer

    some small nits, otherwise looks good!

    valentynkit valentynkit commented on code on Jul 14, 2026 19:48 UTC
    Code Review
    src/gossip/pull_response.zig:1
    @@ -147,3 +147,39 @@ test "gossip.pull_response: test filtering values works" {
             return err;
         };
     }
    +
    +test "gossip.pull_response: zero-capacity filter does not divide by zero" {
    +    // a filter with keys but a zero-length bit array makes the response call
    +    // contains on a zero-capacity filter
    +    var prng = std.Random.DefaultPrng.init(std.testing.random_seed);
    +    const random = prng.random();
    +
    +    var gossip_table = try GossipTable.init(std.testing.allocator, std.testing.allocator);
    +    defer gossip_table.deinit();
    +
    +    const kp = try KeyPair.generateDeterministic([_]u8{1} ** 32);
    +    for (0..8) |_| {
    +        const id = Pubkey.initRandom(random);
    +        var legacy_contact_info = LegacyContactInfo.default(id);
    +        legacy_contact_info.wallclock = 0;
    +        const value = SignedGossipData.initSigned(&kp, .{
    +            .LegacyContactInfo = legacy_contact_info,
    +        });
    +        _ = try gossip_table.insert(value, 0);
    +    }
    +
    +    // mask_bits 0 matches every entry, so the filter is queried against them
    +    var filter = try GossipPullFilter.init(std.testing.allocator);
    +    defer filter.deinit();
    +    try filter.filter.addKey(1);
    +
    +    var result = try filterSignedGossipDatas(
    +        random,
    +        std.testing.allocator,
    +        &gossip_table,
    +        &filter,
    +        0,
    +        100,
    +    );
    +    defer result.deinit();

    Thanks, applied the fix.

    valentynkit valentynkit commented on code on Jul 14, 2026 19:51 UTC
    Code Review
    src/bloom/bloom.zig:1
    @@ -60,6 +61,7 @@ pub const Bloom = struct {
         }
     
         pub fn contains(self: *const Bloom, key: []const u8) bool {
    +        if (self.bits.capacity() == 0) return false;

    Yeah, i missed the case when keys are empty.
    Agave contains returns false when keys.isempty || bits.isempty.
    Extended the guard to cover empty keys too.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Jul 15, 2026 01:06 UTC
    Reviewer

    Pull request overview

    Fixes a remote crash vector in the Bloom filter used by gossip pull requests by preventing modulo-by-zero when a filter has keys but a zero-capacity bitset (reachable via wire encoding).

    Changes:

  • Add early-return guards in Bloom.contains and Bloom.add when the bitset has zero capacity (and treat “no keys” as matching nothing).

  • Add Bloom-level tests covering zero-capacity bitsets, deserialization of that state, and “no keys” behavior.

  • Add gossip-layer regression tests ensuring pull-request deserialization and pull-response filtering don’t crash on zero-capacity filters.
  • Reviewed changes

    Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

    | File | Description |
    | ---- | ----------- |
    | src/bloom/bloom.zig | Adds zero-capacity (and empty-keys) guards to prevent divide-by-zero and asserts behavior via new tests. |
    | src/gossip/pull_response.zig | Adds regression test ensuring pull response filtering won’t panic on a zero-capacity Bloom filter. |
    | src/gossip/message.zig | Adds regression test ensuring a deserialized PullRequest with a zero-capacity filter does not crash and behaves safely. |

    ---

    💡 <a href="/Syndica/sig/new/main?filename=.github/instructions/*.instructions.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add Copilot custom instructions</a> for smarter, more guided reviews. <a href="https://docs.github.com/en/copilot/customizing-copilot/adding-repository-custom-instructions-for-github-copilot" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn how to get started</a>.

    ajw221 ajw221 approved these changes on Jul 20, 2026 19:45 UTC
    Approved Reviewer

    Approved these changes.

    dnut dnut approved these changes on Jul 20, 2026 19:47 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    valentynkit valentynkit
    Labels
    risk: low confidence: 74.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 33.7% (LOW) · Higher = larger blast radius
    33.7%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 74.0% · Lower = rushed or shallow review
    74.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 8.8% · Safe to merge
    8.8%
    Repository