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

fix: Use canonical hexadecimal strings for Eip155 address encoding #2120

Merged
merged 7 commits into from
Dec 6, 2024

Conversation

CalicoNino
Copy link
Contributor

@CalicoNino CalicoNino commented Dec 6, 2024

Purpose / Abstract

Summary by CodeRabbit

Release Notes

  • Documentation

    • Updated the CHANGELOG.md with new entries for unreleased features and bug fixes related to the Nibiru EVM.
    • Corrected spelling errors and clarified audit-related information in the documentation.
  • New Features

    • Enhanced serialization and deserialization processes for EIP55 address handling, focusing on string representations.
    • Improved error handling and context management in transaction tracing methods.
  • Bug Fixes

    • Fixed gas consumption calculations in NibiruBankKeeper and ensured correct address encoding for EIP155.
  • Tests

    • Added new tests for validating EIP55 address marshaling and updated existing tests to reflect changes in serialization formats.

@CalicoNino CalicoNino requested a review from a team as a code owner December 6, 2024 22:54
Copy link
Contributor

coderabbitai bot commented Dec 6, 2024

Walkthrough

The changes in this pull request include updates to the CHANGELOG.md to document notable changes in the Nibiru project, particularly regarding fixes and features related to the Nibiru EVM. Modifications in the eth/eip55.go file enhance the serialization and deserialization of the EIP55Addr struct. The eth/eip55_test.go file has been updated with new tests to validate these changes. Additionally, the x/evm/keeper/grpc_query.go file has been modified to improve error handling and context management in transaction tracing methods.

Changes

File Change Summary
CHANGELOG.md Updated with new entries under "Unreleased" for fixes and features related to Nibiru EVM. Corrected spelling errors and clarified audit section.
eth/eip55.go Modified serialization/deserialization methods for EIP55Addr to use hexadecimal string representation. Updated method signatures for clarity.
eth/eip55_test.go Added TestStringEncoding to validate marshaling/unmarshaling of EIP55Addr. Adjusted expected outputs in TestProtobufEncoding.
x/evm/keeper/grpc_query.go Enhanced TraceBlock and TraceEthTxMsg methods with improved error handling and timeout management. Minor comment adjustments for clarity.

Assessment against linked issues

Objective Addressed Explanation
Correct gas consumption during send operations in "NibiruBankKeeper" (#2119)
Ensure toEthAddr in MsgConvertCoinToEvm is the final receiver (#391) The changes do not address the issue with toEthAddr.
Fix QueryFunTokenMapping returning invalid erc20Addr (#392) It is unclear if the changes impact the query results.

Possibly related PRs

Suggested reviewers

  • onikonychev

Poem

🐰 In the land of code where rabbits play,
Changes hop in, brightening the day.
With strings of hex, our addresses gleam,
Fixes and features, a developer's dream!
Changelog updated, clarity in sight,
Hopping along, everything feels right! 🌟


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.

@CalicoNino CalicoNino changed the title fix: Use Canonical Hexdecimal strings for Eip155 encoding fix: Use canonical heaxdecimal strings for Eip155 address encoding Dec 6, 2024
Copy link

codecov bot commented Dec 6, 2024

Codecov Report

Attention: Patch coverage is 60.00000% with 4 lines in your changes missing coverage. Please review.

Project coverage is 64.79%. Comparing base (5a7f90d) to head (9aa15f7).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
eth/eip55.go 60.00% 3 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2120      +/-   ##
==========================================
- Coverage   64.80%   64.79%   -0.01%     
==========================================
  Files         273      273              
  Lines       21638    21636       -2     
==========================================
- Hits        14022    14020       -2     
  Misses       6644     6644              
  Partials      972      972              
Files with missing lines Coverage Δ
x/evm/keeper/grpc_query.go 79.58% <ø> (ø)
eth/eip55.go 74.28% <60.00%> (-1.39%) ⬇️

@CalicoNino CalicoNino self-assigned this Dec 6, 2024
@Unique-Divine Unique-Divine enabled auto-merge (squash) December 6, 2024 23:46
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: 7

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5a7f90d and 9aa15f7.

📒 Files selected for processing (4)
  • CHANGELOG.md (2 hunks)
  • eth/eip55.go (1 hunks)
  • eth/eip55_test.go (3 hunks)
  • x/evm/keeper/grpc_query.go (1 hunks)
🔇 Additional comments (5)
x/evm/keeper/grpc_query.go (1)

653-653: Comment Update is Appropriate

The updated comment accurately reflects the function's operation.

eth/eip55_test.go (3)

119-127: Update Expected JSON Values in Tests

The changes to expectedJson in TestProtobufEncoding should align with the serialization methods. If the serialization is corrected as per the earlier comments, ensure that the expected JSON values in the tests are updated accordingly.


143-143: Review Assertion for Marshaled Bytes

The assertion comparing the marshaled bytes may not be valid if the serialization method is corrected. Please verify that the test accurately reflects the expected output after fixing the serialization methods.


151-152: Correct Size Method Assertions

The assertions for the Size method should be updated to reflect the corrected size calculation. Ensure that the tests validate the size based on the raw byte length of the address.

CHANGELOG.md (1)

48-48: Changelog Entry Added for EIP155 Address Encoding Fix

The changelog entry correctly documents the fix related to the use of canonical hexadecimal strings for EIP155 address encoding.

}

// MarshalTo serializes a EIP55Addr directly into a pre-allocated byte slice ("data").
// MarshalTo implements the gogo proto custom type interface.
// Implements the gogo proto custom type interface.
// Ref: https://github.com/cosmos/gogoproto/blob/v1.5.0/custom_types.md
func (h *EIP55Addr) MarshalTo(data []byte) (n int, err error) {
copy(data, h.Bytes())
copy(data, []byte(h.Address.Hex()))
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect Serialization in MarshalTo Method

The MarshalTo method should copy the raw bytes of the address into the data slice to conform with protobuf serialization requirements. Copying the hexadecimal string representation ([]byte(h.Address.Hex())) is inappropriate and may cause serialization issues.

Suggested fix:

func (h *EIP55Addr) MarshalTo(data []byte) (n int, err error) {
-	copy(data, []byte(h.Address.Hex()))
+	copy(data, h.Address.Bytes())
	return h.Size(), nil
}
📝 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
copy(data, []byte(h.Address.Hex()))
copy(data, h.Address.Bytes())

@@ -36,53 +35,49 @@
// Marshal implements the gogo proto custom type interface.
// Ref: https://github.com/cosmos/gogoproto/blob/v1.5.0/custom_types.md
func (h EIP55Addr) Marshal() ([]byte, error) {
return h.Bytes(), nil
return []byte(h.Address.Hex()), nil
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect Protobuf Serialization Format in Marshal Method

The Marshal method should return the raw bytes of the address to conform with protobuf serialization expectations. Returning the hexadecimal string representation ([]byte(h.Address.Hex())) may lead to serialization issues.

Suggested fix:

func (h EIP55Addr) Marshal() ([]byte, error) {
-	return []byte(h.Address.Hex()), nil
+	return h.Address.Bytes(), nil
}
📝 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 []byte(h.Address.Hex()), nil
return h.Address.Bytes(), nil

}

// MarshalJSON returns the [EIP55Addr] as JSON bytes.
// Implements the gogo proto custom type interface.
// Ref: https://github.com/cosmos/gogoproto/blob/v1.5.0/custom_types.md
func (h EIP55Addr) MarshalJSON() ([]byte, error) {
return json.Marshal(h.String())
return []byte(h.String()), nil
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Invalid JSON Encoding in MarshalJSON Method

Directly returning []byte(h.String()) bypasses JSON encoding and may result in invalid JSON output. The MarshalJSON method should use json.Marshal(h.String()) to ensure proper JSON formatting and escaping.

Proposed fix:

func (h EIP55Addr) MarshalJSON() ([]byte, error) {
-	return []byte(h.String()), nil
+	return json.Marshal(h.String())
}
📝 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 []byte(h.String()), nil
return json.Marshal(h.String())

eth/eip55.go Show resolved Hide resolved
Comment on lines +60 to +64
addr, err := NewEIP55AddrFromStr(string(data))
if err != nil {
return err
}
*h = addr
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect Deserialization in Unmarshal Method

The Unmarshal method should reconstruct the address from the raw bytes provided, not from a string representation. Converting data to a string and parsing it may result in incorrect deserialization, especially if the original data is not a valid string.

Suggested fix:

func (h *EIP55Addr) Unmarshal(data []byte) error {
-	addr, err := NewEIP55AddrFromStr(string(data))
-	if err != nil {
-		return err
-	}
-	*h = addr
+	if len(data) != gethcommon.AddressLength {
+		return fmt.Errorf("invalid EIP55Addr length: %d", len(data))
+	}
+	h.Address = gethcommon.BytesToAddress(data)
	return nil
}
📝 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
addr, err := NewEIP55AddrFromStr(string(data))
if err != nil {
return err
}
*h = addr
if len(data) != gethcommon.AddressLength {
return fmt.Errorf("invalid EIP55Addr length: %d", len(data))
}
h.Address = gethcommon.BytesToAddress(data)
return nil

}

addr, err := NewEIP55AddrFromStr(*text)
addr, err := NewEIP55AddrFromStr(string(bz))
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect JSON Decoding in UnmarshalJSON Method

The UnmarshalJSON method should use json.Unmarshal to correctly parse the JSON-encoded data. Directly converting bz to a string and parsing it may fail to handle JSON encoding properly, especially with quotation marks.

Proposed fix:

func (h *EIP55Addr) UnmarshalJSON(bz []byte) error {
-	addr, err := NewEIP55AddrFromStr(string(bz))
+	var addrStr string
+	if err := json.Unmarshal(bz, &addrStr); err != nil {
+		return err
+	}
+	addr, err := NewEIP55AddrFromStr(addrStr)
	if err != nil {
		return err
	}
	*h = addr
	return nil
}

Committable suggestion skipped: line range outside the PR's diff.

eth/eip55_test.go Show resolved Hide resolved
@Unique-Divine Unique-Divine merged commit debaa4d into main Dec 6, 2024
15 checks passed
@Unique-Divine Unique-Divine deleted the nino/funtoken branch December 6, 2024 23:55
@CalicoNino CalicoNino changed the title fix: Use canonical heaxdecimal strings for Eip155 address encoding fix: Use canonical hexadecimal strings for Eip155 address encoding Dec 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants