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): proper nonce management in statedb #2130

Merged
merged 7 commits into from
Jan 8, 2025
Merged

Conversation

onikonychev
Copy link
Contributor

@onikonychev onikonychev commented Dec 25, 2024

Summary by CodeRabbit

  • Documentation

  • New Features

    • Introduced new methods for transaction handling and nonce management in Ethereum RPC backend
    • Added client context retrieval method for Backend
  • Tests

    • Added new test suite for nonce increment and transaction handling
    • Enhanced testing of EVM state database journal changes
  • Improvements

    • Refined nonce management in EVM transaction processing
    • Streamlined transaction building and broadcasting methods

Copy link
Contributor

coderabbitai bot commented Dec 25, 2024

Warning

Rate limit exceeded

@Unique-Divine has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 16 minutes and 31 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 14a5200 and 817c7ba.

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

Walkthrough

This pull request encompasses changes across multiple files related to nonce management, transaction handling, and testing in the Ethereum backend. The modifications include adding new methods for nonce retrieval and transaction building, updating the changelog, and refining nonce handling in the EVM module. The changes primarily focus on improving the robustness of transaction processing and testing capabilities, with a particular emphasis on consistent nonce management across different components of the system.

Changes

File Change Summary
CHANGELOG.md Updated "Unreleased" section with entries for PRs #2127 and #2130
eth/rpc/backend/backend_suite_test.go Added methods: getCurrentNonce(), broadcastSDKTx(), buildContractCreationTx(), buildContractCallTx()
eth/rpc/backend/call_tx.go Added ClientCtx() method to Backend struct
eth/rpc/backend/nonce_test.go Added test TestNonceIncrementWithMultipleMsgsTx() and helper method buildSDKTxWithEVMMessages()
x/evm/keeper/msg_server.go Modified ApplyEvmMsg() to explicitly reset and increment nonce for sender
x/evm/statedb/journal_test.go Updated assertion for dirty journal entries in TestComplexJournalChanges()

Sequence Diagram

sequenceDiagram
    participant Client
    participant Backend
    participant EVMKeeper
    participant StateDB

    Client->>Backend: Send Transaction
    Backend->>Backend: Get Current Nonce
    Backend->>EVMKeeper: Apply EVM Message
    EVMKeeper->>EVMKeeper: Reset Sender Nonce
    EVMKeeper->>StateDB: Process Transaction
    StateDB-->>EVMKeeper: Transaction Result
    EVMKeeper->>EVMKeeper: Increment Nonce
    EVMKeeper-->>Backend: Transaction Response
    Backend-->>Client: Transaction Confirmation
Loading

Possibly related PRs

Suggested reviewers

  • Unique-Divine

Poem

🐰 Nonce dancing, transactions flow,
Ethereum's rhythm starts to grow
Blocks align with careful might
Code hops forward, pure delight!
A rabbit's leap through protocol's gate 🚀


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@onikonychev onikonychev marked this pull request as ready for review January 7, 2025 17:38
@onikonychev onikonychev requested a review from a team as a code owner January 7, 2025 17:38
Copy link

codecov bot commented Jan 7, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 65.16%. Comparing base (20531e7) to head (817c7ba).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2130      +/-   ##
==========================================
+ Coverage   65.13%   65.16%   +0.02%     
==========================================
  Files         277      277              
  Lines       22168    22169       +1     
==========================================
+ Hits        14440    14447       +7     
+ Misses       6738     6732       -6     
  Partials      990      990              
Files with missing lines Coverage Δ
eth/rpc/backend/call_tx.go 56.29% <100.00%> (+0.34%) ⬆️
x/evm/keeper/msg_server.go 77.00% <100.00%> (-0.05%) ⬇️

... and 2 files with indirect coverage changes

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 comments (1)
eth/rpc/backend/call_tx.go (1)

Line range hint 147-148: Handle nonce retrieval errors explicitly

The current implementation ignores potential errors from getAccountNonce. Given that this PR focuses on proper nonce management, we should handle these errors explicitly to prevent potential transaction failures.

Consider modifying the code to handle errors:

-        nonce, _ := b.getAccountNonce(*args.From, true, 0, b.logger) // #nosec G703s
+        nonce, err := b.getAccountNonce(*args.From, true, 0, b.logger)
+        if err != nil {
+            return args, fmt.Errorf("failed to get account nonce: %w", err)
+        }
         args.Nonce = (*hexutil.Uint64)(&nonce)
🧹 Nitpick comments (2)
eth/rpc/backend/nonce_test.go (1)

47-75: Consider adding error handling for gas estimation

The helper function buildSDKTxWithEVMMessages calculates total gas by summing individual transaction gas limits. This might not account for the overhead of processing multiple messages in a single transaction.

Consider adding a buffer to the total gas calculation:

 totalGas := uint64(0)
 for _, tx := range txs {
     totalGas += tx.Gas()
 }
+// Add buffer for multi-msg overhead
+totalGas += uint64(len(txs) * 10000)
eth/rpc/backend/backend_suite_test.go (1)

237-238: Remove commented code

There's a commented line that appears to be unused test data.

-    //recipient := crypto.CreateAddress(s.fundedAccEthAddr, 29381)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between de7239f and 14a5200.

📒 Files selected for processing (6)
  • CHANGELOG.md (1 hunks)
  • eth/rpc/backend/backend_suite_test.go (4 hunks)
  • eth/rpc/backend/call_tx.go (2 hunks)
  • eth/rpc/backend/nonce_test.go (1 hunks)
  • x/evm/keeper/msg_server.go (2 hunks)
  • x/evm/statedb/journal_test.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: integration-tests
🔇 Additional comments (4)
eth/rpc/backend/backend_suite_test.go (1)

192-202: LGTM! Well-structured nonce retrieval

The getCurrentNonce function properly retrieves the current block number and uses it to get the accurate nonce. This centralization of nonce retrieval logic improves maintainability.

x/evm/statedb/journal_test.go (1)

159-162: LGTM! Updated test expectations

The test now correctly expects one dirty journal entry after a precompile call, aligning with the new nonce management behavior.

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

338-341: LGTM! Improved nonce management

The changes properly handle nonce management by:

  1. Resetting the nonce before EVM execution
  2. Incrementing it after processing, regardless of the outcome
  3. This fixes potential nonce inconsistencies and aligns with Ethereum's behavior

The implementation ensures that nonces are managed consistently, which is crucial for transaction ordering and replay protection.

Also applies to: 358-359

eth/rpc/backend/call_tx.go (1)

343-345: Consider the implications of exposing ClientCtx

While this getter provides access to the client context needed for nonce management, exposing the entire client context could lead to potential misuse. Consider:

  1. Creating specific methods for the required functionality instead of exposing the entire context
  2. Documenting the intended usage and any thread-safety considerations

Let's verify the usage of this new method:

✅ Verification successful

ClientCtx() exposure is appropriately scoped

The method appears to be specifically added for testing purposes, with no production code dependencies. The current implementation is safe and follows testing patterns commonly used in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all calls to ClientCtx() to understand its usage pattern
rg "ClientCtx\(\)" --type go

# Look for any concurrent access patterns
ast-grep --pattern 'go func() {
  $$$
  $x.ClientCtx()
  $$$
}'

Length of output: 592


Script:

#!/bin/bash
# Search for interfaces that might require ClientCtx()
ast-grep --pattern 'type $interface interface {
  $$$
  ClientCtx() $return
  $$$
}'

# Look for the Backend struct definition to understand its role
ast-grep --pattern 'type Backend struct {
  $$$
}'

Length of output: 756

Comment on lines +32 to +33
s.Assert().NotEqual(rsp.Code, 0)
s.Require().NoError(s.network.WaitForNextBlock())
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

Assertion should check for success, not failure

The assertion is checking for non-zero response code, which typically indicates failure. For a successful transaction, the response code should be zero.

-    s.Assert().NotEqual(rsp.Code, 0)
+    s.Assert().Equal(rsp.Code, 0)
📝 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
s.Assert().NotEqual(rsp.Code, 0)
s.Require().NoError(s.network.WaitForNextBlock())
s.Assert().Equal(rsp.Code, 0)
s.Require().NoError(s.network.WaitForNextBlock())

@Unique-Divine Unique-Divine merged commit 2c4c224 into main Jan 8, 2025
15 checks passed
@Unique-Divine Unique-Divine deleted the fix/evm-multi-tx branch January 8, 2025 05:02
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