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: skip sequence number check at simulation #107

Merged
merged 1 commit into from
Nov 13, 2024

Conversation

beer-1
Copy link
Collaborator

@beer-1 beer-1 commented Nov 13, 2024

Description

in normal geth, it allows to simulate gas without sequence number.


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

    • Enhanced transaction creation process to support multiple signing modes.
    • Improved signature verification logic to accommodate Ethereum signatures.
  • Bug Fixes

    • Adjusted sequence number checks for Ethereum signatures during transaction simulation.
  • Tests

    • Introduced a new test suite for verifying signature behavior under different signing modes and simulation conditions.

@beer-1 beer-1 self-assigned this Nov 13, 2024
@beer-1 beer-1 requested a review from a team as a code owner November 13, 2024 07:15
Copy link

coderabbitai bot commented Nov 13, 2024

Walkthrough

The changes in this pull request primarily involve modifications to transaction handling and signature verification within the Ante module. The CreateTestTx method has been updated to include an additional signMode parameter, enhancing flexibility for transaction signing. The signature verification logic has also been improved to accommodate Ethereum signing modes, allowing for a more dynamic handling of sequence checks during transaction simulation. Additionally, a new test suite has been introduced to validate these changes, ensuring the correct behavior of the signature verification process under various conditions.

Changes

File Change Summary
app/ante/ante_test.go Updated CreateTestTx method to include signMode signing.SignMode parameter.
app/ante/fee_test.go Modified CreateTestTx method to include signMode signing.SignMode parameter; added import for authsign.
app/ante/sigverify.go Enhanced SigVerificationDecorator with ek EVMKeeper field; modified AnteHandle for Ethereum signing mode.
app/ante/sigverify_test.go Introduced a new test suite sigverify_test.go to validate signature verification logic under different conditions.

Possibly related PRs

Suggested reviewers

  • djm07073

🐇 In the code we hop and play,
New signing modes come out to play.
With tests that check each little line,
The signatures are now just fine!
So let’s celebrate with joy and cheer,
For flexible signing is finally here! 🥕


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 13, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 28.25%. Comparing base (23ccbfb) to head (f8af24b).
Report is 2 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #107      +/-   ##
==========================================
+ Coverage   28.07%   28.25%   +0.17%     
==========================================
  Files         126      126              
  Lines       14231    14237       +6     
==========================================
+ Hits         3996     4022      +26     
+ Misses       9669     9642      -27     
- Partials      566      573       +7     
Files with missing lines Coverage Δ
app/ante/sigverify.go 26.44% <100.00%> (+21.22%) ⬆️

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

🧹 Outside diff range and nitpick comments (7)
app/ante/sigverify_test.go (5)

13-21: Consider adding clarifying comments for account setup.

While the setup code is correct, it would be helpful to add a comment explaining why the public key needs to be set explicitly for the test account.

 	acc1 := suite.app.AccountKeeper.NewAccountWithAddress(suite.ctx, addr1)
+	// Set public key explicitly as it's required for signature verification
 	acc1.SetPubKey(priv1.PubKey())

22-37: Document the test scenario setup more explicitly.

While the code correctly sets up a test scenario with an invalid sequence number, the purpose could be more clearly documented.

+	// Setup a transaction with an invalid sequence number (100) to test sequence check behavior
+	// during simulation and non-simulation scenarios
 	sigV2 := signing.SignatureV2{
 		PubKey: priv1.PubKey(),
 		Data: &signing.SingleSignatureData{
 			SignMode:  evmkeeper.SignMode_SIGN_MODE_ETHEREUM,
 			Signature: nil,
 		},
-		// invalid sequence
+		// Use an invalid sequence number (100) to verify sequence check behavior
 		Sequence: 100,
 	}

38-41: Consider adding more explicit assertions for simulation mode.

While the test correctly verifies that no error occurs, consider adding assertions to explicitly verify that we're in simulation mode and using Ethereum sign mode.

 	// 1. simulate should skip sequence check
 	sigVerifyAnte := ante.NewSigVerificationDecorator(suite.app.AccountKeeper, suite.app.EVMKeeper, suite.app.TxConfig().SignModeHandler())
+	// Verify we're using Ethereum sign mode
+	tx := suite.txBuilder.GetTx()
+	suite.Equal(evmkeeper.SignMode_SIGN_MODE_ETHEREUM, tx.GetSignatures()[0].Data.(*signing.SingleSignatureData).SignMode)
 	_, err = sigVerifyAnte.AnteHandle(suite.ctx, suite.txBuilder.GetTx(), true, func(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, err error) { return ctx, nil })
 	suite.NoError(err)

43-48: Enhance error validation for sequence check failure.

Consider adding more specific error validation to ensure the sequence check fails for the expected reason.

 	_, err = sigVerifyAnte.AnteHandle(suite.ctx, suite.txBuilder.GetTx(), true, func(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, err error) { return ctx, nil })
-	suite.ErrorIs(err, sdkerrors.ErrWrongSequence)
+	suite.ErrorIs(err, sdkerrors.ErrWrongSequence)
+	suite.Contains(err.Error(), "account sequence mismatch")

50-56: Add validation for non-simulation context.

Consider adding assertions to explicitly verify the non-simulation context.

 	// 3. non-simulate should check sequence
 	sigV2.Data.(*signing.SingleSignatureData).SignMode = evmkeeper.SignMode_SIGN_MODE_ETHEREUM
 	err = suite.txBuilder.SetSignatures(sigV2)
 	suite.NoError(err)
+	// Create a new context with simulation flag set to false
+	nonSimCtx := suite.ctx.WithIsReCheckTx(true)
-	_, err = sigVerifyAnte.AnteHandle(suite.ctx, suite.txBuilder.GetTx(), false, func(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, err error) { return ctx, nil })
+	_, err = sigVerifyAnte.AnteHandle(nonSimCtx, suite.txBuilder.GetTx(), false, func(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, err error) {
+		suite.False(simulate, "should be in non-simulation mode")
+		return ctx, nil
+	})
 	suite.ErrorIs(err, sdkerrors.ErrWrongSequence)
app/ante/ante_test.go (1)

Line range hint 82-128: Consider adding explicit simulation test cases

While the CreateTestTx helper now supports different signing modes, I don't see explicit test cases for the simulation scenario where sequence number checks are skipped. Consider adding test cases that:

  1. Verify successful transaction simulation without sequence numbers
  2. Compare behavior between normal and simulation modes
  3. Test edge cases specific to simulation mode

Example test structure:

func (suite *AnteTestSuite) TestSimulationWithoutSequence() {
    // Test simulation mode
    tx, err := suite.CreateTestTx(
        []cryptotypes.PrivKey{priv},
        []uint64{accNum},
        []uint64{accSeq},
        suite.ctx.ChainID(),
        signing.SignMode_SIGN_MODE_DIRECT,  // or appropriate simulation mode
    )
    suite.Require().NoError(err)
    
    // Verify sequence check is skipped in simulation
    // Add assertions here
}
app/ante/sigverify.go (1)

86-92: Consider supporting multiple Ethereum signatures in simulation

Currently, the sequence check is skipped only when there is exactly one signature (len(sigs) == 1). If there is a possibility of transactions with multiple Ethereum signatures, you may want to extend the logic to handle those cases.

You could modify the condition to iterate over all signatures and set skipSequenceCheck to true if all meet the criteria:

skipSequenceCheck := false
if simulate {
  skip := true
  for _, sig := range sigs {
    if sigData, ok := sig.Data.(*signing.SingleSignatureData); ok {
      if sigData.SignMode != evmkeeper.SignMode_SIGN_MODE_ETHEREUM {
        skip = false
        break
      }
    } else {
      skip = false
      break
    }
  }
  skipSequenceCheck = skip
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 23ccbfb and f8af24b.

📒 Files selected for processing (4)
  • app/ante/ante_test.go (3 hunks)
  • app/ante/fee_test.go (2 hunks)
  • app/ante/sigverify.go (2 hunks)
  • app/ante/sigverify_test.go (1 hunks)
🔇 Additional comments (8)
app/ante/sigverify_test.go (1)

1-11: LGTM! Package and imports are well-organized.

The imports are properly structured and include all necessary dependencies for the test suite.

app/ante/fee_test.go (3)

9-9: LGTM!

The addition of the authsign import is appropriate for handling sign mode conversion.


37-39: LGTM! Sign mode handling is properly implemented.

The conversion from API sign mode to internal format is correctly handled with proper error checking.


37-39: Add test case for sequence number skipping during simulation.

While the current test cases cover various fee scenarios, there's no explicit verification that sequence numbers are skipped during simulation. Consider adding a test case that specifically validates this behavior.

Let's check if there are other test files that might cover this:

Would you like me to help draft a test case that verifies sequence number skipping during simulation?

app/ante/ante_test.go (1)

82-82: LGTM: Method signature enhancement improves test flexibility

The addition of the signMode parameter allows for explicit control over transaction signing modes, which is essential for testing simulation scenarios where sequence checks need to be skipped.

app/ante/sigverify.go (3)

25-25: Import evmkeeper for Ethereum signing mode

The addition of the evmkeeper import is appropriate for accessing Ethereum-specific constants and functionalities.


85-93: Verify logic for skipping sequence check during simulation

The introduction of skipSequenceCheck to bypass the sequence check when simulating transactions with a single Ethereum signature is a valid approach. Ensure that this logic does not unintentionally affect other transaction types or introduce security risks.

To confirm that this change is safe, consider reviewing all simulation scenarios to ensure that sequence checks are appropriately enforced where necessary.


95-95: Maintain consistency in sequence checking logic

The modified condition now respects the skipSequenceCheck flag, which is good. Ensure that this change aligns with the overall authentication logic and does not affect non-simulated transactions.

app/ante/ante_test.go Show resolved Hide resolved
app/ante/sigverify.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 63aa650 into main Nov 13, 2024
9 checks passed
@beer-1 beer-1 deleted the feat/skip-sequence-check-at-simulation branch November 13, 2024 09:10
beer-1 added a commit that referenced this pull request Nov 13, 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