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

test: ibc-rate-limit test updates #8759

Merged
merged 11 commits into from
Oct 10, 2024
Merged

test: ibc-rate-limit test updates #8759

merged 11 commits into from
Oct 10, 2024

Conversation

crnbarr93
Copy link
Contributor

What is the purpose of the change

These changes introduce some new tests and adjustments to previous tests related to the ibc-rate-limiting module and smart contract. The original bytecode for the rate limiter contract has been renamed to ibc_rate_limiter_v1.wasm and the newer version has been named ibc_rate_limiter.wasm.

Tests include the following:

  • Restricted channels for native send/receive
  • Restricted channels for non-native send/receive
  • Migration from v1 to the newer contract version with active state
  • Previous tests now include a restricted channel, but these should be unaffected as the correct channel is assigned

Testing and Verifying

This change added tests and can be verified as follows:

go test ./x/ibc-rate-limit/ibc_middleware_test.go

Documentation and Release Note

  • Does this pull request introduce a new feature or user-facing behavior changes?
  • Changelog entry added to Unreleased section of CHANGELOG.md?

Where is the change documented?

  • Specification (x/{module}/README.md)
  • Osmosis documentation site
  • Code comments?
  • N/A

@PaddyMc PaddyMc added the V:state/compatible/no_backport State machine compatible PR, depends on prior breaks label Oct 8, 2024
Copy link
Contributor

coderabbitai bot commented Oct 8, 2024

Walkthrough

The changes in this pull request introduce new methods and modifications to the osmosisibctesting and ibc_rate_limit packages. A new method, InstantiateRLContractRaw, is added for instantiating a rate limiting contract with a specified code ID, enhancing flexibility. Additionally, a MigrateContract method is introduced for contract migration. In the testing suite, several new methods are added for managing channel quotas and restrictions, along with updates to existing methods to incorporate these features. New tests validate the correct behavior of the rate limiting functionality.

Changes

File Path Change Summary
tests/osmosisibctesting/wasm.go - Added InstantiateRLContractRaw method for instantiating contracts with a specified code ID.
- Added MigrateContract method for migrating contracts to a new code ID.
- Updated InstantiateRLContract to use the new method.
x/ibc-rate-limit/ibc_middleware_test.go - Added methods for managing channel quotas: BuildRemovePath, BuildResetPathQuota, BuildSetDenomRestrictions, RemovePath, ResetPathQuota, SetDenomRestrictions.
- Modified fullSendTest and fullRecvTest methods for channel restrictions.
- Introduced migration test for the IBC rate limit contract.

Possibly related PRs

  • perf: Speedup one JSON unmarshal #8398: This PR modifies the ibc_module.go file, which is also referenced in the main PR, and involves changes to the validation logic that may relate to the contract instantiation and migration processes discussed in the main PR.
  • Remove IBC-rate limits descendant recheck calls #8420: This PR also involves changes to the ibc_module.go file, specifically in the OnAcknowledgementPacket function, which could be relevant to the contract migration and acknowledgment processes mentioned in the main PR.

Suggested labels

V:state/compatible/backport, A:backport/v25.x

Suggested reviewers

  • nicolaslara
  • PaddyMc

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
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 (18)
tests/osmosisibctesting/wasm.go (3)

26-28: Consider making the code ID configurable

The function now uses a hardcoded code ID of 1 when calling InstantiateRLContractRaw. While this simplifies the function, it might be less flexible for future changes or different environments.

Consider making the code ID configurable, either through a parameter or a constant:

-func (chain *TestChain) InstantiateRLContract(suite *suite.Suite, quotas string) sdk.AccAddress {
-	addr := chain.InstantiateRLContractRaw(1, suite, quotas)
+func (chain *TestChain) InstantiateRLContract(suite *suite.Suite, quotas string, codeId uint64) sdk.AccAddress {
+	addr := chain.InstantiateRLContractRaw(codeId, suite, quotas)
	return addr
}

This change would allow for more flexibility in testing different versions of the contract.


Line range hint 30-47: Approve new InstantiateRLContractRaw function with a minor suggestion

The new InstantiateRLContractRaw function is well-implemented, providing flexibility with the custom code ID and correctly using the governance module as both the creator and admin of the contract.

Consider adding a bit more context to the error returned from contractKeeper.Instantiate:

-	addr, _, err := contractKeeper.Instantiate(chain.GetContext(), codeId, creator, creator, initMsgBz, "rate limiting contract", nil)
-	suite.Require().NoError(err)
+	addr, _, err := contractKeeper.Instantiate(chain.GetContext(), codeId, creator, creator, initMsgBz, "rate limiting contract", nil)
+	suite.Require().NoError(err, "failed to instantiate rate limiting contract")

This will provide more context if the test fails due to this error.


94-98: Approve new MigrateContract function with a minor suggestion

The new MigrateContract function is well-implemented, providing the necessary functionality for contract migration as outlined in the PR objectives.

Consider wrapping the error returned from contractKeeper.Migrate with some context:

-	return contractKeeper.Migrate(chain.GetContext(), contract, sender, newCodeId, msg)
+	result, err := contractKeeper.Migrate(chain.GetContext(), contract, sender, newCodeId, msg)
+	if err != nil {
+		return nil, fmt.Errorf("failed to migrate contract: %w", err)
+	}
+	return result, nil

This will provide more context about the operation that failed if an error occurs during contract migration.

x/ibc-rate-limit/ibc_middleware_test.go (15)

342-345: Replace fmt.Printf and fmt.Println with proper logging or remove them

The use of fmt.Printf and fmt.Println for outputting messages can clutter test outputs. Consider using the test suite's logging functions, such as suite.T().Logf(), or remove these statements if they are unnecessary.


352-355: Replace fmt.Printf and fmt.Println with proper logging or remove them

The print statements here are used for debugging purposes. To keep the test outputs clean, consider using suite.T().Logf() for logging or remove these statements if they're no longer needed.


408-408: Remove unnecessary fmt.Println statement

The fmt.Println(denomTrace) appears to be a leftover from debugging. Removing this statement will help keep test outputs concise.


429-429: Replace fmt.Printf with proper logging or remove it

Using fmt.Printf for outputting test information can clutter the output. Consider using suite.T().Logf() or remove the print statement if it's not needed.


Line range hint 447-447: Remove unnecessary fmt.Println statement

The fmt.Println(denomTrace) seems to be for debugging purposes. It would be better to remove it to keep the test output clean.


Line range hint 485-485: Replace fmt.Printf with proper logging or remove it

Consider replacing fmt.Printf with suite.T().Logf() or removing the print statement to maintain clean test outputs.


504-504: Remove unnecessary fmt.Println statement

The fmt.Println("trying to send ", sendAmount) is likely used for debugging. Removing it will help keep the test outputs focused.


508-508: Replace fmt.Printf with proper logging or remove it

Using suite.T().Logf() instead of fmt.Printf will integrate better with the test framework's output.


519-519: Remove unnecessary fmt.Println statement

The fmt.Println("trying to send ", sendAmount) can be removed to keep the test output concise.


Line range hint 557-557: Remove unnecessary fmt.Println statement

Removing this debug statement will help keep test outputs clean.


Line range hint 592-592: Replace fmt.Printf with proper logging or remove it

Consider using suite.T().Logf() for consistency and better integration with the test suite.


635-635: Remove unnecessary fmt.Println statement

This print statement appears to be for debugging and can be removed.


Line range hint 652-652: Remove unnecessary fmt.Println statement

Cleaning up this debug statement will keep the test output focused.


810-810: Remove unnecessary fmt.Println statement

To maintain clean and professional test outputs, consider removing this print statement.


857-857: Remove unnecessary fmt.Println statement

Removing this will help keep the test outputs clean and avoid clutter.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0711797 and 90591e2.

⛔ Files ignored due to path filters (2)
  • x/ibc-rate-limit/bytecode/rate_limiter.wasm is excluded by !**/*.wasm, !**/*.wasm
  • x/ibc-rate-limit/bytecode/rate_limiter_v1.wasm is excluded by !**/*.wasm, !**/*.wasm
📒 Files selected for processing (2)
  • tests/osmosisibctesting/wasm.go (3 hunks)
  • x/ibc-rate-limit/ibc_middleware_test.go (8 hunks)
🧰 Additional context used
🔇 Additional comments (5)
tests/osmosisibctesting/wasm.go (1)

Line range hint 1-112: Summary of changes and alignment with PR objectives

The modifications to this file enhance the testing capabilities for rate limiting contracts and align well with the PR objectives. Key improvements include:

  1. More flexible contract instantiation with custom code IDs.
  2. Support for contract migration, which is crucial for testing the migration process mentioned in the PR objectives.
  3. Simplified InstantiateRLContract function, which now delegates to the more flexible InstantiateRLContractRaw.

These changes provide the necessary tools to implement the new tests described in the PR objectives, particularly for testing restricted channels and verifying the migration process from the older contract version to the new one.

x/ibc-rate-limit/ibc_middleware_test.go (4)

828-869: Ensure proper error handling in TestV1Migrate

The migration test seems comprehensive. However, after migration, it's crucial to verify that all functionalities, including new features, work as expected. Consider adding assertions to check the state of the contract and ensure that restrictions are enforced correctly post-migration.


493-511: Confirm that restrictions are correctly enforced in TestSendTransferWithRestrictedChannelNative

The test verifies that sending funds via a restricted channel fails, which is correct. Ensure that the RemovePath and SetDenomRestrictions methods are functioning as intended and that any changes to channel IDs or denominations are accurately reflected in the test.


515-535: Confirm correctness of non-native token restrictions in TestSendTransferWithRestrictedChannelNonNative

The test checks restrictions on non-native tokens. Verify that denomination traces and channel restrictions are correctly handled, and that the test accurately reflects the intended behavior.


403-410: Check for potential issues with denomination handling

In the conditional block, ensure that the denomination parsing and assignment to denom and restrictedDenom are correct. Pay special attention to the use of GetFullDenomPath and IBCDenom to avoid any inconsistencies.

x/ibc-rate-limit/ibc_middleware_test.go Show resolved Hide resolved
x/ibc-rate-limit/ibc_middleware_test.go Show resolved Hide resolved
x/ibc-rate-limit/ibc_middleware_test.go Show resolved Hide resolved
x/ibc-rate-limit/ibc_middleware_test.go Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (7)
x/ibc-rate-limit/ibc_middleware_test.go (7)

331-337: Add error handling for ExecuteContract call

The ExecuteContract call may fail, but the error is currently being ignored. It's important to handle potential errors to ensure the test behaves correctly in failure scenarios. Consider adding error handling like this:

_, err := suite.chainA.ExecuteContract(addr, osmosisApp.AccountKeeper.GetModuleAddress(govtypes.ModuleName), []byte(resetQuota), sdk.Coins{})
suite.Require().NoError(err, "Failed to execute RemovePath contract call")

This will cause the test to fail if the contract execution fails, making it easier to identify and debug issues.


339-347: Remove debug print statements

The method contains debug print statements that should be removed before merging to production. While helpful during development, these statements can clutter logs in a production environment. Consider removing or commenting out these lines:

fmt.Printf("resetting path quota for denom=%s channel=%s quota_id=%s", denom, channel, quota_id)
fmt.Println(resetQuota)

If you want to keep some form of logging for debugging purposes, consider using a proper logging framework that can be easily enabled/disabled based on the environment.


Line range hint 403-432: LGTM: Denomination restrictions correctly implemented

The changes to fullSendTest look good. The method now properly handles setting denomination restrictions for both native and non-native tokens. This enhances the test coverage by ensuring that the rate limiting works correctly with the new restriction feature.

One minor suggestion for improved readability:

restrictedDenom := denom
if !native {
    denomTrace := transfertypes.ParseDenomTrace(transfertypes.GetPrefixedDenom("transfer", "channel-0", denom))
    restrictedDenom = denomTrace.GetFullDenomPath()
    denom = denomTrace.IBCDenom()
}

This slight reorganization makes it clearer that restrictedDenom is always set, regardless of whether the token is native or not.


493-512: LGTM: Comprehensive test for restricted channel with native tokens

This test case effectively verifies that the rate limiting middleware correctly prevents sending native tokens through a restricted channel. It covers the essential steps:

  1. Setting up the rate limiting
  2. Removing the path quota
  3. Setting channel restrictions
  4. Attempting to send on the restricted channel

The test correctly expects an error when trying to send on the restricted channel, which is the desired behavior.

One minor suggestion to improve the test's robustness:

_, err = suite.AssertSend(false, suite.MessageFromAToB(sdk.DefaultBondDenom, osmomath.NewInt(1)))
suite.Require().Error(err)
suite.Require().Contains(err.Error(), "channel is not allowed for this denom", "Error should specifically mention channel restriction")

This additional assertion ensures that the error is specifically related to the channel restriction, rather than any other type of error that might occur during the send operation.


514-536: LGTM: Comprehensive test for restricted channel with non-native tokens

This test case effectively verifies that the rate limiting middleware correctly prevents sending non-native (IBC) tokens through a restricted channel. It covers the essential steps:

  1. Setting up the rate limiting
  2. Removing the path quota
  3. Setting channel restrictions for the full IBC denomination path
  4. Attempting to send on the restricted channel

The test correctly expects an error when trying to send on the restricted channel, which is the desired behavior.

Similar to the native token test, consider adding a more specific error check:

_, err = suite.AssertSend(false, suite.MessageFromAToB(denom, osmomath.NewInt(1)))
suite.Require().Error(err)
suite.Require().Contains(err.Error(), "channel is not allowed for this denom", "Error should specifically mention channel restriction")

This additional assertion ensures that the error is specifically related to the channel restriction for the IBC token.


Line range hint 740-802: LGTM: Comprehensive test for denomination restriction flow

This test case effectively verifies the entire flow of denomination restrictions in the rate limiting middleware. It covers all crucial scenarios:

  1. Sending without restrictions
  2. Adding restrictions
  3. Sending on allowed and disallowed channels
  4. Removing restrictions
  5. Verifying unrestricted sending after removal

The test is well-structured and provides good coverage of the denomination restriction functionality.

To improve clarity and maintainability, consider breaking down the test into sub-tests using t.Run(). This can make it easier to identify which part of the flow failed if an error occurs. For example:

func (suite *MiddlewareTestSuite) TestDenomRestrictionFlow() {
    // Setup code...

    suite.Run("Send without restrictions", func() {
        _, err := suite.AssertSend(true, suite.MessageFromAToB(denom, sendAmount))
        suite.Require().NoError(err, "Send should succeed without restrictions")
    })

    suite.Run("Add restrictions", func() {
        // Add restriction code...
    })

    suite.Run("Send with restrictions", func() {
        // Test allowed and disallowed sends...
    })

    suite.Run("Remove restrictions", func() {
        // Remove restrictions and verify unrestricted sending...
    })
}

This structure can make the test more readable and easier to maintain.


828-871: LGTM: Comprehensive test for contract migration from v1 to v2

This test case effectively verifies the migration process of the ibc-rate-limit contract from v1 to v2. It covers all crucial steps:

  1. Setting up and testing the v1 contract
  2. Migrating to v2
  3. Testing v2 functionality, including new features like denomination restrictions

The test is well-structured and provides good coverage of the migration process and post-migration functionality.

To improve clarity and make the test's steps more explicit, consider adding comments or log statements at key points in the test. For example:

// Test v1 functionality
suite.testChannelQuota(sendAmount, 2)

fmt.Println("Migrating contract from v1 to v2...")
// Migrate to new contract
_, err := suite.chainA.MigrateContract(addr, osmosisApp.AccountKeeper.GetModuleAddress(govtypes.ModuleName), newCodeId, []byte("{}"))
suite.Require().NoError(err)

fmt.Println("Testing v2 functionality...")
// Set the restrictions (new v2 feature)
suite.SetDenomRestrictions(addr, denom, channel)

// Test v2 functionality
suite.testChannelQuota(sendAmount, 1)

These additions can make it easier to follow the flow of the test and understand what's being tested at each stage.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 90591e2 and f227789.

📒 Files selected for processing (1)
  • x/ibc-rate-limit/ibc_middleware_test.go (8 hunks)
🧰 Additional context used
🔇 Additional comments (4)
x/ibc-rate-limit/ibc_middleware_test.go (4)

Line range hint 546-575: LGTM: Denomination restrictions correctly implemented for receive test

The changes to fullRecvTest look good. The method now properly handles setting denomination restrictions for both native and non-native tokens in the context of receiving transfers. This enhances the test coverage by ensuring that the rate limiting works correctly with the new restriction feature for incoming transfers.

The implementation correctly differentiates between native and non-native tokens, setting the appropriate restricted denomination in each case. This is crucial for testing the behavior of the rate limiting middleware in various scenarios.


606-622: LGTM: Correct verification of receive behavior with restricted channels for native tokens

This test case effectively verifies that the rate limiting middleware does not prevent receiving native tokens through a channel that is restricted for sending. This is an important distinction in the middleware's behavior. The test covers the key points:

  1. Setting up the rate limiting
  2. Removing the path quota
  3. Setting channel restrictions to only allow channel-1
  4. Attempting to receive on channel-0 (which is restricted for sending)

The test correctly expects no error when receiving on the restricted channel, which confirms that the restriction only applies to outgoing transfers. This is crucial for maintaining the correct behavior of the IBC protocol while implementing send restrictions.


624-639: LGTM: Correct verification of receive behavior with restricted channels for non-native tokens

This test case effectively verifies that the rate limiting middleware does not prevent receiving non-native (IBC) tokens through a channel that is restricted for sending. This complements the native token test and ensures comprehensive coverage. The test covers the key points:

  1. Setting up the rate limiting
  2. Removing the path quota
  3. Setting channel restrictions to only allow channel-1 for the local denomination
  4. Attempting to receive on channel-0 (which is restricted for sending)

The test correctly expects no error when receiving on the restricted channel, confirming that the restriction only applies to outgoing transfers, even for IBC tokens. This is crucial for maintaining the correct behavior of the IBC protocol while implementing send restrictions for various token types.


Line range hint 1-871: Overall assessment: Comprehensive and well-structured test suite

The changes to this file significantly enhance the test coverage for the IBC rate limiting middleware. Key improvements include:

  1. New methods for managing channel quotas and denomination restrictions.
  2. Updated existing tests to incorporate new functionality.
  3. New test cases covering restricted channels for both native and non-native tokens.
  4. A comprehensive test for the denomination restriction flow.
  5. A migration test from v1 to v2 of the rate limiting contract.

These additions ensure that the middleware's core functionalities, including the new features, are thoroughly tested. The test cases are well-structured and cover a wide range of scenarios, which is crucial for maintaining the reliability of the IBC rate limiting system.

Minor suggestions for improvement mainly focus on:

  • Using a JSON library for message construction instead of string formatting.
  • Adding more specific error checks in some test cases.
  • Improving clarity in some tests by adding comments or using sub-tests.
  • Removing debug print statements from production code.

Overall, these changes represent a significant improvement in the test coverage and quality of the IBC rate limiting middleware.

x/ibc-rate-limit/ibc_middleware_test.go Show resolved Hide resolved
Copy link
Contributor

@iboss-ptk iboss-ptk left a comment

Choose a reason for hiding this comment

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

LGTM 🚀

@crnbarr93 crnbarr93 merged commit 6c843fa into main Oct 10, 2024
1 check passed
@crnbarr93 crnbarr93 deleted the connor/ibc-rate-limit-tests branch October 10, 2024 16:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A:no-changelog V:state/compatible/no_backport State machine compatible PR, depends on prior breaks
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants