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: do not use posthandler to handle failed tx sequence increment #92

Merged
merged 2 commits into from
Oct 31, 2024

Conversation

beer-1
Copy link
Collaborator

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

Description

Closes: #XXXX

to handle this issue: cosmos/cosmos-sdk#22396
we changed to sequence decrement be done in x/evm msg handler.


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 IncrementSequenceDecorator for managing sequence numbers in transactions.
    • Added a constant ContextKeySequenceIncremented for enhanced context tracking.
  • Bug Fixes

    • Streamlined sequence number handling to prevent double incrementing during EVM operations.
  • Removals

    • Removed the IncrementSequenceDecorator and associated methods from the sigverify and posthandler packages, simplifying transaction processing.
  • Tests

    • Added a new test suite to validate the functionality of the IncrementSequenceDecorator.

@beer-1 beer-1 self-assigned this Oct 30, 2024
@beer-1 beer-1 requested a review from a team as a code owner October 30, 2024 04:06
Copy link

coderabbitai bot commented Oct 30, 2024

Walkthrough

The changes in this pull request primarily involve the modification and removal of sequence management decorators within the ante and posthandler packages. The IncrementSequenceDecorator has been replaced with a new implementation from the evmante package, resulting in the removal of existing sequence management logic. Additionally, new sequence handling methods have been introduced in the msgServerImpl struct to align with the updated transaction processing flow. The changes aim to streamline the handling of sequence numbers in transactions, particularly in the context of EVM interactions.

Changes

File Path Change Summary
app/ante/ante.go Replaced NewIncrementSequenceDecorator with evmante.NewIncrementSequenceDecorator in two functions.
app/ante/sigverify.go Removed IncrementSequenceDecorator and its methods, simplifying transaction handling.
app/ante/sigverify_test.go Deleted file containing unit tests for the removed IncrementSequenceDecorator.
app/posthandler/posthandler.go Removed NewSequenceIncrementDecorator(ak) from NewPostHandler, altering post-handler functionality.
app/posthandler/sequence.go Deleted file containing the SequenceIncrementDecorator, which managed account sequences for EVM transactions.
x/evm/ante/context_keys.go Added new constant ContextKeySequenceIncremented for tracking sequence increments in context.
x/evm/ante/sequence.go Introduced IncrementSequenceDecorator with methods for incrementing sequence numbers of signers in transactions.
x/evm/keeper/msg_server.go Added handleSequenceIncremented method for managing sequence number adjustments in EVM operations.

🐰 In the land of code where rabbits hop,
Sequence numbers now take a new stop.
With decorators fresh and logic refined,
EVM and Cosmos are now intertwined.
Hooray for the changes, let’s all cheer,
For a smoother path, let’s all persevere! 🌟


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

codecov bot commented Oct 30, 2024

Codecov Report

Attention: Patch coverage is 51.16279% with 21 lines in your changes missing coverage. Please review.

Project coverage is 28.19%. Comparing base (0ff2791) to head (9edaf63).
Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
x/evm/keeper/msg_server.go 38.09% 9 Missing and 4 partials ⚠️
x/evm/ante/sequence.go 60.00% 5 Missing and 3 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main      #92      +/-   ##
==========================================
- Coverage   28.24%   28.19%   -0.06%     
==========================================
  Files         124      124              
  Lines       13756    13710      -46     
==========================================
- Hits         3886     3866      -20     
+ Misses       9317     9292      -25     
+ Partials      553      552       -1     
Files with missing lines Coverage Δ
app/ante/ante.go 63.33% <100.00%> (ø)
app/ante/sigverify.go 5.21% <ø> (-18.06%) ⬇️
app/posthandler/posthandler.go 100.00% <ø> (ø)
x/evm/ante/sequence.go 60.00% <60.00%> (ø)
x/evm/keeper/msg_server.go 48.91% <38.09%> (-0.52%) ⬇️

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

🧹 Outside diff range and nitpick comments (1)
x/evm/ante/sequence.go (1)

33-33: Return the original context on error

Returning an empty sdk.Context{} may lead to unexpected behaviors downstream. It's better to return the original ctx to maintain context integrity.

