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: increment sequence number at every call and create #102

Merged
merged 2 commits into from
Nov 8, 2024

Conversation

beer-1
Copy link
Member

@beer-1 beer-1 commented Nov 8, 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

  • New Features

    • Improved handling of sequence numbers for EVM messages, enhancing clarity and error management during contract calls and creations.
  • Bug Fixes

    • Resolved potential issues with double incrementing of sequences during message processing.
  • Tests

    • Added new tests to verify correct sequence increment behavior during contract calls and creations.

@beer-1 beer-1 requested a review from a team as a code owner November 8, 2024 03:30
@beer-1 beer-1 self-assigned this Nov 8, 2024
Copy link

coderabbitai bot commented Nov 8, 2024

Walkthrough

The pull request modifies the handling of sequence numbers in the EVM's ante and keeper packages. The IncrementSequenceDecorator now uses a pointer for the incremented flag in the context, allowing for potential reversion. The msgServerImpl methods have updated signatures and logic to improve error handling and streamline sequence management during contract calls and creations. Additionally, new tests have been added to validate the behavior of sequence increments in these scenarios.

Changes

File Change Summary
x/evm/ante/sequence.go Modified IncrementSequenceDecorator to store the incremented flag as a pointer to a boolean variable instead of a direct boolean value.
x/evm/keeper/msg_server.go Updated handleSequenceIncremented method to return an error instead of a context. Simplified sequence increment logic in Create, Create2, and Call methods.
x/evm/keeper/msg_server_test.go Added two test functions: Test_MsgServer_NonceIncrement_Call and Test_MsgServer_NonceIncrement_Create to verify sequence increment behavior during contract operations.

Possibly related PRs

Suggested reviewers

  • Vritra4

Poem

🐇 In the realm of code, we hop and play,
With sequences dancing in a new array.
Flags now point, they twist and turn,
In contracts we trust, as we learn.
So let’s celebrate with a joyful cheer,
For clearer paths in code, we hold dear! 🎉


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c9ae22f and 05733f9.

📒 Files selected for processing (1)
  • x/evm/keeper/msg_server.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • x/evm/keeper/msg_server.go

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 Nov 8, 2024

Codecov Report

Attention: Patch coverage is 82.60870% with 4 lines in your changes missing coverage. Please review.

Project coverage is 28.40%. Comparing base (240904b) to head (05733f9).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
x/evm/keeper/msg_server.go 80.95% 3 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #102      +/-   ##
==========================================
+ Coverage   28.33%   28.40%   +0.06%     
==========================================
  Files         126      126              
  Lines       14024    14037      +13     
==========================================
+ Hits         3974     3987      +13     
+ Misses       9489     9488       -1     
- Partials      561      562       +1     
Files with missing lines Coverage Δ
x/evm/ante/sequence.go 61.90% <100.00%> (+1.90%) ⬆️
x/evm/keeper/msg_server.go 52.04% <80.95%> (+3.12%) ⬆️

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/keeper/msg_server.go (1)

266-292: Consider adding debug logging for sequence number operations

While the implementation is correct, adding debug logging would improve observability of sequence number changes, especially useful for debugging in production environments.

Consider adding logs like this:

 func (k *msgServerImpl) handleSequenceIncremented(ctx context.Context, sender sdk.AccAddress, isCreate bool) error {
 	sdkCtx := sdk.UnwrapSDKContext(ctx)
+	k.Logger(ctx).Debug("handling sequence increment",
+		"sender", sender.String(),
+		"is_create", isCreate)
 	if sdkCtx.Value(evmante.ContextKeySequenceIncremented) == nil {
+		k.Logger(ctx).Debug("sequence increment flag not set")
 		return nil
 	}

 	incremented := sdkCtx.Value(evmante.ContextKeySequenceIncremented).(*bool)
 	if isCreate && *incremented {
+		k.Logger(ctx).Debug("decrementing sequence for create operation")
 		// if the sequence is already incremented, decrement it to prevent double incrementing the sequence number at create.
 		acc := k.accountKeeper.GetAccount(ctx, sender)
 		if err := acc.SetSequence(acc.GetSequence() - 1); err != nil {
 			return err
 		}

 		k.accountKeeper.SetAccount(ctx, acc)
 	} else if !isCreate && !*incremented {
+		k.Logger(ctx).Debug("incrementing sequence for call operation")
 		// if the sequence is not incremented and the message is call, increment the sequence number.
 		acc := k.accountKeeper.GetAccount(ctx, sender)
 		if err := acc.SetSequence(acc.GetSequence() + 1); err != nil {
 			return err
 		}

 		k.accountKeeper.SetAccount(ctx, acc)
 	}

 	// set the flag to false
 	*incremented = false
+	k.Logger(ctx).Debug("reset sequence increment flag")

 	return nil
 }
x/evm/keeper/msg_server_test.go (2)

184-247: Enhance test readability and reliability.

While the test logic is correct, consider the following improvements:

  1. Add descriptive comments for each test case to clarify the expected behavior.
  2. Use named constants or variables for sequence increments to make the intent clearer.
  3. Consider splitting into separate sub-tests using t.Run() to isolate test cases.

Here's a suggested refactor:

 func Test_MsgServer_NonceIncrement_Call(t *testing.T) {
+    const (
+        initialIncrement = 1
+        callIncrement    = 1
+        createIncrement  = 1
+    )
+
     ctx, input := createDefaultTestInput(t)
     _, _, addr := keyPubAddr()
     caller := common.BytesToAddress(addr.Bytes())
     // ... setup code ...

-    // increment sequence
+    // Setup: Set initial sequence and increment flag
     incremented := true
     ctx = ctx.WithValue(evmante.ContextKeySequenceIncremented, &incremented)
     acc := input.AccountKeeper.GetAccount(ctx, addr)
-    seq := acc.GetSequence() + 1
+    seq := acc.GetSequence() + initialIncrement
     acc.SetSequence(seq)
     input.AccountKeeper.SetAccount(ctx, acc)

-    // should not increment sequence
-    msgServer := keeper.NewMsgServerImpl(&input.EVMKeeper)
-    res, err := msgServer.Call(ctx, &types.MsgCall{
-        Sender:       addr.String(),
-        ContractAddr: contractAddr.Hex(),
-        Input:        hexutil.Encode(inputBz),
-    })
+    t.Run("first call should not increment sequence when flag is set", func(t *testing.T) {
+        msgServer := keeper.NewMsgServerImpl(&input.EVMKeeper)
+        res, err := msgServer.Call(ctx, &types.MsgCall{
+            Sender:       addr.String(),
+            ContractAddr: contractAddr.Hex(),
+            Input:        hexutil.Encode(inputBz),
+        })
+        require.NoError(t, err)
+        require.Equal(t, "0x", res.Result)
+        require.NotEmpty(t, res.Logs)

+        acc := input.AccountKeeper.GetAccount(ctx, addr)
+        require.Equal(t, seq, acc.GetSequence(), "sequence should remain unchanged")
+    })

+    t.Run("subsequent call should increment sequence", func(t *testing.T) {
+        // ... similar refactor for second call test
+    })

+    t.Run("create should increment sequence", func(t *testing.T) {
+        // ... similar refactor for create test
+    })
 }

184-307: Overall assessment: Tests are functional but could be improved.

The tests effectively verify the sequence increment behavior for both contract calls and creations. While they are functionally correct, consider the suggested refactors to improve:

  1. Test maintainability through helper functions
  2. Code reusability by reducing duplication
  3. Test clarity with better structure and documentation

The core test logic and assertions are solid, making this a good foundation for the sequence increment fixes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 240904b and c9ae22f.

📒 Files selected for processing (3)
  • x/evm/ante/sequence.go (1 hunks)
  • x/evm/keeper/msg_server.go (4 hunks)
  • x/evm/keeper/msg_server_test.go (2 hunks)
🧰 Additional context used
📓 Learnings (1)
x/evm/keeper/msg_server.go (1)
Learnt from: beer-1
PR: initia-labs/minievm#92
File: x/evm/keeper/msg_server.go:269-0
Timestamp: 2024-10-30T04:33:01.501Z
Learning: In `x/evm/keeper/msg_server.go`, within the `handleSequenceIncremented` method, it's safe to decrement the sequence number without checking for underflow because it was already incremented earlier.
🔇 Additional comments (6)
x/evm/ante/sequence.go (1)

46-47: Verify thread safety and context behavior with pointers.

The change to use a pointer for the incremented flag is a good approach as it enables state reversion after the first call. However, there are some important considerations:

  1. Thread Safety: Using a shared pointer without synchronization could lead to race conditions if the context is accessed concurrently. Consider adding appropriate synchronization mechanisms.

  2. Context Behavior: Ensure that the context properly handles pointer values, especially during cloning or value retrieval operations.

Let's verify the context usage pattern:

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

36-39: LGTM: Simplified error handling in Create method

The change to directly handle errors from handleSequenceIncremented improves code clarity and maintains proper sequence number management.


101-104: LGTM: Consistent error handling in Create2 method

The change maintains consistency with the Create method implementation.


166-169: LGTM: Consistent error handling in Call method

The change maintains consistency with other message handlers while properly managing sequence numbers for call operations.


261-264: LGTM: Clear documentation and improved error handling

The documentation clearly explains the different sequence number increment behaviors between Cosmos SDK and EVM, which is crucial for understanding this complex interaction.

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

12-12: LGTM: Import addition is appropriate.

The added import for evmante is necessary for accessing the context key used in sequence increment tests.

x/evm/keeper/msg_server_test.go Show resolved Hide resolved
Copy link
Contributor

@djm07073 djm07073 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 5df5933 into main Nov 8, 2024
9 checks passed
@beer-1 beer-1 deleted the fix/sequence-increment-at-every-msg-call branch November 8, 2024 07:14
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