-
Notifications
You must be signed in to change notification settings - Fork 107
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
Conversation
WalkthroughThe changes in this pull request involve updates to several files in the Changes
Possibly related PRs
Suggested reviewers
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
@@ -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 |
There was a problem hiding this comment.
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
?
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ 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
|
There was a problem hiding this 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
inutils.go
. Please correct it toErrIncorrectLength
to maintain code quality.🔗 Analysis chain
Line range hint
1-93
: Verify alignment with PR objectivesThe 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 documentationThe 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:
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.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 hexAdd 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
- The comment correction for
Hash32
improves documentation clarity.- The introduction of
RootSize
and its use in theRoot
type definition improves maintainability, but consider usingbytes.B32
directly for consistency with other types.- The length check addition in
NewRootFromHex
improves function robustness, aligning with the PR objective.- 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 theRoot
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 asprefixLen
instring.go
andconst.go
. To maintain consistency with the newly exportedPrefix
constant, please rename these variables toPrefixLen
.
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 ofPrefix
throughout the fileThe changes in this file primarily involve replacing
prefix
withPrefix
across various functions. This modification suggests a broader refactoring to makePrefix
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
📒 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! ExportingPrefix
improves reusability.The changes look good and align with the PR objectives:
- Renaming
prefix
toPrefix
makes it accessible outside the package, improving reusability across the codebase.- Updating
prefixLen
to usePrefix
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 variablesThe change from
prefix
toPrefix
suggests that this variable is now exported. While this change is straightforward, it has potential implications:
- Ensure that
Prefix
is properly defined and exported in the package.- Consider if this change affects the package's API and if it's intentional.
- For consistency, review if
prefixLen
andinitialCapacity
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 thePrefix
variableThe change from
prefix
toPrefix
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:
- Ensure that exporting
Prefix
aligns with the package's design intentions.- Document the purpose and expected usage of
Prefix
in the package documentation.- 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 appropriateThe renaming from
prefix
toPrefix
inbytes.go
aligns with the existing usage of the exportedPrefix
constant defined inconst.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 thePrefix
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 ofPrefix
The change from
prefix
toPrefix
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 ofPrefix
The change from
prefix
toPrefix
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 ofPrefix
in validationThe change from
prefix
toPrefix
in the validation logic is consistent with the previous modifications. The use ofstrings.ToLower()
ensures a case-insensitive comparison, maintaining the robustness of the validation.
80-82
: LGTM: Consistent use ofPrefix
in encodingThe change from
prefix
toPrefix
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.
@@ -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 |
There was a problem hiding this comment.
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
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:]) |
There was a problem hiding this comment.
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.
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)) | |
} |
There was a problem hiding this 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
📒 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 ofErrIncorrectLength
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 ofErrIncorrectLength
inUnmarshalJSONHelper
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 ofErrIncorrectLength
inUnmarshalTextHelper
The replacement of the inline error with
ErrIncorrectLength
is appropriate and consistent with the change inUnmarshalJSONHelper
. This change further enhances the consistency of error handling across the package.
Line range hint
1-94
: Verify alignment with PR objectivesWhile 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 ofNewRootFromHex
?To check for the implementation of
NewRootFromHex
, you can run:✅ Verification successful
Next Step: Review Changes in
consensus.go
Related toNewRootFromHex
To ensure the PR objectives of hardening
NewRootFromHex
are met, please provide the changes made tomod/primitives/pkg/common/consensus.go
.
PR Objective Met:
NewRootFromHex
is hardened to handle input lengths less than 32The changes in
mod/primitives/pkg/common/consensus.go
effectively implement the hardening ofNewRootFromHex
by adding a length check againstRootSize
.🏁 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.goLength 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 aRoot
, 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 forHash32
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.
type Root [RootSize]byte | ||
|
||
const RootSize = 32 |
There was a problem hiding this comment.
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:
- Maintains the
RootSize
constant for clarity and potential future use. - Utilizes the existing
bytes.B32
type, ensuring consistency. - 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.
There was a problem hiding this 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
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, | ||
}, | ||
} |
There was a problem hiding this comment.
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.
// 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) | ||
} | ||
}) | ||
} | ||
} |
There was a problem hiding this comment.
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.
NewRootFromHex
would panic ifinput
length is less than 32.A related question is if should define
Root
as an alias ofbytes.B32
Summary by CodeRabbit
New Features
NewRootFromHex
function.Improvements
B32
andRoot
to use constants for better maintainability.Prefix
variable.Bug Fixes
NewRootFromHex
function to ensure proper error handling.