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

[CT-1262] add e2e tests for permissioned keys success cases #2479

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

Conversation

jayy04
Copy link
Contributor

@jayy04 jayy04 commented Oct 8, 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

Release Notes

  • New Features

    • Introduced a new decorator for managing public key events within transactions.
    • Added a gas consumption step during signature verification to optimize transaction processing.
    • New test cases for successful order placements using permissioned keys.
  • Bug Fixes

    • Improved transaction processing logic by restructuring ante decorators for clarity and maintainability.
    • Enhanced isolation in tests for affiliate registration to ensure accurate results.
  • Tests

    • Enhanced test coverage for circuit breaker and permissioned key functionalities.
    • Added a new test for successful order placements using permissioned keys.

@jayy04 jayy04 requested a review from a team as a code owner October 8, 2024 14:24
Copy link

linear bot commented Oct 8, 2024

Copy link
Contributor

coderabbitai bot commented Oct 8, 2024

Walkthrough

This pull request introduces significant changes to the transaction processing logic within the application. Key modifications include restructuring the NewAnteHandler function and the lockingAnteHandler to utilize sdk.ChainAnteDecorators, enhancing the organization of ante decorators. A new EmitPubKeyEventsDecorator is added to manage public key events, and the CircuitBreakerDecorator is modified to streamline its handler types. Additionally, new tests validate the functionality of permissioned keys in the order placement process and ensure proper isolation in affiliate registration tests.

Changes

File Path Change Summary
protocol/app/ante.go Restructured NewAnteHandler and lockingAnteHandler to use sdk.ChainAnteDecorators, removing direct calls to setPubKey and sigGasConsume. Updated method signatures and internal logic.
protocol/app/ante/pubkey.go Introduced EmitPubKeyEventsDecorator for managing public key events, including the AnteHandle method and a helper function for signature data conversion.
protocol/x/accountplus/ante/circuit_breaker.go Updated CircuitBreakerDecorator fields from sdk.AnteDecorator to sdk.AnteHandler. Modified constructor and method signatures to align with new handler types.
protocol/x/accountplus/authenticator/signature_authenticator.go Added gas consumption logic to the Authenticate method and updated Initialize to handle invalid public key configurations.
protocol/x/clob/e2e/permissioned_keys_test.go Added TestPlaceOrder_PermissionedKeys_Success to validate successful order placements using permissioned keys, covering various scenarios such as order placement and removal upon key removal.
protocol/x/affiliates/e2e/register_affiliate_test.go Relocated initialization of the test application and context within the test case loop for better isolation between tests.

Possibly related PRs

Suggested labels

feature:timestamp_nonce

Suggested reviewers

  • teddyding

Poem

In the fields where rabbits play,
New handlers hop in bright array.
With keys and orders, all in line,
Our code now dances, oh so fine!
So let us cheer, with joyful thump,
For changes made, we proudly jump! 🐇✨


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.

Base automatically changed from jy/ct-1262 to main October 8, 2024 14:25
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: 4

🧹 Outside diff range and nitpick comments (2)
protocol/x/clob/e2e/permissioned_keys_test.go (2)

666-666: Add a Comment for the New Test Function

Consider adding a comment above the new test function TestPlaceOrder_PermissionedKeys_Success to describe its purpose. This enhances code readability and helps future maintainers understand the test scenarios covered.

Apply this diff to add the comment:

