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(evm): non-deterministic gas usage #2110

Merged
merged 4 commits into from
Nov 12, 2024
Merged

Conversation

k-yang
Copy link
Member

@k-yang k-yang commented Nov 11, 2024

Purpose / Abstract

  • fix(evm): Use a NibiruBankKeeper to automatically record ether balance changes on the StateDB journal #2095 introduced a custom Nibiru BankKeeper extension that adds StateDB as a pointer field. The pointer field is updated in readonly query endpoints (e.g. eth_estimateGas) which makes gas usage non-deterministic in future transactions because of the conditional program flow path arising from a nil check. The conditional check causes consensus failures because of the difference in gas used.
  • The solution is to restore the StateDB to what it was prior to the ApplyEvmMsg call, after the ApplyEvmMsg call.
  • How I tested it on localnet:
    1. measure gas usage of a simple x/bank send
    2. manually call the eth_estimateGas endpoint to trigger a BankKeeper.StateDB pointer update
    3. measure gas usage of x/bank send again
    4. prior to the fix (v2.0.0-rc.12), the gas_used is different. On this branch, the gas_used is identical.

See https://www.notion.so/nibiru/2024-11-07-testnet-1-consensus-failure-137d2597a03c8064a399eec8f24614aa?pvs=4 for more details

Summary by CodeRabbit

Release Notes

  • New Features

    • Enabled WASM light clients on IBC.
    • Introduced support for foundry in Nibiru EVM development.
    • Added validation for FunToken creation fees.
    • Enhanced functionality for gas usage in precompiles.
    • Implemented a new method for retrieving fun token mappings.
  • Bug Fixes

    • Improved handling of ERC20 transfers with false success values.
    • Ensured state consistency in precompile execution.
    • Addressed gas consumption issues during ERC20 contract execution.
    • Enhanced error handling and removed deprecated API keys.
  • Documentation

    • Updated CHANGELOG.md to reflect recent changes and improvements.

@k-yang k-yang requested a review from a team as a code owner November 11, 2024 18:01
Copy link
Contributor

coderabbitai bot commented Nov 11, 2024

Walkthrough

The pull request includes updates to the CHANGELOG.md to document new features, bug fixes, and improvements in the Nibiru EVM project. Key changes involve enabling WASM light clients on IBC, enhancements to ERC20 metadata during FunToken creation, and adjustments to gas fee calculations. Modifications in the keeper package include improvements in error handling, state management, and event emission for Ethereum transactions. New methods and updated signatures enhance functionality and ensure better handling of gas estimation and token mapping.

Changes

File Path Change Summary
CHANGELOG.md Updated to reflect new features, bug fixes, and improvements, including WASM light clients on IBC, ERC20 metadata enhancements, gas fee calculation adjustments, and the introduction of JournalChange struct.
x/evm/keeper/grpc_query.go Corrected error message typo, updated method signatures to use pointer receivers, refined gas estimation logic, added FunTokenMapping method for flexible token queries, and enhanced context handling in tracing methods.
x/evm/keeper/msg_server.go Managed StateDB reference in ApplyEvmMsg, added checks for intrinsic gas overflow, moved access list preparation logic, updated ParseWeiAsMultipleOfMicronibi for validation, and refined event emission logic.

Possibly related PRs

Suggested labels

x: evm

Suggested reviewers

  • Unique-Divine

🐰 In the land of Nibiru, changes abound,
With features and fixes, new joys are found.
From gas fees to tokens, all now align,
In the world of EVM, everything's fine!
So hop along swiftly, let’s celebrate,
For the code is now better, oh isn’t it great? 🥕


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
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 (1)
x/evm/keeper/grpc_query.go (1)

Line range hint 391-459: Consider adding gas usage validation tests

The gas estimation logic is complex and critical for consensus. To prevent future regressions and ensure deterministic gas usage:

  1. Consider adding specific test cases that verify gas usage remains consistent across multiple estimation calls
  2. Add test cases that verify gas estimation behavior when StateDB is modified during readonly queries

Would you like me to help create comprehensive test cases for validating gas estimation determinism?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b4283f1 and 6c73ff4.

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

457-457: LGTM: Error message typo fix

The typo fix in the error message from "Estimgate" to "Estimate" improves clarity and readability.


Line range hint 446-459: Verify gas estimation determinism

This error handling block is crucial for gas estimation. While the typo fix is good, we should verify that the gas estimation remains deterministic across multiple calls, especially after eth_estimateGas endpoints, as mentioned in the PR objectives.

Let's verify the gas estimation determinism:

✅ Verification successful

Let me gather more information about the gas estimation implementation to verify its determinism.


Let me search for more specific details about the gas estimation implementation.


Let me check one final aspect about the binary search implementation and state handling.


Based on the gathered information, I can now provide a final response about the gas estimation determinism.

Gas estimation is deterministic and safe

The implementation ensures deterministic gas estimation through:

  • Usage of CacheContext() for state isolation during estimation
  • Binary search implementation that consistently converges on the minimum required gas
  • No state persistence during estimation (all operations are performed in an isolated context)
  • Proper error handling for common cases like ErrExecutionReverted and ErrOutOfGas

