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: add Reason() method to VmError interface #8

Merged
merged 1 commit into from
Oct 25, 2024

Conversation

arrivets
Copy link

@arrivets arrivets commented Oct 25, 2024

This PR just adds the Reason method to the VmError interface.
The method is already implemented by vmErrorWithRet.
It's useful to have access to the reason field when there's and execution reverted error.

Summary by CodeRabbit

  • New Features

    • Introduced a Reason() method to provide detailed error information for EVM execution failures.
    • Enhanced error reporting by including a reason field in the VM error structure.
  • Bug Fixes

    • Improved clarity of error handling by formatting revert reasons in error messages.
  • Tests

    • Added a new test function to validate the behavior of the updated VM error handling.

Copy link

coderabbitai bot commented Oct 25, 2024

Walkthrough

The changes introduce a new method Reason() to the VmError interface in x/evm/types/errors.go, allowing for more detailed error reporting by returning a reason string. The vmErrorWithRet struct is updated to include a reason field. Additionally, the NewVmErrorWithRet function is modified to populate this field when the error corresponds to ErrExecutionReverted. A new test function, TestNewVmErrorWithRet, is added in x/evm/types/errors_test.go to validate the behavior of the updated function, enhancing test coverage for error handling.

Changes

File Change Summary
x/evm/types/errors.go Added method Reason() string to VmError interface; added reason field to vmErrorWithRet; updated NewVmErrorWithRet to populate reason for ErrExecutionReverted.
x/evm/types/errors_test.go Added new test function TestNewVmErrorWithRet to validate NewVmErrorWithRet behavior with various test cases.

Poem

In the land of code where errors reside,
A new reason blooms, no longer to hide.
With tests that now dance, ensuring all's right,
The rabbit hops on, in the soft moonlight.
"Errors explained!" he joyfully sings,
"With clarity now, see what each failure brings!" 🐇✨


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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
x/evm/types/errors_test.go (1)

55-91: Consider adding documentation to explain test cases.

While the test cases are comprehensive, adding comments to explain the purpose and expected behavior of each test case would improve maintainability. Consider documenting:

  • The significance of the revertSelector in error handling
  • Why certain byte sequences are used in the test data
  • The relationship between vmErr, reason, and ret fields
 func TestNewVmErrorWithRet(t *testing.T) {
+	// TestNewVmErrorWithRet validates the behavior of NewVmErrorWithRet function
+	// by testing various scenarios of error creation with different return data formats.
 	testCases := []struct {
 		name   string
 		vmErr  string
 		reason string
 		ret    []byte
 		hash   string
 	}{
+		// Test empty return data handling
 		{
 			"Empty reason",
 			"execution reverted",
x/evm/types/errors.go (1)

Line range hint 279-297: Consider enhancing error handling in NewVmErrorWithRet

While the implementation is functional, there are a few areas where error handling could be improved:

  1. The error from abi.UnpackRevert is silently ignored if unpacking fails. Consider logging or including this error in the JSON output for debugging purposes.
  2. The reason field is only populated for ErrExecutionReverted. Consider documenting this limitation or providing a meaningful value for other error types.

Here's a suggested improvement:

 if e.vmErr == vm.ErrExecutionReverted.Error() {
     e.err = vm.ErrExecutionReverted
     e.ret = common.CopyBytes(ret)
     reason, errUnpack := abi.UnpackRevert(e.ret)
     if errUnpack == nil {
         e.err = fmt.Errorf("%s: %s", e.err.Error(), reason)
         e.reason = reason
         e.cause = errorsmod.Wrap(ErrExecutionReverted, e.toJSON())
+    } else {
+        e.reason = "failed to unpack revert reason"
+        e.cause = errorsmod.Wrapf(ErrExecutionReverted, "failed to unpack revert reason: %v", errUnpack)
     }
 } else {
     e.err = errors.New(e.vmErr)
+    e.reason = e.vmErr // Use VM error as reason for non-revert errors
     e.cause = errorsmod.Wrap(ErrVMExecution, e.toJSON())
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 874b2db and a9fdaa3.

📒 Files selected for processing (2)
  • x/evm/types/errors.go (1 hunks)
  • x/evm/types/errors_test.go (1 hunks)
🔇 Additional comments (4)
x/evm/types/errors_test.go (1)

54-104: Implementation aligns well with PR objectives.

The test implementation effectively validates the new Reason() method functionality while maintaining comprehensive coverage of various error scenarios. The test structure ensures that the VmError interface enhancement works as intended.

x/evm/types/errors.go (3)

131-131: LGTM: Clean interface addition

The new Reason() method is a well-designed addition to the VmError interface, maintaining consistency with existing methods and providing a clean way to access error reasons.


Line range hint 132-150: LGTM: Clean implementation of Reason() method

The implementation follows the established pattern of other getter methods in the struct, including proper nil checks and consistent error handling.


Line range hint 279-297: Verify security implications of unconstrained revert reasons

The current implementation accepts revert reasons without validation, which could lead to potential issues:

  1. Memory exhaustion from extremely large revert reasons
  2. Potential XSS if the error messages are displayed in a web interface
  3. Log injection if the reasons are written to logs

Let's verify the maximum size of revert reasons in the codebase:

Comment on lines +93 to +104
for _, tc := range testCases {
tc := tc
vmErrorWithRet := NewVmErrorWithRet(
tc.vmErr,
tc.ret,
tc.hash,
0,
)
require.Equal(t, tc.vmErr, vmErrorWithRet.VmError())
require.Equal(t, tc.reason, vmErrorWithRet.Reason())
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test robustness and organization.

Consider the following improvements to strengthen the test implementation:

  1. Move the gas value into the test case structure instead of hardcoding it
  2. Use t.Run for subtests to improve test organization and output
  3. Add assertions for complete error state (e.g., hash value)
 	testCases := []struct {
 		name   string
 		vmErr  string
 		reason string
 		ret    []byte
 		hash   string
+		gas    uint64
 	}{
 		{
 			"Empty reason",
 			"execution reverted",
 			"",
 			nil,
 			"0x",
+			0,
 		},
 		// ... other test cases
 	}

 	for _, tc := range testCases {
-		tc := tc
-		vmErrorWithRet := NewVmErrorWithRet(
-			tc.vmErr,
-			tc.ret,
-			tc.hash,
-			0,
-		)
-		require.Equal(t, tc.vmErr, vmErrorWithRet.VmError())
-		require.Equal(t, tc.reason, vmErrorWithRet.Reason())
+		tc := tc // capture range variable
+		t.Run(tc.name, func(t *testing.T) {
+			vmErrorWithRet := NewVmErrorWithRet(
+				tc.vmErr,
+				tc.ret,
+				tc.hash,
+				tc.gas,
+			)
+			require.Equal(t, tc.vmErr, vmErrorWithRet.VmError())
+			require.Equal(t, tc.reason, vmErrorWithRet.Reason())
+			require.Equal(t, tc.hash, vmErrorWithRet.ErrorData())
+		})
 	}

Committable suggestion was skipped due to low confidence.

@arrivets arrivets merged commit 8f05d8e into develop Oct 25, 2024
8 of 9 checks passed
@maxim-inj maxim-inj deleted the chore/vmerror-reason branch October 26, 2024 12:04
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.

2 participants