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

[OTE-553] Skip sequence increment for timestamp nonce #1956

Merged
merged 12 commits into from
Jul 23, 2024

Conversation

jerryfan01234
Copy link
Contributor

@jerryfan01234 jerryfan01234 commented Jul 23, 2024

Changelist

[Describe or list the changes made in this PR]

Test Plan

[Describe how this PR was tested (if applicable)]

Author/Reviewer Checklist

  • If this PR has changes that result in a different app state given the same prior state and transaction list, manually add the state-breaking label.
  • If the PR has breaking postgres changes to the indexer add the indexer-postgres-breaking label.
  • If this PR isn't state-breaking but has changes that modify behavior in PrepareProposal or ProcessProposal, manually add the label proposal-breaking.
  • If this PR is one of many that implement a specific feature, manually label them all feature:[feature-name].
  • If you wish to for mergify-bot to automatically create a PR to backport your change to a release branch, manually add the label backport/[branch-name].
  • Manually add any of the following labels: refactor, chore, bug.

Summary by CodeRabbit

  • New Features

    • Introduced a new decorator for managing transaction sequence increments based on timestamp nonces, improving transaction processing behavior.
    • Added functionality to validate timestamp nonce sequences, enhancing nonce management.
  • Bug Fixes

    • Simplified error handling in account state retrieval, streamlining the codebase.
  • Tests

    • Expanded test coverage for new functionality related to timestamp nonces, ensuring robust validation processes.

Copy link
Contributor

coderabbitai bot commented Jul 23, 2024

Walkthrough

The recent modifications enhance the Cosmos SDK's ante handling by introducing a custom sequence incrementing mechanism tailored for the DYDX protocol. Key changes include the addition of a IncrementSequenceDecorator that conditionally increments account sequences based on transaction signatures, improving transaction processing logic. The updates also include comprehensive tests to ensure the robustness of these changes, providing better functionality and compatibility across the system.

Changes

File Path Change Summary
protocol/app/ante.go Replaced incrementSequence decorator with customante.NewIncrementSequenceDecorator.
protocol/app/ante/timestampnonce.go Introduced IncrementSequenceDecorator for managing account sequence increments, validating transaction signatures, and conditionally skipping increments.
protocol/app/ante/timestampnonce_test.go Added tests for IncrementSequenceDecorator, covering various transaction scenarios to ensure correct sequence handling.
protocol/x/accountplus/keeper/timestampnonce.go Introduced constants and functions related to timestamp nonce management, including a validation function.
protocol/x/accountplus/keeper/timestampnonce_test.go Added tests for the IsTimestampNonce function, checking its behavior against defined cutoff values.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AnteHandler
    participant AccountKeeper
    
    User->>AnteHandler: Submit Transaction
    AnteHandler->>AccountKeeper: Validate Transaction
    AccountKeeper->>AnteHandler: Return Validation Result
    alt Valid Transaction
        AnteHandler->>AccountKeeper: Increment Sequence (if not Timestamp Nonce)
        AccountKeeper->>AnteHandler: Update Account State
    end
    AnteHandler->>User: Return Transaction Result
Loading

Poem

In the meadow where codes play,
A rabbit hops with joy today.
New sequences dance, signatures sing,
With every change, the systems spring!
Hoppy updates, oh what a delight,
Together, we'll code through the night! 🐇✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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.

@jerryfan01234 jerryfan01234 force-pushed the timestamp-nonce branch 2 times, most recently from b5d93df to 7b47bc9 Compare July 23, 2024 14:51
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.

Caution

Inline review comments failed to post

Actionable comments posted: 6

Outside diff range, codebase verification and nitpick comments (1)
protocol/x/accountplus/keeper/keeper_test.go (1)

Line range hint 85-115:
Resolve merge conflict artifacts.

The merge conflict artifacts (<<<<<<< HEAD, =======, >>>>>>> timestamp-nonce-2) need to be removed to ensure the code compiles correctly.

<<<<<<< HEAD
		expectedAccount := keeper.DefaultAccountState(constants.CarlAccAddress)
=======
		expectedAccount := types.AccountState{
			Address:               constants.CarlAccAddress.String(),
			TimestampNonceDetails: keeper.DeepCopyTimestampNonceDetails(keeper.InitialTimestampNonceDetails),
		}
>>>>>>> timestamp-nonce-2

		err := k.InitializeAccount(ctx, constants.CarlAccAddress)
		require.Nil(t, err, "Should be able to initialize account if it did not exist")

		actualAccount, found := k.GetAccountState(ctx, constants.CarlAccAddress)
		require.True(t, found, "Could not find account")
		require.Equal(t, actualAccount, expectedAccount)
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f3af0fe and 427c2c6.

Files selected for processing (9)
  • protocol/app/ante.go (2 hunks)
  • protocol/app/ante/timestampnonce.go (1 hunks)
  • protocol/app/ante/timestampnonce_test.go (1 hunks)
  • protocol/x/accountplus/genesis.go (1 hunks)
  • protocol/x/accountplus/genesis_test.go (1 hunks)
  • protocol/x/accountplus/keeper/keeper.go (1 hunks)
  • protocol/x/accountplus/keeper/keeper_test.go (3 hunks)
  • protocol/x/accountplus/keeper/timestampnonce.go (1 hunks)
  • protocol/x/accountplus/keeper/timestampnonce_test.go (1 hunks)
Additional comments not posted (11)
protocol/x/accountplus/keeper/timestampnonce_test.go (1)

17-30: LGTM!

The new test function TestDeepCopyTimestampNonceDetails effectively validates the deep copy functionality of TimestampNonceDetails. It ensures that the original and copied instances are distinct and covers the necessary aspects of the deep copy operation.

protocol/x/accountplus/keeper/timestampnonce.go (4)

11-11: LGTM!

The constant TimestampNonceSequenceCutoff is well-defined and sets a clear threshold for timestamp nonce sequences.


13-16: LGTM!

The variable InitialTimestampNonceDetails is well-initialized and provides a clear starting point for timestamp nonce details.


18-32: LGTM!

The function DeepCopyTimestampNonceDetails is well-implemented and ensures that a deep copy of the TimestampNonceDetails is created. It handles nil input appropriately and copies the slice elements effectively.


34-36: LGTM!

The function IsTimestampNonce is well-implemented and provides a clear check for timestamp nonce sequences.

protocol/app/ante/timestampnonce.go (3)

18-22: LGTM!

The function correctly initializes the DydxIncrementSequenceDecorator struct.


24-55: LGTM!

The AnteHandle function correctly implements the ante processing logic for the decorator.


14-16: LGTM!

The DydxIncrementSequenceDecorator struct and its methods are correctly defined.

protocol/app/ante/timestampnonce_test.go (1)

19-74: LGTM!

The TestDydxIncrementSequenceDecorator function correctly implements the test logic for the decorator.

protocol/app/ante.go (2)

108-108: Ensure custom decorator implementation is correct.

The custom decorator customante.NewDydxIncrementSequenceDecorator replaces the standard ante.NewIncrementSequenceDecorator. Ensure that the custom decorator implementation aligns with the expected behavior of the transaction sequence incrementing.


143-143: Ensure custom decorator implementation is correct.

The custom decorator customante.DydxIncrementSequenceDecorator replaces the standard ante.IncrementSequenceDecorator. Ensure that the custom decorator implementation aligns with the expected behavior of the transaction sequence incrementing.

Comments failed to post (6)
protocol/x/accountplus/keeper/keeper.go

78-80: Acknowledged: Planned refactor for InitializeAccount.

The TODO comment suggests a refactor to improve efficiency by directly writing with timestamp-nonce.

Do you want me to assist with this refactor or open a GitHub issue to track this task?

protocol/x/accountplus/genesis.go

17-28: Reintroduce error handling for robustness.

The removal of error handling in ExportGenesis assumes that k.GetAllAccountStates(ctx) will not return an error. This assumption can lead to potential runtime issues if an error occurs. Reintroduce appropriate error handling to ensure robustness.

- return &types.GenesisState{
-   Accounts: k.GetAllAccountStates(ctx),
+ accounts, err := k.GetAllAccountStates(ctx)
+ if err != nil {
+   panic(err)
+ }
+ return &types.GenesisState{
+   Accounts: accounts,
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.

	accounts, err := k.GetAllAccountStates(ctx)
	if err != nil {
		panic(err)
	}
	return &types.GenesisState{
		Accounts: accounts,
protocol/x/accountplus/genesis_test.go

43-52: Resolve merge conflict artifacts.

The merge conflict artifacts (<<<<<<< HEAD, =======, >>>>>>> timestamp-nonce-2) need to be removed to ensure the code compiles correctly.

<<<<<<< HEAD
=======
	TimestampNonces: []uint64{baseTsNonce + 5, baseTsNonce + 6, baseTsNonce + 7},
	MaxEjectedNonce: baseTsNonce + 1,
},
},
{
	Address: constants.CarlAccAddress.String(),
	TimestampNonceDetails: types.TimestampNonceDetails{
>>>>>>> timestamp-nonce-2
	TimestampNonces: []uint64{baseTsNonce + 5, baseTsNonce + 6, baseTsNonce + 7},
	MaxEjectedNonce: baseTsNonce + 1,
},
},
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.

							TimestampNonces: []uint64{baseTsNonce + 5, baseTsNonce + 6, baseTsNonce + 7},
							MaxEjectedNonce: baseTsNonce + 1,
						},
					},
					{
						Address: constants.CarlAccAddress.String(),
						TimestampNonceDetails: types.TimestampNonceDetails{
							TimestampNonces: []uint64{baseTsNonce + 5, baseTsNonce + 6, baseTsNonce + 7},
							MaxEjectedNonce: baseTsNonce + 1,
						},
					},
protocol/x/accountplus/keeper/keeper_test.go

13-19: Resolve merge conflict artifacts.

The merge conflict artifacts (<<<<<<< HEAD, =======, >>>>>>> timestamp-nonce-2) need to be removed to ensure the code compiles correctly.

<<<<<<< HEAD
=======
	"github.com/dydxprotocol/v4-chain/protocol/x/accountplus/testutils"
>>>>>>> timestamp-nonce-2
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.

	"github.com/dydxprotocol/v4-chain/protocol/x/accountplus/testutils"

69-77: Resolve merge conflict artifacts.

The merge conflict artifacts (<<<<<<< HEAD, =======, >>>>>>> timestamp-nonce-2) need to be removed to ensure the code compiles correctly.

<<<<<<< HEAD
		err := k.InitializeAccount(ctx, constants.AliceAccAddress)
=======
		_, err := k.InitializeAccount(ctx, constants.AliceAccAddress)
>>>>>>> timestamp-nonce-2
		require.NotNil(t, err, "Account should not be able to be initialized if already exists")
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.

		_, err := k.InitializeAccount(ctx, constants.AliceAccAddress)
		require.NotNil(t, err, "Account should not be able to be initialized if already exists")

26-58: Resolve merge conflict artifacts.

The merge conflict artifacts (<<<<<<< HEAD, =======, >>>>>>> timestamp-nonce-2) need to be removed to ensure the code compiles correctly.

<<<<<<< HEAD
		Accounts: []types.AccountState{
			{
				Address: constants.AliceAccAddress.String(),
				TimestampNonceDetails: types.TimestampNonceDetails{
=======
		Accounts: []*types.AccountState{
			{
				Address: constants.AliceAccAddress.String(),
				TimestampNonceDetails: &types.TimestampNonceDetails{
>>>>>>> timestamp-nonce-2
					TimestampNonces: []uint64{baseTsNonce + 1, baseTsNonce + 2, baseTsNonce + 3},
					MaxEjectedNonce: baseTsNonce,
				},
			},
			{
				Address: constants.BobAccAddress.String(),
<<<<<<< HEAD
				TimestampNonceDetails: types.TimestampNonceDetails{
=======
				TimestampNonceDetails: &types.TimestampNonceDetails{
>>>>>>> timestamp-nonce-2
					TimestampNonces: []uint64{baseTsNonce + 5, baseTsNonce + 6, baseTsNonce + 7},
					MaxEjectedNonce: baseTsNonce + 1,
				},
			},
		},
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.

		Accounts: []*types.AccountState{
			{
				Address: constants.AliceAccAddress.String(),
				TimestampNonceDetails: &types.TimestampNonceDetails{
					TimestampNonces: []uint64{baseTsNonce + 1, baseTsNonce + 2, baseTsNonce + 3},
					MaxEjectedNonce: baseTsNonce,
				},
			},
			{
				Address: constants.BobAccAddress.String(),
				TimestampNonceDetails: &types.TimestampNonceDetails{
					TimestampNonces: []uint64{baseTsNonce + 5, baseTsNonce + 6, baseTsNonce + 7},
					MaxEjectedNonce: baseTsNonce + 1,
				},
			},
		},

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 427c2c6 and 19da03c.

Files selected for processing (5)
  • protocol/app/ante.go (2 hunks)
  • protocol/app/ante/timestampnonce.go (1 hunks)
  • protocol/app/ante/timestampnonce_test.go (1 hunks)
  • protocol/x/accountplus/keeper/timestampnonce.go (1 hunks)
  • protocol/x/accountplus/keeper/timestampnonce_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • protocol/app/ante.go
  • protocol/app/ante/timestampnonce.go
  • protocol/app/ante/timestampnonce_test.go
  • protocol/x/accountplus/keeper/timestampnonce.go
Additional comments not posted (1)
protocol/x/accountplus/keeper/timestampnonce_test.go (1)

Line range hint 1-7:
Imports look good.

The imported packages are necessary and correctly used in the test function.

@jerryfan01234 jerryfan01234 changed the title Timestamp nonce [OTE-553] Skip sequence increment for timestamp nonce Jul 23, 2024
Copy link

linear bot commented Jul 23, 2024

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 19da03c and 9e4e31b.

Files selected for processing (5)
  • protocol/app/ante.go (2 hunks)
  • protocol/app/ante/timestampnonce.go (1 hunks)
  • protocol/app/ante/timestampnonce_test.go (1 hunks)
  • protocol/x/accountplus/keeper/timestampnonce.go (1 hunks)
  • protocol/x/accountplus/keeper/timestampnonce_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (5)
  • protocol/app/ante.go
  • protocol/app/ante/timestampnonce.go
  • protocol/app/ante/timestampnonce_test.go
  • protocol/x/accountplus/keeper/timestampnonce.go
  • protocol/x/accountplus/keeper/timestampnonce_test.go

ak: ak,
}
}

Copy link
Contributor

Choose a reason for hiding this comment

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

Add a comment saying this is forked from x/auth/ante/sigverify.go

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Will add in upcoming PR

@jerryfan01234 jerryfan01234 merged commit 0076245 into main Jul 23, 2024
18 checks passed
@jerryfan01234 jerryfan01234 deleted the timestamp-nonce branch July 23, 2024 18:03
return sdk.Context{}, err
}

for _, signature := range signatures {
Copy link
Contributor

@teddyding teddyding Jul 25, 2024

Choose a reason for hiding this comment

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

Note this technically changes the semantics of IncrementSequenceDecorator. It used to increment sequence for all sigTx.GetSigners() (everyone who's supposed to sign the transaction), now it's iterating over all the signatures (everyone who signed the transactions). These are not inherently the same set, so it's relying on upstream logic to call SigVerifyDecorator correctly (checking they are the same set).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Is there a need to revert to iterating on signers and check that the signer has a signature?

ak ante.AccountKeeper
}

func NewIncrementSequenceDecorator(ak ante.AccountKeeper) IncrementSequenceDecorator {
Copy link
Contributor

@teddyding teddyding Jul 25, 2024

Choose a reason for hiding this comment

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

What's the rationale behind forking this decorator here, vs updating it in the dydxprotocol/cosmo-sdk fork? So that we can call accountpluskeeper helper function?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I was under the impression that updating the fork required additional release complexity.

There is actually a ticket to deprecate IncrementSequenceDecorator altogether by adding the incrementation into sigverify. (https://linear.app/dydx/issue/OTE-624/combine-incrementsequencedecorator-into-sigverificationdecorator)

I think I will have time to address this ticket and the other comments before v6 release. Will publish new PR soon

}

for _, signature := range signatures {
if accountpluskeeper.IsTimestampNonce(signature.Sequence) {
Copy link
Contributor

@teddyding teddyding Jul 25, 2024

Choose a reason for hiding this comment

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

We have a very specific use case for timestamp nonce feature, and it seems to me the following will never happen:

  • timestamp nonce transaction that requires multiple signers
  • (vacuously true from above) timestamp nonce being used in combination with regular sequence

Given this and previous comment, the easiest/least disruptive change (and avoiding a fork) seems to be:

  • Implement a function IsTimestampNounceTx similar to this
  • Update this logic to
	if !isShortTerm && !useTimestampNonce {
		if ctx, err = h.incrementSequence.AnteHandle(ctx, tx, simulate, noOpAnteHandle); err != nil {
			return ctx, err
		}
	}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

Successfully merging this pull request may close these issues.

3 participants