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(primitives): hardened NewU256FromBigInt #2079

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

Conversation

abi87
Copy link
Contributor

@abi87 abi87 commented Oct 16, 2024

Made sure that negative big.Int won't be treated as U256 via error.
Minor changes in the callers to remove some code duplications

Summary by CodeRabbit

  • Bug Fixes
    • Introduced validation to prevent the creation of U256 from negative integers, ensuring more robust error handling.
    • Specific error message provided for attempts to create U256 from negative big.Int values.
  • New Features
    • Enhanced error handling in the genesis payload processing, improving the reliability of the execution payload injection.
    • Added constants for default gas limit and base fee to standardize initialization across the codebase.
  • Tests
    • Updated test cases for the math.Gwei type to improve clarity and error handling in expected values.

Copy link
Contributor

coderabbitai bot commented Oct 16, 2024

Walkthrough

The changes introduce enhanced error handling across multiple functions in the codebase. The NewU256FromBigInt function in the math package now returns an error for negative big.Int inputs. The payload.go file in the genesis package has been updated to handle errors more explicitly when injecting execution payloads. Additionally, modifications to the BeaconBlock and BeaconBlockBody structs replace hardcoded panic messages with a defined error variable. New constants for gas limits and fees are introduced in genesis.go, improving configuration standardization.

Changes

File Change Summary
mod/primitives/pkg/math/u256.go Updated NewU256FromBigInt to return an error for negative big.Int inputs.
mod/cli/pkg/commands/genesis/payload.go Enhanced error handling in AddExecutionPayloadCmd and modified executableDataToExecutionPayloadHeader to return an error.
mod/consensus-types/pkg/types/block.go Changed panic message in NewFromSSZ to reference ErrForkVersionNotSupported.
mod/consensus-types/pkg/types/body.go Updated panic messages in Empty and BlockBodyKZGOffset to use ErrForkVersionNotSupported.
mod/consensus-types/pkg/types/genesis.go Added constants defaultGasLimit and defaultBaseFeePerGas for standardizing gas values.
mod/primitives/pkg/math/u64_test.go Modified test cases for math.Gwei to include error handling in expected values.

Possibly related PRs

Suggested reviewers

  • itsdevbear
  • ocnc
  • nidhi-singh02

Poem

In the meadow where numbers play,
A check was added, hip-hip-hooray!
No more negatives, just positive cheer,
U256 shines bright, oh so clear!
With a hop and a skip, we validate right,
In the land of math, all is now 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.

@abi87 abi87 self-assigned this Oct 16, 2024
Copy link

codecov bot commented Oct 16, 2024

Codecov Report

Attention: Patch coverage is 38.29787% with 29 lines in your changes missing coverage. Please review.

Project coverage is 22.22%. Comparing base (8c2030a) to head (797debf).

Files with missing lines Patch % Lines
mod/cli/pkg/commands/genesis/payload.go 0.00% 17 Missing ⚠️
mod/primitives/pkg/math/u256.go 45.45% 5 Missing and 1 partial ⚠️
mod/consensus-types/pkg/types/genesis.go 81.25% 2 Missing and 1 partial ⚠️
mod/consensus-types/pkg/types/body.go 0.00% 2 Missing ⚠️
mod/consensus-types/pkg/types/block.go 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2079      +/-   ##
==========================================
- Coverage   22.23%   22.22%   -0.02%     
==========================================
  Files         356      356              
  Lines       16022    16040      +18     
  Branches       12       12              
==========================================
+ Hits         3563     3565       +2     
- Misses      12306    12320      +14     
- Partials      153      155       +2     
Files with missing lines Coverage Δ
mod/consensus-types/pkg/types/block.go 92.72% <0.00%> (ø)
mod/consensus-types/pkg/types/body.go 69.38% <0.00%> (ø)
mod/consensus-types/pkg/types/genesis.go 87.20% <81.25%> (-3.27%) ⬇️
mod/primitives/pkg/math/u256.go 41.17% <45.45%> (-8.83%) ⬇️
mod/cli/pkg/commands/genesis/payload.go 0.00% <0.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: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 8c2030a and 10abea4.

📒 Files selected for processing (1)
  • mod/primitives/pkg/math/u256.go (1 hunks)
🧰 Additional context used

mod/primitives/pkg/math/u256.go Outdated Show resolved Hide resolved
mod/primitives/pkg/math/u256.go Outdated Show resolved Hide resolved
@abi87 abi87 marked this pull request as draft October 16, 2024 20:09
@abi87 abi87 marked this pull request as ready for review October 16, 2024 20:17
@@ -87,7 +87,7 @@ func (b *BeaconBlock) NewFromSSZ(
block = &BeaconBlock{}
return block, block.UnmarshalSSZ(bz)
case version.DenebPlus:
panic("unsupported fork version")
panic(ErrForkVersionNotSupported)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

just found out this error was not consolidated and fixed it. It was used in one of the relevant callers

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: 5

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

Line range hint 1-265: Suggestion: Improve consistency in error handling across fork versions.

While the change on line 90 improves error handling for unsupported fork versions, there are other areas in the file where similar improvements could be made:

  1. In the NewWithVersion method (around line 60), consider using the same ErrForkVersionNotSupported error for consistency.

  2. In the NewFromSSZ method, the error handling differs between cases. Consider unifying the approach:

func (b *BeaconBlock) NewFromSSZ(bz []byte, forkVersion uint32) (*BeaconBlock, error) {
	switch forkVersion {
	case version.Deneb:
		block := &BeaconBlock{}
		err := block.UnmarshalSSZ(bz)
		return block, err
	case version.DenebPlus:
		return nil, ErrForkVersionNotSupported
	default:
		return nil, ErrForkVersionNotSupported
	}
}

This approach provides consistent error handling and allows callers to handle errors uniformly.

Would you like me to propose these changes as a separate pull request?

mod/consensus-types/pkg/types/body.go (1)

Line range hint 1-368: Consider addressing unimplemented methods and improving documentation.

The overall structure of the file is well-organized and consistent with Ethereum 2.0 specifications. However, there are a few areas that could be improved:

  1. Several methods (e.g., GetAttestations, SetAttestations, GetSlashingInfo, SetSlashingInfo) are not implemented and panic with "not implemented". Consider implementing these methods or providing a timeline for their implementation.

  2. The comment "I think this is a bug" in the GetTopLevelRoots method needs attention. Investigate and resolve this potential issue.

  3. Consider adding more comprehensive documentation, especially for complex methods like HashTreeRootWith.

  4. The TODO: chainspec comment in the DefineSSZ method should be addressed or clarified.

Would you like assistance in generating documentation templates for the complex methods or in creating issues to track the unimplemented methods?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 10abea4 and 797debf.

📒 Files selected for processing (6)
  • mod/cli/pkg/commands/genesis/payload.go (6 hunks)
  • mod/consensus-types/pkg/types/block.go (1 hunks)
  • mod/consensus-types/pkg/types/body.go (2 hunks)
  • mod/consensus-types/pkg/types/genesis.go (2 hunks)
  • mod/primitives/pkg/math/u256.go (2 hunks)
  • mod/primitives/pkg/math/u64_test.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (9)
mod/consensus-types/pkg/types/genesis.go (3)

37-40: LGTM: New constants improve code maintainability.

The addition of defaultGasLimit and defaultBaseFeePerGas constants is a good practice. It centralizes these important values, making the code more maintainable and reducing the risk of inconsistencies.

Please confirm that these values (30,000,000 for gas limit and 3,906,250 for base fee) align with the project's requirements and any relevant EIPs or network specifications.


171-171: LGTM: Consistent use of new constants in ExecutionPayloadHeader.

The changes to use defaultGasLimit for GasLimit and the newly created baseFeePerGas for BaseFeePerGas in the ExecutionPayloadHeader initialization are consistent with the earlier modifications. This ensures standardized values are used throughout the genesis configuration.

Also applies to: 175-175


Line range hint 37-175: Overall assessment: Improvements in consistency and error handling.

The changes in this file align well with the PR objectives of hardening the code. The introduction of constants for gas limit and base fee, along with improved error handling, enhances the robustness and maintainability of the genesis configuration. The modifications are consistent throughout the file and improve the overall code quality.

mod/consensus-types/pkg/types/body.go (1)

66-66: ⚠️ Potential issue

Improve error handling and consider adding support for other fork versions.

The change from a hardcoded panic message to ErrForkVersionNotSupported improves code maintainability. However, there are a few points to consider:

  1. Ensure that ErrForkVersionNotSupported is properly defined and imported, as it's not visible in the provided code.
  2. Consider adding support for other fork versions or documenting why only the Deneb version is supported.
  3. Instead of panicking, consider returning an error to allow better error handling by the caller.

To verify the definition and usage of ErrForkVersionNotSupported, please run the following script:

mod/cli/pkg/commands/genesis/payload.go (4)

24-24: Importing "fmt" package is appropriate

The addition of the "fmt" package is necessary for error formatting and handling in the updated code.


163-167: Good addition of error handling for baseFeePerGas conversion

Adding error handling for the baseFeePerGas conversion improves the robustness of the function by preventing potential issues with negative or invalid values.


130-131: 🧹 Nitpick (assertive)

Update function comment to reflect new error return

The function executableDataToExecutionPayloadHeader now returns an error in addition to *types.ExecutionPayloadHeader. The function comment should be updated to document this change, ensuring clarity for future maintainers.

Apply this diff to update the function comment:

-// Converts the eth executable data type to the beacon execution payload header
-// interface.
+// Converts the Ethereum executable data type to the beacon execution payload header.
+// Returns an error if the conversion fails.

Likely invalid or redundant comment.


Line range hint 132-196: Verify all callers handle the updated function signature

The function executableDataToExecutionPayloadHeader now returns an additional error value. Ensure that all callers of this function in the codebase have been updated to handle the error appropriately to prevent unhandled exceptions or panics.

Run the following script to identify all calls to executableDataToExecutionPayloadHeader and check for proper error handling:

This script searches for all usages of executableDataToExecutionPayloadHeader and checks if they handle the returned error. It helps ensure consistency and prevent potential runtime issues due to unhandled errors.

✅ Verification successful

To address the regex parsing error and obtain the necessary information, I'll modify the search pattern and re-run the script. Here's the updated approach:

This script will search for the function calls without using complex regex, which should avoid the parsing error. It will also provide some context around each call, allowing us to check for error handling.


To get more context around the function call and determine if the error is being handled properly, let's run another script:

This script will show us more context around the function call in the payload.go file and search for other potential callers in the codebase.


Based on the analysis of the provided context, I can now generate the final response:

Error handling for executableDataToExecutionPayloadHeader has been correctly implemented

The function executableDataToExecutionPayloadHeader now returns an additional error value, and the code has been updated to handle this error appropriately. In the file mod/cli/pkg/commands/genesis/payload.go, the error is checked immediately after the function call:

genesisInfo.ExecutionPayloadHeader, err =
    executableDataToExecutionPayloadHeader(
        version.ToUint32(genesisInfo.ForkVersion),
        payload,
        chainSpec.MaxWithdrawalsPerPayload(),
    )
if err != nil {
    return errors.Wrap(err, "failed to unmarshal beacon state")
}

This implementation correctly checks for any error returned by the function and handles it by wrapping it with additional context and returning it.

No other callers of this function were found in the codebase, suggesting that this is the only place where the function is used.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all calls to executableDataToExecutionPayloadHeader and ensure errors are handled.

# Search for all Go files in the repository
fd --type f --extension go | while read -r file; do
    # Exclude the current file to avoid false positives
    if [[ "$file" != "mod/cli/pkg/commands/genesis/payload.go" ]]; then
        # Look for lines where executableDataToExecutionPayloadHeader is called
        rg -N '(\w+,\s*)?err\s*:?\=\s*executableDataToExecutionPayloadHeader\(' "$file" || {
            # If not found, output the file and line where it's called without error handling
            rg -N 'executableDataToExecutionPayloadHeader\(' "$file" && echo "Error handling may be missing in $file"
        }
    fi
done

Length of output: 299921


Script:

#!/bin/bash
# Search for calls to executableDataToExecutionPayloadHeader and check for error handling

# Find all Go files in the repository
fd --type f --extension go | while read -r file; do
    # Look for lines where executableDataToExecutionPayloadHeader is called
    if grep -n "executableDataToExecutionPayloadHeader" "$file"; then
        echo "Found in $file:"
        # Show the lines containing the function call and the next few lines for context
        grep -n -A 5 "executableDataToExecutionPayloadHeader" "$file"
        echo "---"
    fi
done

Length of output: 63656


Script:

#!/bin/bash
# Show more context around the executableDataToExecutionPayloadHeader function call

echo "Context for executableDataToExecutionPayloadHeader in mod/cli/pkg/commands/genesis/payload.go:"
grep -n -B 10 -A 10 "executableDataToExecutionPayloadHeader(" mod/cli/pkg/commands/genesis/payload.go

echo -e "\nSearching for other potential callers in the codebase:"
grep -r -n "executableDataToExecutionPayloadHeader(" . --include="*.go" | grep -v "mod/cli/pkg/commands/genesis/payload.go"

Length of output: 1851

mod/primitives/pkg/math/u256.go (1)

39-49: Ensure all callers handle the new error return from NewU256FromBigInt

The function NewU256FromBigInt now returns an error in addition to *U256. Please verify that all callers of this function have been updated to handle the error appropriately to prevent potential runtime panics or unhandled errors.

Run the following script to find all usages of NewU256FromBigInt and check for proper error handling:

✅ Verification successful

All callers correctly handle the error return from NewU256FromBigInt.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of NewU256FromBigInt and check if the error is handled.

# Search for usages and display context lines
rg --type go 'NewU256FromBigInt\(' -A 3 -B 1

Length of output: 2493

mod/consensus-types/pkg/types/genesis.go Show resolved Hide resolved
mod/consensus-types/pkg/types/block.go Show resolved Hide resolved
mod/consensus-types/pkg/types/body.go Show resolved Hide resolved
mod/primitives/pkg/math/u64_test.go Show resolved Hide resolved
mod/cli/pkg/commands/genesis/payload.go Show resolved Hide resolved
LogsBloom: [256]byte{},
Random: common.Bytes32{},
Number: 0,
GasLimit: defaultGasLimit,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

nit: moved magic value to a const. Likely outside PR's scope but I rather have all magic values together in one place, rather than spread in the codebase where we use them.

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.

1 participant