Skip to content

perf(api): optimize block JSON serialization - #2

Closed
bladehan1 wants to merge 1 commit into
developfrom
feat/opt_block_json_serialization
Closed

bladehan1 wants to merge 1 commit into
developfrom
feat/opt_block_json_serialization

Conversation

@bladehan1

@bladehan1 bladehan1 commented Mar 20, 2026 •

Copy link
Copy Markdown
Owner
  1. remove redundant full BlockList serialization in printBlockList
  2. serialize only block_header instead of entire block in printBlockToJSON
  3. enhance testPrintBlockList to verify JSON structure after refactoring

What does this PR do?

Why are these changes required?

This PR has been tested by:

  • Unit Tests
  • Manual Testing

Follow up

Extra details


Summary by cubic

Optimizes block JSON serialization to reduce CPU work and payload size. Block lists are now built as minimal JSON, and individual blocks include only blockID, block_header, and transactions when present.

  • Refactors
    • printBlockList: stop serializing the full BlockList; build { "block": [...] } directly.
    • printBlockToJSON: output "blockID" and a parsed "block_header" instead of the full block; include "transactions" only if present.
    • Tests: extend UtilMockTest.testPrintBlockList to assert the new JSON structure and keys.

Written for commit 840f97b. Summary will update on new commits.

Summary by CodeRabbit

  • Bug Fixes
    • Corrected block response structure to include explicit block header information in API responses.

…intBlockToJSON

1. remove redundant full BlockList serialization in printBlockList
2. serialize only block_header instead of entire block in printBlockToJSON
3. enhance testPrintBlockList to verify JSON structure after refactoring
@coderabbitai

coderabbitai Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The changes restructure the JSON output format for blocks in Util.java by replacing parsed JsonFormat output with explicit JSONObject construction, introducing a new "block_header" field and standardizing "blockID" inclusion. Corresponding test assertions validate the new structure.

Changes

Cohort / File(s) Summary
Block JSON Output Restructuring
framework/src/main/java/org/tron/core/services/http/Util.java
Modified printBlockList to construct fresh JSONObject with "block" field instead of parsing JsonFormat output; updated printBlockToJSON to explicitly build JSONObject with "blockID" and new "block_header" field (parsed from block header), while preserving transaction handling logic.
Block JSON Output Validation
framework/src/test/java/org/tron/core/services/http/UtilMockTest.java
Updated testPrintBlockList to parse output as JSON and assert presence of top-level "block" array field; added assertions verifying each block contains non-empty "blockID" and non-null "block_header" keys; adjusted second test block instance identifier from 1 to 2.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A rabbit hops through JSON trees,
Restructuring blocks with ease and glee,
New headers bloom, IDs stand tall,
The format transforms—best of all! 🌿✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'perf(api): optimize block JSON serialization' directly and clearly describes the main change: optimizing JSON serialization performance for blocks by removing redundant serialization operations.

✏️ 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 feat/opt_block_json_serialization
📝 Coding Plan
  • Generate coding plan for human review comments

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

No issues found across 2 files

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
framework/src/main/java/org/tron/core/services/http/Util.java (1)

100-100: Use a direct loop instead of stream().forEach in this hot path.

Since this PR is perf-focused, replacing blocks.stream().forEach(...) with a plain for loop avoids lambda/stream overhead during serialization.

♻️ Suggested change
-    blocks.stream().forEach(block -> jsonArray.add(printBlockToJSON(block, selfType)));
+    for (Block block : blocks) {
+      jsonArray.add(printBlockToJSON(block, selfType));
+    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@framework/src/main/java/org/tron/core/services/http/Util.java` at line 100,
Replace the hot-path call blocks.stream().forEach(block ->
jsonArray.add(printBlockToJSON(block, selfType))) with a direct indexed/enhanced
for loop to avoid stream/lambda overhead: iterate over the blocks collection
with for (BlockType block : blocks) and call
jsonArray.add(printBlockToJSON(block, selfType)) inside the loop; update the
Util class where printBlockToJSON and jsonArray are used so behavior remains
identical but without using stream().forEach.
framework/src/test/java/org/tron/core/services/http/UtilMockTest.java (1)

57-69: Good structural assertions; consider validating header content, not only key presence.

Right now the test can still pass if all entries have the same/mismatched header payload. Since fixtures are deterministic (heights 1 and 2), assert block_header.raw_data.number per index.

✅ Stronger assertion example
     for (int i = 0; i < blockArray.size(); i++) {
       JSONObject blockJson = blockArray.getJSONObject(i);
       Assert.assertTrue(blockJson.containsKey("blockID"));
       Assert.assertTrue(blockJson.containsKey("block_header"));
       Assert.assertFalse(blockJson.getString("blockID").isEmpty());
       Assert.assertNotNull(blockJson.getJSONObject("block_header"));
+      JSONObject rawData = blockJson.getJSONObject("block_header").getJSONObject("raw_data");
+      Assert.assertEquals(i + 1L, rawData.getLongValue("number"));
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@framework/src/test/java/org/tron/core/services/http/UtilMockTest.java` around
lines 57 - 69, Update the assertions in UtilMockTest.java inside the loop that
inspects blockArray (the blockJson checks) to validate header content: for each
JSONObject blockJson, after confirming "block_header" presence, extract
blockJson.getJSONObject("block_header").getJSONObject("raw_data").getLong("number")
and assert it equals the expected block height for that index (e.g., 1 for i==0
and 2 for i==1) so the test verifies the deterministic fixture values rather
than only key presence.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@framework/src/main/java/org/tron/core/services/http/Util.java`:
- Line 100: Replace the hot-path call blocks.stream().forEach(block ->
jsonArray.add(printBlockToJSON(block, selfType))) with a direct indexed/enhanced
for loop to avoid stream/lambda overhead: iterate over the blocks collection
with for (BlockType block : blocks) and call
jsonArray.add(printBlockToJSON(block, selfType)) inside the loop; update the
Util class where printBlockToJSON and jsonArray are used so behavior remains
identical but without using stream().forEach.

In `@framework/src/test/java/org/tron/core/services/http/UtilMockTest.java`:
- Around line 57-69: Update the assertions in UtilMockTest.java inside the loop
that inspects blockArray (the blockJson checks) to validate header content: for
each JSONObject blockJson, after confirming "block_header" presence, extract
blockJson.getJSONObject("block_header").getJSONObject("raw_data").getLong("number")
and assert it equals the expected block height for that index (e.g., 1 for i==0
and 2 for i==1) so the test verifies the deterministic fixture values rather
than only key presence.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: efb18bc4-6c01-495b-b161-de541dc23e3f

📥 Commits

Reviewing files that changed from the base of the PR and between 62d8a55 and 840f97b.

📒 Files selected for processing (2)
  • framework/src/main/java/org/tron/core/services/http/Util.java
  • framework/src/test/java/org/tron/core/services/http/UtilMockTest.java

@bladehan1 bladehan1 closed this Apr 17, 2026
@bladehan1
bladehan1 deleted the feat/opt_block_json_serialization branch June 10, 2026 06:18
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.

1 participant