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 NewRootFromHex #2051

Merged
merged 6 commits into from
Oct 10, 2024

Conversation

abi87
Copy link
Contributor

@abi87 abi87 commented Oct 8, 2024

NewRootFromHex would panic if input length is less than 32.
A related question is if should define Root as an alias of bytes.B32

Summary by CodeRabbit

  • New Features

    • Introduced a new error variable for incorrect length handling to streamline error management.
    • Added unit tests for enhanced coverage of the NewRootFromHex function.
  • Improvements

    • Updated type declarations for B32 and Root to use constants for better maintainability.
    • Enhanced hex encoding functionality with consistent use of the Prefix variable.
  • Bug Fixes

    • Implemented length checks in the NewRootFromHex function to ensure proper error handling.

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

coderabbitai bot commented Oct 8, 2024

Walkthrough

The changes in this pull request involve updates to several files in the primitives package, primarily focusing on enhancing maintainability by replacing hardcoded array sizes with constants. The B32 and Root types now utilize B32Size and RootSize, respectively. Additionally, a new error variable ErrIncorrectLength has been introduced for improved error handling in JSON unmarshalling. Various modifications in the hex package include renaming variables to ensure consistency and exportability. New unit tests for the NewRootFromHex function have also been added to enhance test coverage.

Changes

File Path Change Summary
mod/primitives/pkg/bytes/b32.go Updated B32 type from [32]byte to [B32Size]byte.
mod/primitives/pkg/bytes/utils.go Added ErrIncorrectLength variable for error handling.
mod/primitives/pkg/common/consensus.go Changed Root type from [32]byte to [RootSize]byte and added length check in NewRootFromHex.
mod/primitives/pkg/common/consensus_test.go Introduced unit tests for NewRootFromHex.
mod/primitives/pkg/encoding/hex/bytes.go Renamed variable prefix to Prefix in EncodeBytes.
mod/primitives/pkg/encoding/hex/const.go Renamed constant prefix to Prefix, making it exported.
mod/primitives/pkg/encoding/hex/string.go Capitalized Prefix variable in several methods.
mod/primitives/pkg/encoding/hex/u64.go Updated copy function to use Prefix instead of prefix.

Possibly related PRs

  • chore(ssz): Cleanup #1612: Changes in the common/consensus.go file involve updating the Root type's definition to use a constant for size, similar to the changes made to the B32 type in the main PR, which also involves using a constant for size.
  • chore(primitives): fixed ExecutionAddress validation #2034: The modifications to the ExecutionAddress struct's UnmarshalText method involve using hex decoding, which relates to the error handling improvements in the main PR where a new error variable was introduced for length validation in the bytes package.
  • chore(primitives): hex.String basic cleanup #2044: The enhancements in the B32 type's maintainability through the use of a constant are connected to the cleanup in the hex.String component, where similar improvements in code readability and maintainability were made.

Suggested reviewers

  • itsdevbear
  • ocnc
  • nidhi-singh02

🐇 In the code where bytes reside,
Constants now take the stride.
Errors caught with a gentle hand,
Tests to ensure we understand.
With prefixes bold and sizes right,
Our code now shines, oh what a sight! 🌟


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.