+// TestPlaceOrder_PermissionedKeys_Success tests successful order placements using permissioned keys.
 func TestPlaceOrder_PermissionedKeys_Success(t *testing.T) {

1379-1382: Avoid Using panic in Test Code

Using panic(err) in test code can halt the entire test suite on failure. Instead, use require.NoError(t, err) to fail the specific test case gracefully without affecting others.

Apply this diff to replace panic with require.NoError:

 bytes, err := tApp.App.TxConfig().TxEncoder()(tx)
-if err != nil {
-    panic(err)
-}
+require.NoError(t, err, "Failed to encode transaction")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 34c1ea2 and 04816be.

📒 Files selected for processing (6)
  • protocol/app/ante.go (1 hunks)
  • protocol/app/app.go (1 hunks)
  • protocol/testutil/constants/stateful_orders.go (1 hunks)
  • protocol/x/accountplus/ante/circuit_breaker.go (2 hunks)
  • protocol/x/accountplus/ante/circuit_breaker_test.go (1 hunks)
  • protocol/x/clob/e2e/permissioned_keys_test.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (13)
protocol/x/accountplus/ante/circuit_breaker.go (3)

21-22: LGTM! Verify function calls in codebase.

The parameter type changes from sdk.AnteDecorator to sdk.AnteHandler in the NewCircuitBreakerDecorator function are consistent with the struct field modifications. This ensures type consistency when creating new instances of CircuitBreakerDecorator.

To ensure this change doesn't introduce any issues, please run the following script to check for any calls to NewCircuitBreakerDecorator in the codebase:

#!/bin/bash
# Description: Check for calls to NewCircuitBreakerDecorator

# Test: Search for NewCircuitBreakerDecorator function calls
rg --type go 'NewCircuitBreakerDecorator\('

47-47: LGTM! Verify correct behavior of AnteHandle method.

The changes to the AnteHandle method are consistent with the type changes from sdk.AnteDecorator to sdk.AnteHandler. The removal of the next parameter and the inclusion of the simulate parameter in both method calls align with the new handler type's expected signature.

To ensure this change doesn't introduce any unexpected behavior, please run the following script to check for any tests related to the AnteHandle method:

#!/bin/bash
# Description: Check for tests related to AnteHandle method

# Test: Search for test functions that might be testing AnteHandle
rg --type go 'func.*Test.*AnteHandle'

Additionally, please ensure that the simulate parameter is being used correctly in both the authenticator and original ante handler flows.

Also applies to: 51-51


14-15: Overall changes look good. Ensure comprehensive update across codebase.

The modifications to CircuitBreakerDecorator and its associated methods consistently update the ante handler types from sdk.AnteDecorator to sdk.AnteHandler. This change simplifies the interface and aligns with the SDK's AnteHandler type, which is a positive improvement.

To ensure a smooth transition:

  1. Update all relevant parts of the application that interact with CircuitBreakerDecorator.
  2. Modify any existing tests to reflect these changes.
  3. Update documentation to reflect the new method signatures and usage patterns.
  4. Consider running integration tests to verify that the changes don't introduce any unexpected behavior in the transaction processing flow.

Run the following script to identify potential areas that might need updates:

#!/bin/bash
# Description: Identify potential areas needing updates due to AnteDecorator changes

# Test 1: Search for AnteDecorator usages
echo "Searching for AnteDecorator usages:"
rg --type go 'AnteDecorator'

# Test 2: Search for CircuitBreakerDecorator usages
echo "Searching for CircuitBreakerDecorator usages:"
rg --type go 'CircuitBreakerDecorator'

# Test 3: Search for NewCircuitBreakerDecorator usages
echo "Searching for NewCircuitBreakerDecorator usages:"
rg --type go 'NewCircuitBreakerDecorator'

# Test 4: Search for AnteHandle method usages
echo "Searching for AnteHandle method usages:"
rg --type go '\.AnteHandle\('

Review the output of this script to identify any areas of the codebase that might need updates to align with the new changes.

Also applies to: 21-22, 47-47, 51-51

protocol/x/accountplus/ante/circuit_breaker_test.go (3)

Line range hint 86-94: LGTM: New AnteHandle method enhances test capabilities

The addition of the AnteHandle method to MockAnteDecorator is a positive change. It allows for more nuanced testing of the CircuitBreaker's behavior by simulating different decorator responses based on the Called field.

This enhancement will provide more comprehensive test coverage for the CircuitBreaker functionality.


Line range hint 1-194: Overall assessment: Improved test structure with potential for wider impact

The changes to this test file, particularly in the TestCircuitBreakerAnte function and the addition of the AnteHandle method to MockAnteDecorator, represent an improvement in the test structure and capabilities. The use of sdk.ChainAnteDecorators aligns the test more closely with SDK patterns, while the new mock method allows for more nuanced testing.

However, these changes, especially the modification to the decorator chaining, could potentially impact the behavior of the CircuitBreaker or how it's tested. To ensure the integrity of the tests:

  1. Verify that all test cases still pass and behave as expected.
  2. Consider adding additional test cases that specifically target the new chaining behavior.
  3. Review any other tests or code that may rely on the previous CircuitBreaker instantiation method to ensure consistency across the codebase.

To assist in this verification, please run the following script:

#!/bin/bash
# Description: Run the CircuitBreaker tests and check for any failures or unexpected behaviors

# Test: Run the CircuitBreaker tests
go test -v ./protocol/x/accountplus/ante -run TestCircuitBreakerAnte

# Additional check: Look for any other files that might be affected by the changes
rg --type go "CircuitBreakerDecorator" ./protocol

Review the test results and any files highlighted by the script to ensure full compatibility with the changes.


154-155: Verify the impact of chaining ante decorators

The modification to wrap mockTestAuthenticator and mockTestClassic with sdk.ChainAnteDecorators changes how these decorators are chained together. While this change aligns with the SDK's decorator chaining pattern, it's important to ensure that this doesn't alter the expected behavior of the CircuitBreaker.

To confirm that this change doesn't introduce any unintended side effects, please run the following verification script:

If the script returns results, review those occurrences to ensure consistency across all tests.

✅ Verification successful

No other tests rely on the previous decorator chaining method

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the CircuitBreaker behavior remains consistent with the new decorator chaining.

# Test: Check if there are any other tests relying on the previous decorator chaining method
rg --type go "NewCircuitBreakerDecorator\s*\(" ./protocol/x/accountplus/ante

Length of output: 1181

protocol/testutil/constants/stateful_orders.go (1)

297-308: New long-term order added for Bob with ClobPairId 1

The new order LongTermOrder_Bob_Num0_Id0_Clob1_Buy25_Price30_GTBT10 has been added, which is similar to existing orders but uses ClobPairId 1 instead of 0. This addition expands the test coverage to include orders for different CLOB pairs.

A few observations:

  1. The order is consistent with the naming convention used for other long-term orders.
  2. It uses the same SubaccountId (Bob_Num0) and ClientId (0) as some existing Bob orders, which is fine for testing purposes.
  3. The order parameters (Side, Quantums, Subticks, GoodTilBlockTime) are within the range of values used in other test orders.

This addition will allow for more comprehensive testing of the system's behavior with multiple CLOB pairs.

To ensure consistency and completeness, let's verify if there are other orders for ClobPairId 1:

protocol/app/ante.go (2)

127-133: Good refactoring: Chaining NewAuthenticatorDecorator with sdk.ChainAnteDecorators

The introduction of sdk.ChainAnteDecorators to chain the NewAuthenticatorDecorator enhances code clarity and maintainability by simplifying the ante decorator chain.


135-141: Streamlined ante handlers using sdk.ChainAnteDecorators

Chaining SetPubKeyDecorator, SigGasConsumeDecorator, and SigVerificationDecorator with sdk.ChainAnteDecorators simplifies the ante handler logic and improves readability.

protocol/x/clob/e2e/permissioned_keys_test.go (3)

670-670: Verify Usage of Alice's Public Key in Authenticator Config

The SignatureVerification authenticator is configured with constants.AlicePrivateKey.PubKey().Bytes(). Verify that using Alice's public key here is intentional and aligns with the test scenarios. This ensures that only transactions signed by Alice's private key are accepted.


848-848: Confirm Account Number and Sequence Number for Alice

In this test case, the transaction is signed using Alice's private key, but AccountNum is set to []uint64{1} and SeqNum is []uint64{0}. Ensure that these values correspond to Alice's account. If Alice's account number is 0, the AccountNum should be updated to reflect this.

Apply this diff if an update is needed:

 Fees:       constants.TestFeeCoins_5Cents,
 Gas:        0,
-AccountNum: []uint64{1},
+AccountNum: []uint64{0},
 SeqNum:     []uint64{0},
 // Sign using Alice's private key.
 Signers: []cryptotypes.PrivKey{constants.AlicePrivateKey},

1395-1400: Check for Empty Expected Log Messages

In the assertion for the response log, require.Contains is used with msg.ExpectedLog, which might be empty in some test cases. Consider adding a check to ensure that ExpectedLog is not empty before using it in the assertion to avoid misleading test results.

Apply this diff to add the check:

+if msg.ExpectedLog != "" {
     require.Contains(
         t,
         resp.Log,
         msg.ExpectedLog,
         "Response log was not as expected",
     )
+}
protocol/app/app.go (1)

1115-1136: LGTM: Initialization of AuthenticatorManager and AccountPlusKeeper

The initialization of the AuthenticatorManager and the AccountPlusKeeper is correctly implemented. The code is clear and aligns with best practices.

Comment on lines 14 to 15
authenticatorAnteHandlerFlow sdk.AnteHandler
originalAnteHandlerFlow sdk.AnteHandler
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Action Required: Address Remaining sdk.AnteDecorator Usages

The recent changes in circuit_breaker.go simplify the interface by transitioning from sdk.AnteDecorator to sdk.AnteHandler. However, the following files still utilize sdk.AnteDecorator:

  • protocol/x/clob/ante/rate_limit.go
  • protocol/x/clob/ante/clob.go
  • protocol/x/accountplus/ante/circuit_breaker_test.go
  • protocol/mocks/AnteDecorator.go
  • protocol/app/ante.go
  • Multiple test files within protocol/app/ante/

To ensure full consistency and prevent potential integration issues, please update these usages to sdk.AnteHandler where appropriate.

🔗 Analysis chain

LGTM! Verify impact on codebase.

The change from sdk.AnteDecorator to sdk.AnteHandler for both authenticatorAnteHandlerFlow and originalAnteHandlerFlow fields simplifies the interface and aligns with the modifications in the rest of the file. This is a good improvement in terms of code clarity and consistency.

To ensure this change doesn't introduce any issues, please run the following script to check for any remaining usages of sdk.AnteDecorator in the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for remaining usages of sdk.AnteDecorator

# Test: Search for sdk.AnteDecorator usages
rg --type go 'sdk\.AnteDecorator'

Length of output: 10145

Comment on lines +1414 to +1416
_, fillAmount, _ := tApp.App.ClobKeeper.GetOrderFillAmount(ctx, orderId)
require.Equal(t, expectedFillAmount, fillAmount.ToUint64())
}
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

Handle Possible Errors from GetOrderFillAmount

The error returned by GetOrderFillAmount is currently ignored. To ensure test accuracy and prevent false positives, it's important to check and handle this error.

Apply this diff to handle the error:

 for orderId, expectedFillAmount := range tc.expectedOrderFillAmounts {
-    _, fillAmount, _ := tApp.App.ClobKeeper.GetOrderFillAmount(ctx, orderId)
+    _, fillAmount, err := tApp.App.ClobKeeper.GetOrderFillAmount(ctx, orderId)
+    require.NoError(t, err, "Failed to get fill amount for order %v", orderId)
     require.Equal(t, expectedFillAmount, fillAmount.ToUint64())
 }
📝 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
_, fillAmount, _ := tApp.App.ClobKeeper.GetOrderFillAmount(ctx, orderId)
require.Equal(t, expectedFillAmount, fillAmount.ToUint64())
}
_, fillAmount, err := tApp.App.ClobKeeper.GetOrderFillAmount(ctx, orderId)
require.NoError(t, err, "Failed to get fill amount for order %v", orderId)
require.Equal(t, expectedFillAmount, fillAmount.ToUint64())
}

Comment on lines +668 to +684
{
Type: "SignatureVerification",
Config: constants.AlicePrivateKey.PubKey().Bytes(),
},
{
Type: "MessageFilter",
Config: []byte("/dydxprotocol.clob.MsgPlaceOrder"),
},
{
Type: "ClobPairIdFilter",
Config: []byte("0,1"),
},
{
Type: "SubaccountFilter",
Config: []byte("0,1"),
},
}
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

