Skip to content

fix: error when block range exceeds in eth filter and logs#6856

Merged
akaladarshi merged 6 commits intomainfrom
akaladarshi/add-block-range-err
Apr 7, 2026
Merged

fix: error when block range exceeds in eth filter and logs#6856
akaladarshi merged 6 commits intomainfrom
akaladarshi/add-block-range-err

Conversation

@akaladarshi
Copy link
Copy Markdown
Collaborator

@akaladarshi akaladarshi commented Apr 6, 2026

Summary of changes

Changes introduced in this pull request:

  • Introduced BlockRangeExceeded error which shows the block range provided in the filter and logs API is more the configured
  • Filter and Logs API return this error

Reference issue to close (if applicable)

Closes #6826

Other information and links

Change checklist

  • I have performed a self-review of my own code,
  • I have made corresponding changes to the documentation. All new code adheres to the team's documentation standards,
  • I have added tests that prove my fix is effective or that my feature works (if possible),
  • I have made sure the CHANGELOG is up-to-date. All user-facing changes should be reflected in this document.

Outside contributions

  • I have read and agree to the CONTRIBUTING document.
  • I have read and agree to the AI Policy document. I understand that failure to comply with the guidelines will lead to rejection of the pull request.

Summary by CodeRabbit

  • Bug Fixes

    • Ethereum filter and logs APIs now return a standardized JSON-RPC error (-32005) with a clear message when a requested block range exceeds the allowed maximum, improving error clarity and consistency.
  • Documentation

    • Changelog updated to document the new block-range limit error and its JSON-RPC code.

@akaladarshi akaladarshi requested a review from a team as a code owner April 6, 2026 12:55
@akaladarshi akaladarshi requested review from hanabi1224 and sudo-shashank and removed request for a team April 6, 2026 12:55
@akaladarshi akaladarshi added the RPC requires calibnet RPC checks to run on CI label Apr 6, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 6, 2026

Walkthrough

Introduces Ethereum-compatible block-range error handling: adds EthErrors::BlockRangeExceeded with JSON-RPC code -32005, replaces string errors with structured errors in block-range parsing, and enforces block-range limits in eth filter and trace filter handlers.

Changes

Cohort / File(s) Summary
Changelog
CHANGELOG.md
Added entry documenting block-range error behavior and code -32005.
Error definitions & tests
src/rpc/methods/eth/errors.rs
Added LIMIT_EXCEEDED_CODE = -32005, EthErrors::BlockRangeExceeded { max, given, message }, limit_exceeded() constructor, RpcErrorData mapping, and unit tests validating code/message conversion.
Filter parsing & tests
src/rpc/methods/eth/filter/mod.rs
Replaced string ensure! failures with EthErrors::limit_exceeded(...); updated tests to downcast to EthErrors::BlockRangeExceeded and assert LIMIT_EXCEEDED_CODE and message contents.
RPC handlers
src/rpc/methods/eth.rs
EthGetLogs::handle preserves BlockRangeExceeded errors while wrapping other parse failures; EthTraceFilter::handle adds explicit block-range limit check and returns BlockRangeExceeded on violations.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant RPC as "RPC Handler\n(EthGetLogs / EthTraceFilter)"
    participant Parser as "Filter Parser\n(parse_block_range)"
    participant Events as "Events Store\n(get_events_for_parsed_filter)"

    Client->>RPC: eth_getLogs / trace_filter request
    RPC->>Parser: parse_eth_filter_spec / parse_block_range
    alt range > max
        Parser-->>RPC: EthErrors::BlockRangeExceeded (error)
        RPC-->>Client: JSON-RPC ServerError (-32005) with message
    else parsed
        Parser-->>RPC: ParsedFilter
        RPC->>Events: get_events_for_parsed_filter(parsed)
        Events-->>RPC: events
        RPC-->>Client: JSON-RPC response (events)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Suggested reviewers

  • sudo-shashank
  • hanabi1224
  • LesnyRumcajs
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: introducing a BlockRangeExceeded error that is returned when the block range exceeds the configured maximum in the eth filter and logs APIs.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 akaladarshi/add-block-range-err
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch akaladarshi/add-block-range-err

Comment @coderabbitai help to get the list of available commands and usage tips.

@akaladarshi akaladarshi force-pushed the akaladarshi/add-block-range-err branch from 7f8bac9 to df123ff Compare April 6, 2026 12:58
Comment thread src/rpc/methods/eth.rs Outdated
Comment thread src/rpc/methods/eth.rs Outdated
Comment thread src/rpc/methods/eth.rs Outdated
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

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 (3)
src/rpc/methods/eth.rs (1)

3164-3172: Preserve all structured ETH errors and keep the source chain.

Line 3171 replaces the original parse error with a fresh anyhow!, so non-range failures lose their cause chain, and any future EthErrors variant returned here will also lose its RPC metadata. Fast-path any EthErrors unchanged and use e.context("failed to parse events for filter") for everything else.

As per coding guidelines, "Use anyhow::Result<T> for most operations and add context with .context() when errors occur".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/rpc/methods/eth.rs` around lines 3164 - 3172, The current map_err
replaces non-range errors with a new anyhow! which drops the source; instead, in
the closure for .parse_eth_filter_spec(&ctx, &eth_filter).map_err(|e| { ... }),
fast-path and return the original error unchanged if it is any EthErrors (not
just BlockRangeExceeded) by detecting downcast_ref::<EthErrors>(), otherwise
return e.context("failed to parse events for filter") so the original source
chain is preserved and non-EthErrors gain context; reference
parse_eth_filter_spec, ctx, eth_filter and EthErrors when locating the code to
update.
src/rpc/methods/eth/errors.rs (1)

21-26: Tighten the public construction API for BlockRangeExceeded.

limit_exceeded() is now public but undocumented, and the public message field lets callers bypass the helper and build inconsistent { max, given, message } combinations. I’d add a doc comment to the helper and derive the display/message from max/given instead of storing it separately.

As per coding guidelines, "Document public functions and structs with doc comments".

Also applies to: 46-52

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/rpc/methods/eth/errors.rs` around lines 21 - 26, BlockRangeExceeded
currently stores a free-form public message and exposes an undocumented public
constructor limit_exceeded(), which allows inconsistent instances; remove the
public message field (make it private/omit it), change the #[error("{message}")]
to derive the display from the numeric fields (e.g., #[error("block range
exceeded: max = {max}, given = {given}")]) so the error text is computed from
max and given, and then either restrict the helper constructor limit_exceeded()
to a narrower visibility (pub(crate) or private) or add a doc comment to it
explaining its use if it must remain public; apply the same change to the other
similar error variant that follows.
CHANGELOG.md (1)

50-50: Polish the changelog sentence for readability and consistency.

The phrase “when block range exceeds in the eth filter and logs API” is a bit awkward. Consider a cleaner wording:

Suggested wording tweak
-- [`#6856`](https://github.com/ChainSafe/forest/pull/6856): Return ethereum compatible error `BlockRangeExceeded` with code `-32005` when block range exceeds in the eth filter and logs API.
+- [`#6856`](https://github.com/ChainSafe/forest/pull/6856): Return Ethereum-compatible `BlockRangeExceeded` (`-32005`) when the requested block range exceeds the configured limit in `eth_filter` and `eth_getLogs`.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@CHANGELOG.md` at line 50, Edit the changelog entry that mentions PR `#6856` to
improve readability: rephrase the sentence about returning the
ethereum-compatible error BlockRangeExceeded (code -32005) so it clearly states
that this error is returned when the requested block range exceeds limits in the
eth_filter and logs APIs; keep the error name `BlockRangeExceeded`, the code
`-32005`, and the PR reference `#6856` intact while making the sentence
grammatically clear and consistent with other changelog entries.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/rpc/methods/eth.rs`:
- Around line 3870-3879: The config allows max_filter_height_range = 0 but
trace_filter treats 0 as "unlimited" while parse_block_range enforces a hard
zero cap; fix by validating the deserialized config to reject 0 (require
positive integer) or make trace_filter apply the same sentinel handling as
parse_block_range; specifically update the config validation code where
max_filter_height_range is deserialized (and any initialization of
ctx.eth_event_handler.max_filter_height_range) to error on 0, or alternatively
change the check in trace_filter (the block using
ctx.eth_event_handler.max_filter_height_range and the comparison with
to_block/from_block) to treat 0 the same as parse_block_range’s behavior so both
eth_getLogs/eth_newFilter and trace_filter are consistent.

---

Nitpick comments:
In `@CHANGELOG.md`:
- Line 50: Edit the changelog entry that mentions PR `#6856` to improve
readability: rephrase the sentence about returning the ethereum-compatible error
BlockRangeExceeded (code -32005) so it clearly states that this error is
returned when the requested block range exceeds limits in the eth_filter and
logs APIs; keep the error name `BlockRangeExceeded`, the code `-32005`, and the
PR reference `#6856` intact while making the sentence grammatically clear and
consistent with other changelog entries.

In `@src/rpc/methods/eth.rs`:
- Around line 3164-3172: The current map_err replaces non-range errors with a
new anyhow! which drops the source; instead, in the closure for
.parse_eth_filter_spec(&ctx, &eth_filter).map_err(|e| { ... }), fast-path and
return the original error unchanged if it is any EthErrors (not just
BlockRangeExceeded) by detecting downcast_ref::<EthErrors>(), otherwise return
e.context("failed to parse events for filter") so the original source chain is
preserved and non-EthErrors gain context; reference parse_eth_filter_spec, ctx,
eth_filter and EthErrors when locating the code to update.

In `@src/rpc/methods/eth/errors.rs`:
- Around line 21-26: BlockRangeExceeded currently stores a free-form public
message and exposes an undocumented public constructor limit_exceeded(), which
allows inconsistent instances; remove the public message field (make it
private/omit it), change the #[error("{message}")] to derive the display from
the numeric fields (e.g., #[error("block range exceeded: max = {max}, given =
{given}")]) so the error text is computed from max and given, and then either
restrict the helper constructor limit_exceeded() to a narrower visibility
(pub(crate) or private) or add a doc comment to it explaining its use if it must
remain public; apply the same change to the other similar error variant that
follows.
🪄 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: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b1186afe-3b75-44cf-b3f3-81a90db02674

📥 Commits

Reviewing files that changed from the base of the PR and between e7c2f0f and df123ff.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • src/rpc/methods/eth.rs
  • src/rpc/methods/eth/errors.rs
  • src/rpc/methods/eth/filter/mod.rs

Comment thread src/rpc/methods/eth.rs Outdated
@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 6, 2026

Codecov Report

❌ Patch coverage is 79.71014% with 14 lines in your changes missing coverage. Please review.
✅ Project coverage is 64.00%. Comparing base (1892606) to head (6ea3215).
⚠️ Report is 1 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
src/rpc/methods/eth.rs 44.44% 7 Missing and 3 partials ⚠️
src/rpc/methods/eth/filter/mod.rs 84.61% 1 Missing and 3 partials ⚠️
Additional details and impacted files
Files with missing lines Coverage Δ
src/rpc/methods/eth/errors.rs 69.38% <100.00%> (+69.38%) ⬆️
src/rpc/methods/eth/filter/mod.rs 88.33% <84.61%> (-0.17%) ⬇️
src/rpc/methods/eth.rs 65.46% <44.44%> (-0.10%) ⬇️

... and 17 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 1892606...6ea3215. Read the comment docs.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@akaladarshi akaladarshi force-pushed the akaladarshi/add-block-range-err branch from dbb5cd4 to 544c3c7 Compare April 6, 2026 16:09
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
src/rpc/methods/eth/errors.rs (2)

21-26: Variant structure looks good, but max and given fields are unused outside construction.

The max and given fields are stored in the enum but only used during limit_exceeded() to build the message. The RpcErrorData methods only access message. This is fine if the fields are retained for debugging/logging or potential future use (e.g., structured error data), but if they serve no other purpose, consider simplifying to just store the message.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/rpc/methods/eth/errors.rs` around lines 21 - 26, The BlockRangeExceeded
enum variant stores max and given but they're never accessed outside
construction; simplify by removing those unused fields and only storing the
generated message (or, alternatively, use them in RpcErrorData or
limit_exceeded()); update the BlockRangeExceeded definition in
src/rpc/methods/eth/errors.rs to only include message (or keep fields but expose
them via RpcErrorData accessors), and adjust any construction sites and the
limit_exceeded() helper to build the message from provided values before
constructing the variant so RpcErrorData and callers continue to read message
correctly.

46-52: Consider adding a doc comment for the public constructor.

Per coding guidelines, public functions should be documented. A brief doc comment would help clarify the purpose and parameters.

📝 Suggested doc comment
+    /// Create a new BlockRangeExceeded error indicating the requested block range
+    /// exceeds the configured maximum.
     pub fn limit_exceeded(max_block_range: u64, given: u64) -> Self {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/rpc/methods/eth/errors.rs` around lines 46 - 52, The public constructor
limit_exceeded (which builds the BlockRangeExceeded variant) lacks a doc
comment; add a brief /// doc comment above pub fn limit_exceeded explaining its
purpose (constructs a BlockRangeExceeded error for when a requested block range
is larger than allowed), document the parameters max_block_range and given and
describe the resulting error message format, and mention that it returns
Self::BlockRangeExceeded so callers know what error is produced.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/rpc/methods/eth/errors.rs`:
- Around line 21-26: The BlockRangeExceeded enum variant stores max and given
but they're never accessed outside construction; simplify by removing those
unused fields and only storing the generated message (or, alternatively, use
them in RpcErrorData or limit_exceeded()); update the BlockRangeExceeded
definition in src/rpc/methods/eth/errors.rs to only include message (or keep
fields but expose them via RpcErrorData accessors), and adjust any construction
sites and the limit_exceeded() helper to build the message from provided values
before constructing the variant so RpcErrorData and callers continue to read
message correctly.
- Around line 46-52: The public constructor limit_exceeded (which builds the
BlockRangeExceeded variant) lacks a doc comment; add a brief /// doc comment
above pub fn limit_exceeded explaining its purpose (constructs a
BlockRangeExceeded error for when a requested block range is larger than
allowed), document the parameters max_block_range and given and describe the
resulting error message format, and mention that it returns
Self::BlockRangeExceeded so callers know what error is produced.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 993b3ee7-8201-4269-b43b-9cae6642c358

📥 Commits

Reviewing files that changed from the base of the PR and between dbb5cd4 and 544c3c7.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • src/rpc/methods/eth.rs
  • src/rpc/methods/eth/errors.rs
  • src/rpc/methods/eth/filter/mod.rs
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/rpc/methods/eth.rs

@akaladarshi akaladarshi enabled auto-merge April 6, 2026 16:14
@akaladarshi akaladarshi added this pull request to the merge queue Apr 7, 2026
Merged via the queue into main with commit 733c7fe Apr 7, 2026
55 checks passed
@akaladarshi akaladarshi deleted the akaladarshi/add-block-range-err branch April 7, 2026 10:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

RPC requires calibnet RPC checks to run on CI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Make block range handling more strict in filter APIs

2 participants