@@ -65,14 +65,19 @@ type (

// Root represents a 32-byte Merkle root.
// We use this type to represent roots that come from the consensus layer.
type Root [32]byte
type Root [RootSize]byte
Copy link
Contributor Author

Choose a reason for hiding this comment

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

q: should this be a bytes.B32?

Copy link

codecov bot commented Oct 8, 2024

Codecov Report

Attention: Patch coverage is 92.85714% with 1 line in your changes missing coverage. Please review.

Project coverage is 22.03%. Comparing base (93a6004) to head (f14722c).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
mod/primitives/pkg/encoding/hex/string.go 85.71% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2051      +/-   ##
==========================================
+ Coverage   21.98%   22.03%   +0.05%     
==========================================
  Files         357      357              
  Lines       15958    15961       +3     
  Branches       12       12              
==========================================
+ Hits         3508     3517       +9     
+ Misses      12301    12295       -6     
  Partials      149      149              
Files with missing lines Coverage Δ
mod/primitives/pkg/bytes/b32.go 100.00% <ø> (ø)
mod/primitives/pkg/bytes/utils.go 100.00% <100.00%> (ø)
mod/primitives/pkg/common/consensus.go 34.61% <100.00%> (+34.61%) ⬆️
mod/primitives/pkg/encoding/hex/bytes.go 84.31% <100.00%> (ø)
mod/primitives/pkg/encoding/hex/u64.go 88.88% <100.00%> (ø)
mod/primitives/pkg/encoding/hex/string.go 81.17% <85.71%> (ø)

@abi87 abi87 marked this pull request as ready for review October 8, 2024 09:26
@abi87 abi87 requested a review from itsdevbear as a code owner October 8, 2024 09:26
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: 10

🧹 Outside diff range comments (4)
mod/primitives/pkg/bytes/utils.go (1)

NewRootFromHex has been successfully hardened by adding a length check and replacing the hard-coded value with a constant, aligning with the PR objectives. However, there's a typo in the error variable name ErrIncorrectLenght in utils.go. Please correct it to ErrIncorrectLength to maintain code quality.

🔗 Analysis chain

Line range hint 1-93: Verify alignment with PR objectives

The changes in this file improve error handling consistency, which is good. However, the PR objectives mentioned hardening NewRootFromHex, which is not present in this file. Please ensure that the changes align with the stated PR objectives and that all necessary modifications have been included in the pull request.

To verify the presence and modifications of NewRootFromHex:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for NewRootFromHex function
rg --type go 'func NewRootFromHex'

Length of output: 125


Script:

#!/bin/bash
# Check if consensus.go was modified in the PR
git diff --name-only origin/main...HEAD | grep 'mod/primitives/pkg/common/consensus.go'

Length of output: 126


Script:

#!/bin/bash
# Get diffs for the NewRootFromHex function in consensus.go
git diff origin/main...HEAD mod/primitives/pkg/common/consensus.go | grep -A 10 -B 10 'func NewRootFromHex'

Length of output: 650

mod/primitives/pkg/encoding/hex/bytes.go (1)

Line range hint 1-114: Overall code quality is good, consider adding package-level documentation

The file maintains good code quality with well-structured functions, appropriate error handling, and helpful comments. The recent change doesn't seem to negatively impact the existing code.

To further improve the file:

  1. Consider adding a package-level comment at the top of the file, explaining the purpose of the hex package and its main functionalities. This would provide better context for developers using or maintaining this package.

  2. If Prefix is now exported, ensure it's properly documented in the package documentation.

Here's a suggestion for a package-level comment:

// Package hex provides utilities for encoding and decoding hexadecimal strings.
// It includes functions for converting between byte slices and hex strings,
// as well as JSON and text unmarshalling for hex-encoded data.
package hex

Add this comment at the beginning of the file, right after the license header.

mod/primitives/pkg/common/consensus.go (1)

Line range hint 1-124: Summary of review findings

  1. The comment correction for Hash32 improves documentation clarity.
  2. The introduction of RootSize and its use in the Root type definition improves maintainability, but consider using bytes.B32 directly for consistency with other types.
  3. The length check addition in NewRootFromHex improves function robustness, aligning with the PR objective.
  4. A typo was found in the error variable name (ErrIncorrectLenght), which should be corrected.

Overall, the changes align with the PR objectives of hardening NewRootFromHex and improving maintainability. Please address the suggestions regarding the Root type definition and the typo correction to further enhance the code quality.

mod/primitives/pkg/encoding/hex/string.go (1)

Update Variable Names for Consistency

Several instances of prefix remain in variable names, such as prefixLen in string.go and const.go. To maintain consistency with the newly exported Prefix constant, please rename these variables to PrefixLen.

  • mod/primitives/pkg/encoding/hex/string.go: if strings.ToLower(string(s[:prefixLen])) != Prefix {
  • mod/primitives/pkg/encoding/hex/const.go: prefixLen = len(Prefix)
🔗 Analysis chain

Line range hint 1-94: Summary: Consistent use of Prefix throughout the file

The changes in this file primarily involve replacing prefix with Prefix across various functions. This modification suggests a broader refactoring to make Prefix an exported constant, which improves the API of the package by making the hex string prefix accessible to users.

The changes maintain the existing logic while enhancing consistency throughout the file. All modifications have been reviewed and approved, with a minor suggestion for improvement in the FromBigInt function.

To ensure consistency across the package, please run the following command to check for any remaining instances of the lowercase prefix:

This will help identify any places where the refactoring might have been missed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining instances of lowercase 'prefix' in the package
rg --type go -i '\bprefix\b' mod/primitives/pkg/encoding/hex/

Length of output: 2533

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 1c0a378 and 939222a.

📒 Files selected for processing (8)
  • mod/primitives/pkg/bytes/b32.go (1 hunks)
  • mod/primitives/pkg/bytes/utils.go (3 hunks)
  • mod/primitives/pkg/common/consensus.go (2 hunks)
  • mod/primitives/pkg/common/consensus_test.go (1 hunks)
  • mod/primitives/pkg/encoding/hex/bytes.go (1 hunks)
  • mod/primitives/pkg/encoding/hex/const.go (1 hunks)
  • mod/primitives/pkg/encoding/hex/string.go (4 hunks)
  • mod/primitives/pkg/encoding/hex/u64.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (11)
mod/primitives/pkg/encoding/hex/const.go (1)

24-25: LGTM! Exporting Prefix improves reusability.

The changes look good and align with the PR objectives:

  1. Renaming prefix to Prefix makes it accessible outside the package, improving reusability across the codebase.
  2. Updating prefixLen to use Prefix maintains consistency with the renamed constant.

These modifications enhance the package's flexibility without altering its functionality.

mod/primitives/pkg/encoding/hex/u64.go (1)

35-35: Verify the consistency of exported variables

The change from prefix to Prefix suggests that this variable is now exported. While this change is straightforward, it has potential implications:

  1. Ensure that Prefix is properly defined and exported in the package.
  2. Consider if this change affects the package's API and if it's intentional.
  3. For consistency, review if prefixLen and initialCapacity should also be exported or remain as local variables.

To confirm the proper definition and usage of Prefix, run the following script:

mod/primitives/pkg/common/consensus_test.go (2)

1-21: LGTM: Proper licensing and package declaration.

The file starts with the correct BUSL-1.1 license header, and the package is appropriately named common_test following Go conventions for test files.


23-31: LGTM: Appropriate imports.

The import statements include all necessary packages for the test file, including standard library packages, the package under test, and testing utilities. The imports are well-organized.

mod/primitives/pkg/bytes/b32.go (1)

35-35: Excellent use of a constant for array size!

This change from [32]byte to [B32Size]byte is a great improvement. It enhances code maintainability by centralizing the size definition and eliminates the use of magic numbers. This makes the code more robust and easier to modify in the future if needed.

mod/primitives/pkg/encoding/hex/bytes.go (1)

35-35: Verify the intention behind exporting the Prefix variable

The change from prefix to Prefix makes this variable exported, allowing it to be accessed and potentially modified from other packages. While this might be intentional, it's important to consider the following:

  1. Ensure that exporting Prefix aligns with the package's design intentions.
  2. Document the purpose and expected usage of Prefix in the package documentation.
  3. Consider the potential impact on other parts of the codebase that might now be able to modify this prefix.

To better understand the context and usage of Prefix, please run the following script:

This will help us understand if Prefix is properly defined and how it's used across the codebase.

✅ Verification successful

Change to Prefix is consistent and appropriate

The renaming from prefix to Prefix in bytes.go aligns with the existing usage of the exported Prefix constant defined in const.go. This change promotes consistency across the package and utilizes the centralized definition of the hex prefix.

  • Consistency: All functions within the encoding/hex package now use the Prefix constant, ensuring uniformity.
  • Maintainability: Using a single exported Prefix reduces the risk of discrepancies and simplifies maintenance.
  • No Adverse Effects: Since Prefix is a constant, exporting it does not introduce risks of unintended modifications.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the definition and usage of Prefix in the package

# Find the definition of Prefix
echo "Definition of Prefix:"
rg --type go -n "var Prefix" mod/primitives/pkg/encoding/hex

# Check for other usages of Prefix in the package
echo "\nOther usages of Prefix:"
rg --type go -n "Prefix" mod/primitives/pkg/encoding/hex

# Check if Prefix is used in other packages
echo "\nUsage of hex.Prefix in other packages:"
rg --type go -n "hex\.Prefix" --glob '!mod/primitives/pkg/encoding/hex/**'

Length of output: 1973

mod/primitives/pkg/common/consensus.go (1)

49-49: LGTM: Comment correction improves clarity.

The change from "as er" to "as per" in the comment for Hash32 is a good correction that enhances the documentation's accuracy.

mod/primitives/pkg/encoding/hex/string.go (4)

41-41: LGTM: Consistent use of Prefix

The change from prefix to Prefix maintains consistency with the rest of the codebase. The logic remains unchanged, ensuring that an empty string is represented as "0x0".


45-45: LGTM: Consistent use of Prefix

The change from prefix to Prefix is consistent with the previous modification and maintains uniformity throughout the function. The logic remains intact, ensuring proper handling of invalid hex strings.


71-72: LGTM: Consistent use of Prefix in validation

The change from prefix to Prefix in the validation logic is consistent with the previous modifications. The use of strings.ToLower() ensures a case-insensitive comparison, maintaining the robustness of the validation.


80-82: LGTM: Consistent use of Prefix in encoding

The change from prefix to Prefix when initializing the encoding slice is consistent with the previous modifications. The core logic of the function remains unchanged, ensuring that the uint64 value is correctly encoded as a hex string with the appropriate prefix.

mod/primitives/pkg/common/consensus_test.go Outdated Show resolved Hide resolved
mod/primitives/pkg/common/consensus_test.go Outdated Show resolved Hide resolved
@@ -32,7 +32,7 @@ const (

// B32 represents a 32-byte fixed-size byte array.
// For SSZ purposes it is serialized a `Vector[Byte, 32]`.
type B32 [32]byte
type B32 [B32Size]byte
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Hardcoded [32]byte declarations still present in the codebase

The verification uncovered multiple instances where [32]byte is used directly instead of utilizing B32Size. To maintain consistency and enhance maintainability, it's recommended to refactor these declarations to use B32Size.

Key files with hardcoded [32]byte declarations:

  • mod/state-transition/pkg/core/types.go
  • mod/engine-primitives/pkg/engine-primitives/transactions_test.go
  • mod/execution/pkg/deposit/contract.go
  • mod/primitives/pkg/encoding/ssz/merkle/proof.go
  • mod/primitives/pkg/encoding/ssz/merkle/tree_test.go
  • mod/primitives/pkg/crypto/sha256/sha256.go
  • mod/consensus-types/pkg/types/block_test.go
  • mod/da/pkg/types/sidecar_test.go
  • mod/payload/pkg/cache/payload_id_test.go
  • mod/node-api/handlers/proof/merkle/constants_test.go
  • examples/berad/pkg/state-transition/types.go
  • ...and others as identified in the shell script output.

Refactoring these instances will ensure that the B32 type consistently leverages the defined B32Size, reducing redundancy and potential errors.

🔗 Analysis chain

Verify consistent usage of B32Size across the codebase

While this change is excellent, it's important to ensure that B32Size is used consistently throughout the codebase wherever a 32-byte size is needed for B32 type.

Let's verify the usage of B32Size across the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining hardcoded [32]byte declarations and B32Size usage

# Search for any remaining [32]byte declarations
echo "Checking for remaining [32]byte declarations:"
rg --type go '\[32\]byte'

# Search for B32Size usage
echo "Checking B32Size usage:"
rg --type go 'B32Size'

Length of output: 25285

mod/primitives/pkg/bytes/utils.go Outdated Show resolved Hide resolved
mod/primitives/pkg/bytes/utils.go Outdated Show resolved Hide resolved
mod/primitives/pkg/bytes/utils.go Outdated Show resolved Hide resolved
mod/primitives/pkg/common/consensus.go Outdated Show resolved Hide resolved
Comment on lines +89 to +94
return NewString(Prefix + "0")
} else if sign > 0 {
return NewString(prefix + bigint.Text(hexBase))
return NewString(Prefix + bigint.Text(hexBase))
}
// this return should never reach if precondition is met
return NewString(prefix + bigint.Text(hexBase)[1:])
return NewString(Prefix + bigint.Text(hexBase)[1:])
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM with a minor suggestion: Consistent use of Prefix in BigInt encoding

The changes from prefix to Prefix in the FromBigInt function are consistent with the previous modifications. The logic for handling zero, positive, and negative big integers remains intact.

Consider simplifying the function by removing the negative case, as the precondition states that bigint should be non-negative. This would make the function more robust and aligned with its documented behavior:

 func FromBigInt(bigint *big.Int) String {
 	if sign := bigint.Sign(); sign == 0 {
 		return NewString(Prefix + "0")
-	} else if sign > 0 {
+	} else {
 		return NewString(Prefix + bigint.Text(hexBase))
 	}
-	// this return should never reach if precondition is met
-	return NewString(Prefix + bigint.Text(hexBase)[1:])
 }

This change would eliminate the possibility of unexpected behavior if the function is called with a negative number, despite the precondition.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return NewString(Prefix + "0")
} else if sign > 0 {
return NewString(prefix + bigint.Text(hexBase))
return NewString(Prefix + bigint.Text(hexBase))
}
// this return should never reach if precondition is met
return NewString(prefix + bigint.Text(hexBase)[1:])
return NewString(Prefix + bigint.Text(hexBase)[1:])
return NewString(Prefix + "0")
} else {
return NewString(Prefix + bigint.Text(hexBase))
}

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 939222a and e6bcae2.

📒 Files selected for processing (3)
  • mod/primitives/pkg/bytes/utils.go (3 hunks)
  • mod/primitives/pkg/common/consensus.go (2 hunks)
  • mod/primitives/pkg/common/consensus_test.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (7)
mod/primitives/pkg/common/consensus_test.go (1)

21-31: LGTM: Proper package declaration and imports.

The package declaration and imports are correctly set up for the test file. The use of common_test package name follows Go conventions, and all necessary imports are included.

mod/primitives/pkg/bytes/utils.go (4)

28-28: Approve the introduction of ErrIncorrectLength

The addition of the ErrIncorrectLength variable is a good practice. It provides a standardized error for incorrect length scenarios and addresses the typo mentioned in previous reviews. This change enhances code consistency and maintainability.


39-39: Approve the use of ErrIncorrectLength in UnmarshalJSONHelper

The replacement of the inline error with ErrIncorrectLength is appropriate. This change improves consistency in error handling across the package and reduces redundancy.


52-52: Approve the use of ErrIncorrectLength in UnmarshalTextHelper

The replacement of the inline error with ErrIncorrectLength is appropriate and consistent with the change in UnmarshalJSONHelper. This change further enhances the consistency of error handling across the package.


Line range hint 1-94: Verify alignment with PR objectives

