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(auth): audit issues with unordered txs #23392

Open
wants to merge 11 commits into
base: main
Choose a base branch
from

Conversation

facundomedica
Copy link
Member

@facundomedica facundomedica commented Jan 15, 2025

Description

Closes: #XXXX

Marked ready for review after the green light by the auditor.


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 (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • 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.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

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 support for unordered transactions across multiple system components.
    • Improved transaction signature verification process.
    • New methods for creating and testing unordered transactions.
  • Bug Fixes

    • Refined error handling for transaction sequence and signature verification.
    • Corrected transaction identifier calculation for unordered transactions.
  • Refactor

    • Modified transaction processing logic to use timeout timestamps instead of gas limits.
    • Updated signature verification mechanisms for more robust transaction management.

Copy link
Contributor

coderabbitai bot commented Jan 15, 2025

📝 Walkthrough

Walkthrough

This pull request introduces modifications to handling unordered transactions across multiple files in the blockchain system. The changes primarily focus on updating the logic for processing unordered transactions, specifically shifting from using gas limits to timeout timestamps for nonce determination. The modifications impact transaction identification, signature verification, and mempool management, ensuring a more consistent approach to handling transactions that do not follow the standard sequential processing model.

Changes

File Change Summary
types/mempool/priority_nonce.go, types/mempool/sender_nonce.go Modified Insert and Remove methods to use timeout timestamp instead of gas limit for unordered transaction nonce handling, including validation for non-negative timestamps.
x/auth/ante/sigverify.go Added logic to bypass sequence number verification for unordered transactions in verifySig and adjusted increaseSequence method accordingly.
x/auth/ante/unordered.go Enhanced TxIdentifier function to handle signature data and validate transaction types, replacing fee checks and adding signature retrieval logic. Added a new addSignatures function.
types/mempool/mempool_test.go, types/mempool/priority_nonce_test.go, types/mempool/sender_nonce_test.go, x/auth/ante/ante_test.go, x/auth/ante/testutil_test.go Added new test functions to validate the handling of unordered transactions across different components, including mempool and ante handler.

Sequence Diagram

sequenceDiagram
    participant TX as Unordered Transaction
    participant Mempool as Mempool
    participant SigVerify as Signature Verification
    participant Ante as Ante Handler

    TX->>Mempool: Insert Transaction
    Mempool->>Mempool: Validate Timeout Timestamp
    Mempool-->>TX: Nonce Assigned

    TX->>SigVerify: Verify Signature
    SigVerify->>SigVerify: Check Unordered Flag
    SigVerify-->>Ante: Skip Sequence Verification
    Ante->>TX: Process Transaction
Loading

Possibly related PRs

Suggested labels

C:x/tx, C:Simulations

Suggested reviewers

  • julienrbrt
  • testinginprod
  • aljo242
  • sontrinh16
  • kocubinski

📜 Recent review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7119934 and 5104784.

📒 Files selected for processing (1)
  • types/mempool/sender_nonce_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • types/mempool/sender_nonce_test.go
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: tests (00)
  • GitHub Check: Analyze
  • GitHub Check: Summary

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.

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.

@facundomedica facundomedica marked this pull request as ready for review January 20, 2025 12:55
@facundomedica facundomedica requested a review from a team as a code owner January 20, 2025 12:55
Copy link
Contributor

@facundomedica your pull request is missing a changelog!

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

🧹 Nitpick comments (6)
x/auth/ante/unordered.go (2)

210-210: Correct the error message when writing gas to buffer.

The error message currently states "failed to write unordered to buffer," which is misleading. It should accurately reflect the operation of writing gas to the buffer.

Apply this diff to correct the error message:

 if err := binary.Write(buf, binary.LittleEndian, sigTx.GetGas()); err != nil {
     return errorsmod.Wrap(
         sdkerrors.ErrInvalidRequest,
-        "failed to write unordered to buffer",
+        "failed to write gas to buffer",
     )
 }

223-245: Ensure consistent error handling in addSignatures function.

In the default case of the switch statement, the error is returned using fmt.Errorf, whereas elsewhere, errors are wrapped using errorsmod.Wrap. For consistency and better error categorization, consider using errorsmod.Wrapf instead of fmt.Errorf.

Apply this diff to make the error handling consistent:

 default:
-    return fmt.Errorf("unexpected SignatureData %T", data)
+    return errorsmod.Wrapf(
+        sdkerrors.ErrInvalidRequest,
+        "unexpected SignatureData %T",
+        data,
+    )
 }
