Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(consensus-type): Fixed ExecutionPayload json marshalling #2042

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

abi87
Copy link
Contributor

@abi87 abi87 commented Oct 4, 2024

The ExecutionPayload struct implements MarshalJSON on a pointer receiver instead of on a value receiver.
Due to how the json library handles these definitions, using json.Marshal on a value receiver will result in attempting to use the default marshalling behavior instead of the custom defined MarshalJSON method.

This could result in unexpected bytes or invalid round trip conversions if the value receiver is ever used to marshal via json.

Summary by CodeRabbit

  • New Features

    • Enhanced JSON marshaling and unmarshaling processes for the ExecutionPayload struct.
    • Updated the type of the BaseFeePerGas field for improved data handling.
  • Bug Fixes

    • Improved nil value checks for several fields during unmarshalling, ensuring data integrity.
  • Tests

    • Added a new test to verify JSON marshaling behavior for both value and pointer types of ExecutionPayload.

@abi87 abi87 self-assigned this Oct 4, 2024
Copy link
Contributor

coderabbitai bot commented Oct 4, 2024

Walkthrough

The changes in this pull request primarily involve modifications to the ExecutionPayload struct in the payload.go file, specifically altering the receiver type of the MarshalJSON method from a pointer to a value. Additionally, the type of the BaseFeePerGas field has been updated from *math.U256 to *math.U256Hex. The UnmarshalJSON method has been enhanced to check for nil values in several fields, improving robustness. A new test function has been added in payload_test.go to validate the JSON marshaling behavior for both value and pointer types.

Changes

File Change Summary
mod/consensus-types/pkg/types/payload.go - Updated MarshalJSON method from pointer to value receiver.
- Changed BaseFeePerGas field type from *math.U256 to *math.U256Hex.
- Enhanced UnmarshalJSON to check for nil values in BlobGasUsed and ExcessBlobGas.
mod/consensus-types/pkg/types/payload_test.go - Added TestExecutionPayload_MarshalJSON_ValueAndPointer to test JSON marshaling behavior.

Possibly related PRs

Suggested reviewers

  • nidhi-singh02
  • itsdevbear
  • ocnc

🐰 In the meadow, changes bloom,
A struct transformed, dispelling gloom.
With JSON's dance, both value and point,
The payloads sing, a joyful joint.
So hop along, let tests delight,
In code we trust, our future's bright! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Oct 4, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 22.23%. Comparing base (a2cce37) to head (9829574).

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main    #2042   +/-   ##
=======================================
  Coverage   22.23%   22.23%           
=======================================
  Files         356      356           
  Lines       16022    16022           
  Branches       12       12           
=======================================
  Hits         3563     3563           
  Misses      12306    12306           
  Partials      153      153           
Files with missing lines Coverage Δ
mod/consensus-types/pkg/types/payload.go 91.96% <100.00%> (ø)

Copy link
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

🧹 Outside diff range comments (1)
mod/consensus-types/pkg/types/payload.go (1)

Line range hint 318-426: LGTM! The changes improve the robustness of the unmarshaling process.

The addition of nil checks for BlobGasUsed and ExcessBlobGas fields enhances the reliability of the JSON unmarshaling process. The casting of BaseFeePerGas from *math.U256Hex to *math.U256 maintains consistency with the struct definition.

For consistency, consider adding error messages for missing BlobGasUsed and ExcessBlobGas fields, similar to other required fields. For example:

 if dec.BlobGasUsed != nil {
 	p.BlobGasUsed = *dec.BlobGasUsed
+} else {
+	return errors.New("missing required field 'blobGasUsed' for ExecutionPayload")
 }
 if dec.ExcessBlobGas != nil {
 	p.ExcessBlobGas = *dec.ExcessBlobGas
+} else {
+	return errors.New("missing required field 'excessBlobGas' for ExecutionPayload")
 }

This change would make the error handling more consistent across all fields.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between f767228 and 7b1539d.

📒 Files selected for processing (2)
  • mod/consensus-types/pkg/types/payload.go (1 hunks)
  • mod/consensus-types/pkg/types/payload_test.go (1 hunks)
🔇 Additional comments (3)
mod/consensus-types/pkg/types/payload_test.go (1)

Line range hint 1-174: Overall assessment of changes to payload_test.go

The addition of the TestExecutionPayload_MarshalJSON_ValueAndPointer function is a positive step towards addressing the JSON marshaling inconsistency mentioned in the PR objectives. This test helps ensure that the ExecutionPayload struct's JSON marshaling behaves consistently for both value and pointer receivers.