While the changes in this file improve error handling and consistency, they don't directly address the stated PR objective of hardening the NewRootFromHex function to handle input lengths less than 32. Could you please clarify how these changes relate to the PR objectives, or if there are additional files that implement the hardening of NewRootFromHex?

To check for the implementation of NewRootFromHex, you can run:

✅ Verification successful

Next Step: Review Changes in consensus.go Related to NewRootFromHex

To ensure the PR objectives of hardening NewRootFromHex are met, please provide the changes made to mod/primitives/pkg/common/consensus.go.


PR Objective Met: NewRootFromHex is hardened to handle input lengths less than 32

The changes in mod/primitives/pkg/common/consensus.go effectively implement the hardening of NewRootFromHex by adding a length check against RootSize.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the NewRootFromHex function implementation
rg --type go -A 10 'func NewRootFromHex'

Length of output: 692


Script:

#!/bin/bash
# Fetch changes in consensus.go related to NewRootFromHex
git diff origin/main -- mod/primitives/pkg/common/consensus.go

Length of output: 1108

mod/primitives/pkg/common/consensus.go (2)

78-80: Approve length check addition and error handling improvement.

The addition of the length check in NewRootFromHex is a good improvement. It ensures that the input is the correct size before creating a Root, which aligns with the PR objective of hardening this function. This change prevents potential panics and improves error handling.