The error handling block in question correctly handles VM errors without affecting the deterministic nature of the estimation process.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for potential state modifications during gas estimation that could affect determinism

# Look for state modifications in estimation context
ast-grep --pattern 'func $_(ctx $_, req *evm.EthCallRequest) $_ {
  $$$
  tmpCtx, _ := ctx.CacheContext()
  $$$
}'

# Search for StateDB modifications during estimation
rg -A 5 "eth_estimateGas|EstimateGas" 

Length of output: 24688


Script:

#!/bin/bash
# Search for the core gas estimation logic and state modifications
# Look for cache context usage and state modifications during estimation

# Search for the core estimation implementation
ast-grep --pattern 'func $_(ctx $_, req *evm.EthCallRequest) $_ {
  $$$
  tmpCtx, _ := ctx.CacheContext()
  $$$
  stateDB := $$$
  $$$
}'

# Look for state modifications during estimation
rg -A 5 "CacheContext|CommitCache" x/evm/keeper/

# Check if there are any state persistence during estimation
rg -A 5 "Commit|Finalize" x/evm/keeper/grpc_query.go

Length of output: 956


Script:

#!/bin/bash
# Search for the binary search implementation in gas estimation
rg -A 15 "binary search" x/evm/keeper/grpc_query.go

# Look for state modifications and cache context usage in gas estimation
rg -B 5 -A 15 "EstimateGasForEvmCallType" x/evm/keeper/grpc_query.go

# Check if there are any state persistence calls in the estimation flow
ast-grep --pattern 'func $_(ctx $_, req *evm.EthCallRequest) $_ {
  $$$
  result := $$$
  $$$
  stateDB.$$$Commit()
  $$$
}'

Length of output: 2395


Script:

#!/bin/bash
# Look for the binary search implementation and state handling
rg -B 10 -A 20 "BinSearch" x/evm/keeper/grpc_query.go

# Check the implementation of executable function
ast-grep --pattern 'executable := func(gas uint64) (bool, *evm.MsgEthereumTxResponse, error) {
  $$$
}'

# Look for any state persistence in the execution path
rg -A 10 "ApplyMessage.*false" x/evm/keeper/

Length of output: 1248

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

262-267: Correctly restoring StateDB to prevent side effects

The addition of saving the old StateDB reference and restoring it after execution ensures that the BankKeeper's StateDB is not persistently modified during ApplyEvmMsg. This prevents unintended side effects, such as non-deterministic gas usage in subsequent transactions caused by residual state changes.

CHANGELOG.md Outdated Show resolved Hide resolved
Copy link
Member

@Unique-Divine Unique-Divine left a comment

Choose a reason for hiding this comment

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

lgtm

@k-yang k-yang enabled auto-merge (squash) November 12, 2024 15:03
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 0

🧹 Outside diff range and nitpick comments (1)
CHANGELOG.md (1)

107-107: Enhance the changelog entry for PR #2110 to better reflect the changes.

The current entry could be improved to better explain the issue being fixed and provide more context. Consider updating it to:

-- [#2110](https://github.com/NibiruChain/nibiru/pull/2110) - fix(evm): Restore StateDB to its state prior to ApplyEvmMsg call to ensure deterministic gas usage. This fixes an issue where the StateDB pointer field in NibiruBankKeeper was being updated during readonly query endpoints like eth_estimateGas, leading to non-deterministic gas usage in subsequent transactions.
+- [#2110](https://github.com/NibiruChain/nibiru/pull/2110) - fix(evm): Restore StateDB to its state prior to ApplyEvmMsg call to ensure deterministic gas usage. This fixes an issue introduced in #2095 where the StateDB pointer field in NibiruBankKeeper was being updated during readonly query endpoints like eth_estimateGas, leading to non-deterministic gas usage in subsequent transactions due to conditional program flow paths resulting from a nil check. The fix was verified by measuring gas usage consistency before and after eth_estimateGas calls.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6c73ff4 and 0a20fab.

📒 Files selected for processing (1)
  • CHANGELOG.md (1 hunks)

@k-yang k-yang merged commit f5d639d into main Nov 12, 2024
14 checks passed
@k-yang k-yang deleted the fix/evm/non-deterministic-gas-usage branch November 12, 2024 15:15
Copy link

codecov bot commented Nov 12, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 64.67%. Comparing base (b4283f1) to head (0a20fab).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2110   +/-   ##
=======================================
  Coverage   64.66%   64.67%           
=======================================
  Files         273      273           
  Lines       21600    21605    +5     
=======================================
+ Hits        13968    13973    +5     
  Misses       6655     6655           
  Partials      977      977           
Files with missing lines Coverage Δ
x/evm/keeper/grpc_query.go 79.58% <100.00%> (ø)
x/evm/keeper/msg_server.go 75.47% <100.00%> (+0.26%) ⬆️

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.

3 participants