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

feat: track latest 256 cosmos block hashes #76

Merged
merged 5 commits into from
Oct 21, 2024

Conversation

beer-1
Copy link
Collaborator

@beer-1 beer-1 commented Oct 19, 2024

Description

cosmosSDK currently does not allow to change state at abci listener
cosmos/cosmos-sdk#22246

We cannot store the EVM block hashes due to above reason, so just track cosmos block hash instead of EVM block hash.
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

  • New Features

    • Introduced a new PreBlock function to track the latest 256 block hashes in the EVM module.
    • Enhanced the AppModule structure to include pre-block processing capabilities.
    • Integrated the EVM indexer into the application, allowing for improved management of EVM-related operations.
    • Added a method to set the EVM indexer within the application.
  • Bug Fixes

    • Adjusted block hash tracking to occur at the end of the EVM module's endblocker instead of the ABCI listener.

@beer-1 beer-1 self-assigned this Oct 19, 2024
@beer-1 beer-1 requested a review from a team as a code owner October 19, 2024 16:56
Copy link

coderabbitai bot commented Oct 19, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces changes to the handling of block hash tracking in the Cosmos SDK's EVM module. The ListenFinalizeBlock method in indexer/abci.go has been modified to comment out the block hash tracking call, indicating that this functionality will now be managed in the new PreBlock function within x/evm/abci.go. Additionally, the AppModule structure in x/evm/module.go has been updated to implement the HasPreBlocker interface, allowing for pre-block processing. The app/app.go file has also been adjusted to incorporate the EVM indexer.

Changes

File Change Summary
indexer/abci.go Modified ListenFinalizeBlock to comment out TrackBlockHash, indicating tracking will occur in the EVM module's PreBlock.
x/evm/abci.go Added PreBlock function to track the latest 256 block hashes, utilizing telemetry measurement.
x/evm/module.go Enhanced AppModule to implement HasPreBlocker interface and added PreBlock method for pre-block logic.
app/app.go Introduced evmIndexer field and SetEVMIndexer method in MinitiaApp; updated NewMinitiaApp to include evmConfig.

Possibly related PRs

  • feat: keep latest 256 block hashes on state #66: The changes in this PR involve modifications to the ListenFinalizeBlock method in indexer/abci.go, specifically related to the TrackBlockHash functionality, which is directly relevant to the changes made in the main PR regarding block hash tracking.
  • feat: track latest 256 cosmos block hashes #76: This PR also modifies the ListenFinalizeBlock method in indexer/abci.go, commenting out the same call to TrackBlockHash and addressing the limitation of state changes in the ABCI listener, aligning closely with the main PR's changes regarding block hash tracking.

Poem

In the land of blocks where hashes play,
A new tracker dawns at the start of the day.
With EVM's magic, we keep them in line,
As rabbits hop by, all is perfectly fine! 🐇✨
So here's to the changes, both clever and bright,
In the cosmos of code, we leap with delight!


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

🧹 Outside diff range and nitpick comments (2)
x/evm/abci.go (2)

13-14: Enhance function documentation for clarity.

While the current comment provides a basic description, it could be more informative. Consider expanding the documentation to include:

  • The purpose of tracking the latest 256 block hashes
  • How this relates to the EVM module's functionality
  • Any important side effects or state changes

Example:

// EndBlocker tracks the latest 256 block hashes for the EVM module.
// This function is called at the end of each block to update the block hash history,
// which is crucial for certain EVM operations and maintaining chain state consistency.
// It returns an error if the tracking operation fails.

15-17: LGTM: Implementation is sound, with a suggestion for improvement.

The function correctly implements the block hash tracking with appropriate type conversions and telemetry. However, consider adding some error logging before returning the error:

func EndBlocker(ctx sdk.Context, k *keeper.Keeper) error {
	defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker)
	err := k.TrackBlockHash(ctx, uint64(ctx.BlockHeight()), common.BytesToHash(ctx.HeaderHash()))
	if err != nil {
		ctx.Logger().Error("failed to track block hash", "error", err)
	}
	return err
}

This will provide more context in case of failures, aiding in debugging and monitoring.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1581f89 and 6d427f9.

📒 Files selected for processing (3)
  • indexer/abci.go (1 hunks)
  • x/evm/abci.go (1 hunks)
  • x/evm/module.go (2 hunks)
🧰 Additional context used
🔇 Additional comments (5)
x/evm/abci.go (2)

3-11: LGTM: Imports are appropriate and well-organized.

The imports are relevant to the function's implementation, with no unused imports. The use of aliases follows Go conventions.


1-17: Overall assessment: Good implementation with minor suggestions for improvement.

This new EndBlocker function successfully addresses the PR objective of tracking cosmos block hashes. It aligns with the Cosmos SDK module patterns and provides a solution to the limitation mentioned in cosmos-sdk issue #22246.

Key points:

  1. The function correctly integrates with the Cosmos SDK context and keeper.
  2. It uses telemetry for performance monitoring.
  3. Proper type conversions are used for compatibility with Ethereum types.

Suggestions for improvement:

  1. Enhance the function documentation for better clarity.
  2. Add error logging for improved debugging and monitoring.

These changes provide a solid foundation for tracking the latest 256 cosmos block hashes, which is crucial for maintaining consistency between the Cosmos SDK and EVM module.

indexer/abci.go (1)

204-210: Alignment with PR objectives and follow-up tasks

The changes align with the PR objectives to address the cosmosSDK limitation and track cosmos block hashes instead of EVM block hashes. However, there are a few points to consider:

  1. The TODO comment could be more specific about the planned implementation. Consider updating it to something like:
    "TODO: Implement tracking of cosmos block hashes in the x/evm endblocker to address cosmosSDK limitation (issue #22246)."

  2. Ensure that the cosmos block hash tracking is properly implemented in the x/evm endblocker, as mentioned in the comment.

  3. Consider adding a link to the relevant pull request or issue where the endblocker changes are being implemented for better traceability.

To verify the implementation of cosmos block hash tracking in the x/evm endblocker, please run the following script:

This script will help verify if the cosmos block hash tracking has been implemented in the x/evm endblocker and if there are any remaining TODO comments related to this task.

x/evm/module.go (2)

32-33: Implemented HasEndBlocker Interface

The AppModule struct now correctly implements the appmodule.HasEndBlocker interface, enabling end-of-block processing within the module.


161-167: Added EndBlock Method for End-of-Block Logic

The EndBlock method is properly implemented to execute end-of-block logic. Unwrapping the sdk.Context using sdk.UnwrapSDKContext(ctx) ensures compatibility with the underlying SDK context required by the EndBlocker function.

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 (5)
x/evm/abci.go (3)

13-14: LGTM: Function declaration is appropriate, with a minor suggestion for the comment.

The PreBlock function declaration aligns well with the PR objective to track cosmos block hashes. The function signature and return types are consistent with Cosmos SDK conventions.

Consider updating the comment to be more specific:

// PreBlock tracks the latest 256 cosmos block hashes

This change would more accurately reflect the PR's objective and the function's purpose.


15-17: LGTM: Implementation is concise and correct, with a suggestion for error handling.

The PreBlock function implementation effectively tracks the latest cosmos block hashes:

  • Good use of telemetry for performance monitoring.
  • Correct usage of the previous block height for tracking.
  • Appropriate conversion of the header hash to a common hash format for Ethereum compatibility.

Consider adding explicit error handling:

func PreBlock(ctx sdk.Context, k *keeper.Keeper) (sdk.ResponsePreBlock, error) {
	defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker)
	err := k.TrackBlockHash(ctx, uint64(ctx.BlockHeight()-1), common.BytesToHash(ctx.HeaderHash()))
	if err != nil {
		// Log the error or handle it as appropriate
		return sdk.ResponsePreBlock{}, fmt.Errorf("failed to track block hash: %w", err)
	}
	return sdk.ResponsePreBlock{}, nil
}

This change would provide more explicit error handling and potentially useful error information.


1-17: Summary: Implementation successfully addresses PR objectives

This new file x/evm/abci.go effectively implements the PreBlock function to track the latest 256 cosmos block hashes, addressing the limitation mentioned in the PR objectives. The implementation is concise, correct, and focuses on the core functionality required.

Key points:

  1. The function correctly tracks cosmos block hashes instead of EVM block hashes.
  2. It integrates well with the Cosmos SDK architecture by implementing the PreBlock function.
  3. The implementation uses appropriate Cosmos SDK and Ethereum types and conventions.

The changes in this file, combined with the modifications mentioned in other files (such as commenting out the block hash tracking in indexer/abci.go), successfully achieve the goal of tracking cosmos block hashes in the EVM module.

To further improve the robustness of this implementation, consider:

  1. Adding unit tests to verify the correct behavior of the PreBlock function.
  2. Documenting the rationale behind tracking 256 block hashes, possibly in a comment or in the module's documentation.
  3. Ensuring that other parts of the system that previously relied on EVM block hashes are updated to use these cosmos block hashes correctly.
x/evm/module.go (1)

164-167: Consider reorganizing method placement for better readability.

While the placement of the PreBlock method at the end of the file is acceptable, consider moving it closer to other lifecycle methods (e.g., InitGenesis, ExportGenesis) for better code organization and readability.

app/app.go (1)

Line range hint 210-218: Verify initialization and error handling for evmIndexer in indexer setup.

When setting the EVM indexer using app.SetEVMIndexer(evmIndexer), ensure that evmIndexer is properly initialized and not nil. Consider adding error handling to manage potential initialization failures and prevent nil assignments.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6d427f9 and e840fe6.

📒 Files selected for processing (3)
  • app/app.go (2 hunks)
  • x/evm/abci.go (1 hunks)
  • x/evm/module.go (2 hunks)
🧰 Additional context used
🔇 Additional comments (8)
x/evm/abci.go (1)

1-11: LGTM: Package declaration and imports are appropriate.

The package name evm is suitable for the EVM module, and the imports are relevant to the function's purpose. There are no unused imports, which is good for code cleanliness.

x/evm/module.go (3)

32-33: LGTM: Appropriate interface implementation added.

The addition of appmodule.HasPreBlocker interface implementation is consistent with the PR objectives. This change enables the module to perform pre-block processing, which is essential for tracking block hashes as described in the PR summary.


164-167: LGTM: PreBlock method correctly implemented.

The PreBlock method is implemented as expected, unwrapping the SDK context and calling the PreBlock function with the appropriate parameters. This implementation aligns with the PR objectives for tracking block hashes in the pre-block phase.


Line range hint 1-167: Overall assessment: Changes align with PR objectives.

The modifications to x/evm/module.go successfully implement the required functionality for pre-block processing and block hash tracking. The new PreBlock method and the HasPreBlocker interface implementation are correctly added. Minor improvements in comments and code organization have been suggested. These changes effectively address the PR's goal of tracking the latest 256 cosmos block hashes.

app/app.go (4)

70-70: Appropriate import of evmtypes added.

The addition of the import statement for evmtypes is necessary for referencing EVM module constants like evmtypes.ModuleName.


Line range hint 144-144: Added evmIndexer field to MinitiaApp struct.

Including evmIndexer evmindexer.EVMIndexer in the MinitiaApp struct enhances the application's ability to manage EVM indexing functionality.


232-232: Confirm the addition of evmtypes.ModuleName to SetOrderPreBlockers is intentional.

Adding evmtypes.ModuleName to SetOrderPreBlockers changes the execution order of pre-blockers. Verify that this change aligns with the desired module processing sequence and does not introduce unintended side effects.


Line range hint 176-183: Ensure all calls to NewMinitiaApp are updated with the new evmConfig parameter.

Adding evmConfig evmconfig.EVMConfig to the NewMinitiaApp function signature may break existing code that relies on this function. Please verify that all instances where NewMinitiaApp is called have been updated to include the new parameter, or consider providing a default value to maintain backward compatibility.

Run the following script to find all calls to NewMinitiaApp that may need updating:

✅ Verification successful

Verification Successful: All NewMinitiaApp calls include the evmConfig parameter.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all calls to `NewMinitiaApp` and ensure they include the `evmConfig` parameter.

# Expected: All calls should include `evmConfig`.

rg 'NewMinitiaApp\(' -A 5

Length of output: 4324

x/evm/module.go Outdated Show resolved Hide resolved
Copy link

codecov bot commented Oct 20, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 28.46%. Comparing base (1581f89) to head (e840fe6).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main      #76      +/-   ##
==========================================
+ Coverage   28.43%   28.46%   +0.03%     
==========================================
  Files         120      121       +1     
  Lines       13000    12999       -1     
==========================================
+ Hits         3696     3700       +4     
+ Misses       8759     8754       -5     
  Partials      545      545              
Files with missing lines Coverage Δ
app/app.go 55.82% <100.00%> (+0.13%) ⬆️
indexer/abci.go 0.00% <ø> (ø)
x/evm/abci.go 100.00% <100.00%> (ø)

@beer-1 beer-1 merged commit 729fa81 into main Oct 21, 2024
1 of 2 checks passed
@beer-1 beer-1 deleted the feat/track-cosmos-block-hash branch October 21, 2024 02:34
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