The previously mentioned typo in the error variable name has been correctly addressed. The function now uses bytes.ErrIncorrectLength, which is the correct error variable name.

These changes enhance the robustness of the NewRootFromHex function and improve its error handling capabilities.


49-49: Approve comment correction for Hash32 type.

The correction of "as er" to "as per" in the comment for the Hash32 type is a good catch. This minor change improves the readability and correctness of the documentation.

Thank you for paying attention to these details, as they contribute to the overall quality of the codebase.

mod/primitives/pkg/common/consensus_test.go Outdated Show resolved Hide resolved
mod/primitives/pkg/common/consensus_test.go Outdated Show resolved Hide resolved
mod/primitives/pkg/common/consensus_test.go Outdated Show resolved Hide resolved
Comment on lines +68 to +70
type Root [RootSize]byte

const RootSize = 32
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

Consider using bytes.B32 for Root type while maintaining the RootSize constant.

The change to use RootSize instead of a hardcoded value improves maintainability. However, as previously suggested, using bytes.B32 for the Root type could further enhance consistency with other type definitions in this file (e.g., Bytes32, Hash32).

Consider the following approach:

const RootSize = 32

type Root = bytes.B32

This approach:

  1. Maintains the RootSize constant for clarity and potential future use.
  2. Utilizes the existing bytes.B32 type, ensuring consistency.
  3. Keeps Root as a distinct named type, preserving its semantic meaning.