types/mempool/sender_nonce.go (1)

148-154: Refactor duplicated code for handling unordered transactions.

The logic for handling unordered transactions in both the Insert (lines 148-154) and Remove (lines 239-245) methods is duplicated. To improve maintainability and reduce code duplication, consider refactoring this code into a helper function.

Here's an example of how you might refactor the code:

func getUnorderedNonce(tx sdk.Tx) (uint64, error) {
    if unordered, ok := tx.(sdk.TxWithUnordered); ok && unordered.GetUnordered() {
        timestamp := unordered.GetTimeoutTimeStamp().Unix()
        if timestamp < 0 {
            return 0, errors.New("invalid timestamp value")
        }
        return uint64(timestamp), nil
    }
    return 0, nil
}

Then, update the Insert method:

 // Insert adds a tx to the mempool.
 func (snm *SenderNonceMempool) Insert(_ context.Context, tx sdk.Tx) error {
     // Existing code...

     nonce := sig.Sequence

-    // if it's an unordered tx, we use the timeout timestamp instead of the nonce
-    if unordered, ok := tx.(sdk.TxWithUnordered); ok && unordered.GetUnordered() {
-        timestamp := unordered.GetTimeoutTimeStamp().Unix()
-        if timestamp < 0 {
-            return errors.New("invalid timestamp value")
-        }
-        nonce = uint64(timestamp)
-    }
+    // Get the nonce for unordered transactions
+    if unorderedNonce, err := getUnorderedNonce(tx); err != nil {
+        return err
+    } else if unorderedNonce != 0 {
+        nonce = unorderedNonce
+    }

     // Existing code...
 }

And similarly, update the Remove method:

 // Remove removes a tx from the mempool.
 func (snm *SenderNonceMempool) Remove(tx sdk.Tx) error {
     // Existing code...

     nonce := sig.Sequence

-    // if it's an unordered tx, we use the timeout timestamp instead of the nonce
-    if unordered, ok := tx.(sdk.TxWithUnordered); ok && unordered.GetUnordered() {
-        timestamp := unordered.GetTimeoutTimeStamp().Unix()
-        if timestamp < 0 {
-            return errors.New("invalid timestamp value")
-        }
-        nonce = uint64(timestamp)
-    }
+    // Get the nonce for unordered transactions
+    if unorderedNonce, err := getUnorderedNonce(tx); err != nil {
+        return err
+    } else if unorderedNonce != 0 {
+        nonce = unorderedNonce
+    }

     // Existing code...
 }

Also applies to: 239-245

types/mempool/priority_nonce.go (1)

227-233: Refactor duplicated code for handling unordered transactions.

The logic for handling unordered transactions in both the Insert (lines 227-233) and Remove (lines 472-478) methods is duplicated. To enhance maintainability and reduce code duplication, consider extracting this logic into a shared helper function.

Create a helper function like this:

func getUnorderedNonce(tx sdk.Tx) (uint64, error) {
    if unordered, ok := tx.(sdk.TxWithUnordered); ok && unordered.GetUnordered() {
        timestamp := unordered.GetTimeoutTimeStamp().Unix()
        if timestamp < 0 {
            return 0, errors.New("invalid timestamp value")
        }
        return uint64(timestamp), nil
    }
    return 0, nil
}

Then, modify the Insert method:

 // Insert attempts to insert a Tx into the mempool.
 func (mp *PriorityNonceMempool[C]) Insert(ctx context.Context, tx sdk.Tx) error {
     // Existing code...

     nonce := sig.Sequence

-    // if it's an unordered tx, we use the timeout timestamp instead of the nonce
-    if unordered, ok := tx.(sdk.TxWithUnordered); ok && unordered.GetUnordered() {
-        timestamp := unordered.GetTimeoutTimeStamp().Unix()
-        if timestamp < 0 {
-            return errors.New("invalid timestamp value")
-        }
-        nonce = uint64(timestamp)
-    }
+    // Get the nonce for unordered transactions
+    if unorderedNonce, err := getUnorderedNonce(tx); err != nil {
+        return err
+    } else if unorderedNonce != 0 {
+        nonce = unorderedNonce
+    }

     // Existing code...
 }

And update the Remove method:

 // Remove removes a transaction from the mempool.
 func (mp *PriorityNonceMempool[C]) Remove(tx sdk.Tx) error {
     // Existing code...

     nonce := sig.Sequence

-    // if it's an unordered tx, we use the timeout timestamp instead of the nonce
-    if unordered, ok := tx.(sdk.TxWithUnordered); ok && unordered.GetUnordered() {
-        timestamp := unordered.GetTimeoutTimeStamp().Unix()
-        if timestamp < 0 {
-            return errors.New("invalid timestamp value")
-        }
-        nonce = uint64(timestamp)
-    }
+    // Get the nonce for unordered transactions
+    if unorderedNonce, err := getUnorderedNonce(tx); err != nil {
+        return err
+    } else if unorderedNonce != 0 {
+        nonce = unorderedNonce
+    }

     // Existing code...
 }

Also applies to: 472-478

x/auth/ante/sigverify.go (2)

337-337: Fix indentation.

The line is indented incorrectly compared to the surrounding code.

-				sdkerrors.ErrWrongSequence,
+			sdkerrors.ErrWrongSequence,

325-339: Document security implications of unordered transactions.

The introduction of unordered transactions that bypass sequence checks is a significant architectural change. Consider:

  1. Adding documentation about potential security implications.
  2. Clarifying when unordered transactions should/shouldn't be used.
  3. Documenting how replay protection works for unordered transactions.
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 69defb4 and 9a7dbff.

📒 Files selected for processing (4)
  • types/mempool/priority_nonce.go (2 hunks)
  • types/mempool/sender_nonce.go (2 hunks)
  • x/auth/ante/sigverify.go (1 hunks)
  • x/auth/ante/unordered.go (5 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
types/mempool/priority_nonce.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

types/mempool/sender_nonce.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/auth/ante/unordered.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/auth/ante/sigverify.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (1)
x/auth/ante/sigverify.go (1)

322-324: LGTM! Clean implementation of unordered transaction check.

The code follows Go's best practices for type assertion and interface checking.

x/auth/ante/sigverify.go Outdated Show resolved Hide resolved
@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Jan 20, 2025
@aljo242
Copy link
Collaborator

aljo242 commented Jan 20, 2025

Can we get tests to cover this new logic?

Copy link
Member

@tac0turtle tac0turtle left a comment

Choose a reason for hiding this comment

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

looks good, can we add a test case or two to make sure it works as expected

Copy link
Contributor

@alpe alpe left a comment

Choose a reason for hiding this comment

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

I am not fully aware about the functional requirements for unordered TX so I can not comment on that. The code looks good.
I added some minor comments and nits.

return err
timestamp := unordered.GetTimeoutTimeStamp().Unix()
if timestamp < 0 {
return errors.New("invalid timestamp value")
Copy link
Contributor

Choose a reason for hiding this comment

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

This was in the old code before but as you touched it ( ;-) ), it would make sense to have this block moved before snm.senders is set in L145. We should not add elements to the object before the error cases are handled

x/auth/ante/sigverify.go Outdated Show resolved Hide resolved
}
}
default:
return fmt.Errorf("unexpected SignatureData %T", data)
Copy link
Contributor

@alpe alpe Jan 21, 2025

Choose a reason for hiding this comment

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

personal preference:
This works with the specified types but is easy to miss and limits the types supported. If you would add a io.Writer to signing.SignatureData, you can call this and don't need the cast and ensure all types are supported.

Copy link
Member Author

Choose a reason for hiding this comment

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

not sure I understand this one 🤔

