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 statedb context at get_hash #112

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Conversation

beer-1
Copy link
Collaborator

@beer-1 beer-1 commented Nov 15, 2024

Description

Closes: #XXXX


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced new Context() method in MockStateDB and StateDB interface for enhanced state management.
    • Added ContextOfSnapshot method to StateDB for retrieving context associated with snapshots.
  • Updates

    • Updated dependency versions for improved compatibility and performance, including github.com/ethereum/go-ethereum.
    • Updated Go toolchain to version go1.23.0.
  • Bug Fixes

    • Removed unnecessary callableEVM interface to simplify method signatures and enhance clarity.

@beer-1 beer-1 requested a review from a team as a code owner November 15, 2024 03:58
Copy link

coderabbitai bot commented Nov 15, 2024

Walkthrough

The pull request introduces updates to the go.mod files for both the main module and the integration-tests module, focusing on dependency version changes and the introduction of custom replacements for several packages. Additionally, modifications are made to the keeper package, where method signatures are simplified by removing an interface and directly using a pointer to vm.EVM. New context-related methods are added to the StateDB struct and MockStateDB struct, enhancing functionality without altering existing logic.

Changes

File Change Summary
go.mod Updated Go toolchain to go1.23.0, incremented github.com/ethereum/go-ethereum from v1.14.9 to v1.14.11, added replacements for custom package versions.
integration-tests/go.mod Updated github.com/ethereum/go-ethereum from v1.14.9 to v1.14.11, added replacements for custom versions of several dependencies.
x/evm/keeper/context.go Updated method signatures in NewStateDB and buildBlockContext to use *vm.EVM instead of callableEVM, removed callableEVM interface.
x/evm/precompiles/cosmos/common_test.go Added Context() method to MockStateDB struct to return current sdk.Context.
x/evm/precompiles/erc20_registry/common_test.go Added Context() method to MockStateDB struct to return current sdk.Context.
x/evm/state/statedb.go Changed evm field type in StateDB from callableEVM to *vm.EVM, added ContextOfSnapshot and Context methods.
x/evm/types/expected_keeper.go Added Context() method to StateDB interface to return sdk.Context.

Possibly related PRs

Suggested reviewers

  • Vritra4
  • djm07073

Poem

🐰 In the garden where code does bloom,
Dependencies shift, making room.
With EVM's grace, we simplify,
Contexts added, oh me, oh my!
A hop, a skip, through modules we go,
Enhancing our paths, watch our projects grow! 🌼


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.

@beer-1 beer-1 changed the title fix: use statedb context fix: use statedb context at get_hash Nov 15, 2024
Copy link

codecov bot commented Nov 15, 2024

Codecov Report

Attention: Patch coverage is 71.42857% with 2 lines in your changes missing coverage. Please review.

Project coverage is 28.18%. Comparing base (8be43a3) to head (e7bad2e).

Files with missing lines Patch % Lines
x/evm/state/statedb.go 0.00% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main     #112   +/-   ##
=======================================
  Coverage   28.17%   28.18%           
=======================================
  Files         126      126           
  Lines       14275    14279    +4     
=======================================
+ Hits         4022     4024    +2     
- Misses       9680     9682    +2     
  Partials      573      573           
Files with missing lines Coverage Δ
x/evm/keeper/context.go 76.73% <100.00%> (+0.11%) ⬆️
x/evm/state/statedb.go 64.33% <0.00%> (-0.32%) ⬇️

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 (6)
x/evm/precompiles/erc20_registry/common_test.go (1)

Line range hint 1-80: Consider adding documentation about mock's scope

While the mock implementation is well-structured, it would be helpful to add documentation explaining which methods are intentionally implemented (context-related) versus intentionally left as panicking stubs. This would help other developers understand the mock's intended use case.

Consider adding a comment like this at the type declaration:

+// MockStateDB implements evmtypes.StateDB with focus on context management.
+// Only context-related methods are implemented, while other interface methods
+// are intentionally left as panicking stubs.
 type MockStateDB struct {
integration-tests/go.mod (1)

12-12: Consider documenting the fork management strategy

The project heavily relies on custom forks of major dependencies (cometbft, ibc-go, go-ethereum). While this provides better control over the codebase, it also increases maintenance overhead.

Consider:

  1. Documenting the fork management strategy
  2. Setting up automated processes to:
    • Monitor upstream changes
    • Regularly sync forks with upstream
    • Track divergence from upstream
  3. Creating a timeline for upstreaming custom changes where possible

Also applies to: 231-240

go.mod (2)

Line range hint 284-291: Document the rationale for custom replacements

The custom replacements section introduces forks of critical dependencies without documenting the reasons for these changes. While there's a comment about grpc issues, other replacements lack explanation.

Consider adding comments for each replacement to document:

  1. Why the fork was necessary
  2. What changes were made
  3. When we expect to remove the replacement

Example format:

 // initia custom
 replace (
+    // Fork needed to add feature X and fix issue Y
+    // Track upstream PR: https://github.com/cometbft/cometbft/pull/XXX
     github.com/cometbft/cometbft => github.com/initia-labs/cometbft v0.0.0-20241113064430-a371e2dc387f

Line range hint 290-291: Consider pinning GRPC version in a more maintainable way

The GRPC version is pinned to address issues with cosmos/relayer, but this might affect other dependencies.

Consider:

  1. Creating an issue to track when this can be removed
  2. Adding tests to verify the relayer functionality
  3. Contributing a fix upstream to cosmos/relayer
x/evm/keeper/context.go (1)

Line range hint 47-128: Consider refactoring the transfer logic into separate functions.

The buildBlockContext method contains complex transfer and balance check logic embedded within closures. Consider extracting these into separate methods for better maintainability and testability:

  • canTransfer function (~30 lines)
  • transfer function (~20 lines)

This would:

  1. Improve code readability
  2. Make the logic easier to test
  3. Reduce the cognitive complexity of the method
x/evm/state/statedb.go (1)

Line range hint 582-594: LGTM: Well-implemented context access methods.

The new methods provide clean access to snapshot and current contexts, which is essential for transaction isolation. Consider adding documentation comments to explain:

  • The relationship between snapshots and contexts
  • The significance of -1 as a special snapshot ID
+// ContextOfSnapshot returns the context associated with a specific snapshot.
+// If i is -1, returns the initial context before any snapshots were created.
 func (s *StateDB) ContextOfSnapshot(i int) sdk.Context {

+// Context returns the current context which may be a snapshot context
+// if any snapshots are active.
 func (s *StateDB) Context() sdk.Context {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8be43a3 and e7bad2e.

📒 Files selected for processing (7)
  • go.mod (1 hunks)
  • integration-tests/go.mod (1 hunks)
  • x/evm/keeper/context.go (3 hunks)
  • x/evm/precompiles/cosmos/common_test.go (1 hunks)
  • x/evm/precompiles/erc20_registry/common_test.go (1 hunks)
  • x/evm/state/statedb.go (4 hunks)
  • x/evm/types/expected_keeper.go (1 hunks)
🔇 Additional comments (12)
x/evm/types/expected_keeper.go (1)

91-91: LGTM! Verify implementations across the codebase.

The addition of Context() method is a logical complement to the existing ContextOfSnapshot(i int) method, providing direct access to the current context.

Let's verify that all implementations of StateDB interface properly implement this new method:

✅ Verification successful

Let me search more specifically for the StateDB implementation and its Context method.


Implementation verified and consistent across the codebase

The Context() method is properly implemented in:

  • Main implementation in x/evm/state/statedb.go
  • Test mock implementations in precompiles test files
  • Snapshot implementation in x/evm/state/snapshot.go

All implementations consistently return the context field from their respective structs, maintaining uniform behavior across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all StateDB implementations and verify they implement the new Context() method

# Find all Go files that might contain StateDB implementations
echo "Searching for potential StateDB implementations..."
rg -l "StateDB" --type go

# Look for struct types that implement StateDB interface
echo "Checking for Context() method implementations..."
ast-grep --pattern 'type $_ struct {
  $$$
}

func ($_ $_) Context() sdk.Context {
  $$$
}'

Length of output: 789


Script:

#!/bin/bash
# First, let's find the actual StateDB implementation
echo "Searching for StateDB implementation..."
rg "type StateDB struct" -A 5

# Then look for Context method implementation
echo -e "\nSearching for Context() method implementation..."
rg "func \(.*?\) Context\(\) sdk.Context" -A 2

# Let's also check the interface usage to understand the impact
echo -e "\nChecking StateDB interface usage..."
rg "StateDB interface" -A 5

Length of output: 1620

x/evm/precompiles/erc20_registry/common_test.go (2)

76-79: LGTM: Clean implementation of Context() method

The implementation is straightforward and consistent with the existing context management pattern in the mock.


76-79: Well-integrated with existing snapshot management

The new Context() method integrates seamlessly with the existing snapshot-related methods, maintaining a consistent approach to context management throughout the mock implementation.

Also applies to: 31-75

x/evm/precompiles/cosmos/common_test.go (1)

82-86: LGTM! Well-implemented context getter method.

The new Context() method is a clean and straightforward implementation that:

  • Properly implements the types.StateDB interface
  • Maintains consistency with existing context-related methods
  • Integrates well with the snapshot management functionality
integration-tests/go.mod (3)

12-12: LGTM: Minor version bump of go-ethereum

The update from v1.14.9 to v1.14.11 is a patch version increment, which typically includes bug fixes and security updates.


12-12: Verify compatibility with the new go-ethereum version

Let's ensure there are no breaking changes in the go-ethereum update that could affect the statedb context implementation.

#!/bin/bash
# Description: Check for breaking changes in go-ethereum v1.14.11

# Search for StateDB-related changes in the codebase that might be affected
rg -l "StateDB" | xargs rg "github.com/ethereum/go-ethereum" -A 5

# Look for any TODO or FIXME comments related to go-ethereum
rg -i "TODO.*ethereum|FIXME.*ethereum"

Line range hint 236-240: Verify the specific commit hashes of custom replacements

The replacements use specific commit hashes, which is good for reproducibility. Let's verify these commits are the intended versions and are properly tagged.

✅ Verification successful

Custom replacements are properly defined with specific commit hashes

The review comment's concern about verifying commit hashes in custom replacements has been addressed. Looking at the go.mod file, we can see that all custom replacements are properly defined with specific commit hashes:

  • cometbft: v0.0.0-20241113064430-a371e2dc387f
  • ibc-go/v8: v8.0.0-20240802003717-19c0b4ad450d
  • evm: v0.0.0-20241108055119-3d312736d7fb
  • cometbft-client: v0.0.0-20240924071428-ef115cefa07e

Each replacement uses a precise commit hash, ensuring reproducible builds. The replacements are well-documented with comments explaining their purpose where needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify commit hashes and tags for custom replacements

# Check if the commits exist and are properly tagged
for repo in "cometbft" "ibc-go" "evm" "cometbft-client"; do
  echo "Checking $repo..."
  gh api repos/initia-labs/$repo/commits/$(rg "$repo.*v0\.0\.0-[0-9]+" -o | cut -d'-' -f2)
done

Length of output: 1617


Script:

#!/bin/bash
# Let's try a different approach to extract and verify the replacements

# First, let's get all the replace directives
echo "Replace directives in go.mod:"
rg "^replace.*=>" integration-tests/go.mod

# Then, let's check the content of go.mod to see the exact versions
echo -e "\nFull go.mod content:"
cat integration-tests/go.mod

Length of output: 14693

go.mod (2)

Line range hint 3-5: Verify Go toolchain compatibility

The Go toolchain has been updated to version 1.23.0, which is newer than the module's declared Go version (1.22.7). This mismatch could lead to compatibility issues.

Consider either:

  1. Updating the module's Go version to match the toolchain version:
-go 1.22.7
+go 1.23.0
  1. Or downgrading the toolchain version to match the module's Go version:
-toolchain go1.23.0
+toolchain go1.22.7

31-31: Verify go-ethereum version compatibility

The go-ethereum dependency has been updated to v1.14.11. This version is later replaced with a custom fork, but we should verify compatibility with other dependencies.

✅ Verification successful

Based on the search results, I can see that the codebase heavily uses go-ethereum packages but primarily for core functionality like types, common utilities, ABI handling, and VM operations. The search didn't reveal any direct Ethereum protocol interface implementations that would be sensitive to version changes.

Let's verify the specific version compatibility by checking the changelog and any breaking changes:


Go-ethereum version compatibility is maintained through custom fork

The go.mod shows that while go-ethereum v1.14.11 is specified, it's actually replaced with a custom fork:

github.com/ethereum/go-ethereum => github.com/initia-labs/evm v0.0.0-20241108055119-3d312736d7fb

This means the codebase is using a controlled fork of go-ethereum maintained by Initia Labs, which ensures compatibility with the rest of the dependencies. The fork is specifically versioned and maintained by the same organization.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential compatibility issues with go-ethereum v1.14.11

# Search for direct usage of go-ethereum packages
echo "Checking for go-ethereum usage patterns..."
rg --type go "github.com/ethereum/go-ethereum" -A 3

# Look for potential breaking changes in ethereum interfaces
ast-grep --pattern 'interface {
  $$$
  Ethereum$$$
  $$$
}'

Length of output: 45497


Script:

#!/bin/bash
# Check go.mod for any other ethereum-related dependencies that might have version constraints
cat go.mod | grep -A 5 -B 5 "github.com/ethereum/go-ethereum"

# Look for any replace directives that might affect go-ethereum
cat go.mod | grep -A 2 "replace"

Length of output: 1575

x/evm/keeper/context.go (1)

Line range hint 27-37: LGTM! Good simplification of the type system.

The change from an interface to a concrete *vm.EVM type reduces unnecessary abstraction while maintaining functionality. The method correctly initializes the StateDB with proper gas metering and all required dependencies.

x/evm/state/statedb.go (2)

73-73: LGTM: Constructor signature updated consistently.

The constructor parameter type change aligns with the field type modification.


46-46: Consider the architectural implications of using concrete EVM type.

The change from callableEVM interface to *vm.EVM creates tighter coupling with the concrete implementation. While this might improve performance by eliminating interface dispatch, it could make testing more challenging and reduce flexibility for future changes.

Comment on lines +114 to +116
// use snapshot context to get block hash
ctx := evm.StateDB.(types.StateDB).Context()
bz, err := k.EVMBlockHashes.Get(ctx, n)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add type assertion safety check.

The type assertion evm.StateDB.(types.StateDB) could panic if the type doesn't match. Consider adding a safety check:

-ctx := evm.StateDB.(types.StateDB).Context()
+stateDB, ok := evm.StateDB.(types.StateDB)
+if !ok {
+    return common.Hash{}
+}
+ctx := stateDB.Context()
📝 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
// use snapshot context to get block hash
ctx := evm.StateDB.(types.StateDB).Context()
bz, err := k.EVMBlockHashes.Get(ctx, n)
// use snapshot context to get block hash
stateDB, ok := evm.StateDB.(types.StateDB)
if !ok {
return common.Hash{}
}
ctx := stateDB.Context()
bz, err := k.EVMBlockHashes.Get(ctx, n)

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.

1 participant