If there's a specific reason for keeping Root as a separate type declaration, please clarify. Otherwise, this change could simplify the code while maintaining type safety and consistency with other primitives.

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 e6bcae2 and 05720ec.

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

Comment on lines +33 to +67
func TestNewRootFromHex(t *testing.T) {
tests := []struct {
name string
input func() string
expectedErr error
}{
{
name: "EmptyString",
input: func() string {
return ""
},
expectedErr: hex.ErrEmptyString,
},
{
name: "ShortSize",
input: func() string {
return hex.Prefix + strings.Repeat("f", 2*common.RootSize-2)
},
expectedErr: bytes.ErrIncorrectLength,
},
{
name: "RightSize",
input: func() string {
return hex.Prefix + strings.Repeat("f", 2*common.RootSize)
},
expectedErr: nil,
},
{
name: "LongSize",
input: func() string {
return hex.Prefix + strings.Repeat("f", 2*common.RootSize+2)
},
expectedErr: bytes.ErrIncorrectLength,
},
}
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 error checking for more precise validation.

The test cases are well-structured and cover important scenarios. To improve the robustness of the tests, consider enhancing the error checking to verify the specific error type, not just its presence or absence.

Modify the error checking block in the test execution loop as follows:

if tt.expectedErr != nil {
    require.ErrorIs(t, err, tt.expectedErr)
} else {
    require.NoError(t, err)
}

This change ensures that the exact expected error type is returned, providing more precise error validation.

Comment on lines +1 to +84
// SPDX-License-Identifier: BUSL-1.1
//
// Copyright (C) 2024, Berachain Foundation. All rights reserved.
// Use of this software is governed by the Business Source License included
// in the LICENSE file of this repository and at www.mariadb.com/bsl11.
//
// ANY USE OF THE LICENSED WORK IN VIOLATION OF THIS LICENSE WILL AUTOMATICALLY
// TERMINATE YOUR RIGHTS UNDER THIS LICENSE FOR THE CURRENT AND ALL OTHER
// VERSIONS OF THE LICENSED WORK.
//
// THIS LICENSE DOES NOT GRANT YOU ANY RIGHT IN ANY TRADEMARK OR LOGO OF
// LICENSOR OR ITS AFFILIATES (PROVIDED THAT YOU MAY USE A TRADEMARK OR LOGO OF
// LICENSOR AS EXPRESSLY REQUIRED BY THIS LICENSE).
//
// TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
// AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
// EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
// TITLE.

package common_test

import (
"strings"
"testing"

"github.com/berachain/beacon-kit/mod/primitives/pkg/bytes"
"github.com/berachain/beacon-kit/mod/primitives/pkg/common"
"github.com/berachain/beacon-kit/mod/primitives/pkg/encoding/hex"
"github.com/stretchr/testify/require"
)

func TestNewRootFromHex(t *testing.T) {
tests := []struct {
name string
input func() string
expectedErr error
}{
{
name: "EmptyString",
input: func() string {
return ""
},
expectedErr: hex.ErrEmptyString,
},
{
name: "ShortSize",
input: func() string {
return hex.Prefix + strings.Repeat("f", 2*common.RootSize-2)
},
expectedErr: bytes.ErrIncorrectLength,
},
{
name: "RightSize",
input: func() string {
return hex.Prefix + strings.Repeat("f", 2*common.RootSize)
},
expectedErr: nil,
},
{
name: "LongSize",
input: func() string {
return hex.Prefix + strings.Repeat("f", 2*common.RootSize+2)
},
expectedErr: bytes.ErrIncorrectLength,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var err error
f := func() {
input := tt.input()
_, err = common.NewRootFromHex(input)
}
require.NotPanics(t, f)
if tt.expectedErr != nil {
require.ErrorIs(t, err, tt.expectedErr)
} else {
require.NoError(t, err)
}
})
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Excellent test implementation for NewRootFromHex.

The test file is well-structured, follows Go best practices, and provides good coverage for the NewRootFromHex function. It effectively addresses the PR objective of hardening the function by testing various input scenarios, including those that could potentially cause panics.

The table-driven test approach allows for easy addition of more test cases in the future. The use of subtests, panic checks, and error assertions contributes to the robustness of the tests.

As the codebase evolves, consider expanding these tests to cover more edge cases and potential error scenarios. This will help maintain the reliability of the NewRootFromHex function over time.

@itsdevbear itsdevbear enabled auto-merge (squash) October 10, 2024 17:57
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.

3 participants