isUnordered := ok && unorderedTx.GetUnordered()

// only check sequence if the tx is not unordered
if !isUnordered {
Copy link
Collaborator

Choose a reason for hiding this comment

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

@facundomedica can we test this?

Copy link
Member Author

Choose a reason for hiding this comment

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

added a test for it 👌

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

♻️ Duplicate comments (1)
types/mempool/sender_nonce.go (1)

142-150: 🛠️ Refactor suggestion

Move error check before modifying state.

The error check for invalid timestamp should be moved before the senderTxs lookup to maintain proper error handling flow.

Apply this diff to improve the error handling:

 	// if it's an unordered tx, we use the timeout timestamp instead of the nonce
 	if unordered, ok := tx.(sdk.TxWithUnordered); ok && unordered.GetUnordered() {
 		timestamp := unordered.GetTimeoutTimeStamp().Unix()
+		if timestamp < 0 {
+			return errors.New("invalid timestamp value")
+		}
 		nonce = uint64(timestamp)
-		if timestamp < 0 {
-			return errors.New("invalid timestamp value")
-		}
 	}
🧹 Nitpick comments (5)
types/mempool/sender_nonce_test.go (2)

197-246: Enhance test coverage for unordered transactions.

The test should include additional scenarios:

  1. Transactions with same timeout timestamp
  2. Transactions with expired timeout
  3. Invalid timeout values (nil, past time)
  4. Mix of ordered and unordered transactions

Line range hint 982-987: Improve test robustness.

Consider these improvements:

  1. Use relative time values (e.g., time.Now().Add(duration)) to avoid potential timezone issues
  2. Add cleanup to remove test transactions from mempool after test completion
-	now := time.Now()
-	oneHour := now.Add(1 * time.Hour)
-	thirtyMin := now.Add(30 * time.Minute)
-	twoHours := now.Add(2 * time.Hour)
-	fifteenMin := now.Add(15 * time.Minute)
+	baseTime := time.Now()
+	timeouts := []time.Duration{
+		time.Hour,
+		30 * time.Minute,
+		2 * time.Hour,
+		15 * time.Minute,
+	}
x/auth/ante/testutil_test.go (1)

245-304: Add input validation for unordered transaction parameters.

Consider validating:

  1. Timeout timestamp for unordered transactions (should not be zero when unordered is true)
  2. Consistency between unordered flag and timeout value
 func (suite *AnteTestSuite) CreateTestUnorderedTx(
 	ctx sdk.Context, privs []cryptotypes.PrivKey,
 	accNums, accSeqs []uint64,
 	chainID string, signMode apisigning.SignMode,
 	unordered bool, unorderedTimeout time.Time,
 ) (xauthsigning.Tx, error) {
+	if unordered && unorderedTimeout.IsZero() {
+		return nil, fmt.Errorf("timeout timestamp required for unordered transactions")
+	}
 	suite.txBuilder.SetUnordered(unordered)
 	suite.txBuilder.SetTimeoutTimestamp(unorderedTimeout)
types/mempool/priority_nonce_test.go (1)

974-1010: Consolidate duplicate test logic.

This test has similar setup and verification logic as TestUnorderedTx in sender_nonce_test.go. Consider:

  1. Creating shared test utilities for unordered transaction testing
  2. Adding unique test cases specific to priority handling

Additionally, the test should verify priority-specific behavior:

  1. Interaction between priority and timeout ordering
  2. Priority updates for unordered transactions
🧰 Tools
🪛 golangci-lint (1.62.2)

1009-1009: File is not gofumpt-ed with -extra

(gofumpt)

🪛 GitHub Actions: Lint

[error] 1009-1009: File is not gofumpt-ed with -extra. Formatting issue detected.

types/mempool/sender_nonce.go (1)

239-245: Extract common unordered tx logic to reduce duplication.

The unordered transaction handling logic is duplicated between Insert and Remove methods. Consider extracting it into a helper function.

Create a helper function like this:

// getNonceFromTx returns the appropriate nonce for a transaction, using the timeout
// timestamp for unordered transactions and sequence number for regular transactions.
func getNonceFromTx(tx sdk.Tx, sig signing.SignatureV2) (uint64, error) {
    if unordered, ok := tx.(sdk.TxWithUnordered); ok && unordered.GetUnordered() {
        timestamp := unordered.GetTimeoutTimeStamp().Unix()
        if timestamp < 0 {
            return 0, errors.New("invalid timestamp value")
        }
        return uint64(timestamp), nil
    }
    return sig.Sequence, nil
}

Then use it in both Insert and Remove methods:

-	nonce := sig.Sequence
-	if unordered, ok := tx.(sdk.TxWithUnordered); ok && unordered.GetUnordered() {
-		timestamp := unordered.GetTimeoutTimeStamp().Unix()
-		if timestamp < 0 {
-			return errors.New("invalid timestamp value")
-		}
-		nonce = uint64(timestamp)
-	}
+	nonce, err := getNonceFromTx(tx, sig)
+	if err != nil {
+		return err
+	}
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7f37647 and 3c075bc.

📒 Files selected for processing (6)
  • types/mempool/mempool_test.go (3 hunks)
  • types/mempool/priority_nonce_test.go (1 hunks)
  • types/mempool/sender_nonce.go (2 hunks)
  • types/mempool/sender_nonce_test.go (2 hunks)
  • x/auth/ante/ante_test.go (2 hunks)
  • x/auth/ante/testutil_test.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
x/auth/ante/ante_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

types/mempool/sender_nonce_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

types/mempool/priority_nonce_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

types/mempool/mempool_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

x/auth/ante/testutil_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

types/mempool/sender_nonce.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🪛 golangci-lint (1.62.2)
x/auth/ante/ante_test.go

1418-1418: File is not gofumpt-ed with -extra

(gofumpt)

types/mempool/priority_nonce_test.go

1009-1009: File is not gofumpt-ed with -extra

(gofumpt)

🪛 GitHub Actions: Lint
x/auth/ante/ante_test.go

[error] 1418-1418: File is not gofumpt-ed with -extra. Formatting issue detected.

types/mempool/priority_nonce_test.go

[error] 1009-1009: File is not gofumpt-ed with -extra. Formatting issue detected.

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: tests (00)
  • GitHub Check: test-system-v2
  • GitHub Check: build (amd64)
  • GitHub Check: Analyze
  • GitHub Check: Summary
🔇 Additional comments (3)
types/mempool/mempool_test.go (1)

59-73: LGTM! Clean implementation of TxWithUnordered interface.

The implementation correctly handles the timeout timestamp and unordered flag.

x/auth/ante/ante_test.go (2)

9-9: LGTM!

The time package import is required for setting the timeout timestamp in the unordered transaction test.


1389-1419: LGTM! Test coverage for unordered transactions looks good.

The test thoroughly verifies that:

  1. A normal sequential tx with sequence 0 succeeds
  2. A second tx with the same sequence fails (replay protection)
  3. An unordered tx with the same sequence succeeds (sequence check bypassed)

The test demonstrates that unordered transactions correctly bypass sequence checks while maintaining other validations.

🧰 Tools
🪛 golangci-lint (1.62.2)

1418-1418: File is not gofumpt-ed with -extra

(gofumpt)

🪛 GitHub Actions: Lint

[error] 1418-1418: File is not gofumpt-ed with -extra. Formatting issue detected.

for i, tx := range orderedTxs {
require.Equal(t, txs[i].id, tx.(testTx).id)
}

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

Fix gofumpt formatting.

Run gofumpt -l -w . to fix the formatting issue.

🧰 Tools
🪛 golangci-lint (1.62.2)

1009-1009: File is not gofumpt-ed with -extra

(gofumpt)

🪛 GitHub Actions: Lint

[error] 1009-1009: File is not gofumpt-ed with -extra. Formatting issue detected.

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

🧹 Nitpick comments (2)
x/auth/ante/ante_test.go (2)

1389-1393: Test setup could be more comprehensive.

Consider adding multiple test accounts to verify unordered transactions behavior across different accounts.

-	accs := suite.CreateTestAccounts(1)
+	accs := suite.CreateTestAccounts(2)

1389-1418: Add test for concurrent unordered transactions.

The test should verify that multiple unordered transactions with the same sequence can be processed concurrently.

+func TestAnteHandlerConcurrentUnorderedTx(t *testing.T) {
+	suite := SetupTestSuite(t, false)
+	accs := suite.CreateTestAccounts(1)
+	msg := testdata.NewTestMsg(accs[0].acc.GetAddress())
+
+	suite.bankKeeper.EXPECT().SendCoinsFromAccountToModule(gomock.Any(), accs[0].acc.GetAddress(), authtypes.FeeCollectorName, testdata.NewTestFeeAmount()).Return(nil).AnyTimes()
+
+	privs, accNums, accSeqs := []cryptotypes.PrivKey{accs[0].priv}, []uint64{1000}, []uint64{0}
+
+	// Create multiple unordered transactions with same sequence
+	var wg sync.WaitGroup
+	for i := 0; i < 3; i++ {
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+			tx, _ := suite.CreateTestUnorderedTx(suite.ctx, privs, accNums, accSeqs, suite.ctx.ChainID(), apisigning.SignMode_SIGN_MODE_DIRECT, true, time.Now().Add(time.Minute))
+			_, err := suite.anteHandler(suite.ctx, tx, false)
+			require.NoError(t, err)
+		}()
+	}
+	wg.Wait()
+}
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3c075bc and 7119934.

📒 Files selected for processing (2)
  • types/mempool/priority_nonce_test.go (1 hunks)
  • x/auth/ante/ante_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • types/mempool/priority_nonce_test.go
🧰 Additional context used
📓 Path-based instructions (1)
x/auth/ante/ante_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: tests (00)
  • GitHub Check: test-system-v2
  • GitHub Check: Analyze
  • GitHub Check: Summary

Comment on lines +1401 to +1403
// we try to send another tx with the same sequence, it will fail
_, err = suite.DeliverMsgs(t, privs, []sdk.Msg{msg}, testdata.NewTestFeeAmount(), testdata.NewTestGasLimit(), accNums, accSeqs, suite.ctx.ChainID(), false)
require.Error(t, err)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error assertion.

The error check should verify the specific error type for sequence mismatch.

-	require.Error(t, err)
+	require.ErrorIs(t, err, sdkerrors.ErrWrongSequence)
📝 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
// we try to send another tx with the same sequence, it will fail
_, err = suite.DeliverMsgs(t, privs, []sdk.Msg{msg}, testdata.NewTestFeeAmount(), testdata.NewTestGasLimit(), accNums, accSeqs, suite.ctx.ChainID(), false)
require.Error(t, err)
// we try to send another tx with the same sequence, it will fail
_, err = suite.DeliverMsgs(t, privs, []sdk.Msg{msg}, testdata.NewTestFeeAmount(), testdata.NewTestGasLimit(), accNums, accSeqs, suite.ctx.ChainID(), false)
require.ErrorIs(t, err, sdkerrors.ErrWrongSequence)

Comment on lines +1411 to +1417
tx, txErr := suite.CreateTestUnorderedTx(suite.ctx, privs, accNums, accSeqs, suite.ctx.ChainID(), apisigning.SignMode_SIGN_MODE_DIRECT, true, time.Now().Add(time.Minute))
require.NoError(t, txErr)
txBytes, err := suite.clientCtx.TxConfig.TxEncoder()(tx)
bytesCtx := suite.ctx.WithTxBytes(txBytes)
require.NoError(t, err)
_, err = suite.anteHandler(bytesCtx, tx, false)
require.NoError(t, err)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add timeout validation test cases.

The test should include cases for expired and future timeouts to ensure proper validation.

+	// Test expired timeout
+	expiredTx, _ := suite.CreateTestUnorderedTx(suite.ctx, privs, accNums, accSeqs, suite.ctx.ChainID(), apisigning.SignMode_SIGN_MODE_DIRECT, true, time.Now().Add(-time.Minute))
+	_, err = suite.anteHandler(bytesCtx, expiredTx, false)
+	require.ErrorIs(t, err, sdkerrors.ErrTxTimeoutHeight)
+
+	// Test far future timeout
+	futureTx, _ := suite.CreateTestUnorderedTx(suite.ctx, privs, accNums, accSeqs, suite.ctx.ChainID(), apisigning.SignMode_SIGN_MODE_DIRECT, true, time.Now().Add(24*time.Hour))
+	_, err = suite.anteHandler(bytesCtx, futureTx, false)
+	require.ErrorIs(t, err, sdkerrors.ErrInvalidTimeout)

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +1394 to +1399
// First send a normal sequential tx with sequence 0
suite.bankKeeper.EXPECT().SendCoinsFromAccountToModule(gomock.Any(), accs[0].acc.GetAddress(), authtypes.FeeCollectorName, testdata.NewTestFeeAmount()).Return(nil).AnyTimes()

privs, accNums, accSeqs := []cryptotypes.PrivKey{accs[0].priv}, []uint64{1000}, []uint64{0}
_, err := suite.DeliverMsgs(t, privs, []sdk.Msg{msg}, testdata.NewTestFeeAmount(), testdata.NewTestGasLimit(), accNums, accSeqs, suite.ctx.ChainID(), false)
require.NoError(t, err)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add assertion for account sequence.

The test should verify that the account sequence is incremented after the first transaction.

 	_, err := suite.DeliverMsgs(t, privs, []sdk.Msg{msg}, testdata.NewTestFeeAmount(), testdata.NewTestGasLimit(), accNums, accSeqs, suite.ctx.ChainID(), false)
 	require.NoError(t, err)
+	// Verify sequence is incremented
+	acc := suite.accountKeeper.GetAccount(suite.ctx, accs[0].acc.GetAddress())
+	require.Equal(t, uint64(1), acc.GetSequence())
📝 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
// First send a normal sequential tx with sequence 0
suite.bankKeeper.EXPECT().SendCoinsFromAccountToModule(gomock.Any(), accs[0].acc.GetAddress(), authtypes.FeeCollectorName, testdata.NewTestFeeAmount()).Return(nil).AnyTimes()
privs, accNums, accSeqs := []cryptotypes.PrivKey{accs[0].priv}, []uint64{1000}, []uint64{0}
_, err := suite.DeliverMsgs(t, privs, []sdk.Msg{msg}, testdata.NewTestFeeAmount(), testdata.NewTestGasLimit(), accNums, accSeqs, suite.ctx.ChainID(), false)
require.NoError(t, err)
// First send a normal sequential tx with sequence 0
suite.bankKeeper.EXPECT().SendCoinsFromAccountToModule(gomock.Any(), accs[0].acc.GetAddress(), authtypes.FeeCollectorName, testdata.NewTestFeeAmount()).Return(nil).AnyTimes()
privs, accNums, accSeqs := []cryptotypes.PrivKey{accs[0].priv}, []uint64{1000}, []uint64{0}
_, err := suite.DeliverMsgs(t, privs, []sdk.Msg{msg}, testdata.NewTestFeeAmount(), testdata.NewTestGasLimit(), accNums, accSeqs, suite.ctx.ChainID(), false)
require.NoError(t, err)
// Verify sequence is incremented
acc := suite.accountKeeper.GetAccount(suite.ctx, accs[0].acc.GetAddress())
require.Equal(t, uint64(1), acc.GetSequence())

Copy link
Collaborator

@aljo242 aljo242 left a comment

Choose a reason for hiding this comment

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

approving with small nit

func (s *MempoolTestSuite) TestUnorderedTx() {
t := s.T()

ctx := sdk.NewContext(nil, false, log.NewNopLogger())
Copy link
Collaborator

Choose a reason for hiding this comment

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

We should be able to just use context.Background() for this test

Copy link
Member Author

Choose a reason for hiding this comment

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

We need an sdk.Context here, because below we call ctx.WithPriority when calling mp.Insert

Copy link
Collaborator

@aljo242 aljo242 left a comment

Choose a reason for hiding this comment

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

Looks like the new tests are failing here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:x/auth
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants