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

Derive Cosmos addresses from public keys #273

Merged
merged 1 commit into from
Oct 29, 2024

Conversation

joshklop
Copy link
Collaborator

@joshklop joshklop commented Oct 27, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new CosmosETHAddress type for improved handling of Ethereum addresses in the Cosmos context.
    • Added functionality to convert secp256k1 public keys to Cosmos Ethereum addresses.
  • Bug Fixes

    • Streamlined address conversion processes across various modules, enhancing clarity and maintainability.
  • Tests

    • Expanded test coverage for address conversions and added new tests for the CosmosETHAddress functionality.
    • Updated integration tests to utilize the new address conversion methods.
  • Chores

    • Removed outdated utility functions and cleaned up code dependencies related to address handling.

Copy link
Contributor

coderabbitai bot commented Oct 27, 2024

Walkthrough

The changes in this pull request primarily involve the transition from using the utils package for Ethereum to Cosmos address conversion to utilizing the monomer package. This includes modifications across several test files and the introduction of new functionalities in monomer.go. Key updates include the removal of the EvmToCosmosAddress function, the addition of a new type and methods in monomer, and adjustments in multiple test files to reflect the new address handling approach.

Changes

File Change Summary
builder/builder_test.go Removed import of utils, replaced EvmToCosmosAddress calls with monomer.CosmosETHAddress(...).Encode(...).
e2e/stack_test.go Renamed userAddress to userETHAddress, added userCosmosETHAddress, updated function calls with new variables.
monomer.go Added CosmosETHAddress type, PubkeyToCosmosETHAddress function, and Encode method; imported cryptographic packages.
monomer_test.go Added TestCosmosETHAddress to validate conversion of public keys to Cosmos Ethereum addresses.
utils/utils.go Removed EvmToCosmosAddress function and related import statements.
x/rollup/keeper/deposits.go Replaced utils.EvmToCosmosAddress calls with monomer.CosmosETHAddress, updated error handling.
x/rollup/tests/integration/rollup_test.go Added import for monomer, removed utils, updated address conversion calls to use monomer.

Possibly related PRs

Suggested reviewers

  • natebeauregard

Poem

🐰 In the code where rabbits play,
We’ve found a brighter way!
With monomer now in sight,
Address conversions feel just right.
Hopping through tests, we cheer,
For clarity and code so dear!
🐇✨


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.

@joshklop joshklop force-pushed the joshklop.fix-address-conversion branch 2 times, most recently from ce8d1a6 to bcc0c62 Compare October 27, 2024 23:09
@joshklop joshklop force-pushed the joshklop.fix-address-conversion branch from bcc0c62 to fc7bc42 Compare October 27, 2024 23:29
@joshklop joshklop marked this pull request as ready for review October 27, 2024 23:29
@joshklop
Copy link
Collaborator Author

I was planning to do this later, but it's required for fixing the e2e tests.

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

🧹 Outside diff range and nitpick comments (5)
monomer_test.go (1)

226-239: Add documentation explaining the test's purpose.

While the test implementation is correct, adding a comment block explaining the test's purpose and the relationship between Cosmos and Ethereum addresses would improve maintainability.

+// TestCosmosETHAddress verifies that public keys are correctly converted to Cosmos Ethereum addresses
+// and properly encoded using the Cosmos address format. It validates that our implementation matches
+// the Cosmos SDK's address derivation process.
 func TestCosmosETHAddress(t *testing.T) {
monomer.go (2)

27-27: Consider documenting the reason for disabling staticcheck.

The ripemd160 package has a staticcheck disable comment. While this is a commonly used cryptographic hash function in blockchain address derivation, it would be helpful to document why the staticcheck warning is being ignored.


244-266: Strong architectural design for address handling.

The implementation demonstrates good architectural choices:

  1. Clear separation of concerns between address creation and encoding
  2. Type safety through the custom CosmosETHAddress type
  3. Follows standard cryptographic practices for address derivation
  4. Integrates well with both Ethereum and Cosmos ecosystems

Consider adding examples in the documentation to demonstrate typical usage patterns.

Add usage examples to the documentation:

// Example:
//
//	pubKey := // ... your secp256k1 public key
//	addr := PubkeyToCosmosETHAddress(pubKey)
//	bech32Addr, err := addr.Encode("cosmos")
//	if err != nil {
//		// handle error
//	}
x/rollup/keeper/deposits.go (1)

124-128: Maintain consistent error handling patterns.

While the address conversion is correct, consider using types.WrapError for consistency with other error handling in this file:

 mintAddr, err := monomer.CosmosETHAddress(from).Encode(addrPrefix)
 if err != nil {
     ctx.Logger().Error("Failed to convert EVM to Cosmos address", "err", err)
-    return nil, fmt.Errorf("evm to cosmos address: %v", err)
+    return nil, types.WrapError(types.ErrInvalidL1Txs, "failed to convert EVM to Cosmos address: %v", err)
 }
e2e/stack_test.go (1)

Line range hint 1-644: Consider adding integration test for address conversion edge cases.

While the current tests cover the happy path, consider adding test cases for:

  1. Invalid address formats
  2. Zero addresses
  3. Contract addresses
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 63bbf2c and fc7bc42.

📒 Files selected for processing (7)
  • builder/builder_test.go (1 hunks)
  • e2e/stack_test.go (7 hunks)
  • monomer.go (3 hunks)
  • monomer_test.go (2 hunks)
  • utils/utils.go (0 hunks)
  • x/rollup/keeper/deposits.go (2 hunks)
  • x/rollup/tests/integration/rollup_test.go (3 hunks)
💤 Files with no reviewable changes (1)
  • utils/utils.go
🔇 Additional comments (19)
monomer_test.go (1)

10-12: LGTM: Required imports for Cosmos address handling.

The new imports are appropriate for handling secp256k1 keys and Cosmos SDK types.

x/rollup/tests/integration/rollup_test.go (2)

26-27: LGTM: Import changes align with the transition to monomer package.

The addition of monomer imports and removal of utils import is consistent with the PR objective of deriving Cosmos addresses from public keys.


55-58: LGTM: Address conversion implementation is consistent and robust.

The transition to monomer.CosmosETHAddress(...).Encode(...) is well-implemented with proper error handling and consistent use of the system's Bech32 prefix.

Let's verify the consistency of address conversion across the codebase:

Also applies to: 67-68

✅ Verification successful

Address conversion changes are consistent across the codebase

The verification confirms:

  • No instances of the old EvmToCosmosAddress method remain in the codebase
  • The new monomer.CosmosETHAddress(...).Encode(...) pattern is consistently used across all relevant files:
    • Integration tests (x/rollup/tests/integration/rollup_test.go)
    • Keeper logic (x/rollup/keeper/deposits.go)
    • E2E tests (e2e/stack_test.go)
    • Builder tests (builder/builder_test.go)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all Ethereum to Cosmos address conversions use the new monomer package
# and that there are no remaining instances of the old utils.EvmToCosmosAddress.

# Test 1: Search for any remaining instances of the old conversion method
echo "Checking for old conversion method..."
rg "EvmToCosmosAddress"

# Test 2: Verify consistent usage of the new conversion method
echo "Verifying new conversion method usage..."
rg "CosmosETHAddress.*Encode"

Length of output: 1595

monomer.go (3)

245-250: LGTM! Well-documented type definition.

The CosmosETHAddress type is well-documented with clear references to ADR-28 and explicit limitations regarding secp256k1 keys.


264-266: LGTM! Clean and correct implementation.

The Encode method correctly uses the Cosmos SDK's bech32 package for address encoding with appropriate error handling.


252-262: 🛠️ Refactor suggestion

Consider adding input validation for secp256k1 keys.

While the function documentation states that passing non-secp256k1 keys results in undefined behavior, it might be better to add explicit validation to prevent potential issues.

Consider adding validation:

 func PubkeyToCosmosETHAddress(pubKey *ecdsa.PublicKey) CosmosETHAddress {
+    if pubKey.Curve != secp256k1.S256() {
+        panic("PubkeyToCosmosETHAddress only supports secp256k1 keys")
+    }
     sha := sha256.Sum256(secp256k1.CompressPubkey(pubKey.X, pubKey.Y))
x/rollup/keeper/deposits.go (3)

Line range hint 130-134: Same error handling inconsistency as above.

This segment has the same error handling inconsistency as noted in the previous comment.


194-197: Same error handling inconsistency as above.

This segment has the same error handling inconsistency as noted in the first comment.


Line range hint 124-197: Verify complete migration from utils.EvmToCosmosAddress.

Let's verify that all instances of the old function have been replaced and the new function is properly imported.

✅ Verification successful

Based on the shell script results, I can now generate the final response:

Migration from utils.EvmToCosmosAddress to monomer.CosmosETHAddress is complete

The verification shows:

  • No remaining instances of utils.EvmToCosmosAddress in the codebase
  • Proper import of monomer package where CosmosETHAddress is used
  • Consistent usage of CosmosETHAddress across the codebase, particularly in deposit-related operations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining instances of the old function and verify imports

# Test 1: Check for any remaining instances of the old function
echo "Checking for remaining instances of EvmToCosmosAddress..."
rg "EvmToCosmosAddress"

# Test 2: Verify proper import of the new function
echo "Verifying monomer package imports..."
rg "github.com/polymerdao/monomer"

# Test 3: Check for usage of CosmosETHAddress
echo "Checking usage of CosmosETHAddress..."
rg "CosmosETHAddress"

Length of output: 19372

builder/builder_test.go (3)

316-317: LGTM: Clean transition to monomer package for recipient address conversion

The conversion from Ethereum to Cosmos address format using monomer.CosmosETHAddress().Encode() is implemented correctly with proper error handling.


321-322: LGTM: Clean transition to monomer package for mint address conversion

The conversion from Ethereum to Cosmos address format using monomer.CosmosETHAddress().Encode() is implemented correctly with proper error handling.


316-322: Verify test coverage for address conversion

The changes replace the old address conversion utility with the new monomer package implementation. Let's verify that all test cases related to address conversion are passing.

✅ Verification successful

Let me gather more context about the test coverage by checking the implementation and test files more thoroughly.


Let me try one more verification to check the test coverage and assertions:


Let me check the actual test implementation for address conversion:


Based on the gathered information, I can now provide the final response:

Address conversion changes are properly tested

The new monomer.CosmosETHAddress implementation is well-tested with:

  • Dedicated unit test TestCosmosETHAddress that verifies the core conversion functionality
  • Integration tests in multiple files:
    • builder/builder_test.go: Tests deposit flow address conversion
    • e2e/stack_test.go: Tests withdrawal flow and user address conversions

The old EvmToCosmosAddress utility has been completely replaced, and all test cases are using the new implementation consistently.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any other tests that might be using the old address conversion utility

# Test: Search for any remaining references to the old conversion utility
rg "EvmToCosmosAddress" 

# Test: Verify all test files that use the new conversion utility
rg "CosmosETHAddress.*Encode.*cosmos"

Length of output: 535


Script:

#!/bin/bash
# Check the implementation and test files for address conversion
# Look for any potential address conversion implementations or related tests
ast-grep --pattern 'func $_($$$) { 
  $$$
  CosmosETHAddress($$$)
  $$$
}'

# Check test files for any address-related assertions
rg -B2 -A2 "require.*addr" ".*_test.go"

Length of output: 169


Script:

#!/bin/bash
# Search for test files containing address conversion tests
rg -B3 -A3 "require.*NoError.*\b(addr|address)" --type go

# Look for any potential test failures or errors related to address conversion
rg "func Test.*Address" --type go

Length of output: 675


Script:

#!/bin/bash
# Check the implementation of TestCosmosETHAddress
rg -B5 -A15 "func TestCosmosETHAddress" monomer_test.go

# Check for any related test assertions in builder_test.go
rg -B3 -A3 "CosmosETHAddress.*Encode.*cosmos.*require" builder_test.go

Length of output: 999

e2e/stack_test.go (7)

251-251: LGTM! Clear variable naming improves code readability.

The renaming of userAddress to userETHAddress and introduction of userCosmosETHAddress makes the code more explicit about address types and their purposes.

Also applies to: 257-258


264-264: LGTM! Consistent use of address types in deposit flow.

The deposit flow correctly uses the appropriate address types:

  • userETHAddress for checking L1 balance
  • userCosmosETHAddress for the deposit target

Also applies to: 271-271


297-298: LGTM! Proper event filtering with correct address types.

The filter parameters correctly use:

  • userETHAddress for the depositor address
  • userCosmosETHAddress for the target address

320-322: LGTM! Proper address encoding for Cosmos.

The code correctly encodes the ETH address into Cosmos format using the new Encode method.


332-332: LGTM! Proper withdrawal flow with correct address handling.

The withdrawal flow correctly:

  1. Uses userCosmosETHAddress as the sender
  2. Properly encodes the sender address for Cosmos
  3. Maintains proper type safety throughout the flow

Also applies to: 335-344


404-404: LGTM! Consistent balance checking in finalization flow.

The finalization flow maintains consistency in using userETHAddress for L1 balance checks.

Also applies to: 437-437


537-537: LGTM! Proper address conversion in ERC20 flow.

The ERC20 flow correctly uses monomer.CosmosETHAddress for address conversion.

Comment on lines +226 to +239
func TestCosmosETHAddress(t *testing.T) {
privKey, err := secp256k1.GeneratePrivateKey()
require.NoError(t, err)
pubKey := privKey.PubKey().ToECDSA()
got := monomer.PubkeyToCosmosETHAddress(pubKey)
wantBytes := (&cosmossecp256k1.PubKey{
Key: privKey.PubKey().SerializeCompressed(), // https://github.com/cosmos/cosmos-sdk/blob/346044afd0ecd4738c13993d2ac75da8e242266d/crypto/keys/secp256k1/secp256k1.go#L44-L45
}).Address().Bytes()
require.Equal(t, wantBytes, common.Address(got).Bytes())
// We have to use the `cosmos` hrp here because sdk.AccAddress.String() uses the global SDK config variable that uses the `cosmos` hrp.
gotEncoded, err := got.Encode("cosmos")
require.NoError(t, err)
require.Equal(t, sdk.AccAddress(wantBytes).String(), gotEncoded)
}
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 adding test cases for edge cases.

The current test only covers the happy path. Consider adding test cases for:

  1. Invalid public keys
  2. Different address prefixes
  3. Zero addresses
  4. Known test vectors from the Cosmos SDK

This would ensure robust handling of various scenarios.

Would you like me to provide an implementation for these additional test cases?

@joshklop
Copy link
Collaborator Author

Now that I think about it, I believe the address conversions in the wallet web app will need to change. We'll want to simply obtain the data part of the bech32 encoding, which should be simple, but I'm not sure how to do that using the bech32 js library yet.

@natebeauregard
Copy link
Collaborator

Now that I think about it, I believe the address conversions in the wallet web app will need to change. We'll want to simply obtain the data part of the bech32 encoding, which should be simple, but I'm not sure how to do that using the bech32 js library yet.

Yeah good catch. I copied the bech32 JS library from the bech32 npm library with a few minor changes to expose it directly in the browser. There may be something we could use in their and if not there's probably a different pre-existing library that we could use for our frontend conversion.

Copy link
Collaborator

@natebeauregard natebeauregard left a comment

Choose a reason for hiding this comment

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

Monomer changes LGTM. I'll wait to approve until the frontend wallet server changes are in as well. I wonder if we can use some of the helpers from the Evmos JS converter.

@joshklop
Copy link
Collaborator Author

Hmm, it seems to work fine for me. Perhaps I'm doing something wrong though. Mind checking on your end @natebeauregard ?

@natebeauregard
Copy link
Collaborator

natebeauregard commented Oct 29, 2024

Hmm, it seems to work fine for me. Perhaps I'm doing something wrong though. Mind checking on your end @natebeauregard ?

@joshklop When you say it seems to work fine for me are you referring to the frontend bech32 library in the wallet integration server? If so that's great, have you tested with prefixes other than "cosmos"? I can test as well on my end once I get some more context

@joshklop
Copy link
Collaborator Author

When you say it seems to work fine for me are you referring to the frontend bech32 library in the wallet integration server?

I'm able to deposit funds to L2 and transfer them around. I would expect that the different address translation would cause them to be sent to a different address (i.e., not my keplr address). However, thinking about this again, it actually makes sense: the way you did address translation in frontend happened to be compatible with both address conversion methods.

If so that's great, have you tested with prefixes other than "cosmos"?

I have not. Might be interesting to try it though. I'll see if I can get to it tomorrow, pretty unlikely however.

@natebeauregard
Copy link
Collaborator

When you say it seems to work fine for me are you referring to the frontend bech32 library in the wallet integration server?

I'm able to deposit funds to L2 and transfer them around. I would expect that the different address translation would cause them to be sent to a different address (i.e., not my keplr address). However, thinking about this again, it actually makes sense: the way you did address translation in frontend happened to be compatible with both address conversion methods.

If so that's great, have you tested with prefixes other than "cosmos"?

I have not. Might be interesting to try it though. I'll see if I can get to it tomorrow, pretty unlikely however.

Sounds good, thanks for the clarification. I can test the prefix case tm morning and can approve/merge if it works!

@natebeauregard
Copy link
Collaborator

Alternative prefixes work as well :)

@natebeauregard natebeauregard merged commit db3add8 into main Oct 29, 2024
16 checks passed
@natebeauregard natebeauregard deleted the joshklop.fix-address-conversion branch October 29, 2024 17:46
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