Apply this diff to return the original context:

 if err != nil {
-    return sdk.Context{}, err
+    return ctx, err
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0ff2791 and 094de6c.

📒 Files selected for processing (8)
  • app/ante/ante.go (2 hunks)
  • app/ante/sigverify.go (0 hunks)
  • app/ante/sigverify_test.go (0 hunks)
  • app/posthandler/posthandler.go (0 hunks)
  • app/posthandler/sequence.go (0 hunks)
  • x/evm/ante/context_keys.go (1 hunks)
  • x/evm/ante/sequence.go (1 hunks)
  • x/evm/keeper/msg_server.go (5 hunks)
💤 Files with no reviewable changes (4)
  • app/ante/sigverify.go
  • app/ante/sigverify_test.go
  • app/posthandler/posthandler.go
  • app/posthandler/sequence.go
🔇 Additional comments (10)
x/evm/ante/context_keys.go (1)

8-8: LGTM! Verify usage of the new context key.

The addition of ContextKeySequenceIncremented follows good practices with clear naming and proper use of iota.

Let's verify how this new context key is being used in the codebase:

✅ Verification successful

Context key usage is properly integrated and follows a clear pattern

The verification shows the context key is correctly used in a coordinated way across the codebase:

  • Set in x/evm/ante/sequence.go to mark sequence increment
  • Checked and handled appropriately in x/evm/keeper/msg_server.go for create transactions
  • Properly cleaned up by setting to nil after processing

The implementation demonstrates proper context value lifecycle management and follows Go best practices.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check usage of ContextKeySequenceIncremented to ensure it's properly integrated
# Expected: Should find references in ante handlers or message handlers where sequence is managed

# Search for direct references to the constant
rg -A 5 "ContextKeySequenceIncremented"

# Search for methods that might be setting/getting this context value
ast-grep --pattern 'ctx.Value($$$ContextKeySequenceIncremented$$$)'
ast-grep --pattern 'ctx.WithValue($$$ContextKeySequenceIncremented$$$)'

Length of output: 947

app/ante/ante.go (2)

114-114: LGTM: Consistent sequence handling in OPinit ante handler.

The change maintains consistency with the main ante handler by using the same evmante.NewIncrementSequenceDecorator. The placement after signature verification is correct.


100-100: Verify the decorator ordering for sequence management.

The placement of evmante.NewIncrementSequenceDecorator after signature verification but before IBC and auction decorators is correct. This ensures that sequence numbers are incremented only after the transaction is validated but before any chain-specific processing.

Let's verify the sequence handling implementation:

✅ Verification successful

Decorator ordering and implementation verified successfully

The verification confirms:

  • The evmante.IncrementSequenceDecorator is properly implemented in x/evm/ante/sequence.go with correct sequence increment logic for transaction signers
  • It's used consistently in both ante handler chains in app/ante/ante.go
  • No other sequence decorators remain in the codebase, confirming complete migration
  • The implementation aligns with the PR's objective of moving sequence handling to the EVM module
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the sequence handling implementation in evmante package

# Test 1: Check the implementation of the new sequence decorator
ast-grep --pattern 'func NewIncrementSequenceDecorator($_) $_'

# Test 2: Verify there are no remaining references to old sequence decorator
rg "NewSequenceIncrementDecorator|SequenceIncrementDecorator" -g '!*.md'

Length of output: 411


Script:

#!/bin/bash
# Let's verify the implementation details and usage of the sequence decorator

# Check the full implementation of IncrementSequenceDecorator
rg -A 20 "type IncrementSequenceDecorator struct" x/evm/ante/sequence.go

# Check where it's being used in ante handlers
rg "IncrementSequenceDecorator" app/ante/

# Check if there are any other sequence decorators still in use
rg "Sequence.*Decorator" --type go

Length of output: 1559

x/evm/ante/sequence.go (1)

24-48: Ensure alignment with transaction sequence handling logic

This decorator modifies the sequence numbers of all signers. Ensure that this logic aligns with the overall transaction processing in the application and that it doesn't conflict with other mechanisms that handle sequence numbers.

Would you like assistance in reviewing related parts of the codebase to confirm consistency?

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

16-16: Importing "evmante" package is necessary for sequence handling.

The addition of the evmante import is appropriate, as it provides access to constants and functions needed for the updated sequence management logic.


35-40: Proper sequence handling in the Create method.

The addition of handleSequenceIncremented ensures that the sequence number is correctly managed to prevent double incrementing during EVM contract creation.


100-105: Proper sequence handling in the Create2 method.

Calling handleSequenceIncremented in the Create2 method aligns the sequence management logic with the Create method, ensuring consistency in contract creation operations.


165-167: Ensuring correct sequence management in the Call method.

Invoking handleSequenceIncremented with isCreate set to false correctly handles the sequence number for contract calls, preventing unintended sequence adjustments.


264-277: ⚠️ Potential issue

Check for nil account to prevent a nil pointer dereference.

In the handleSequenceIncremented function, after retrieving the sender's account, there is no check to ensure that acc is not nil before calling acc.SetSequence(). If the account does not exist, this could lead to a nil pointer dereference.

Consider adding a check for nil:

acc := k.accountKeeper.GetAccount(ctx, sender)
if acc == nil {
    return ctx, sdkerrors.ErrUnknownAddress.Wrapf("account %s does not exist", sender)
}

276-277: Ensure consistent context after modification.

The function returns a new context with evmante.ContextKeySequenceIncremented set to nil. Verify that this updated context is properly propagated and used in subsequent operations to maintain context integrity.

Run the following script to check for proper context propagation:

✅ Verification successful

Let me gather more context about how this context value is used in the codebase.


Context propagation is correctly implemented

The context value ContextKeySequenceIncremented is used in a well-defined flow:

  • It's set to true in the ante handler (x/evm/ante/sequence.go)
  • Checked in handleSequenceIncremented to manage account sequence
  • Finally set to nil after processing, which is the correct behavior to prevent reuse

The context modifications are properly handled and the sequence increment flag serves its intended purpose in the transaction lifecycle.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the returned context is used after calling handleSequenceIncremented.

# Test: Search for instances where the context is not updated after handleSequenceIncremented.
# Expect: All subsequent uses of context should be the updated one.

rg -A 3 'handleSequenceIncremented\(.*\)' x/evm/keeper/ | rg -v 'ctx ='

Length of output: 1020


Script:

#!/bin/bash
# Search for usages of ContextKeySequenceIncremented
rg -A 5 "ContextKeySequenceIncremented" --type go

# Search for any code that retrieves this context value
ast-grep --pattern 'Value($_, evmante.ContextKeySequenceIncremented)'

Length of output: 885

x/evm/ante/sequence.go Show resolved Hide resolved
x/evm/ante/sequence.go Show resolved Hide resolved
x/evm/keeper/msg_server.go Outdated Show resolved Hide resolved
@initia-labs initia-labs deleted a comment from coderabbitai bot Oct 30, 2024
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 (3)
x/evm/ante/sequence_test.go (3)

17-17: Consider documenting the significance of account number 50.

Adding a comment explaining why this specific account number was chosen would improve test clarity.

+  // Set arbitrary account number for testing
   suite.NoError(acc.SetAccountNumber(uint64(50)))

33-34: Good test isolation practice.

Testing the IncrementSequenceDecorator in isolation follows good testing practices. However, consider adding integration tests with other decorators to ensure proper interaction.


36-46: Add descriptions for test cases.

Consider adding names or descriptions for each test case to clarify the specific scenario being tested.

   testCases := []struct {
+    name        string
     ctx         sdk.Context
     simulate    bool
     expectedSeq uint64
   }{
-    {suite.ctx.WithIsReCheckTx(true), false, 1},
+    {
+      name:        "recheck tx without simulation",
+      ctx:         suite.ctx.WithIsReCheckTx(true),
+      simulate:    false,
+      expectedSeq: 1,
+    },
     // ... similar changes for other test cases
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 094de6c and 9edaf63.

📒 Files selected for processing (1)
  • x/evm/ante/sequence_test.go (1 hunks)
🔇 Additional comments (1)
x/evm/ante/sequence_test.go (1)

20-28: Consider adding validation for transaction builder operations.

While SetMsgs error is checked, other builder operations like SetFeeAmount and SetGasLimit should also be validated for completeness.

x/evm/ante/sequence_test.go Show resolved Hide resolved
Copy link
Contributor

@Vritra4 Vritra4 left a comment

Choose a reason for hiding this comment

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

LGTM

@beer-1 beer-1 merged commit ed359ac into main Oct 31, 2024
9 checks passed
@beer-1 beer-1 deleted the fix/sequence-increment branch October 31, 2024 09:44
This was referenced Nov 15, 2024
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