Skip to content

refactor(jsonrpc): centralize block selector parsing into JsonRpcApiUtil#11

Open
0xbigapple wants to merge 2 commits intodevelopfrom
refactor/jsonrpc-block-selector
Open

refactor(jsonrpc): centralize block selector parsing into JsonRpcApiUtil#11
0xbigapple wants to merge 2 commits intodevelopfrom
refactor/jsonrpc-block-selector

Conversation

@0xbigapple
Copy link
Copy Markdown
Owner

@0xbigapple 0xbigapple commented Apr 9, 2026

What does this PR do?
Centralize block tag and number resolution into JsonRpcApiUtil to eliminate code duplication, remove Wallet's reverse dependency on the JSON-RPC layer, and simplify complex logic in LogFilterWrapper.

Why are these changes required?
JSON-RPC block selector parsing (tag-to-block-number resolution) is scattered across three layers (Wallet, JsonRpcApiUtil, TronJsonRpcImpl) with duplicated, inconsistent logic. The core Wallet class reverse-depends on the jsonrpc API layer for tag constants, and a -1 sentinel value for "latest" forces every caller to re-interpret results differently. This makes the code fragile and hard to reason about.

This PR has been tested by:

  • Unit Tests
  • Manual Testing

Follow up

Extra details


Summary by cubic

Centralized JSON‑RPC block selector parsing into JsonRpcApiUtil, unified tag handling, and simplified log filter ranges. Resolves “latest” via wallet.getNowBlock() to avoid race conditions.

  • Refactors
    • Added JsonRpcApiUtil.isBlockTag, parseBlockTag, and parseBlockNumber; moved tag constants and errors (including safe) into JsonRpcApiUtil.
    • TronJsonRpcImpl now delegates all block parsing; eth_getBlock* use a shared resolver; state reads (getTrxBalance, getStorageAt, getABIOfSmartContract, eth_call) only accept "latest".
    • Removed Wallet’s JSON‑RPC helpers and the "-1 means latest" sentinel; added getHeadBlockNum().
    • Reworked LogFilterWrapper: fromBlock="latest" is a snapshot; toBlock="latest" is open-ended (Long.MAX_VALUE); consistent range validation.
    • Tests: expanded parsing coverage (including rejecting safe), and added LogFilterWrapperStrategyTest.

Written for commit 0b375d5. Summary will update on new commits.

Summary by CodeRabbit

  • Refactor
    • Consolidated and standardized JSON-RPC block identifier parsing across API endpoints for improved consistency.
    • Enhanced block tag recognition and error handling with clearer messages for unsupported or invalid block parameters.
    • Improved block filtering logic for more reliable range-based queries.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 9, 2026

📝 Walkthrough

Walkthrough

This PR refactors JSON-RPC block identifier parsing by centralizing validation and parsing logic in JsonRpcApiUtil, removing equivalent methods from Wallet, and updating RPC service implementations and filters to use the new standardized APIs.

Changes

Cohort / File(s) Summary
Core Block Identifier APIs
framework/src/main/java/org/tron/core/Wallet.java, framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java
Removed Wallet.getByJsonBlockId() and Wallet.getTransactionsByJsonBlockId() methods; centralized block tag constants and parsing into JsonRpcApiUtil with new public APIs: isBlockTag(), parseBlockTag(), and parseBlockNumber(). Added Wallet.getHeadBlockNum() to expose chain head block number.
RPC Service Updates
framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java, framework/src/main/java/org/tron/core/services/jsonrpc/filters/LogFilterWrapper.java
Refactored RPC methods and log filter block range normalization to use the new JsonRpcApiUtil parsing APIs instead of removed Wallet methods. Introduced requireLatestBlockTag() helper to enforce tag restrictions. Updated block selector handling to parse numeric values and validate tags through standardized exception paths.
Test Coverage
framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java, framework/src/test/java/org/tron/core/services/jsonrpc/LogFilterWrapperStrategyTest.java
Replaced testGetByJsonBlockId with testBlockTagParsing to validate new JsonRpcApiUtil helpers. Added comprehensive new test class LogFilterWrapperStrategyTest covering four block range normalization strategies and error conditions for inverted ranges.

Sequence Diagram(s)

sequenceDiagram
    participant RPC as RPC Method
    participant Util as JsonRpcApiUtil
    participant Wallet as Wallet
    
    RPC->>Util: parseBlockNumber(blockIdentifier)
    
    alt Is Block Tag
        Util->>Util: isBlockTag(identifier)?
        Util->>Util: parseBlockTag(tag, wallet)
        
        alt Valid Tag (latest/earliest/finalized)
            Util->>Wallet: getHeadBlockNum() or getNowBlock()
            Wallet-->>Util: blockNumber
        else Invalid Tag (pending/safe)
            Util-->>RPC: JsonRpcInvalidParamsException
        end
        Util-->>RPC: blockNumber
        
    else Hex Number
        Util->>Util: ByteArray.jsonHexToLong(identifier)
        Util-->>RPC: blockNumber
        
    else Invalid
        Util-->>RPC: JsonRpcInvalidParamsException
    end
    
    RPC->>Wallet: getBlockByNum(blockNumber)
    Wallet-->>RPC: Block
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 The block tags hop and parse with care,
From latest hops to blocks so rare,
No pending dreams in JSON streams,
Just earliest, finalized, and latest gleams! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.28% 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 pull request title accurately describes the main change: centralizing block selector parsing into JsonRpcApiUtil, which is the primary refactoring objective.
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 refactor/jsonrpc-block-selector

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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 and usage tips.

@0xbigapple 0xbigapple requested a review from Copilot April 9, 2026 07:14
@0xbigapple
Copy link
Copy Markdown
Owner Author

0xbigapple commented Apr 9, 2026

@coderabbitai review this pr

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 9, 2026

Tip

For best results, initiate chat on the files or code changes.

@0xbigapple, it looks like your message is just a mention without a specific request. How can I help you with this PR? Here are a few things I can do:

  • 🔍 Review the PR — Perform a full review of the changes.
  • 📋 Summarize changes — Regenerate or explain the PR summary.
  • 🧪 Suggest tests — Recommend additional test cases for the refactored logic.
  • 🐛 Analyze specific code — Deep-dive into any particular file or function.
  • 📝 Create issues — Open follow-up issues for anything out of scope.

Just let me know what you need!

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 9, 2026

@0xbigapple, I'll kick off a full review of this PR right away! I'll analyze the centralization of block selector parsing into JsonRpcApiUtil, the removal of Wallet's reverse dependency on the JSON-RPC layer, the reworked LogFilterWrapper strategies, and the test coverage. Results will be posted shortly.

✅ Actions performed

Full review triggered.

Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 6 files

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Centralizes JSON-RPC block selector (tag/number) parsing into JsonRpcApiUtil to reduce duplication and remove Wallet’s reverse dependency on the JSON-RPC layer, while simplifying LogFilterWrapper’s block-range normalization.

Changes:

  • Moved block tag constants and tag/number parsing into JsonRpcApiUtil (isBlockTag, parseBlockTag, parseBlockNumber).
  • Refactored LogFilterWrapper to use explicit “strategy” handling for from/to block semantics instead of -1 sentinel logic.
  • Updated TronJsonRpcImpl and tests to use the new centralized parsing and constants; removed JSON-RPC-specific block selector helpers from Wallet.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java Adds canonical block tag constants and parsing helpers to centralize block selector resolution.
framework/src/main/java/org/tron/core/services/jsonrpc/filters/LogFilterWrapper.java Rewrites from/to block normalization into explicit strategies, using centralized parsing helpers.
framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java Switches endpoints from Wallet block-selector helpers to centralized parsing and adds requireLatestBlockTag() helper.
framework/src/main/java/org/tron/core/Wallet.java Removes JSON-RPC-specific block selector APIs and adds getHeadBlockNum() accessor.
framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java Updates block selector/tag parsing tests to exercise JsonRpcApiUtil parsing directly.
framework/src/test/java/org/tron/core/services/jsonrpc/LogFilterWrapperStrategyTest.java Adds unit tests validating LogFilterWrapper strategy behavior against develop-branch semantics.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8f6f59aafc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copy link
Copy Markdown

@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: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java`:
- Around line 557-563: parseBlockNumber currently lets ByteArray.jsonHexToLong
throw raw parsing exceptions; change it so any failure to parse a non-tag block
string is normalized to JsonRpcInvalidParamsException with the BLOCK_NUM_ERROR
code. Keep the existing isBlockTag -> parseBlockTag path unchanged, but wrap the
ByteArray.jsonHexToLong(blockNumOrTag) call in a try/catch that catches
parsing/number format exceptions and rethrows new
JsonRpcInvalidParamsException(BLOCK_NUM_ERROR) (or the project’s equivalent
constant) so no raw NumberFormatException or "Incorrect hex syntax" leaks out.
- Around line 531-535: JsonRpcApiUtil currently dereferences
wallet.getNowBlock() for the LATEST_STR branch, which can be null; update the
LATEST_STR handling in JsonRpcApiUtil to null-check wallet.getNowBlock() (and
its getBlockHeader()/getRawData() chain) and, if null, return/throw a controlled
JSON-RPC error response instead of letting an NPE bubble up; specifically modify
the branch that uses LATEST_STR and wallet.getNowBlock() to detect an
empty/unready block store and return a meaningful JSON-RPC error (using the
existing rpc error/exception type your codebase uses) so callers receive a
proper error rather than a null-pointer.

In `@framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java`:
- Around line 308-320: Replace direct ByteArray.hexToBigInteger(...).longValue()
parsing in the four branches with the centralized parser: call
JsonRpcApiUtil.parseBlockNumber(blockNumOrTag, wallet) instead of
ByteArray.hexToBigInteger usage so oversized or malformed selectors are rejected
consistently; locate the occurrences in TronJsonRpcImpl where blockNumOrTag is
handled (currently using JsonRpcApiUtil.isBlockTag/parseBlockTag in some
branches and ByteArray.hexToBigInteger in others) and swap those ByteArray-based
parses to JsonRpcApiUtil.parseBlockNumber, keeping the same exception behavior
(throw JsonRpcInvalidParamsException(BLOCK_NUM_ERROR) on parse failure).

In `@framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java`:
- Around line 462-466: Add a regression test that simulates a skewed header by
advancing the wallet's in-memory head (use wallet.getNowBlock() or the
setter/mocking facility around that) to a number greater than the persisted
latest block (LATEST_BLOCK_NUM) and then call parseBlockTag("latest", wallet);
assert that parseBlockTag still returns the persisted head block number
(LATEST_BLOCK_NUM). Locate the existing test block around parseBlockTag and
insert the skew step before calling parseBlockTag so the test verifies
resolution uses the persisted head despite a larger in-memory/header number.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 27296e3e-c2e2-4d9c-904f-edb1620f3af5

📥 Commits

Reviewing files that changed from the base of the PR and between 039821c and 8f6f59a.

📒 Files selected for processing (6)
  • framework/src/main/java/org/tron/core/Wallet.java
  • framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java
  • framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java
  • framework/src/main/java/org/tron/core/services/jsonrpc/filters/LogFilterWrapper.java
  • framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java
  • framework/src/test/java/org/tron/core/services/jsonrpc/LogFilterWrapperStrategyTest.java

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

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


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

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