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 GweiFromWei to avoid integer truncation #2080

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

abi87
Copy link
Contributor

@abi87 abi87 commented Oct 16, 2024

A Gwei amount larger than (2**64) * (10**9) or negative would not be representable as uint64, but currently would be truncated rather than rejected.
This should not happen but we still want to guard against a serialization bug or other mishap.
This PR fixes this.

Summary by CodeRabbit

  • New Features

    • Enhanced GweiFromWei function now includes error handling for overflow conditions.
    • New error message for overflow scenarios has been introduced.
  • Bug Fixes

    • Improved test cases for GweiFromWei to cover invalid inputs and error scenarios.
  • Documentation

    • Updated documentation to reflect changes in function signature and error handling.

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

coderabbitai bot commented Oct 16, 2024

Walkthrough

The changes made in this pull request involve modifications to the GweiFromWei function in the mod/primitives/pkg/math/u64.go file, enhancing its functionality and error handling. The function now returns a tuple of Gwei and error, enabling it to signal overflow conditions. Additionally, the corresponding test cases in u64_test.go have been updated to accommodate the new function signature and include more comprehensive error handling scenarios.

Changes

File Path Change Summary
mod/primitives/pkg/math/u64.go - Updated GweiFromWei function signature to return (Gwei, error).
- Added var ErrGweiOverflow = errors.New("gwei from big.Int overflows").
mod/primitives/pkg/math/u64_test.go - Updated test cases for GweiFromWei to reflect new function signature and error handling.
- Changed input field to a function returning *big.Int.
- Added expectedErr field to capture potential errors in test cases.

Possibly related PRs

Suggested reviewers

  • itsdevbear
  • ocnc

Poem

In the land of code, where bunnies play,
A function grew stronger, come what may.
With Gwei and errors, it now stands tall,
Overflow fears? Not at all!
Hopping through tests, with joy we cheer,
For better handling, let’s give a cheer! 🐇✨


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 16, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 22.26%. Comparing base (8c2030a) to head (e85c595).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2080      +/-   ##
==========================================
+ Coverage   22.23%   22.26%   +0.02%     
==========================================
  Files         356      356              
  Lines       16022    16028       +6     
  Branches       12       12              
==========================================
+ Hits         3563     3569       +6     
  Misses      12306    12306              
  Partials      153      153              
Files with missing lines Coverage Δ
mod/primitives/pkg/math/u64.go 100.00% <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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

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

📒 Files selected for processing (2)
  • mod/primitives/pkg/math/u64.go (2 hunks)
  • mod/primitives/pkg/math/u64_test.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (6)
mod/primitives/pkg/math/u64.go (3)

27-27: Import statement added

The addition of "github.com/berachain/beacon-kit/mod/errors" is appropriate for enhanced error handling.


140-140: Define custom overflow error

Defining ErrGweiOverflow provides a clear and specific error for overflow conditions, improving error clarity.


143-143: Ensure callers handle the updated GweiFromWei function signature

With the change to GweiFromWei returning an additional error, verify that all calls to this function in the codebase have been updated to handle the error appropriately.

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

✅ Verification successful

All callers of GweiFromWei correctly handle the returned error.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all calls to GweiFromWei and display them with context.

# Expected: Callers should handle the error returned by GweiFromWei.
rg --type go 'GweiFromWei\(' -A 2

Length of output: 667

mod/primitives/pkg/math/u64_test.go (3)

331-334: Enhanced test input flexibility with function-based inputs

Changing the input field to func(t *testing.T) *big.Int allows for dynamic generation of test inputs, which enhances the flexibility and readability of the test cases. This is a good practice for preparing complex inputs and ensures that test setup is clear and maintainable.


385-390: Consistent use of big.Int operations for large values

In the "max uint64 wei" test case, you're correctly using new(big.Int).Mul with big.NewInt and SetUint64 to handle large values without overflow. This ensures the test accurately represents the maximum uint64 value in Gwei.


399-405: Proper error handling and result verification in tests

The test logic correctly checks for expected errors using require.ErrorIs when an error is anticipated, and verifies the result with require.Equal when no error is expected. This ensures that both successful and error scenarios are properly validated.

mod/primitives/pkg/math/u64.go Show resolved Hide resolved
mod/primitives/pkg/math/u64_test.go Show resolved Hide resolved
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