However, to fully address the PR objectives and ensure robust testing, consider implementing the suggested improvements in the previous comment. These enhancements will provide more comprehensive coverage and explicitly verify the custom MarshalJSON implementation.

Additionally, it might be beneficial to add tests that cover edge cases or specific scenarios where the marshaling behavior could potentially differ between value and pointer receivers.

The changes are approved, but implementing the suggested improvements would significantly enhance the test coverage and align more closely with the PR objectives.

mod/consensus-types/pkg/types/payload.go (2)

Line range hint 276-316: LGTM! The changes address the PR objectives effectively.

The modification of the MarshalJSON method from a pointer receiver to a value receiver is a crucial fix. This change ensures that the custom marshaling is used even when the method is called on a value receiver, preventing unexpected behavior during JSON serialization.

The update of BaseFeePerGas to use *math.U256Hex is consistent with the field type change in the struct definition, maintaining type consistency throughout the codebase.


Line range hint 1-626: Summary: The changes effectively address the PR objectives and improve code robustness.

The modifications to the ExecutionPayload struct and its associated methods, particularly the MarshalJSON and UnmarshalJSON functions, successfully address the issues outlined in the PR objectives. The change from a pointer receiver to a value receiver in MarshalJSON ensures consistent behavior when marshaling JSON, regardless of whether it's called on a pointer or value.

The additional nil checks in UnmarshalJSON for BlobGasUsed and ExcessBlobGas fields enhance the robustness of the unmarshaling process. The type changes for BaseFeePerGas are consistently applied throughout the file.

These changes should resolve the JSON marshaling issues and improve the overall reliability of the ExecutionPayload struct's serialization and deserialization processes.

Comment on lines +162 to +174
func TestExecutionPayload_MarshalJSON_ValueAndPointer(t *testing.T) {
val := types.ExecutionPayload{}

// Marshal on raw val uses default json marshal
valSerialized, err := json.Marshal(val)
require.NoError(t, err)

// Marshal on ptr val uses implemented MarshalJSON
ptrSerialized, err := json.Marshal(&val)
require.NoError(t, err)

require.Equal(t, valSerialized, ptrSerialized)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test coverage for ExecutionPayload JSON marshaling

The new test function TestExecutionPayload_MarshalJSON_ValueAndPointer is a good addition to verify the consistency of JSON marshaling for both value and pointer receivers of ExecutionPayload. However, consider the following improvements to make the test more robust:

  1. Use a non-empty ExecutionPayload struct to better represent real-world scenarios. You can utilize the generateExecutionPayload() function for this purpose.

  2. Explicitly verify that the custom MarshalJSON method is being used for the pointer receiver. This can be done by comparing the output with a known expected JSON structure.

  3. Check the actual content of the marshaled JSON, not just that the outputs are equal. This ensures that the serialization is correct, not just consistent.

Here's a suggested improvement:

func TestExecutionPayload_MarshalJSON_ValueAndPointer(t *testing.T) {
	payload := generateExecutionPayload()

	// Marshal on raw val uses default json marshal
	valSerialized, err := json.Marshal(*payload)
	require.NoError(t, err)

	// Marshal on ptr val uses implemented MarshalJSON
	ptrSerialized, err := json.Marshal(payload)
	require.NoError(t, err)

	// Verify that both outputs are equal
	require.Equal(t, valSerialized, ptrSerialized)

	// Verify the content of the marshaled JSON
	var unmarshalled map[string]interface{}
	err = json.Unmarshal(ptrSerialized, &unmarshalled)
	require.NoError(t, err)

	// Add assertions for key fields
	require.Equal(t, payload.ParentHash.String(), unmarshalled["parentHash"])
	require.Equal(t, payload.FeeRecipient.String(), unmarshalled["feeRecipient"])
	// Add more assertions for other fields...

	// Verify that custom MarshalJSON is used for pointer receiver
	customMarshaled, err := payload.MarshalJSON()
	require.NoError(t, err)
	require.Equal(t, ptrSerialized, customMarshaled)
}

This enhanced version of the test provides more comprehensive coverage and explicitly verifies the custom MarshalJSON implementation.

@abi87 abi87 requested review from nidhi-singh02 and removed request for ocnc October 13, 2024 14:23
@abi87 abi87 enabled auto-merge (squash) October 13, 2024 17:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants