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: abort cctx on dust amount in revert outbound (Bitcoin and Solana) #3149

Merged
merged 6 commits into from
Nov 14, 2024

Conversation

ws4charlie
Copy link
Contributor

@ws4charlie ws4charlie commented Nov 12, 2024

Description

  • call validateZRC20Withdrawal to abort the CCTX if dust amount is detected in revert outbound.
  • update existing E2E test TestBitcoinDepositAndCallRevertWithDust and add Solana E2E test TestSolanaDepositAndCallRevertWithDust

Closes: #3135

How Has This Been Tested?

  • Tested CCTX in localnet
  • Tested in development environment
  • Go unit tests
  • Go integration tests
  • Tested via GitHub Actions

Summary by CodeRabbit

  • New Features

    • Added ability to whitelist SPL tokens on Solana.
    • Introduced new tests for handling deposits that revert due to dust amounts.
    • Implemented a function to wait for aborted cross-chain transactions.
  • Bug Fixes

    • Improved error handling for outbound transactions and added validations for ZRC20 withdrawals.
    • Resolved issues with transaction context abortion during dust detection.
  • Refactor

    • Updated test cases and renamed functions to reflect changes from refund to revert scenarios.
    • Enhanced testing framework for Solana-related functionalities.
  • Documentation

    • Updated comments to clarify timeout settings and new functionalities.

Copy link
Contributor

coderabbitai bot commented Nov 12, 2024

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several significant updates, including the addition of features for whitelisting SPL tokens on Solana and enhancements to the testing framework. Key modifications involve refactoring of existing code, such as removing the HSM signer from the zetaclient and improving error handling in outbound transaction processes. New test cases are added to better cover scenarios involving deposits and reverts, particularly focusing on dust amounts. The changelog has been updated to reflect these changes across multiple versions, detailing improvements in functionality and robustness.

Changes

File Path Change Summary
changelog.md Updated to include new features, improvements, refactoring, and fixes, including SPL token whitelisting and enhancements to testing framework.
cmd/zetae2e/local/local.go Modified localE2ETest to replace and add test cases related to Solana deposits, focusing on reversion scenarios.
e2e/e2etests/e2etests.go Added and modified test names for Solana-related functionalities, enhancing coverage for deposit and revert scenarios.
e2e/e2etests/test_bitcoin_deposit_and_call_revert_with_dust.go Updated TestBitcoinDepositAndCallRevertWithDust by removing imports and simplifying test logic to focus on cctx abortion.
e2e/e2etests/test_solana_deposit_and_call_revert_with_dust.go Introduced new test for Solana deposits that revert due to dust amounts, asserting expected outcomes based on transaction context.
e2e/e2etests/test_solana_deposit_refund.go Renamed TestSolanaDepositAndCallRefund to TestSolanaDepositAndCallRevert, updating its focus to handle reverts instead of refunds.
e2e/utils/zetacore.go Added WaitCctxAbortedByInboundHash function to monitor aborted CCTXs and clarified timeout settings in comments.
x/crosschain/keeper/cctx_orchestrator_validate_outbound.go Enhanced error handling and validation for outbound transactions, introducing processFailedOutboundV2 for streamlined handling of failed transactions.

Possibly related PRs

Suggested labels

no-changelog, TON_TESTS, UPGRADE_TESTS

Suggested reviewers

  • kingpinXD
  • fbac
  • swift1337
  • skosito
  • brewmaster012

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.

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.

@ws4charlie ws4charlie marked this pull request as ready for review November 12, 2024 22:58
@ws4charlie ws4charlie added SOLANA_TESTS Run make start-solana-test chain:bitcoin Bitcoin chain related zetacore Issues related to ZetaCore chain:solana and removed breaking:cli labels Nov 12, 2024
Copy link

codecov bot commented Nov 12, 2024

Codecov Report

Attention: Patch coverage is 66.66667% with 3 lines in your changes missing coverage. Please review.

Project coverage is 62.64%. Comparing base (07120f1) to head (11e2c37).
Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
...hain/keeper/cctx_orchestrator_validate_outbound.go 66.66% 2 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           develop    #3149   +/-   ##
========================================
  Coverage    62.64%   62.64%           
========================================
  Files          424      424           
  Lines        30115    30124    +9     
========================================
+ Hits         18866    18872    +6     
- Misses       10408    10410    +2     
- Partials       841      842    +1     
Files with missing lines Coverage Δ
...hain/keeper/cctx_orchestrator_validate_outbound.go 70.24% <66.66%> (-0.14%) ⬇️

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 (13)
e2e/e2etests/test_solana_deposit_and_call_revert_with_dust.go (2)

14-15: Enhance test documentation for better clarity

While the current comment describes the test's purpose, it could be more detailed to help other developers understand the test scenario better.

Consider expanding the documentation like this:

-// TestSolanaDepositAndCallRevertWithDust tests Solana deposit and call that reverts with a dust amount in the revert outbound.
+// TestSolanaDepositAndCallRevertWithDust verifies that a Solana deposit and call transaction
+// is properly aborted when the revert outbound would result in a dust amount.
+// Test scenario:
+// 1. Deposits exactly the rent-exempt amount
+// 2. Attempts a call to a non-existent receiver
+// 3. Verifies that the CCTX is aborted due to dust amount in revert

19-19: Consider using constants for test data

The test uses string literals and direct values that could be defined as constants for better maintainability and reusability.

Consider defining test constants:

+const (
+    testDepositDustMessage = "dust lamports should abort cctx"
+)

-depositAmount := big.NewInt(constant.SolanaWalletRentExempt)
+depositAmount := new(big.Int).SetInt64(constant.SolanaWalletRentExempt)

-data := []byte("dust lamports should abort cctx")
+data := []byte(testDepositDustMessage)

Also applies to: 24-25

e2e/e2etests/test_solana_deposit_refund.go (3)

12-13: Enhance function documentation for better clarity.

Consider expanding the documentation to include:

  • Expected parameters and their format
  • Success criteria for the test
  • Description of the revert scenario being tested
-// TestSolanaDepositAndCallRevert tests deposit of lamports calling a example contract that reverts.
+// TestSolanaDepositAndCallRevert tests the handling of reverted deposits on Solana.
+// Parameters:
+//   - args[0]: Deposit amount in lamports
+// The test verifies that:
+//   - The deposit transaction is processed correctly
+//   - The CCTX status is set to Reverted
+//   - Appropriate error messages are present in the CCTX status

Line range hint 19-23: Address TODO: Optimize contract deployment strategy.

The repeated deployment of the reverter contract in each test could be optimized by:

  1. Deploying once during test suite initialization
  2. Reusing the deployed contract across tests

Would you like me to help create a shared contract deployment mechanism or open an issue to track this optimization?


Line range hint 34-40: Refactor error handling for better maintainability.

The current error checking logic checks two different fields for the error message. Consider:

  1. Standardizing error message location to a single field
  2. Creating a dedicated error validation helper
+func requireRevertError(r *runner.E2ERunner, cctx *crosschaintypes.CrossChainTx) {
+    msg := cctx.CctxStatus.ErrorMessage
+    if msg == "" {
+        msg = cctx.CctxStatus.StatusMessage
+    }
+    require.Contains(r, msg, "revert executed")
+}
+
 // Check the error carries the revert executed.
-// tolerate the error in both the ErrorMessage field and the StatusMessage field
-if cctx.CctxStatus.ErrorMessage != "" {
-    require.Contains(r, cctx.CctxStatus.ErrorMessage, "revert executed")
-} else {
-    require.Contains(r, cctx.CctxStatus.StatusMessage, utils.ErrHashRevertFoo)
-}
+requireRevertError(r, cctx)
e2e/utils/zetacore.go (1)

Line range hint 12-19: Consider documenting timeout increase rationale

The timeout was increased from 6 to 8 minutes, but the comment still references an increase from 4 to 6 minutes. Consider updating the comment to reflect the current change and document why 8 minutes was chosen.

 // The timeout was increased from 4 to 6 , which allows for a higher success in test runs
+// Further increased to 8 minutes to accommodate longer processing times in dust amount scenarios
 // However this needs to be researched as to why the increase in timeout was needed.
 // https://github.com/zeta-chain/node/issues/2690
cmd/zetae2e/local/local.go (1)

Line range hint 432-445: Consider reorganizing test cases for better maintainability.

The Solana test cases could be organized into logical groups (e.g., basic operations, error cases, restricted operations) for better maintainability.

Consider refactoring the test organization:

-		solanaTests := []string{
-			e2etests.TestSolanaDepositName,
-			e2etests.TestSolanaWithdrawName,
-			e2etests.TestSolanaDepositAndCallName,
-			e2etests.TestSolanaDepositAndCallRevertName,
-			e2etests.TestSolanaDepositAndCallRevertWithDustName,
-			e2etests.TestSolanaDepositRestrictedName,
-			e2etests.TestSolanaWithdrawRestrictedName,
-			e2etests.TestSPLDepositName,
-			e2etests.TestSPLDepositAndCallName,
-			e2etests.TestSPLWithdrawName,
-			e2etests.TestSPLWithdrawAndCreateReceiverAtaName,
-			e2etests.TestSolanaWhitelistSPLName,
-		}
+		// Basic Solana operations
+		solanaBasicTests := []string{
+			e2etests.TestSolanaDepositName,
+			e2etests.TestSolanaWithdrawName,
+			e2etests.TestSolanaDepositAndCallName,
+		}
+		
+		// Error handling cases
+		solanaErrorTests := []string{
+			e2etests.TestSolanaDepositAndCallRevertName,
+			e2etests.TestSolanaDepositAndCallRevertWithDustName,
+		}
+		
+		// Restricted operations
+		solanaRestrictedTests := []string{
+			e2etests.TestSolanaDepositRestrictedName,
+			e2etests.TestSolanaWithdrawRestrictedName,
+		}
+		
+		// SPL token operations
+		solanaTokenTests := []string{
+			e2etests.TestSPLDepositName,
+			e2etests.TestSPLDepositAndCallName,
+			e2etests.TestSPLWithdrawName,
+			e2etests.TestSPLWithdrawAndCreateReceiverAtaName,
+			e2etests.TestSolanaWhitelistSPLName,
+		}
+		
+		solanaTests := append(
+			solanaBasicTests,
+			append(
+				solanaErrorTests,
+				append(
+					solanaRestrictedTests,
+					solanaTokenTests...,
+				)...,
+			)...,
+		)
changelog.md (1)

27-27: Fix typographical error in changelog entry.

The word "dected" appears to be misspelled.

-* [3149](https://github.com/zeta-chain/node/pull/3149) - abort the cctx if dust amount is dected in the revert outbound
+* [3149](https://github.com/zeta-chain/node/pull/3149) - abort the cctx if dust amount is detected in the revert outbound
x/crosschain/keeper/cctx_orchestrator_validate_outbound.go (5)

197-207: Enhance Error Context in validateZRC20Withdrawal

While the addition of validateZRC20Withdrawal strengthens the validation process for revert transactions, improving the error handling can provide clearer diagnostics. Consider wrapping the error with additional context.

Apply the following diff to enhance error messages:

if err != nil {
-    return err
+    return fmt.Errorf("validation failed in validateZRC20Withdrawal: %w", err)
}

This modification ensures that any failure in the validation process is accompanied by a descriptive message, aiding in debugging and maintenance.


196-207: Avoid Redundant Validation Calls

The call to validateZRC20Withdrawal immediately after paying the gas fee may introduce redundancy if similar validations have already been performed earlier in the process. Evaluate whether this validation is necessary at this point or if it can be consolidated to prevent unnecessary overhead.

If the validation is essential here, no action is needed. Otherwise, consider removing or consolidating it to streamline the code execution path.


Line range hint 289-294: Consolidate Logic in processFailedOutboundV2

The TODO comment indicates an opportunity to consolidate logic with other functions, as referenced in issue #2627. Refactoring the code can enhance maintainability and reduce duplication.

Consider abstracting common functionalities into shared helper methods or interfaces. This approach will:

  • Simplify the codebase by removing redundant code.
  • Make future updates more manageable.
  • Improve readability for other developers.

Line range hint 297-304: Handle Potential Inconsistency in Sender Chain Validation

The sender chain validation checks if cctx.InboundParams.SenderChainId matches zetaChain.ChainId. If this condition fails, an error is returned. Ensure that this validation logic is consistent across all relevant functions to prevent unintended behaviors.

Consider adding unit tests to verify that transactions with mismatched sender chain IDs are appropriately handled and that the error messages are clear and informative.


Line range hint 318-329: Check for Error Handling in ZEVM Revert Processing

In the call to k.fungibleKeeper.ProcessV2RevertDeposit, errors are wrapped but not differentiated. To facilitate better debugging, specify the nature of potential errors.

Modify the error wrapping to include more context:

if err := k.fungibleKeeper.ProcessV2RevertDeposit(
    // parameters
); err != nil {
-    return errors.Wrap(err, "failed ProcessV2RevertDeposit")
+    return fmt.Errorf("failed to process V2 revert deposit for CCTX %s: %w", cctx.Index, err)
}

This change provides clearer information about which transaction failed and why.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5631ad7 and 2ca634c.

📒 Files selected for processing (8)
  • changelog.md (1 hunks)
  • cmd/zetae2e/local/local.go (1 hunks)
  • e2e/e2etests/e2etests.go (2 hunks)
  • e2e/e2etests/test_bitcoin_deposit_and_call_revert_with_dust.go (1 hunks)
  • e2e/e2etests/test_solana_deposit_and_call_revert_with_dust.go (1 hunks)
  • e2e/e2etests/test_solana_deposit_refund.go (1 hunks)
  • e2e/utils/zetacore.go (1 hunks)
  • x/crosschain/keeper/cctx_orchestrator_validate_outbound.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
cmd/zetae2e/local/local.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

e2e/e2etests/e2etests.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

e2e/e2etests/test_bitcoin_deposit_and_call_revert_with_dust.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

e2e/e2etests/test_solana_deposit_and_call_revert_with_dust.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

e2e/e2etests/test_solana_deposit_refund.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

e2e/utils/zetacore.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/keeper/cctx_orchestrator_validate_outbound.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

🔇 Additional comments (8)
e2e/e2etests/test_solana_deposit_and_call_revert_with_dust.go (1)

1-12: LGTM: Clean and well-organized imports

The imports are relevant and properly organized, with standard library imports separated from external dependencies.

e2e/e2etests/test_bitcoin_deposit_and_call_revert_with_dust.go (2)

39-40: LGTM! Clear and accurate variable naming.

The rename from badMemo to anyMemo better reflects the variable's purpose, as the memo itself isn't inherently bad but rather arbitrary. The memo construction is clear and follows good practices.


44-46: LGTM! Clean and direct test assertion.

The simplified test assertion using WaitCctxAbortedByInboundHash is a more elegant approach compared to the previous implementation. It directly verifies the expected outcome (CCTX abortion) without unnecessary intermediate checks.

e2e/utils/zetacore.go (1)

230-242: LGTM! The implementation is clean and follows established patterns.

The new function WaitCctxAbortedByInboundHash is well-implemented and consistent with the existing codebase patterns, particularly mirroring the structure of WaitCctxRevertedByInboundHash. The function correctly uses the MatchStatus option with CctxStatus_Aborted to wait for aborted transactions.

cmd/zetae2e/local/local.go (1)

436-437: LGTM! Test cases align with PR objectives.

The new test cases appropriately cover the dust amount handling in Solana transactions.

Let's verify the test implementations:

✅ Verification successful

Verified: Dust handling is adequately covered by the new test cases.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify test implementations for the new Solana test cases
# Expected: Find the test implementations that handle dust amounts

# Search for the test implementations
ast-grep --pattern 'func TestSolanaDepositAndCallRevert($$$) {
  $$$
}'

# Search for dust amount validation logic
rg -A 5 "validateZRC20Withdrawal.*dust"

Length of output: 2656


Script:

#!/bin/bash
# Description: Find the implementation of validateZRC20Withdrawal and check for dust handling
# Step 1: Locate the definition of validateZRC20Withdrawal
ast-grep --pattern 'func validateZRC20Withdrawal($$$) { $$$ }'

# Step 2: Search for dust-related logic in the codebase
rg -A 5 "dust" --glob '*.go'

Length of output: 8459

e2e/e2etests/e2etests.go (1)

58-68: LGTM! Well-structured Solana test definitions.

The Solana test constants follow the established naming convention and provide clear, descriptive names for each test case.

x/crosschain/keeper/cctx_orchestrator_validate_outbound.go (2)

Line range hint 185-190: Verify Gas Payment Sufficiency for Revert Transactions

The newly added code segment pays the gas fee for the revert outbound transaction using inputAmount. Please ensure that:

  • inputAmount accurately reflects the required gas fee for the revert transaction.
  • There are sufficient funds to cover this gas payment to prevent potential failure of the revert operation.

Line range hint 331-339: Ensure Transaction Hash Assignment is Accurate

When assigning the transaction hash and observed external height:

  • Confirm that ctx.TxBytes() reliably returns the correct transaction bytes in all execution contexts.
  • Validate that the conversion to an Ethereum-compatible hash via ethcommon.BytesToHash is appropriate.

Run the following script to check the consistency of transaction hashes:

e2e/utils/zetacore.go Show resolved Hide resolved
e2e/e2etests/e2etests.go Show resolved Hide resolved
Copy link
Contributor

@fbac fbac 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. Agree on the comments posted by @lumtis.

@gartnera gartnera added the CONSENSUS_BREAKING_ACK Acknowledge a consensus breaking change label Nov 13, 2024
changelog.md Outdated Show resolved Hide resolved
@ws4charlie ws4charlie added this pull request to the merge queue Nov 14, 2024
Merged via the queue into develop with commit 420f83a Nov 14, 2024
41 checks passed
@ws4charlie ws4charlie deleted the fix-dust-amount-for-revert-case branch November 14, 2024 17:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
breaking:cli chain:bitcoin Bitcoin chain related chain:solana CONSENSUS_BREAKING_ACK Acknowledge a consensus breaking change SOLANA_TESTS Run make start-solana-test zetacore Issues related to ZetaCore
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Use validateZRC20Withdrawal for revert case
5 participants