Refactor Authenticator Configuration into a Helper Function

The authenticator configuration setup is repeated across multiple test cases. Consider refactoring this code into a helper function to adhere to the DRY (Don't Repeat Yourself) principle and enhance maintainability.

Apply this diff to create a helper function:

+func createCompositeAuthenticatorConfig() []byte {
+    config := []aptypes.SubAuthenticatorInitData{
+        {
+            Type:   "SignatureVerification",
+            Config: constants.AlicePrivateKey.PubKey().Bytes(),
+        },
+        {
+            Type:   "MessageFilter",
+            Config: []byte("/dydxprotocol.clob.MsgPlaceOrder"),
+        },
+        {
+            Type:   "ClobPairIdFilter",
+            Config: []byte("0,1"),
+        },
+        {
+            Type:   "SubaccountFilter",
+            Config: []byte("0,1"),
+        },
+    }
+    compositeAuthenticatorConfig, err := json.Marshal(config)
+    if err != nil {
+        panic(err)
+    }
+    return compositeAuthenticatorConfig
+}
+
 func TestPlaceOrder_PermissionedKeys_Success(t *testing.T) {
-    config := []aptypes.SubAuthenticatorInitData{
-        {
-            Type:   "SignatureVerification",
-            Config: constants.AlicePrivateKey.PubKey().Bytes(),
-        },
-        {
-            Type:   "MessageFilter",
-            Config: []byte("/dydxprotocol.clob.MsgPlaceOrder"),
-        },
-        {
-            Type:   "ClobPairIdFilter",
-            Config: []byte("0,1"),
-        },
-        {
-            Type:   "SubaccountFilter",
-            Config: []byte("0,1"),
-        },
-    }
-    compositeAuthenticatorConfig, err := json.Marshal(config)
-    require.NoError(t, err)
+    compositeAuthenticatorConfig := createCompositeAuthenticatorConfig()

Committable suggestion was skipped due to low confidence.

},
{
Type: "MessageFilter",
Config: []byte("/dydxprotocol.clob.MsgPlaceOrder"),
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

Ensure Correct Message Type in MessageFilter

The MessageFilter authenticator uses the message type /dydxprotocol.clob.MsgPlaceOrder. Verify that this string correctly matches the fully-qualified type name of the MsgPlaceOrder message. If the actual message type includes a version suffix (e.g., /dydxprotocol.clob.v1.MsgPlaceOrder), update the filter accordingly to prevent mismatches.

Apply this diff if an update is needed:

 {
     Type:   "MessageFilter",
-    Config: []byte("/dydxprotocol.clob.MsgPlaceOrder"),
+    Config: []byte("/dydxprotocol.clob.v1.MsgPlaceOrder"),
 },

Committable suggestion was skipped due to low confidence.

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

🧹 Outside diff range and nitpick comments (1)
protocol/x/affiliates/e2e/register_affiliate_test.go (1)

45-47: Improved test isolation by moving app initialization inside the test loop.

This change enhances the isolation between test cases by initializing a new test application (tApp) and context (ctx) for each iteration. This approach prevents potential state leakage between test cases, aligning with best practices for test design.

Consider the following points:

  1. Improved reliability: Each test case now runs in a completely fresh environment, reducing the risk of inter-test dependencies.
  2. Slight performance impact: Initializing the app for each test case might increase the overall test execution time. However, the benefits of improved isolation often outweigh this minor performance cost.
  3. Consistency: Ensure this pattern is applied consistently across similar test files for uniformity in the testing approach.

To further improve the test suite:

  1. Consider extracting the app initialization into a helper function to reduce code duplication if this pattern is used across multiple test files.
  2. If performance becomes a concern, you might want to implement parallel test execution using t.Parallel(), which could offset the increased initialization time.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 04816be and a0af7ea.

📒 Files selected for processing (1)
  • protocol/x/affiliates/e2e/register_affiliate_test.go (1 hunks)
🧰 Additional context used

options.SignModeHandler,
sdk.ChainAnteDecorators(
ante.NewSetPubKeyDecorator(options.AccountKeeper),
ante.NewSigGasConsumeDecorator(options.AccountKeeper, options.SigGasConsumer),
Copy link
Contributor

Choose a reason for hiding this comment

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

Could you remind how how gas consumption is done for accountplus flow? A quick search of StaticGas on authenticators suggests they are all 0?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added some gas here. we only support secp256k1 so it's a static value.

customante.NewSigVerificationDecorator(
options.AccountKeeper,
options.SignModeHandler,
sdk.ChainAnteDecorators(
Copy link
Contributor

Choose a reason for hiding this comment

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

For my understanding why was it necessary to move SetPubKey and SigGas under this chain and thus not applicable to smart account flow?

Copy link
Contributor Author

@jayy04 jayy04 Oct 16, 2024

Choose a reason for hiding this comment

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

SetPubKey expects the signer of the message to match the public key (link), and I was getting some errors here.

After moving SetPubKey, I was getting some public key = nil errors in SigGas here because public key is not set. So moved this as well.

This is also how osmosis does it (link)

constants.Order_Alice_Num0_Id1_Clob1_Sell5_Price15_GTB20_IOC.OrderId: 0,
},
},
"Stateful maker order can be matched even if permissioned key is removed": {
Copy link
Contributor

Choose a reason for hiding this comment

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

Could we provide some context on these behaviors when the order is removed? My understanding (please CWIW):

  • For ST orders, we HAVE to remove the maker order because we can't trust BP on this maker order being valid
  • For stateful orders, we don't HAVE TO remove the maker order because we can trust the onchain state. We MAY choose to remove the maker stateful order, but needs additional work (e.g. prune orders when removing authenticators)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yeah that's correct. for ST orders, it's not necessarily about trust, it's more about maintaining the invariant that operations queue is always valid.

Comment on lines +59 to +61
// First consume gas for verifying the signature
params := sva.ak.GetParams(ctx)
ctx.GasMeter().ConsumeGas(params.SigVerifyCostSecp256k1, "secp256k1 signature verification")
Copy link
Contributor Author

Choose a reason for hiding this comment

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

added gas here @teddyding .

we currently only support secp256k1 signature verification so charging some static gas here.

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

🧹 Outside diff range and nitpick comments (5)
protocol/x/accountplus/ante/circuit_breaker.go (2)

21-22: LGTM! Consider a minor naming improvement.

The changes to the NewCircuitBreakerDecorator function are well-implemented and consistent with the updates to the CircuitBreakerDecorator struct. The parameter types have been correctly updated to sdk.AnteHandler, and the struct initialization reflects the new field names and types.

Consider shortening the parameter name authenticatorAnteHandlerFlow to authenticatorFlow for better readability, as the AnteHandler part is already implied by the type:

func NewCircuitBreakerDecorator(
    cdc codec.BinaryCodec,
    authenticatorFlow sdk.AnteHandler,
    defaultAnteHandlerFlow sdk.AnteHandler,
) CircuitBreakerDecorator {
    // ...
}

Also applies to: 26-27


Line range hint 39-43: LGTM! Update method comment.

The removal of the next sdk.AnteHandler parameter from the AnteHandle method signature is correct and consistent with the changes to use sdk.AnteHandler instead of sdk.AnteDecorator.

Please update the method comment to reflect the removal of the next parameter:

// AnteHandle checks if a tx is a smart account tx and routes it through the correct series of ante handlers.
//
// Note that whether or not to use the new authenticator flow is determined by the presence of the `TxExtension`.
// This is different from the Osmosis's implementation, which falls back to the original flow if
// smart account is disabled.
// The reason for this is because only minimal validation is done on resting maker orders when they get matched
// and this approach mitigates an issue for maker orders when smart account gets disabled through governance.
func (ad CircuitBreakerDecorator) AnteHandle(
    ctx sdk.Context,
    tx sdk.Tx,
    simulate bool,
) (newCtx sdk.Context, err error) {
    // ...
}
protocol/x/accountplus/authenticator/signature_authenticator.go (2)

Line range hint 36-41: Prevent invalid public key assignment in Initialize method

In the Initialize method, the current logic assigns sva.PubKey regardless of the validity of config. If config length does not match secp256k1.PubKeySize, sva.PubKey is set to nil but then immediately overwritten with an invalid key. This can lead to unexpected behavior when the public key is used elsewhere.

Apply this diff to ensure that sva.PubKey is only set when config is valid:

 func (sva SignatureVerification) Initialize(config []byte) (types.Authenticator, error) {
     if len(config) != secp256k1.PubKeySize {
         sva.PubKey = nil
+        return sva, nil
     }
     sva.PubKey = &secp256k1.PubKey{Key: config}
     return sva, nil
 }

Line range hint 68-69: Correct typo in error message

The error message "pubkey on not set on account or authenticator" contains a typo. It should read "pubkey not set on account or authenticator" for clarity.

Apply this diff to fix the typo:

 if sva.PubKey == nil {
-    return errorsmod.Wrap(sdkerrors.ErrInvalidPubKey, "pubkey on not set on account or authenticator")
+    return errorsmod.Wrap(sdkerrors.ErrInvalidPubKey, "pubkey not set on account or authenticator")
 }
protocol/app/ante/pubkey.go (1)

88-89: Remove unnecessary re-declaration of err.

At line 88, var err error is declared within the function scope where err has already been defined. This re-declaration is unnecessary and could cause confusion.

Apply this diff to remove the redundant declaration:

 sigs := [][]byte{}
-var err error
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a0af7ea and 0b92cbb.

📒 Files selected for processing (4)
  • protocol/app/ante.go (1 hunks)
  • protocol/app/ante/pubkey.go (1 hunks)
  • protocol/x/accountplus/ante/circuit_breaker.go (2 hunks)
  • protocol/x/accountplus/authenticator/signature_authenticator.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • protocol/app/ante.go
🧰 Additional context used
🔇 Additional comments (2)
protocol/x/accountplus/ante/circuit_breaker.go (1)

14-15: LGTM! Consistent with previous recommendations.

The changes to the CircuitBreakerDecorator struct are well-implemented. Updating the types from sdk.AnteDecorator to sdk.AnteHandler and renaming originalAnteHandlerFlow to defaultAnteHandlerFlow improves consistency and clarity. These modifications align with the previous review comments suggesting to address remaining sdk.AnteDecorator usages.

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

98-105: Verify the correctness of cryptotypes.MultiSignature usage and Marshal method.

The cryptotypes.MultiSignature struct is used to aggregate signatures, and its Marshal method is called to obtain the aggregated signature. Ensure that MultiSignature and its Marshal method are correctly implemented and compatible with the intended cryptographic operations.

Run the following script to check the existence and usage of MultiSignature and its Marshal method:

protocol/app/ante/pubkey.go Show resolved Hide resolved
protocol/app/ante/pubkey.go Outdated Show resolved Hide resolved
protocol/app/ante/pubkey.go Outdated Show resolved Hide resolved
@@ -0,0 +1,110 @@
package ante
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@teddyding I added a new decorator that looks identical to SetPubKey but only emits events

reference from Osmosis (link)

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

🧹 Outside diff range and nitpick comments (1)
protocol/app/ante/pubkey.go (1)

16-18: Adjust the comment to match the type definition

The comment above EmitPubKeyEventsDecorator refers to NewEmitPubKeyEventsDecorator but is placed above the type definition. To enhance clarity, please adjust the comment to accurately describe the EmitPubKeyEventsDecorator type.

Apply this diff to correct the comment:

-// NewEmitPubKeyEventsDecorator emits events for each signer's public key.
+// EmitPubKeyEventsDecorator emits events for each signer's public key.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0b92cbb and 906a4ea.

📒 Files selected for processing (1)
  • protocol/app/ante/pubkey.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
protocol/app/ante/pubkey.go (2)

24-71: Proper implementation of AnteHandle method

The AnteHandle method is well-structured and correctly processes the transaction to emit the necessary events. It appropriately handles errors and maintains the flow to the next ante handler.


77-110: Efficient handling of signature data

The signatureDataToBz function effectively converts both single and multi-signature data into raw byte slices. The recursive approach ensures all nested signatures are correctly processed.

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

Successfully merging this pull request may close these issues.

2 participants